# Recursiv SDK — Reference for AI Coding Assistants

> Read this file before writing any code with @recursiv/sdk.
> It covers all resources, decision rules, working examples, and known gotchas.

```typescript
import { Recursiv, personalBuildExpectation } from '@recursiv/sdk'
const r = new Recursiv() // reads RECURSIV_API_KEY from env
```

## Decision rules — pick the right resource

Personal builds use `r.personalBuilds` (`authentication === 'session-bearer'`) with an explicit `{sessionToken, signal?}` on every call, only in the staging pilot. `listProjects` lists clean owned projects; `prepare` stores a request with no model/provisioning. New drafts may await an approved enforced budget. `get` reconciles durable state; `dispatch_claimed` is unconfirmed, never automatically rerun, and `completed` does not prove a working app. `previewEntry` returns a private ticket and its verified existing workspace coordinate, never a public share URL or execution grant. `stop` requests cancellation. Review `approvals` and separately `approve` or `reject`; no automatic approval. A separate explicit `saveVersion` confirms one attempt, title and bounded existing-workspace timebox (not a monetary grant); never auto-renew or resend an uncertain attempt. `saveVersionStatus` reads its durable receipt without runtime. `publicationCandidate` returns a short-lived isolated HTTP review URL for that saved committed static version; a separate explicit `publish` approves that exact candidate to a separate staging target. `publicationStatus` reconciles queued or lost acknowledgments without redeploying; only `completed` means the deployment finished. App API keys are refused. Requires supporting API/package rollout.
For a new private draft only, omit `project_id` and explicitly approve `new_project_budget: { daily_limit_usd: 1, enforced: true }` (finite, above zero, at most $1). This sets a daily model-spend ceiling without funding, model dispatch, repository creation or provisioning; paid admission and the operator's pilot binding still apply. Omit it to leave the draft unbudgeted. Never send it with an existing project or change/omit it when replaying the same request ID; use `get` and the returned durable reference for recovery.
Prepare/get status may include `setup: { owner_id, network_id, project_daily_limit_usd, project_daily_limit_enforced }`, read from the validated owner/tenant and current project settings. An absent or invalid numeric ceiling is `null`; this readback does not grant execution or prove funds. Read it fresh for operator setup; do not persist it as continuity or infer it from client-selected headers.
```typescript
const session = { sessionToken: memberSession.token } // from r.auth sign-in, kept inside your auth boundary
const { data: build } = await r.personalBuilds.prepare({ request_id: crypto.randomUUID(), project_id: selectedOwnedProjectId, prompt: 'Build a music quiz', personal_account_build: true }, session)
const { data: admission } = await r.personalBuilds.admission(build, { ...session, nonce: crypto.randomUUID() })
// Show model and request/day/project caps. Only the person's separate Start build action calls:
await r.personalBuilds.execute(build, { personal_account_build: true, expected_admission: personalBuildExpectation(admission) }, session)
```

| Need | Use | Do NOT use |
|------|-----|-----------|
| Structured/relational data | `r.databases` → Postgres | `r.posts` with JSON blobs |
| Social content, feeds, reactions | `r.posts` + `r.communities` + `r.tags` | `r.databases` for social feeds |
| App file storage (photos, docs, media) | `r.storage` (buckets, presigned URLs) | Social post APIs |
| Post/chat media bytes | `r.uploads.uploadMedia()` | Manual presign + `fetch` PUT |
| User auth and API keys | `r.auth` | Raw fetch to `/api/auth/*` |
| AI agent with model + system prompt | `r.agents` | Direct LLM API calls |
| Agent code/tool execution | `r.projects.executeCode()` + `r.commands` | External sandboxes |
| Deploy to production | `r.projects.deploy()` | Manual CI/CD |
| Messaging between users | `r.chat` | Custom WebSocket layer |
| Team/org management | `r.organizations` | Custom user-group tables |
| Per-project task tracking & decisions | `r.projectBrain` | External project management |
| Persistent agent memory | `r.memory` (facts, decisions, search) | Storing knowledge in `r.posts` or `r.databases` |
| Transactional email (receipts, alerts) | `r.email.send()` | Direct Resend/SendGrid calls |
| Receive external webhooks (Stripe, etc.) | `r.webhooks.register()` | Custom webhook server |
| Server-side cron / scheduled tasks | `r.jobs.create()` | External cron services |
| A member's engagement signals (views, dwell, hides) | `r.signals.batch()` | Raw fetch to `/signals/*`, or a resource's `client` |
| Coarse first-party product counts | `r.telemetry.productCounts()` | Member IDs, paths, URLs or arbitrary event properties |

**IMPORTANT:** Do NOT store structured app data (records, inventory, tasks, settings) as JSON inside `r.posts.content`. Posts are for social content. Use `r.databases` for application data.

---

## Infrastructure

### r.databases — Provision and query Postgres

```typescript
const { data: db } = await r.databases.ensure({ project_id: 'proj_xxx', name: 'my-app-db' })
const { data: creds } = await r.databases.getCredentials({ project_id: 'proj_xxx', name: 'my-app-db' })
// creds.connection_string → "postgresql://user:pass@host:5432/dbname"

const { data: result } = await r.databases.query({
  project_id: 'proj_xxx',
  sql: 'SELECT * FROM items WHERE user_id = $1',
  params: ['user_abc'],
  name: 'my-app-db', // optional, defaults to 'default'
})
// result.rows → [{ id: 1, ... }]
```

Methods: `list({ project_id })`, `create({ project_id, name })`, `ensure({ project_id, name? })`, `getCredentials({ project_id, name })`, `query({ project_id, sql, params?, name? })`

`query` and `ensure` also accept `database_name` as a deprecated alias for `name`.

With the verified customer-query API ([PR #6265](https://github.com/recursivlabs/recursiv/pull/6265), pending deployment), each app customer's `query` accepts **one SQL statement, including writes**. Semicolon-separated statement batches are rejected. Let the API bind customer identity; do not prepend a `set_config` statement. Use separate calls for independent operations (they are not atomic together), or one data-modifying CTE when changes must commit together. Run schema migrations and migration batches through an authorized owner/server connection, not an end-user key; owner migration batches remain supported.

Note: `ensure` is idempotent for existing resources. Creating a missing database or bucket requires project admin authority; pre-provision app infrastructure during setup before regular `project_member` users mount the app. `getCredentials` takes `project_id` + `name`, not `database_id`.

### r.envVars — Environment variables for deployed apps

```typescript
// Give a deployed app the key it needs to boot.
await r.envVars.set({
  project_id: 'proj_xxx',
  key: 'STRIPE_SECRET_KEY',
  value: process.env.STRIPE_SECRET_KEY!,
})

const { data } = await r.envVars.list({ project_id: 'proj_xxx' })
// [{ key: 'STRIPE_SECRET_KEY', value: '••••••••', is_secret: true, ... }]
```

Methods: `list({ project_id, environment? })`, `set({ project_id, key, value, is_secret?, environment? })`, `createProjectApiKey({ project_id, key, scopes?, environment? })`, `delete({ project_id, key, environment? })`

`createProjectApiKey` mints a project-bound Recursiv key straight into the env var (e.g. `RECURSIV_API_KEY` for a server-side form) and returns only `api_key_id` and `api_key_prefix`, never the key. Scopes default to `databases:read` + `databases:write`, can't exceed the calling key's, and can't include `admin`. Calling it again rotates: the previous key in that variable is revoked.

Keys are UPPER_SNAKE_CASE. `environment` is `'preview' | 'production' | 'both'`, default `'both'`.

**Values are write-only.** Anything stored as a secret (the default) comes back masked, so a key that can stand an app up can never read a credential back out of it. `set` and `delete` require project admin. Changes apply on the next deploy.

`DATABASE_URL`, `POSTGRES_URL`, `RECURSIV_PROJECT_ID` and `RECURSIV_ORG_ID` are injected automatically — don't set them here.

### r.projects — Deploy, sandbox, execute code

```typescript
const { data: project } = await r.projects.create({ name: 'My App', organization_id: orgId })
await r.projects.createSandbox(project.id)

const { data: result } = await r.projects.executeCode(project.id, {
  code: 'console.log("hello")',
  language: 'typescript',
})
// result.output → "hello\n"

const { data: deployment } = await r.projects.deploy(project.id, { branch: 'main', type: 'production' })
const { data: logs } = await r.projects.deploymentLogs(project.id, deployment.id)
```

Methods: `list`, `get`, `create`, `delete`, `deploy`, `executeCode`, `sandbox`, `createSandbox`, `stopSandbox`, `deployment`, `deploymentLogs`, `deployments`

Operator API/frontend coordination: `r.deployments.reserveRelease(input)`, `getRelease(releaseId, projectId)`, `advanceRelease(releaseId, input)`, `startRelease(releaseId, input)`, `finishRelease(releaseId, input)`, `recoverRelease(originalReleaseId, input)`. Example read: `const { data: release } = await r.deployments.getRelease(releaseId, projectId)`. Use a project-bound `projects:read`/`projects:write` operator key; follow [shared release phases, live proof and recovery](../../docs/deploy/shared-releases.md). Initial reservation also accepts optional `coordinator_identity_token` after the compatible API is verified live; invalid supplied proof never falls back to tokenless. Keep capabilities and tokens out of logs; uncertain operations retain ownership.

### r.storage — Bucket-based file storage

```typescript
const { data: bucket } = await r.storage.ensureBucket({ name: 'user-photos', project_id: project.id })
const { data: upload } = await r.storage.getUploadUrl({
  bucket_name: 'user-photos', key: 'photo.jpg', content_type: 'image/jpeg', project_id: project.id,
})
// PUT file to upload.url
const { data: download } = await r.storage.getDownloadUrl({
  bucket_name: 'user-photos', key: 'photo.jpg', project_id: project.id,
})
// GET file from download.url
```

Methods: `listBuckets`, `getBucket`, `createBucket`, `ensureBucket`, `listItems`, `createFolder`, `getUploadUrl`, `getDownloadUrl`, `deleteObject`

Note: `ensureBucket` is idempotent for existing buckets. Creating a missing bucket requires project admin authority.

### r.sandbox — Anonymous code execution

```typescript
const r = new Recursiv({ anonymous: true })  // no API key needed
const { data } = await r.sandbox.execute({ code: '1 + 1', language: 'typescript' })
// Rate-limited: 10/day per IP
```

---

## AI Agents

### r.agents — Managed AI agents

```typescript
const { data: agent } = await r.agents.create({
  name: 'Home Assistant',
  // username is optional; the server generates a collision-resistant handle
  model: 'anthropic/claude-sonnet-4.6', // see SUPPORTED_MODELS
  system_prompt: 'You help homeowners maintain their property.',
  project_id: projectId, // app-customer flow; works with per-user keys. Use organization_id only for team-owned agents.
})

// Sales pipeline: leads an outbound agent owns (network_lead). Caller must own the agent.
const { data: leads } = await r.agents.leads(agent.id, { preset: 'hot', limit: 50 })
// leads[]: { email, company_name, role_target, status, tier, sentiment_label, engagement_score, ... }

// Non-streaming chat (agent responds asynchronously)
const { data: reply } = await r.agents.chat(agent.id, { message: 'When should I service my HVAC?' })
// reply: { message_id, conversation_id, content, created_at, note }

// Streaming (Node.js/browser — requires ReadableStream)
const stream = r.agents.chatStream(agent.id, { message: 'Tell me more' })
for await (const chunk of stream) { process.stdout.write(chunk.delta ?? '') }

// Streaming (React Native / any platform — reads full response then parses)
const { content, conversationId } = await r.agents.chatStreamText(agent.id, {
  message: 'Tell me more',
  conversation_id: existingConvId, // optional
})

// "New chat" with the member's own personal agent: an empty thread in this key's app (201), or the member's existing
// empty one there (200, created: false). 404 agent_not_found for no agent or another network's; 403 not_owner otherwise.
const { data: chat } = await r.agents.createConversation(myAgentId) // { id, type, name: null, members, created, ... }
await r.agents.chatStreamText(myAgentId, { message: 'Plan a weekend in Lisbon', conversation_id: chat.id })
const { data: chats } = await r.agents.conversations(myAgentId) // chats[].name: own name, else first 60 chars of the first message, else null

// The app's agent directory, searched and sorted on the server (0.7.71). Keyless works for visitors:
// new Recursiv({ anonymous: true, inheritEnvironmentApiKey: false }) on the app's API host (public profiles only).
const { data: found, meta } = await r.agents.discover({ q: 'space', sort: 'popular', limit: 20 }) // sort: popular | recent | name
// found[]: { id, name, username, image, bio, follower_count, verified, created_at }; next page: discover({ ..., cursor: meta.next_cursor })

// Give agent access to project infrastructure
await r.agents.grantProjectAccess(agent.id, {
  project_id: project.id,
  permissions: ['execute_code', 'read_files', 'write_files'],
})
```

Methods: `list`, `get`, `create`, `update`, `delete`, `chat`, `chatStream`, `chatStreamText`, `retryChatStream`, `retryChatStreamText` ("Try again": `{ conversation_id, retry_message_id }` re-answers your latest message without sending it twice), `conversations` (each with `name`), `createConversation` ("New chat" with your own personal agent; send with `chatStream`'s `conversation_id`), `discover` (search and sort the app's published agents, cursor paged, keyless-readable), `listDiscoverable`, `leaderboard`, `grantProjectAccess`, `revokeProjectAccess`, `resetRequestCount`, `getByClaimToken`, `claim`, `orchestratorStatus`

### r.brain — AI assistant messaging

```typescript
const { data } = await r.brain.sendMessage({
  message: 'What should I work on next?',
  history: [{ role: 'user', content: 'previous message' }],
  context: { current_route: '/dashboard', org_slug: 'acme' },
})
// Response streams via WebSocket — data.message_id identifies the response
```

Methods: `sendMessage({ message, history?, context? })`

### r.commands — AI command execution

```typescript
// Execute a prompt with AI
const { data } = await r.commands.execute({
  prompt: 'Summarize recent activity',
  current_screen: '/dashboard',
  org_slug: 'acme',
  model: 'anthropic/claude-sonnet-4',
})
// data: { text, actions }
```

Methods: `execute({ prompt, current_screen?, org_slug?, model?, locale?, attachments? })`, `gatePrompt({ messages })`. `gatePrompt` is Recursiv's own signup gate, not a moderation API: it answers only for keys on the platform's networks (404 anywhere else, including an app's own network), ignores `model`, and shares one daily LLM budget with Recursiv's signup page.

### r.projectBrain — Per-project knowledge base & task management

```typescript
const { data: tasks } = await r.projectBrain.tasks(projectId, { status: 'open' })
const { data: decisions } = await r.projectBrain.decisions(projectId)
const { data: milestones } = await r.projectBrain.milestones(projectId)
const { data: usage } = await r.projectBrain.usage(projectId)
await r.projectBrain.completeTask(projectId, taskId, 'Implemented and tested')
await r.projectBrain.updateSettings(projectId, { daily_spending_limit_usd: 0.5, daily_spending_limit_enforced: true })
```

Only a project owner or admin may enable its daily ceiling for native agent chat turns. `daily_spending_limit_enforced: true` applies on paid plans too, independently of global observe-only settings. Use a positive limit; an enabled missing or unreadable budget refuses those turns. One metered chat turn per project is admitted across API instances; all its model calls, retries and empty-reply fallbacks fit the lesser of its request limit and recorded remaining UTC-day allowance. Those turns keep the requested model and initially selected provider/configuration; failure never selects another model or billing route. Separately billed research, image and browser tools are withheld from those turns; directly invoked services retain their own billing controls. Confirmed usage releases the admission. An interrupted or failed usage write keeps the project's chat turns paused for operator reconciliation, including after midnight; it never silently forgets possible spend.

Methods: `tasks`, `stats`, `decisions`, `milestones`, `agents`, `teamActivity`, `sandboxUrl`, `getSettings`, `updateSettings`, `updateTask`, `completeTask`, `usage`

---

## Assistant subjects — `@recursiv/sdk/assistant` (unreleased)

Pure, no network: the same input on a server, a phone or the web. Build the bundle from data you already hold, then render it; never paste post text into a prompt by hand.

```typescript
import { buildSubjectBundle, renderBundleForModel } from '@recursiv/sdk/assistant'
const { bundle, refused, excluded } = buildSubjectBundle({ mode: 'standard', asker: { id, blocked_ids, muted_ids }, post, parent, quoted, replies }) // server: also blocked_by_ids
if (bundle) {
  const { system, user, references } = renderBundleForModel(bundle, 'summarise', { boundary }) // boundary: fresh random, 16+ chars, per call
}
```

- `bundle` is null when the post itself may not be read: author asks off (`ai_ask_allowed` `'off'`, or `'sealed_only'` in Standard), the asker blocked or muted the author or the author blocked the asker, known-minor author (unless asker is author), child-safety hold, moderator suppression, `assist_readable: 'none'`. Make no model call.
- `refused` and `excluded` (`{ role, reason, count }[]`, never ids) are safe to show the asker: blocks, minors, holds and suppression all read `'unavailable'`. `audit` has the detail: server log only, never to a client.
- `known_minor`, `child_safety_hold`, `assistant_suppressed`, media `held: true`, `blocked_by_ids`: server-side inputs, never sent to another member's client (held media is left out of that payload, and so is the post's `ai_caption` whenever any of its media is held: a client cannot see media it was never sent); a client passes the server's per-viewer `assist_readable` instead. Exception: a picture's `held: false`, the payload's "not held" mark beside `checked_at`. Flags fail closed (anything but false/null/absent is set); an unreadable id list throws.
- Replies, parent and quote are left out by the same rules. Media go as alt text and stored caption only; picture and media addresses never reach `references`. Hidden text is stripped; top 20 replies; per-field and total caps (lower them with `limits`, never raise).
- Intents: `explain`, `fact_context` (post, parent, quote), `summarise` (plus replies), `translate` (needs `language`, a BCP 47 tag), `describe`. Output filters allow only `references` ids, handles and URLs, as plain links (never render an image the model wrote). Render only bundles you built from your own reads.
- Post pictures: pass media `id`, the payload's `checked_at` and its `held: false` mark to the builder (`checked_at` is kept only with `held` exactly `false`). `max` = `Math.max(0, 3 - phonePictures)`. `listed = bundlePictures(bundle, intent, { now: Date.now(), max })`, run your checks, then `renderBundleForModel(bundle, intent, { boundary, pictures: { now: Date.now(), max, allowed: passed.map((x) => x.picture), cached: (p) => passed.find((x) => same(x.picture, p))?.prepared_jpeg ?? null } })` (a fresh clock: it can only take pictures away). Your checks load each listed picture from the image cache, prepare it first (longest side ≤ 1536 px, re-encoded as JPEG, metadata stripped; spec 2.2), check the prepared bytes and return `passed` as `{ picture, prepared_jpeg }`; `cached` returns that `prepared_jpeg` (`same` matches `item_id`, `media_id` and `number`): never a second read of the cache, which could return a picture nobody checked and still carries its metadata. The SDK only checks the bytes look like a JPEG. Only pictures on the post, parent or quote (never replies), marked `held: false`, checked under 24 h ago by `now` (5 min ahead allowed), with a plain id, on `allowed` and with a cached base64 JPEG go, as `image_url` data parts inside the content block in `user_parts`; at most `max` (≤ 3), none for `translate`; a picture stale since listing is not replaced; everything else stays alt text, and output is unchanged when none qualifies. With pictures, send `system` + `user_parts` (not `user`/`text`). Never fetch in `cached`; `references` never holds a picture address.
- `sealedTurnCaps({ mode: 'sealed' | 'both', others_content, phone_pictures, temporary, searched_earlier, phone_pictures_earlier, search, earlier_messages, memory, memory_in_chat, memory_tick, about_you, page_opens_limited })` → `{ search, history, memory, about_you, phone_pictures, suggest_memory, reasons }`. `others_content` (`[]` for own words), `phone_pictures` (`0` for none), `temporary`, `searched_earlier`, `phone_pictures_earlier` and `earlier_messages` are required (absent/null throws; `false` is none). `mode: 'both'` with `'encrypted_chat'` throws (G21: Sealed only; Both's Standard half would send it to Minds and the AI company). Searching messages carry no memory/About you/phone pictures (search turns off: `search.off_mix`) and no history (`search.question_only`); someone else's public post blocks search until `page_opens_limited` (Tinfoil ask 3, default false; `search.off_subject`); members-only posts and chat messages never search (`search.off_members`), encrypted-chat messages never (`search.e2ee`) and carry no phone pictures; Both never searches or carries phone pictures (`both.no_search`, `both.no_photo`); temporary chats and encrypted-chat asks get no memory. With others' content only `memory_tick` sends memory/About you (the chip `memory_in_chat` counts only in the member's own chat). No `suggest_memory` with phone pictures in the message (a screenshot can carry someone else's words), or after a search or a phone picture earlier in the chat. Only `true` turns a sending choice on; unknown `mode`/content kinds and picture counts that are not 0 to 3 throw.
- Fixed cards, before any model call: `matchFixedCard(memberWords, { country, locale })` → `{ kind: 'crisis' | 'election', card } | null`. Crisis (self-harm, suicide risk, immediate danger) always shows the card first, then the turn may answer; election logistics only (never candidates, results, fraud claims, votes on a post or poll), and `fixedCardAnswer('election', Date.now())` is `'card_only'` until 2026-11-04T12:00Z. English and Spanish; every number and URL is sourced data (`CRISIS_LINES`, `ELECTION_SITES`), never generated. Pass the member's words, not the post they ask about.

---

## Evidence — Measure agents (evals, accuracy, cost)

### r.evidence — Author evals, run simulations, read graded results

```typescript
// Run a batch of cases through an agent or swarm and grade them (the whole loop)
const { data } = await r.evidence.simulate({
  target: { type: 'swarm', id: swarmId },
  cases: [{ input: 'New account, $9.6k order', expected: { answer: 'ESCALATE' } }],
  evals: [{ name: 'On-policy', type: 'judge', definition: { rubric: 'Follows the risk policy?' }, judge_model: 'anthropic/claude-sonnet-4.6' }],
})
console.log(data.run_id, data.run?.accuracy) // per-step results in data.results

// Read the audit trail — what an agent/swarm actually did and what it cost
const { data: sum } = await r.evidence.summary({ type: 'swarm', id: swarmId })
const { data: events } = await r.evidence.records({ type: 'swarm', id: swarmId }, { limit: 50 })
const first = events[0]
const { data: step } = await r.evidence.recordDetail({ type: 'swarm', id: swarmId }, first.id, first.kind)
// step: model_call → { systemPrompt, promptMessages, responseText, reasoningText, toolCalls }
//       tool_call  → { toolName, args, result, success }

// Save a set once, re-run it after every change so runs compare like with like
const { data: saved } = await r.evidence.createEvalSet({
  name: 'Escalation policy',
  cases: [{ input: 'New account, $9.6k order', expected: { answer: 'ESCALATE' }, trap: true }],
})
const { data: rerun } = await r.evidence.simulate({ target: { type: 'swarm', id: swarmId }, eval_set_id: saved.eval_set_id })
const { data: sets } = await r.evidence.listEvalSets()                   // the key's org, or your own sets
const { data: file } = await r.evidence.exportRun(rerun.run_id, 'csv')   // { filename, mimeType, content }
```

### Task checks — how the org knows a task's work is done

```typescript
// Declare the proof when the task is created (Index vocabulary):
// machine_checked | expert_graded | scenario_tested | field_tested | exempt
const { data: task } = await r.dispatcher.createTask({ title: 'Fix the login redirect', proof_type: 'machine_checked' })

// Attach a check to the task at claim time, before the work, so it runs RED first.
// `check` reads GitHub: the PR named in the close evidence must be merged and the named CI check green.
await r.evidence.createEval({ target: { type: 'task', id: task.id }, name: 'ci', type: 'check', definition: { check: 'unit-tests' }, threshold: 100 })
await r.evidence.runTaskChecks(task.id)            // { passed, failed, errored, results } — red now
// ...do the work, release with pr_urls, then:
await r.evidence.runTaskChecks(task.id)            // green once the PR merged and CI passed
await r.dispatcher.complete(task.id, { notes: 'PR #123 merged' })
// Under the org's "Check and block" policy a close with a failing check is refused with 409 and the names;
// under "Check and flag" it closes and `data.check_warnings` lists them; under "Take its word" checks are not consulted.
// A check counts as passed only if an earlier run of it failed on the same task (red-first).
await r.dispatcher.complete(task.id, { override_reason: 'check misconfigured; work verified by hand' }) // closes anyway, logged permanently
await r.organizationSettings.setTaskClosePolicy(orgId, 'warn')  // off | warn | require
```

Methods: `createEval` (code | judge | match | consensus | check), `runTaskChecks`, `simulate`, `listRuns` (`target_type: 'task'` for a task's runs), `getRun`, `summary`, `records`, `recordDetail`. Eval types: `code` (rule), `judge` (rubric, reference-free — use a different model family), `match` (vs known answer), `consensus` (cross-model agreement; premium). `records` is the continuous activity ledger (every model + tool call); `recordDetail` is the drill-down behind one event (exact prompt/reasoning, or exact tool inputs/outputs).

---

## Memory — Persistent agent memory across sessions

### r.memory — Facts, decisions, and search

```typescript
// Store a fact — persists across sessions, shared with all agents on the same project
const { data: fact } = await r.memory.facts.add({
  fact: 'This project uses Hono, not Express',
  project_id: 'proj_xxx',
  tags: ['architecture', 'routing'],
  source: 'manual',  // 'auto' | 'manual' | 'extraction'
})

// Recall facts for a project
const { data: facts } = await r.memory.facts.list({ project_id: 'proj_xxx' })

// Search query across facts
const { data: filtered } = await r.memory.facts.list({ project_id: 'proj_xxx', query: 'database' })

// Remove a fact
await r.memory.facts.remove(fact.id)

// Log an architectural decision with context
const { data: decision } = await r.memory.decisions.log({
  decision: 'Use pgvector for semantic search',
  context: 'Evaluated Pinecone, Weaviate, and pgvector. pgvector wins on ops simplicity.',
  tags: ['architecture', 'database'],
  project_id: 'proj_xxx',
})

// List decisions
const { data: decisions } = await r.memory.decisions.list({ project_id: 'proj_xxx' })

// Search across all memory types (facts, decisions, conversations)
const { data: results } = await r.memory.search({
  query: 'authentication approach',
  project_id: 'proj_xxx',
  limit: 10,
})

// Build a context block from relevant memories (for enriching prompts)
const { data: ctx } = await r.memory.context({
  message: 'How should I implement caching?',
  project_id: 'proj_xxx',
  max_tokens: 2000,  // token budget for the context block
})
// ctx.context → formatted string of relevant facts + decisions

// Purge all memory for a project (irreversible — GDPR compliance)
await r.memory.purge('proj_xxx')
```

Methods:
- `facts.add`, `facts.list`, `facts.remove`
- `decisions.log`, `decisions.list`
- `search`, `context`, `purge`

### Decision rules

- Use `r.memory.facts.add()` when the agent learns something worth remembering
- Use `r.memory.decisions.log()` for architectural or strategic decisions with context
- Use `r.memory.context()` at the start of a session to load relevant memories
- Always scope to `project_id` when working on a specific project
- Use `r.memory.search()` when looking for specific past knowledge
- Do NOT store secrets, API keys, or credentials as memory facts (the API rejects them)
- Facts are deduplicated — storing the same fact twice updates the timestamp instead of creating a duplicate

### Golden path — Agent with persistent memory

```typescript
// At session start: load relevant context
const { data: ctx } = await r.memory.context({
  message: userMessage,
  project_id: projectId,
})
// Inject ctx.context into system prompt

// During work: remember what you learn
await r.memory.facts.add({
  fact: 'The auth system uses JWT with 15min expiry',
  project_id: projectId,
  tags: ['auth'],
})

// Record decisions
await r.memory.decisions.log({
  decision: 'Use Redis for session caching',
  context: 'Need sub-ms reads, DB was adding 50ms latency',
  project_id: projectId,
})
```

---

## Identity & Auth

### r.auth — Authentication and API keys

```typescript
const session = await r.auth.signUp({ name: 'Jane', email: 'jane@example.com', password: 'secure12345!' })
// session: { token, user: { id, name, email, image } }

const session = await r.auth.signIn({ email: 'jane@example.com', password: 'secure12345!' })

const key = await r.auth.createApiKey(
  { name: 'my-key', scopes: ['posts:read', 'agents:write'], description: 'CI bot', expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString() },
  session.token,
)
// key: { key, id, name, prefix, lastFourChars, scopes, projectId, networkId, expiresAt, createdAt }

await r.auth.signOut(session.token)
```

`getSession(token)` and `signOut(token)` send the explicit session token as
Bearer auth, with a Cookie fallback for native/server runtimes. `getSession`
also answers `session: { id, expiresAt }`; an API-key client lists sessions with
`is_current: false`, so it matches `session.id` to mark its own device.
`createApiKey` requires a signed-in session; optional `expiresAt` is a future ISO timestamp at most one year away. Validate the receipt's stored `projectId`, `networkId` and `expiresAt` before storing an operator key, and never log its key value.

Generated apps use platform-hosted sign-in: `const { data } = await r.auth.exchangeCustomerAppCode({ projectId, redirectUri, codeChallenge, state, dataAccess: 'write', mode: 'sign-in', code, verifier })` returns only a bounded project credential after a registered callback and PKCE check; collect passwords only on a platform-owned origin.

Methods: `signUp`, `signIn`, `getSession`, `signOut`, `createApiKey`, `signInAndCreateKey`, `signUpAndCreateKey`, `verifyOtpAndCreateKey`

Also: `signInWithUsername` / `signInWithUsernameAndCreateKey` (handle + password, resolved on the app's network; pass `{ projectId }` as app context), `forgetPassword(input, appContext?)`, `resetPassword({ newPassword, token }, appContext?)`. Password sign-in on a two-factor account throws `AuthenticationError` with code `two_factor_required`; its `details` is `{ twoFactorToken, methods }`. Finish with `completeTwoFactorSignIn({ twoFactorToken, code, method? })` (`method: 'backup_code'` for a backup code), or `completeTwoFactorSignInAndCreateKey(input, keyInput)` after a `*AndCreateKey` sign-in. Ten wrong codes lock the account's two-factor sign-in for fifteen minutes (`ACCOUNT_TEMPORARILY_LOCKED`, `RateLimitError` with `retryAfter`).

```typescript
// Sign-in on a two-factor account: catch two_factor_required, then send the code with the challenge.
try { await r.auth.signInWithUsername({ username, password }, { projectId }) } catch (e) {
  if (e.code === 'two_factor_required') await r.auth.completeTwoFactorSignIn({ twoFactorToken: e.details.twoFactorToken, code })
}
// Two-factor: session-token calls. verify/disable rotate the session; store the returned sessionToken.
const { totpURI, backupCodes, sessionToken } = await r.auth.enableTwoFactor({ password }, session.token)
const { sessionToken: live } = await r.auth.verifyTwoFactor({ code: '123456' }, sessionToken) // turns 2FA on
// No password (profiles.me().has_password === false)? Confirm with an emailed code instead.
// Enrolling such an account answers PASSWORD_REQUIRED_FOR_TWO_FACTOR unless the server enables it.
await r.auth.requestTwoFactorEmailCode(live, { projectId }) // app context brands the email; then pass { emailCode } where you would pass { password }
await r.auth.disableTwoFactor({ emailCode: '482913' }, live)
```

Two-factor methods: `enableTwoFactor`, `verifyTwoFactor`, `disableTwoFactor`, `regenerateTwoFactorBackupCodes`, `requestTwoFactorEmailCode`, `completeTwoFactorSignIn`, `completeTwoFactorSignInAndCreateKey`. Minds cutover: `legacyHandoff(legacyToken, { attemptId, refreshToken, projectId, timeoutMs })` exchanges the legacy app's session once; it throws `LegacyHandoffError` (`status` 0 when no response came, `code`, `retryAfterSeconds`), and only `legacy_token_used` / `legacy_token_invalid` mean forget the legacy session. With an `attemptId` a success carries `apiKeyDescription`; give the API key made with that session that `description`, so replays of the attempt count only that key. `legacyHandoffAndCreateKey(token, keyInput, { attemptId, refreshToken })` does both; pass the same `attemptId` on every retry. OAuth consent screens: `exchangeSessionForCookie(token)` (browser, sets the API-origin cookie so `/api/auth/mcp/authorize` continues without a second sign-in), `getOAuthClientInfo({ clientId, redirectUri?, scope? })` (public client name, redirect hosts, `redirect_uri_registered`, granted scopes).

**Mobile/React Native auth** (recommended — one call instead of three):
```typescript
const anonSdk = new Recursiv({ anonymous: true, baseUrl });

// Customer-app signup (recommended for new apps): bind the key to a project,
// not to the team org. The user becomes a project_member, not an
// organization_member, keeping app customers separate from the team workspace.
const { apiKey, user } = await anonSdk.auth.signInAndCreateKey(
  { email, password },
  { name: 'my-app', scopes: ['posts:read', 'agents:write'], projectId: 'prj_xxx', consumeSession: true },
);
// projectId is also sent on the password sign-in request so shared API hosts
// resolve the user in this customer app's network before minting the key.
// consumeSession retires the temporary session; omit it for cookie-session flows.

// Team-scoped (legacy / internal-tool flow): bind to an organization. The
// caller must be an org member or the org must allow public signup.
const { apiKey: teamKey } = await anonSdk.auth.signInAndCreateKey(
  { email, password },
  { name: 'my-app', scopes: ['posts:read'], organizationId: 'org_xxx' },
);

const sdk = new Recursiv({ apiKey, baseUrl });
```

**organizationId vs. projectId:** mutually exclusive. `projectId` is the customer-app path (creates `project_member`); `organizationId` is the team-workspace path (creates / requires `organization_member`). Customer apps should use `projectId` so app users don't appear in the team's `/settings/team`.

Available scopes: `posts:read`, `posts:write`, `users:read`, `users:write`, `communities:read`, `communities:write`, `chat:read`, `chat:write`, `projects:read`, `projects:write`, `agents:read`, `agents:write`, `organizations:read`, `organizations:write`, `notifications:read`, `notifications:write`, `tags:read`, `tags:write`, `uploads:write`, `commands:read`, `commands:write`, `settings:read`, `settings:write`, `billing:read`, `billing:write`, `wallet:read`, `wallet:write`, `memory:read`, `memory:write`, `databases:read`, `databases:write`, `storage:read`, `storage:write`, `admin` (requires platform admin role — do NOT use in normal apps)

**Scope enforcement:** Every API call checks scopes. A 403 `AuthorizationError` means your key is missing the required scope. Grant only the scopes your app needs (least privilege). The `admin` scope can only be created by platform administrators — attempting to self-grant it returns 403.

### @recursiv/sdk/next — Next.js App Router server auth

Server-only sub-path (Next 14+, both 14 and 15). Per-user-key pattern: auth flows mint a project-scoped key and store it in an httpOnly cookie; every request rebuilds an SDK bound to the caller's own key. No platform key needed at runtime.

The minted key expires when its cookie does (`cookie.maxAge`, default 30 days, capped at one year), and `signOut()` revokes it best-effort before clearing the cookie (0.7.210). Pass `signOut({ apiKey })` when the key is not in `cookies()`.

```typescript
// src/lib/recursiv.ts
import 'server-only';
import { createRecursivAuth } from '@recursiv/sdk/next';
export const auth = createRecursivAuth(); // RECURSIV_PROJECT_ID + RECURSIV_API_BASE_URL from env

// server action ('use server')
const { user } = await auth.signIn({ email, password }); // mints key + sets cookie
await auth.signOut(); // revokes the key server-side, then clears the cookie

// server component / route handler
const sdk = await auth.getSdk();      // throws AuthenticationError when signed out
const maybe = await auth.trySdk();    // null when signed out
const me = await auth.getUser();      // SessionUser | null

// route handler writing its own response (custom cookie contract)
const auth = createRecursivAuth({ cookie: { name: 'myapp_key', maxAge: 60 * 60 * 24 * 90 } });
const res = NextResponse.json({ ok: true });
await auth.verifyOtp({ email, otp }, { response: res.cookies });

// request-bound, e.g. a route handler that already holds a NextRequest
const key = auth.sessionKeyFromRequest(req);
const sdk2 = auth.sdkFromRequest(req); // Recursiv | null
```

Config: `projectId` (default env `RECURSIV_PROJECT_ID`) XOR `organizationId`; `scopes` (default `DEFAULT_USER_KEY_SCOPES` — pass your own for least privilege); `cookie: { name, maxAge, sameSite, secure, domain, httpOnly, path }`; `apiKey` (only for branded auth emails); `baseUrl`, `timeout`, `maxRetries` (set `maxRetries: 0` if duplicate OTP/checkout POSTs are worse than a retry). Auth results include `keyPrefix` for account-linking records. Never import this sub-path in client components (`server-only` enforces it). Keep it out of `middleware.ts` too (it drags the whole SDK into the edge bundle) — middleware should do a plain presence check on a shared cookie-name constant and redirect.

### r.users

```typescript
const { data: me } = await r.users.me()
const { data: user } = await r.users.get('user_xxx')
```

Methods: `me`, `get`, `followers`, `following`

### r.organizations

```typescript
const { data: org } = await r.organizations.create({ name: 'Acme', slug: 'acme' })
await r.organizations.addMember(org.id, { user_id: 'user_xxx', role: 'member' })
```

Methods: `list`, `get`, `getBySlug`, `create`, `update`, `delete`, `members`, `addMember`, `removeMember`, `invite`, `updateMemberRole`

### r.profiles

```typescript
const { data: profile } = await r.profiles.me()
await r.profiles.follow('user_xxx')
const { data: results } = await r.profiles.search({ query: 'jane' })
const { data: rows } = await r.profiles.followers('user_xxx') // each row: is_following, follows_you
await r.profiles.mute('user_xxx') // server hides their posts and reposts of them from your feeds
```

Methods: `list`, `me`, `get`, `getByUsername`, `search` (ranked by match x ln(1 + followers + min(posts, 100)) over one pool of 200, the same for every page; each row (`ProfileSearchResult`) carries `followers_count`, `posts_count`, `empty` (fold empties under "more handles") and `verified` (the accounts the operator names)), `mentions` (people + agents for an @-picker, follows first), `update`, `follow`, `unfollow`, `followers`, `following`, `followingIds` (your follow set as ids, cursor-paged), `isFollowing` (follows both ways, plus `is_blocking`/`is_muting` when the server knows), `related`, `leaderboard` (`{ sort: 'engagement' | 'followers' | 'active', limit, offset }`; engagement by default), `block`, `unblock`, `blocked`, `mute`, `unmute`, `muted`

---

## Social Primitives

### r.knowledgeSources — Admitted public evidence (unreleased)

`await r.knowledgeSources.notes({ project_id: '019d5190-f0c0-717e-a1bd-ef9c335292b9', reference_url: 'https://x.com/i/status/1234567890123456789', limit: 10 })` returns `{ data: KnowledgeSourceNote[], meta: { limit, offset: 0, has_more } }`. Use `note_id` for an exact upstream string ID or `query` for bounded indexed text search. Works with `new Recursiv({ anonymous: true })` for registered public apps. Every result carries source, upstream status (including unknown), observed/snapshot time, revision, attribution and rights. No live AI/provider call, approval write, private user data or transfer of an X judgment to another post. Requires supporting API deployment; unknown rights and unadmitted revisions are absent.

Private evaluation is separate: `const local = new Recursiv({ anonymous: true, inheritEnvironmentApiKey: false, baseUrl: 'http://127.0.0.1:8189/api/v1' }); await local.knowledgeSources.localEvaluationNotes({ project_id: '019d5190-f0c0-717e-a1bd-ef9c335292b9', query: 'orbit' })`. This requires the explicit bounded-file local harness, returns `LocalKnowledgeEvaluationResponse` with `mode: 'local_evaluation'`, `admission: { state: 'not_admitted', public_display: false }` and a source digest with null database revision number. Nonloopback bases and clients carrying keys reject before transport. Local evaluation grants no public rights and has no production REST route.

### r.chat — Messaging (REST)

```typescript
const { data: dm } = await r.chat.dm({ user_id: 'user_xxx' })
await r.chat.send({ conversation_id: dm.id, content: 'Hello!' })
const { data: group } = await r.chat.createGroup({ name: 'Team', member_ids: ['user_1', 'user_2'] })
const { data: msgs } = await r.chat.messages(dm.id, { limit: 50 })
```

Methods: `conversations`, `communityConversation`, `conversation`, `messages`, `send`, `dm`, `createGroup`, `addMembers`, `removeMember`, `updateGroup`, `deleteConversation`, `leave`, `acceptRequest`, `declineRequest`, `mute`, `unmute`, `setPushLevel`, `reactToMessage`, `editMessage`, `deleteMessage`, `markAsRead`, `unreadCount`, `attachmentUploadUrl`, `uploadAttachment`, `signAttachments`

Mute (0.7.196): `await r.chat.mute(dm.id, { until: new Date(Date.now() + 8 * 3600_000) })` (omit `until`, or `'forever'`, for until `unmute(dm.id)`) stops that conversation's pushes and chat emails for the caller only; the thread and unread count still update. Conversation rows and `conversation(id)` serve the caller's own `muted_until` (null when not muted), never anyone else's; `communityConversation()` does not serve it.

Group chat push level (0.7.196): a group's own chat (`community_id` set) pushes the caller only for a reply to one of their messages or an @mention of their handle (`push_level: 'mentions'`, the default) until they choose every message with `await r.chat.setPushLevel(conversationId, 'all')` (back with `'mentions'`); it answers `{ conversation_id, push_level }`. A mute still wins. A DM or a private group serves `push_level: null`, pushes every message, and `setPushLevel` there answers 400 `push_level_not_offered`. Conversation rows and `conversation(id)` serve the caller's own `push_level`, never anyone else's; `communityConversation()` does not, so read a group's chat level with `conversation(id)`.

Chat photos and voice notes (0.7.82): `const { ref } = await r.chat.uploadAttachment(dm.id, { blob })`, then send `ref`. With the server's private chat storage on, `ref` is `chat-attachment:<key>`: render it with `(await r.chat.signAttachments(dm.id, chatAttachmentKeysIn(message.content))).data.attachments` (URLs live about five minutes, `private, no-store`; `url: null` for a key the caller may not open). `editMessage` changes a message's words only: an edit that drops, adds or swaps a `chat-attachment:` reference gets 400 `attachment_refs_changed` (delete the message instead). Otherwise `ref` is a public URL, as before. A group's chat tied to a community always gets a public URL. Staff reviewing a member's report of a message open its private attachments with `r.reports.signAttachments(reportId)` (a live admin's own key; an AI account or agent key gets 403 `human_required`; only a report filed by a person in that chat, other than the sender and the caller, opens anything: 403 `own_report` or `reporter_not_a_recipient` otherwise).

Scroll back with `messages(id, { cursor: page.meta.next_cursor })`, not a growing `offset`. Conversations carry `can_delete` / `can_leave`; check them before offering Delete or Leave.

Private groups (0.7.59): each member has `role` (`admin` or `member`) and, in a group or a one-on-one chat, `request_status`: `accepted` from the start for the person who wrote, anyone who follows them and agents, else `pending` until that person accepts or replies (a decline reads `pending` to anyone else), so `accepted` alone does not mean they accepted anything. Only the admin (the creator, then the longest-standing person left) may `addMembers(id, { member_ids })`, `removeMember(id, userId)` and `updateGroup(id, { name })` (else 403 `not_admin`). `createGroup({ name, member_ids, encrypted: true, device_id? })` makes an end-to-end encrypted group of people in the pilot, at most 8 counting pending invitees, or throws 409 `conversation_not_eligible` with `details.reason` and creates nothing. `r.realtime.onChatMembers` / `onChatConversation` tell you when people or the name change.

Activity time (0.7.67): conversation rows, `communityConversation()` and `conversation(id)` carry `last_activity_at`, the time `conversations()` sorts by: the newest message, or, in an end-to-end encrypted (`mls_v2`) conversation, the relay's receive time of its newest encrypted message when that is later (membership and key changes and quiet events such as reactions do not move it); its creation when it has no messages. In any other conversation, deleting the newest message moves it back to the previous message (or the creation), so do not keep the later of a cached and a served value. A time only, never content: show it on a row the device cannot decrypt. Omitted by older APIs, and by `conversation(id)` to a member who declined the request.

Who can read it now: conversation rows, `communityConversation()`, `conversation(id)` and each of `messages()` carry `privacy_tier` (`PrivacyTier`), computed by the server from the current members: `standard` where an AI agent is a member, and on an agent's own message (the app, Recursiv and the AI companies that route and answer each turn can read it), `e2ee` for an `mls_v2` conversation (never on a message row), and null when no AI agent is a member now. Null is not a history: messages sent while an agent was a member went to the AI companies with its turns and read null once it leaves, so never show null as "only people saw this". `members_only`, `sealed` and `on_device` are reserved. An agent's reply written by a model through the server's provider chain carries `metadata.ai`, its `AiTurnStamp`: the model that answered and its maker, the route (`openrouter`, `direct` to the maker, or `other`, a service the stamp cannot name), the usage tier, `substituted` (a smaller model for usage limits, or a fallback), whether saved memory, other chats or activity went with the turn, and each tool called by name with its `export_boundary` (no arguments or addresses; an unclassified tool reads `public_network`). Some agent messages carry no stamp (server-written notices, limit replies, messages an agent sends outside a model turn): read a missing stamp as unknown. Label a reply from the stamp, never from the model the member picked. Omitted by older APIs.

### r.e2ee — End-to-end encryption transport (flag-gated)

Relays opaque MLS envelopes, public device credentials and one-time key packages for the shared E2EE core; the server never sees keys or plaintext. Requires the `e2eeV2` network feature flag (otherwise `feature_disabled`) and a key acting as the account owner (agent-scoped keys get `agent_key_not_allowed`). The realm is the network id. Only a direct conversation between two people with an accepted request can start encryption (`conversation_not_eligible` otherwise), and every later append to it is checked the same way again (both people still accepted, still in the pilot, still only the two of them), so a client need not read the policy before each send; a resend of an event already stored still returns `duplicate: true`, even once a Welcome's target device is gone; blocks apply (`blocked`), to resends too; commits must send `expected_commit_seq`.

Ask first instead of trying a call: `r.e2ee.status()` returns `{ enabled: true }` or `{ enabled: false, reason: 'network_off' | 'not_allowlisted' }` for the calling account only. `enabled: false` means frozen: already-encrypted conversations stay readable, nothing new can be sent or enrolled.

```ts
const { data: access } = await r.e2ee.status(); // offer encryption only when access.enabled
const { data: device } = await r.e2ee.registerDevice({ device_name: 'phone-1', realm: networkId, signing_key, credential });
await r.e2ee.publishKeyPackages({ device_id: device.id, packages: [keyPackageBase64] }); // → { published, available }
const { data: stock } = await r.e2ee.keyPackageStatus({ device_id: device.id }); // { available, expiringSoon }; refill when low
const { data: claimed } = await r.e2ee.claimKeyPackage({ device_id: device.id, target_device_id: peerDeviceId });
await r.e2ee.appendEvent(conversationId, { device_id: device.id, envelope }); // idempotent per event_id
await r.e2ee.appendEvent(conversationId, { device_id: device.id, envelope: reaction, silent: true }); // no push, no move up the chat list; every member's doorbell still rings
const { data: page } = await r.e2ee.events(conversationId, { device_id: device.id, after_seq: 0 });
await r.e2ee.acknowledge(conversationId, { device_id: device.id, seq: page.headSeq });
// The other person has no device yet: ask them (0.7.70). The relay writes it into the chat as a message with metadata { kind: 'e2ee_start_request', v: 1 }; their start answers it.
await r.e2ee.requestStart(conversationId); // → { message_id, requested_at, created }; cancelStartRequest(conversationId) withdraws it
// The live requests, however far back: (await r.chat.conversation(conversationId)).data.encryption_requests → [{ sender_id, message_id, requested_at }]
// Doorbell after every append: { conversationId, seq, event? }. `event` (a small application message, as events() returns it) comes only to a socket of the owner's session or an owner key, never an agent-scoped key.
// The policy is required: policyForConversationType(conversation.type) from @recursiv/e2ee ('direct' or 'group').
r.realtime.onE2eeEvent(({ conversationId, event }) => (event ? controller.applyPushed(conversationId, event, policy) : controller.sync(conversationId, undefined, policy)));
```

Link a new device by scanning (0.7.57; `status()` reports `links: true` when the relay can). The new device N shows the link id in a QR code; an approved device A of the same account scans it. The relay is a short-lived mailbox (180 s, 120 s more once scanned; one open link per sign-in, at most 3 per account; 10 creates per sign-in and 20 per account an hour, refused with 409 `link_limit`, never 429). `approval` and `tag` go only to the sign-in that created the link. Reserved labels get 400 `invalid_label`; a 503 `storage_unavailable` is temporary, so keep polling until `expiresAt`. Own devices carry `createdAt` and `lastSeenAt`.

```ts
const { data: link } = await r.e2ee.createLink({ device_name, signing_key, label: 'Pixel 9' }); // on N; count down with expiresAt - now
await r.e2ee.scannedLink(link.id, { device_id: a.id });                                          // on A, after the scan
await r.e2ee.approveLink(link.id, { device_id: a.id, approval, tag });                           // retry-safe
const { data: mine } = await r.e2ee.link(link.id);                                               // N polls, or on r.realtime.onE2eeLink(({ linkId, state }) => ...)
await r.e2ee.completeLink(link.id, { device_id: n.id });                                         // N, once registered
await r.e2ee.linkProgress(link.id, { device_id: a.id, done: 3, total: 7, joined: 3, not_held: 0, failed: 0, last_conversation_id });
await r.e2ee.cancelLink(link.id, { device_id: a.id, reason: 'declined' });                       // "I didn't start this"
const { data: ids, next } = await r.e2ee.conversations({ limit: 200 });                          // encrypted chat ids, keyset-paged
r.realtime.onE2eeDevices(({ deviceId, reason }) => {}); // 'packages': it can be claimed now; 'revoked'
```

Revoking a device other active devices were approved through, or the account's root (main) device, throws a 409 `ConflictError` with code `has_dependents` and `details: { dependents: string[], root: boolean }`; nothing changes (0.7.58). `revokeDevice(id, { cascade: true })` revokes it and every device chained through it, answering `revoked` (ids). Once the root is revoked the account can link a new device only after it resets encrypted chat.

Reset encrypted chat (D2; only where `status()` reports `accountReset: true`): for someone who lost every device, or who starts over on this one. The code is eight digits, emailed to the account's address; the relay warns the owner. One call then revokes every device, signs the account out of every other session, API key and MCP-connected AI client on the network (closing their sockets), and registers this device as the new main device; contacts see that the security code changed. With `accountReset` on, `revokeDevice` on the main device answers 409 `reset_required`, and so does `createLink` when the main device is gone with nothing left to approve. Errors: 403 `confirmation_failed` (wrong, expired or spent code; nothing changed), 409 `code_limit` (`details.retryAfterSeconds`, never 429), 400 `no_email_on_file`, 503 `email_delivery_unavailable`, 409 `conflict` (name or key used before), 403 `forbidden` (an account that is not this network's own, such as a platform owner's; `status()` never reports `accountReset` to such an account, and its main device and links answer as with the feature off).

```ts
const { data: sent } = await r.e2ee.requestResetCode();                   // { expires_at, sent_to: 'b***@minds.com' }
const { data: reset } = await r.e2ee.resetAccount({ email_code, device_name, realm, signing_key, credential, keep_session_token });
// → { reset, resetAt, retiredRoot, revokedDeviceIds, device (the new main device), signedOut: { sessions, keys, connectedApps } }; a retry after a lost answer gets the same result
```

A contact's reset (D2 R2, 0.7.83; where `accountReset` is on). Each member of an encrypted conversation the account shares (a direct chat, or a group both accepted) gets `e2ee:peer` `{ userId, reason: 'root_changed', conversationId }`, once per shared conversation, and each direct-chat contact one push (at most one a day per person who reset; it does not name them): "A contact reset encrypted chat. Open Minds to keep chatting." `peerChanges({ since })` lists the accounts whose main device a reset replaced since then (default and floor 7 days, oldest first, at most 200; a relay without it answers 404: treat it as none). An engine that can accept a contact's new main device sends `trust_change: true` with its messages; in a direct chat with someone who reset, such a message gets 409 `peer_not_joined` (`details.userId`) until a device of this account added their new device, and 409 `stale_epoch` under a key generation before the chat's last key update. Messages without it are accepted as before.

```ts
r.realtime.onE2eePeer(({ userId, conversationId }) => {});              // look at userId's devices again
const { data: changes } = await r.e2ee.peerChanges({ since });          // [{ userId, at }] after time in the background
await r.e2ee.appendEvent(conversationId, { device_id, envelope, trust_change: true }); // ConflictError 'peer_not_joined' | 'stale_epoch'
```

### r.realtime — WebSocket Chat Client

Provides persistent real-time streaming and chat presence, useful for building frontends (e.g. React Native, Web).

Requires the optional peer `socket.io-client` (`npm install socket.io-client`). Nothing else in the SDK needs it; `connect()` throws a clear error if it is missing.

```typescript
// Establish WebSocket connection using short-lived session tokens
await r.realtime.connect()

// Cookie-auth apps (key held server-side): inject a token source instead.
// Called on the initial connect AND every reconnect (always a fresh token).
await r.realtime.connect({
  getToken: async () => (await fetch('/api/ws-token')).json().then((d) => d.token),
})

// Join a conversation room
r.realtime.joinConversation('conv_123')

// Send typing indicator
r.realtime.sendTyping('conv_123')

// Listen to events
const unsub = r.realtime.onMessage((msg) => {
  console.log(`New message from ${msg.sender.name}: ${msg.text}`)
})
// Cleanup listener
unsub()

// Any server event, plus `connect` (fires on every reconnect: refetch what you missed) and `disconnect`
const off = r.realtime.on('notification', (n) => refreshBadge(n))
```

Events: `onMessage`, `onMessageEdit`, `onMessageDelete`, `onMessageReaction`, `onTyping`, `onAgentThinking`, `onE2eeEvent`, `onE2eeLink`, `onE2eeDevices`, `onE2eePeer`, `on(event, fn)`

Reconnects on its own (transport drops, token expiry, refused handshakes) with jittered backoff and a fresh single-use token per attempt; listeners and joined rooms carry over, so no app-side reconnect shim is needed. It stops only on `disconnect()` or a 401/403 from the token source. `connect()` is safe to call repeatedly.

#### React / React Native specific hook

```typescript
import { useChat } from '@recursiv/sdk/react'

function Chat({ conversationId }) {
  const { isConnected, error, sendTyping, sendMessage } = useChat(r, {
    conversationId,
    onMessage: (msg) => console.log('Received:', msg.text),
  })

  return <button onClick={() => sendMessage('Hello!')}>Send</button>
}
```

### r.posts — Content feeds

Native publishing accepts `title` (max 300) and `publication_metadata: {version:1,shareTitle?,description?,thumbnailUrl?,media?:[{url,alt?,caption?}],transcript?,language?}`. `create`/`update` preflight `publicationCapabilities()` once per resource; an unsupported API refuses before any write. Limits: shareTitle160, description320, alt1500, caption2000, transcript100000, language35. Null clears a field (top-level null clears all overrides), omission preserves it; `media` replaces the descriptions list. Thumbnail must be attached media or an attached video's existing poster; media labels must name exact attachment URLs. Only protocol-null posts own overrides; source provenance is preserved. Example: `await r.posts.update(post.id, { title: 'A faithful title', publication_metadata: { version: 1, description: 'An accurate summary' } })`. Reads return `publication_metadata`; publication does not enable crawler indexing.

```typescript
const { data: post } = await r.posts.create({
  content: 'Shipped v2!',
  content_format: 'markdown',
  community_id: 'comm_xxx',
  tag_ids: ['tag_xxx'],
})
const { data: posts } = await r.posts.list({ community_id: 'comm_xxx', tag_id: 'tag_xxx', limit: 20 })
// Public native posts, newest first, without key/cookie/ranking; camelCase fields and no pagination meta.
const { data: publicPosts } = await r.posts.publicList({ projectId, limit: 50, offset: 0 })
const { data: liked } = await r.posts.liked({ limit: 20 }) // caller's upvoted posts
await r.posts.update(post.id, { content: 'Updated content' })
await r.posts.react(post.id, { type: 'fire' })
const { data: results } = await r.posts.search({ query: 'shipped', community_id: 'comm_xxx' })
```

Methods: `list`, `get`, `create`, `update`, `delete`, `search`, `replies(id, { limit, cursor })` (after `replies_next_cursor` on `get`), `react`, `unreact`, `liked`, `bookmarked`, `bookmark`, `unbookmark`

Several posts by id (0.7.77): `const found = await r.posts.getMany(ids)` reads up to `POSTS_BATCH_MAX` (25) per request (`GET /posts/batch`) and returns a `Map` keyed by id: `found.get(id)?.data` is the post as `get` serves it to the member (`viewer`, `user_reaction`, `reposted_by_viewer_id`), without its thread (no `replies`; no thread is read, so a story page's six posts come back in about the time of one), and `found.get(id)?.error` is a `NotFoundError` for one that is gone or not for this member. Each id is asked once. The call throws when the request fails as a whole, as on an API without the route (404): read those ids one by one with `get`.

Legacy Minds post guids to post ids (0.7.206): `const { data } = await r.posts.resolveLegacy(guids)` posts up to `POSTS_LEGACY_RESOLVE_MAX` (200) digit-only guids per request (`POST /posts/legacy/resolve`) and returns `[{ guid, id }]` in the order asked, only for posts the signed-in member may open (as `get` serves them, on their network). A guid with no post or one not for this member is absent, never an error. 60 calls per member per hour (429). Signed out, public posts only: `publicPosts.resolveLegacy` on @minds/sdk.

Feed definitions (types only; no route serves one yet): `FeedDefinition` is `{ v: 1, sources, ranking: { mode, range? }, filters?, exclude? }`, with 1-`FEED_SOURCES_MAX` (50) sources read as one union (`FEED_SOURCE_KINDS`; `FEED_SOURCE_KEY[kind]` names each kind's one field, e.g. `{ kind: 'tag', slug: 'rust' }`, `{ kind: 'account', ref: 'did:plc:…' }`). `filters.politics` stores only `'hide'`; viewer settings, blocks, mutes and compass Mix/Sides never go in a definition. Built-in feeds: `builtinCategoryFeedRef('science')` → `'builtin:category:science'`, plus `'builtin:all'` and `'builtin:for_you'`.

`search` ranks relevance x recency x engagement (recency falls as a power of age: this month outranks years ago) through the promotion safety floor; `sort: 'new'` lists newest first; `media: 'video'` (0.7.69) keeps only posts with a video that plays (relevance only), in the page shape Watch reads, so a player can play a query. Page with `meta.next_cursor` as `cursor`: later relevance pages are slices of the ranking the first page kept for ten minutes (nothing skipped or repeated while it lives; after that, the page continues past the last post's score boundary), newest-first pages continue by (created_at, id). A cursor is bound to its search and sort: another search's, or the other sort's, is 400 `invalid_cursor`. The first relevance page carries `latest` (up to three of the newest matches not on the page, one per author, for a Latest strip); the last page carries `fall_over.lanes` (`new`, `open_network`, `tag`): draw a way on, not a wall.

### r.bookmarks — Synced saves (per member, per app)

```typescript
await r.bookmarks.save({ kind: 'post', post_id: post.id })             // idempotent; a bare repost saves its original (see data.post_id)
await r.bookmarks.save({ kind: 'social', protocol: 'bluesky', native_id: 'at://did:plc:.../app.bsky.feed.post/...',
  author: { display_name: 'Alice', handle: 'alice.bsky.social' }, snippet: 'hello' })
await r.bookmarks.save({ kind: 'article', url: 'https://news.example/a', title: 'Headline', outlet: 'Example' })
const { data: saved, meta } = await r.bookmarks.posts({ limit: 20 })   // = r.posts.bookmarked(); page on meta.next_cursor
const { data: items } = await r.bookmarks.list({ kind: 'social' })     // open-network posts and articles, as saved snapshots
const { data: keys } = await r.bookmarks.keys(undefined, { retry: false }) // every key, for a saved-state cache
const { data: merged } = await r.bookmarks.merge(deviceItems)          // ≤200 per call, each with its own saved_at; idempotent
await r.bookmarks.unsave(key)                                          // or unsave({ postId }); r.posts.bookmark/unbookmark too
```

Newest saved first. Pages can be short while they skip posts the member can no longer read: page on `meta.next_cursor`, not length. Needs the member's own app key (else 403 `project_binding_required`). 503 `bookmarks_unavailable` means the server has no synced bookmarks yet: keep saves on the device (pass `{ retry: false }` to the probe so the 503 is not retried).

Collections (0.7.68) are private, named labels on saves: filing saves first, one thing can sit in several collections, unsaving takes it out of every one, and deleting a collection leaves what it held saved. Use them only when `(await r.network.getConfig()).data.capabilities.bookmark_collections` is true; still treat 503 `lists_unavailable` as off.

```typescript
const { data: lists, meta: caps } = await r.bookmarks.collections.list()   // oldest first; caps.max_collections (25), caps.max_items (1000)
const { data: list } = await r.bookmarks.collections.create({ title: 'Read later' }, { idempotencyKey })  // private; slug from the title
await r.bookmarks.collections.add(list.id, { postId: post.id })           // saves it first if needed; idempotent
await r.bookmarks.collections.add(list.id, socialOrArticleItem)           // one request: saved and filed together, or neither
await r.bookmarks.collections.removeItem(list.id, key)                    // it stays saved
const { data: posts } = await r.bookmarks.collections.posts(list.id)      // = r.bookmarks.posts({ collection: list.id })
const { data: items } = await r.bookmarks.collections.items(list.id)      // open-network posts and articles in it
const { collections: filedIn } = await r.bookmarks.keys()                 // { [key]: [collection ids] }; absent while collections are off
await r.bookmarks.collections.update(list.id, { title: 'Later' })
await r.bookmarks.collections.remove(list.id)
```

404 `collection_not_found` for a collection that is not the member's; 409 `collection_limit`, `collection_item_limit`, `slug_taken`, `bookmark_limit` (filing that would save past the saves cap), and `not_saved` (a key that is not saved, sent without its item); 400 `not_supported_yet` for a kind other than posts or a visibility other than private.

### r.curator.forYouWorld — For You as the world by the member's interests

```typescript
const head = r.curator.forYouWorld({ part: 'stories', session })                // member's own app key; read the two halves at once
const page = await r.curator.forYouWorld({ part: 'items', session, snapshot })   // items + blocks; snapshot = a previous meta.snapshot
// stories: { ref, id, source: today|radar|viral, target, label, kind, breaking, general, theme, counts, reasons, ... }
// items: { ref, kind, target, position, block: 'top' | 'below', media, topic, reasons, explain, card }  // card: an open-network post's (no URL), null for Minds
// blocks: [{ id, type: stories|lead_video|clips|posts|people|groups|topics|viral|categories, refs, deferred?, entities?, categories?, viral? }]
```

404 while the app's operator has it off; always private (`Cache-Control: private, no-store`). A story's or item's `target` is in the app (a radar story by cluster id, a Today story as `today_story`, a post id, `/social/post/<protocol>/<id>`), never a URL out. Send `block: 'top'` with a visible view of a story in the rail or one of the first 10 items: three such views without an open rest it for a week. `meta.partial` names a source that missed its deadline; `meta.interests` are category ids for chips, never for a URL; `meta.foryou_cursor` continues on `r.curator.forYou({ cursor })`.

### r.feeds — The top of a feed (member and visitor)

```typescript
const top = await r.feeds.top({ ref: 'builtin:all', limit: 10, session })   // member's own app key; category:<id>, following, watch, story:<id>
// top.items: { ref, kind, target, position, block: 'top' | 'below', explain }; top.networks: { bluesky, activitypub, nostr } lanes with a card each
// top.lead: the story to open with; every target is in the app (post id, /social/post/<protocol>/<id>, story id), never a URL out
const { data: next } = await r.feeds.stories({ after: storyId })             // the story tail, same ranker as the lead
const page = await r.feeds.publicTop({ projectId, ref: 'all' })              // a visitor's top: safe items only, keyless, edge-cacheable
const live = await r.feeds.firehose({ session, limit: 20, network: 'all' })   // 0.7.195: the member's live stream, never repeated in a session
// live.items: FeedTopItem + { network (farcaster too since 0.7.208), state: 'breaking' | 'viral' | null, publishedAt, chosenAt, card? }; live.retract: refs to remove
// reveal one at a time; read again no sooner than live.meta.refillAfterMs (404 while off; 429 and 503 carry Retry-After)
const feed = r.discovery.createFeed({ networks, top: { ref: 'builtin:all', session }, seen: seenRefs })
```

Each answers 404 while the app's operator has it off; `feeds.top` is private to the member and 503 `feed_top_unavailable` carries Retry-After. With a visible view of a top item, send `block: 'top'` and its position. In a feed session the top's read starts with page 0's reads and the top holds the page at most 1.5 s from its start, the by-id reads of its posts included; off, failed or late, the session is unchanged, and the radar's story reads its posts as soon as the radar answers either way. Page 0 then opens with the top's lead story and items (each item carries `top: { ref, position, block }`), its lanes replace the networks' first reads, and no hot page repeats a top item. `seen` (Minds ids and `<protocol>/<nativeId>` refs) leaves seen posts out of the hot pages, walking on past a page left under five posts (up to three more). `seenClusters` (`Map<id, { n, clicked }>`) and a visitor's `bucket` rotate the story when the top names none (`pickRadarCluster`).

### r.alive — The alive tick (member, 0.7.193)

```typescript
// One request per tick carries every open screen's interests; each part is answered only when asked for.
const tick = await r.alive.tick({ followingSince: newestRow.created_at, posts: idsOnScreen, thread: { id: openPostId, since: newestReplyAt } })
if (tick.following?.fresh) await feed.loadNew()        // the rows wait behind the new-posts pill; nothing moves
for (const [id, n] of Object.entries(tick.counts ?? {})) updateCounts(id, n)   // score, upvote_count, reply_count, reposts_count
if (tick.thread?.newReplies) showNewReplies(tick.thread.newReplies)            // "3 new replies", revealed on a tap
setTimeout(next, tick.nextAfterMs)                     // the server's pace (30 s by default, 120 s under load)
```

The member's own key of the app, `users:read`. Off until the operator sets `ALIVE_TICK_ENABLED`: the tick throws `NotFoundError` (code `alive_disabled`) and the app stops ticking. `following.fresh` is true only for a top-level Minds post after `followingSince` by someone the member follows that they may be served (blocks either way, mutes, tier 1, moderation, safety setting); `counts` holds only posts the member may be served (a repost, quote or reply in view is left out: keep the number you have); `thread.newReplies` never counts the member's own replies, and is at most 100. At most 30 `posts` (400 `too_many_posts`), 4 ticks a minute per member (`RateLimitError`). Asked once (`retry: false`): the next tick is the retry. Tick only while the page is visible.

### r.search

```typescript
// One query, answered as sections. Each has its own time budget; a slow one is listed in `omitted`.
const { data: answer } = await r.search.query({ q: 'apple', limit: 6 })
for (const section of answer.order) render(section, answer.sections[section])
// top_posts, latest_posts, open_network, people, groups, topics, stories, related, trending, media
// What the web has for the words, alone, so it paints beside the rest (0.7.123):
const { data: web } = await r.search.query({ q: 'hockey', sections: ['media'], own_images: shownPictures })
```

`media` (0.7.123): videos (YouTube ids as `embed`, PeerTube embed pages), news articles (0.7.133: also today's articles about the words from the server's news lanes, `source: 'eventregistry'`, `providers.news_index`; show the headline, `description` excerpt, `publisher`, date, `thumbnail` and link only), pictures, sound and one `about` card (Wikipedia), from Brave Search, Wikipedia, PeerTube and Openverse with strict safe search. It answers only when `sections` names it (the default sections leave it out: each answer may spend a paid web search). Every picture passes the same vision check a post's picture does: a visitor sees only pictures judged safe, and a member who turned Show NSFW on gets a suggestive one marked `sensitive` (blur it). Every `thumbnail` is on the API's signed media proxy; play a YouTube embed through youtube-nocookie.com by its player's rules and show each `attribution`. `own_images` (how many pictures the page already shows) lets the server ask for the web's pictures only when fewer than six. Only the networks the server offers it to get it (others: `omitted` `unavailable`); `providers` says what each source did (`timeout`: ask again shortly). Visitors read it as `publicDiscovery.search` `tab: 'media'` (`PublicSearchPage.media`). A PeerTube item the server could read off its own instance carries the same video as `post` (0.7.155), a native Fediverse `SocialPost` (`software: 'peertube'`) that plays in place from its channel: show it instead of opening `url`. A `source: 'youtube'` video (0.7.181) is one the YouTube Data API found for the words, asked only when the web's own videos about them are thin or the words name sport or music, within the server's daily YouTube quota (`providers.youtube`: `skipped`, `budget` past the quota, `unconfigured` without a key): it always carries YouTube's player as `embed`, so play it in place (no autoplay with sound, nothing drawn over the player, YouTube named as the source) rather than opening `url`.

`video_lead` (0.7.173): every clip the answer holds (Top's and Latest's Minds clips, the open networks', the media section's videos) in the order to lead and play it, each `{ section, index, ref, source, on_subject, published_at }`: the most about the words first (`on_subject` `on`, `loose`, `off`), then the freshest, a Minds member's clip winning a tie; the `off` tail (the popular clips, about none of the words) keeps the answer's own order. Lead with `video_lead[0]`; a visitor's page (`publicDiscovery.search`) carries it too, and its `videos` tab's `items` already come in that order. Absent with no clip, from older servers, or when the operator turned it off.

`trending` joins when the answer is thin or old, so a search never dead-ends. A thin answer steps down the search ladder (0.7.79): the word a typo meant, the known words with the rest dropped ("wiggly memes" searches "memes"), what is popular in the category the words are about, then on the app. Every item says how in `via` (`SearchVia`) and `answer.ladder` (`SearchLadder`) says what happened: label it honestly ("No exact matches for X", "Did you mean Y?", "Popular in Comedy right now"); `ladder.unavailable` names sections the key cannot read. Visitors read the same ladder keyless through tRPC `publicDiscovery.search` (`PublicSearchPage`). A visitor's posts tabs may carry `picture` (`SearchPicture`, 0.7.162): `kind`, `textHeavy`, `tileQuality` (0-3) and an optional `focal` point, layout hints from a background picture read, absent until judged: show a `textHeavy` picture whole, crop others at `focal`, never treat it as a safety signal. On the `deep` stage `picture.showsQuery` (0.7.190) says whether the picture itself shows the query (make a big tile where it is `true`); it is absent unless the operator turned on `SEARCH_PICTURE_SUBJECT`, and until judged. `top_posts` is floored as `r.posts.search`'s relevance page is; `people` rows carry `followers_count`, `posts_count`, `empty` and `verified` (see `r.profiles.search`); `groups` rows carry `description` (one line) and `last_active_at`, to tell groups of one name apart. Page further with `r.posts.search`. Needs `posts:read`; `people` needs `users:read`, `groups` `communities:read`; `open_network` and `stories` need `users:read` plus the caller's own app key on its network, `trending` that app key. What the key cannot have is in `omitted` (`scope` / `unavailable`).

Synced search history (0.7.199; where `capabilities.search_history` is true): `r.search.history.list({ retry: false })` → `{ keep, text: [{ id, words, last_at, count }], entities: [{ id, kind: 'person' | 'group' | 'category', entity_id, name, handle?, image, last_at, count }] }`, newest first, at most 50 searches and 20 entities, each entity as it is now (blocked, muted, banned, deleted and tier-1 ones left out). `add({ kind: 'text', words })` or `add({ kind: 'group', id })` after a search or an open; `status: 'refused'` means the search keeps none of those words (drop them on the device too). `remove(id)`, `clear()`. At sign-in, `merge(deviceItems)` once (≤ `SEARCH_HISTORY_MERGE_MAX_ITEMS` 70, each with its own `last_at` and `count`; newest wins; an item last used over 365 days ago is `expired` and not stored; answers the merged `history`), then the device copy is only the instant paint. Member's own app key, `users:read`/`users:write`. 503 `search_history_unavailable`: keep it on the device. `keep: false` (the member set `settings.updateContent({ keep_search_history: false })`, which also deletes it): show none; writes are 409 `search_history_off`.

### r.curator — World Today and its story pages

```typescript
const { data: edition } = await r.curator.today()          // keyless works: new Recursiv({ anonymous: true, inheritEnvironmentApiKey: false })
const story = edition?.stories.find(s => s.discussion)     // story_key + discussion only when the server serves them (0.7.69)
const { data: page } = await r.curator.storyPosts({ storyKey: story!.story_key!, network: 'bluesky', sort: 'latest' })
const more = await r.curator.storyPosts({ storyKey: page.story_key, network: 'bluesky', sort: 'latest', cursor: page.cursor! })
for await (const p of r.curator.storyPostPages({ storyKey: page.story_key }, { reader: 'member' })) render(p.items)
```

`discussion` = `{ total, people, by_network: { minds, bluesky, activitypub, nostr }, pool, capped, built_at, previews }` (≤2 network previews); absent means show the story as before. `storyPosts` is the visitor view (keyless, cached a minute); `memberStoryPosts` is the member's own view (their blocks, mutes and hidden posts removed; `users:read` + `posts:read`). Items narrow on `kind` (`'minds'` → `Post`, `'social'` → `SocialPost`); `text_only` = words only. A removed post counts in `withheld` and is never replaced, so items + `withheld` over every page = the page's `matched` (`discussion.total` for `network: 'all'`, `discussion.by_network[network]` for one network; `discussion` always counts the whole pool). `status: 'expired'` = the cursor's build is gone: restart from page one. 404 while the server does not serve story volume; a non-UUID key throws `ValidationError` before any request.

### r.communities

```typescript
const { data: c } = await r.communities.create({ name: 'Denver Devs', slug: 'denver-devs', privacy: 'public' })
await r.communities.join(c.id)
const { data: found } = await r.communities.search('denver', { limit: 10 })   // name matches first, then size; no 1-member group unless named exactly or yours
const { data: mine } = await r.communities.search('book', { member: true })   // only my groups
const { data: people } = await r.communities.members(c.id, { q: 'ada' })      // name or username
```

Methods: `list` (`q`, `member`, `sort`), `search`, `get`, `related`, `members` (`q`), `create`, `join`, `leave`, `requests` (`q`), moderation (`approveMember`, `banMember`, …), `createInvite`

### r.media — Private creative jobs (unreleased)

`capabilities()` reads the reviewed image, sound and video catalog. An operator must first deploy the additive schema,
configure a distinct private R2 bucket, allowlist models and set a positive project daily spending ceiling. Disabled is
an ordinary capability result. Use your own member app key; agent, organization and acting-as keys are refused.

```typescript
const { data: catalog } = await r.media.capabilities()
const model = catalog.models.find(m => m.kind === 'image')
if (catalog.enabled && model && catalog.billing.mode === 'member') {
  const intent = { kind: 'image' as const, modelId: model.id, prompt: 'A lighthouse at dawn',
    contextType: 'draft' as const, contextId: draftId, idempotencyKey: crypto.randomUUID() }
  const { idempotencyKey, ...quoteInput } = intent
  const { data: price } = await r.media.quote(quoteInput)
  // Show price.memberChargeMicrocents and fundingSummary; continue only on explicit member approval.
  const { data: job } = await r.media.createJob({ ...intent, quoteId: price.id }) // preserve intent after a lost response
  const { data: current } = await r.media.getJob(job.id)
}
```

`billing.mode` must be `member` for this quoted flow; only explicit `pilot` permits unquoted generation. Missing/disabled modes refuse new work. Quote renewal never changes the original idempotency key. `appSubscriptions.aiFunding()` reads the member balance; `setAiPayg({ enabled: true, monthlyCapMicrocents: '100000000' })` opts into a $1 monthly cap only after member consent and server payment-method verification. Paid usage defaults off; read settings again after an uncertain save. Billing rollout and reviewed allowances are separate from publishing the SDK.
`listJobs({contextType,contextId})` recovers private jobs after reload. After a lost create, `findJobByIntent(savedKey)` reads the exact job without price/admission or a provider request; null never clears the key, while 410 `job_deleted` is a definite owned tombstone. `cancelJob(id)` can return `cancel_requested`:
running work may cost money. `submission_uncertain` must never trigger a new paid intent automatically. Estimates and
ceilings are string microcents (100,000,000 = $1), not provider invoices or user charges. `getJobAsset(id)` returns a
short-lived private original only after completion; never save its URL. Attach it only after the user accepts it and
reuse `uploads.uploadMedia` for the delivery copy. `deleteJob(id)` deletes the private draft. Ordinary creative APIs
must never be used as a fallback for Sealed/E2EE chat.

Sealed pricing is separate from ordinary creative APIs: read `sealed.config().billing` (`legacy` or `member`). In member mode show its fixed rates, obtain explicit account-bound acceptance, then pass that exact `pricingVersion` to `sealed.send`. Config reads never imply acceptance; missing/stale consent refuses before forwarding. Checks are included. This header reaches only the gateway; never add it or financial metadata to the encrypted message. Ship the explicit-mode backend, publish/adopt the SDK, then separately review billing activation.

### r.uploads — Post and chat media

```typescript
// Browser/File/Blob callers
const publicUrl = await r.uploads.uploadMedia({
  blob: imageFile,
  contentType: imageFile.type,
})

// React Native / Expo local URI callers
const publicUrl = await r.uploads.uploadMedia({
  uri: pickerAsset.uri,
  contentType: pickerAsset.mimeType ?? 'image/jpeg',
})
```

`uploadMedia` owns the source read, signed-URL request, byte `PUT`, matching
`Content-Type`, non-2xx checks, and public-URL fallback. It throws on every
failure path; catch once at the UI boundary and tell the user. Do not repeat
the presign/PUT sequence in application code.

Scan clearance (0.7.210, supporting API required): when `getMediaUploadUrl` returns `scan_required`,
`uploadMedia` polls after PUT (at most 30 status reads, 30 seconds) and returns only after `cleared`.
Held/failed scans throw `media_scan_refused`; the deadline throws `media_scan_pending`; HTTP errors propagate without retry.
A timeout does not cancel the server job or revoke the upload. Observe the same retained key; do not automatically mint another upload.
Source-only, not published in 0.7.210: require `r.uploads.supportsMediaRequestScope === true` before relying on
optional `uploadMedia({ ..., requestScope })`, typed `<T>(request: () => Promise<T>) => Promise<T>`.
Invoke the callback synchronously once and propagate its result without retries; each SDK API call, including
later scan polls and multipart operations, re-enters it. Source reads/signed PUTs still use `fetchImpl`.
In-flight abort requires an existing scope-aware transport; omitting the hook preserves existing behavior.
The current server pilot is synthetic staging only: allowlisted public single-frame PNGs, dimensions ≤512 each and ≤4 MiB.
It establishes neither production hash coverage nor automatic report filing. Both reads require `uploads:write`:
```typescript
const { data: scan } = await r.uploads.getMediaScanStatus(uploadKey) // key retained from getMediaUploadUrl; same uploader/network/project
const { data: holds } = await r.uploads.listMediaScanHolds(projectId) // live admin on the configured staging project; metadata only
```

Long audio and video (podcast episodes, 0.7.207): images and PDFs stay at 50 MB; audio and video may be
up to the server's ceiling (2 GiB by default). `uploadMedia` sends audio/video of 32 MiB or more
(`multipartThreshold`) in parts straight to storage, three at a time, retrying each part, re-signing
part URLs as they age, and falling back to one PUT on an older API; pass `onProgress(done, total)` for a
progress bar. Manual flow: `startMediaMultipartUpload({ content_type, content_length })` → PUT each
`parts[i].url` with exactly `content_length` bytes (`signMediaMultipartParts(grant, numbers)` for the
rest) → `completeMediaMultipartUpload(grant, [{ part_number, etag }])`, or `abortMediaMultipartUpload(grant)`.
Errors: 413 `too_large`, 400 `invalid_content_type` / `invalid_part` / `size_mismatch` / `type_mismatch`,
403 `invalid_grant` / `community_post_forbidden`, 501 `multipart_unavailable` (use the single PUT),
503 `protected_media_unavailable`, 429 `upload_daily_limit`.

Members-only files (0.7.207): pass the post's group, `uploadMedia({ blob, communityId })` (or `community_id` on
`getMediaUploadUrl` and `startMediaMultipartUpload`). A members-only group's file, and on a members network every
post file, goes to the private bucket and resolves to an `r2-private://` reference (`protected: true`): attach it to
the post as it is; readers who may see it get a short-lived signed URL in the post's media.

Video: check `const { data } = await r.video.entitlement()` before offering the
picker (`data.allowed`, `data.reason` 'tier' | 'quota', `data.remainingSeconds`),
then `r.video.createUpload()`, which runs the same check. Upload in chunks
(tus `chunkSize`) and keep the result for the attached file: a retry resumes the
same video. The TUS signature lasts an hour; past it, call
`r.video.renewUpload(playbackId, { grant: result.resumeGrant })` (0.7.63) for fresh
credentials for the same video. 404 (not yours, expired grant, older API) or 409
`upload_finished` means start a new upload instead. 503 means the video provider
could not answer: keep the partial upload and ask again later (`Retry-After`).

### r.chat — Messaging

```typescript
const { data: dm } = await r.chat.dm({ user_id: 'user_xxx' })
await r.chat.send({ conversation_id: dm.id, content: 'Hello!' })
const { data: group } = await r.chat.createGroup({ name: 'Team', member_ids: ['user_1', 'user_2'] })
const { data: msgs } = await r.chat.messages(dm.id, { limit: 50 })
```

Methods: `conversations`, `communityConversation`, `conversation`, `messages`, `send`, `dm`, `createGroup`, `addMembers`, `removeMember`, `updateGroup`, `deleteConversation`, `leave`, `acceptRequest`, `declineRequest`, `mute`, `unmute`, `setPushLevel`, `reactToMessage`, `editMessage`, `deleteMessage`, `markAsRead`, `unreadCount`

Scroll back with `messages(id, { cursor: page.meta.next_cursor })`, not a growing `offset`. Conversations carry `can_delete` / `can_leave`; check them before offering Delete or Leave.

Private groups (0.7.59): each member has `role` (`admin` or `member`) and, in a group or a one-on-one chat, `request_status`: `accepted` from the start for the person who wrote, anyone who follows them and agents, else `pending` until that person accepts or replies (a decline reads `pending` to anyone else), so `accepted` alone does not mean they accepted anything. Only the admin (the creator, then the longest-standing person left) may `addMembers(id, { member_ids })`, `removeMember(id, userId)` and `updateGroup(id, { name })` (else 403 `not_admin`). `createGroup({ name, member_ids, encrypted: true, device_id? })` makes an end-to-end encrypted group of people in the pilot, at most 8 counting pending invitees, or throws 409 `conversation_not_eligible` with `details.reason` and creates nothing. `r.realtime.onChatMembers` / `onChatConversation` tell you when people or the name change.

Activity time (0.7.67): conversation rows, `communityConversation()` and `conversation(id)` carry `last_activity_at`, the time `conversations()` sorts by: the newest message, or, in an end-to-end encrypted (`mls_v2`) conversation, the relay's receive time of its newest encrypted message when that is later (membership and key changes and quiet events such as reactions do not move it); its creation when it has no messages. In any other conversation, deleting the newest message moves it back to the previous message (or the creation), so do not keep the later of a cached and a served value. A time only, never content: show it on a row the device cannot decrypt. Omitted by older APIs, and by `conversation(id)` to a member who declined the request.

### r.tags

```typescript
const { data: tag } = await r.tags.create({ name: 'bug-report' })
const { data: tags } = await r.tags.list()
```

Methods: `list`, `get`, `create`, `delete`

---

## Platform Resources

### r.telemetry — First-party aggregate product counts

`productCounts({ counts: [{ event, count }] })` sends reviewed event totals under a human member's project-bound key with `users:write`. It is unbillable, including for a free project with zero credits; authentication, scopes and rate limits still apply. No anonymous or agent keys. Only counts are stored in a network/project/UTC-day bucket, retained at most 30 days; member IDs, session IDs, paths, URLs and extra properties are refused. Use `r.signals` separately for personal feed ranking.

`event` is `auth.otp_verified`, `community.join`, `person.follow`, `network.connect_started`, `network.connect_finished`, `social.follow_submitted`, `social.like_submitted`, `social.repost_submitted`, `social.post_submitted`, `social.reply_submitted`, `signal` or `screen.view`. Each `count` is an integer from 1 to 1000; send 1-12 entries. Do not replay an accepted batch: counts increment, and the SDK deliberately does not retry this optional write. `{ data: { accepted: false } }` means storage was unavailable, not that the member's action failed. Catch request failures without blocking the app.

```typescript
// r holds the signed-in member's app-bound key; send no route or member properties.
const result = await r.telemetry.productCounts({ counts: [{ event: 'screen.view', count: 1 }] }).catch(() => null)
const counted = result?.data.accepted === true
```

- `r.connections` (0.7.204) — The signed-in member's own outside accounts on this app, a bank through Plaid first, under their app-bound key (`connections:read` to list and call, `connections:write` to link and remove). The app's Plaid keys are project env vars (`PLAID_CLIENT_ID`, `PLAID_SECRET`, `PLAID_ENV` = `sandbox` | `production`); the member's bank token stays encrypted on the server and never reaches the app. `link({ provider: 'plaid', label?, options?: { daysRequested?, redirectUri?, androidPackageName? } })` → `{ data: { connectId, linkToken, expiration } }`; open Plaid Link with `linkToken`, then `complete({ connectId, payload: { publicToken, institutionName? } })` (asked once, never retried) → the connection. `list({ provider?, label? })` → `{ id, provider, label, status, access, accountLabel, lastUsedAt, createdAt }[]` (`status`: `active`, `needs_attention` = the member must sign in to their bank again, `revoke_failed`). `call({ connectionId, tool, args })`: `plaid.transactions` (`days` ≤ 365, `filter` `home_payments` (default; only lines that look like home work, matched on the server, optional `vendors: [{ id, name?, company? }]`) or `all`) → `{ transactions, complete, historyFrom }` (`complete` false while Plaid still loads history: ask again shortly; `historyFrom` the earliest day the bank shared), and `plaid.accounts` → masks only. `remove({ connectionId })` closes the link at Plaid and deletes the token; account deletion does the same for every link. Errors: 409 `provider_not_configured` (env vars missing), 404 `not_found` (also someone else's), 502 `provider_error` with `provider_code` (Plaid's code, never its message).

```typescript
const { data: { connectId, linkToken } } = await r.connections.link({ provider: 'plaid', label: `home:${homeId}` })
// Plaid Link onSuccess(publicToken, metadata):
const { data: bank } = await r.connections.complete({ connectId, payload: { publicToken, institutionName: metadata.institution?.name } })
const { data } = await r.connections.call<PlaidTransactionsResult<PlaidHomePayment>>({ connectionId: bank.id, tool: 'plaid.transactions', args: { days: 365 } })
```
- `r.settings` — User preferences, sessions, password changes, account deletion. `revokeOtherSessions({ keep_session_token? })` signs out every other device and keeps this key (and the proven session); `revokeAllSessions()` also revokes this key. Accounts with no password confirm `requestEmailChange({ new_email, email_code })` with a code from `requestConfirmationCode('email_change')`. With a project-bound key, `getPreferences()` includes app-scoped `content`; persist changes with `updateContent({ show_nsfw?, autoplay_video?, ai_enabled?, default_feed?, sealed_adult? })`; `content.default_feed_chosen` is true once the member set `default_feed` themselves (absent on older APIs). `privacy.age_is_adult` is true only when the member answered the age question 18 or older (false for 13-17 and for no answer; only their own preferences carry it). `content.sealed_adult` is the Sealed adult-content setting: it reads true only while it is on and the member is a known adult, and `updateContent({ sealed_adult: true })` from anyone else throws `AuthorizationError` with code `sealed_adult_needs_adult` and saves nothing in that request; `sealed_adult: false` is always accepted. Both are absent on older APIs (treat as false). `content.welcome_card_dismissed` is true once the member closed the app's pinned welcome card (`updateContent({ welcome_card_dismissed: true })`), so it stays closed on every device; absent on older APIs (keep what the device holds). Notifications (0.7.72): `getPreferences()` returns `notifications.channels`, each kind (`post_mention`, `post_reply`, `post_repost`, `post_reaction`, `follow`, `message`, and the operator kinds) with `{ inApp, push, email }`; `updateNotifications({ channels: { post_reaction: { push: false } } })` changes that kind only, while `in_app`/`push`/`email` stay master switches over every kind. Quiet hours and the pause (0.7.196): `updateNotifications({ quiet_hours: { start: '22:00', end: '07:00' }, time_zone: 'Europe/London' })` holds pushes in that daily window on the member's clock (a zone saved or sent is required, else 400 `invalid_input`); `paused_until` (ISO, at most 30 days ahead) holds every push until then; null turns either off; `getPreferences()` reads them back as `notifications.quiet_hours` and `notifications.paused_until`. The alerts that can never be turned off (security and sign-in alerts, new encrypted devices, encrypted-chat resets, credits exhausted) always go. Message previews: `updateNotifications({ message_previews: false })` hides who wrote and what from every push about a chat (each says only "New message", "Message request" or "Group invitation", names no sender or group, carries `previews: 'hidden'` in its data and rings on the `messages-private` channel); `true` shows them again, and `getPreferences()` reads it back as `notifications.message_previews` (true by default; absent on older APIs, treat as true). The master switches leave it as it is. `disableAccount({ password })` (0.7.71) deactivates the account (hidden, nothing deleted; signing back in restores it), asked once; an API that does not serve deactivation answers 404 `NotFoundError`, so keep the control hidden until yours does.
- `r.signals` (0.7.71) — The member's engagement signals for their own ranking (For You), under their app-bound key (`agents:write`): `batch(events, { keepalive?, retry? })` sends up to `SIGNAL_BATCH_MAX` (100) `{ event_type, post_id?, dwell_ms?, metadata? }` to POST /signals/batch; `record(event)` sends one to POST /signals/post (for an API before the batch route, which answers that one 404). `event_type`: `view`, `click`, `dwell`, `react_up`, `react_down`, `save`, `hide`, `share`, `mute_source`, `open_chat`, `ask_agent`, `more_like`, `unhide`. Best-effort: a signal the server cannot store answers 200 with `recorded` 0 (or false) and a `reason` (`no_project_scope`, `project_db_unavailable`, `viewing_off`, `rate_limited`, or for `record` `duplicate`). `keepalive: true` is for a flush as the page is hidden or unloads: the request is on the wire before the call returns and is asked once. Only from a public place, never a private message: a `metadata` key or placement (`surface`, `feed`, `source`, `context`, `route`...) naming a chat, DM, inbox, encrypted or Sealed conversation by any spelling (`chatList`, `dmThread`, `/messages/1`) answers 400 (`private_surface`) and nothing in that request is stored; this is read on the metadata as sent, before any key is dropped. An app names its own public places (`{ source: 'discover' }`). In the Minds app a `surface` must be one of `SignalSurface`'s names other than `other` (each a public place the server lists), a `feed`, `source`, `via` or `layoutSource` one the server lists (its feeds, Discover, Watch, stories, the pager and post cards), and any other key naming a place (`context`) is refused there too. With the member's "Use what I watch and read to personalize" off (`settings.updateContent({ personalize_from_viewing: false })`, on by default), only views and explicit choices are stored and `withheld` counts the dwell and opens left out. `clearViewingHistory()` (DELETE /signals/history) is "Clear my viewing history": the member's views, dwell, Watch time and opens in this app are deleted; their hides, "More like this", saves, shares and votes stay. Ingest contract (0.7.93): `metadata` is `SignalMetadata`; the server keeps only its keys (`surface`, `feed`, `block`, `position`, `slot`, `category`, `ref`, `watch_ms`, `duration_ms`, `completed`, `loops`, `sound_on`, `exit` (`swipe`/`leave`/`hide`/`tap`), `visible_count`, `autoplay`, `client_event_id`, `session_seq`, `via`, `source`, `presentation`) and drops the rest; a listed key of the wrong type or past its limit refuses that event (batch: `rejected` + the first ten `rejections` `{ index, reason, key }`, the rest stored; record: 400 `invalid_signal`). `batch`/`record` add a `client_event_id` to each event without one (the same id each time that object is sent), so a retry is stored once (`duplicates`). An open-network item is named by `metadata.ref` (`<protocol>/<native id>`, `cluster:<id>`, `today:<uuid>`). Watch time is held to `duration_ms` x (`loops` + 1) and to the wall clock, a card's dwell to 5 min; a watch under 1 s ending in `exit: 'swipe'` is stored as a skip. Past 600 events a minute per member the rest are `limited` (record: `reason: 'rate_limited'`).

```typescript
await r.signals.batch([{ event_type: 'view', post_id: post.id }, { event_type: 'dwell', post_id: post.id, dwell_ms: 4200 }])
addEventListener('pagehide', () => { void r.signals.batch(pending.splice(0, SIGNAL_BATCH_MAX), { keepalive: true }).catch(() => {}) })
```
- `r.privacy` (unreleased) — `capabilities()` reads GET /privacy/capabilities: `{ api_commit, facts }`, the platform privacy facts the deployed API's build marks enforced (any API key). `@recursiv/sdk/privacy` exports `PRIVACY_FACTS` (each `{ id, status, enforcement, heldBy, capability, step, says }`, generated from the platform's claims registry), `privacyFact(id)`, `isFactEnforced(id)`, `isFactLive(id, capabilities, { deviceFacts?, appFacts? })` and `liveFacts(capabilities, { deviceFacts?, appFacts? })`. Show a privacy sentence only when every fact it rests on is live: enforced in this SDK and listed by the API, and, for a fact held on the phone (`enforcement: 'device'`), also named in `deviceFacts` by the app for the native module it ships; for a fact the app holds (`heldBy: 'app'`, proven by the app's own code and tests, such as Minds' `sealed.guard_checks_every_turn`), also named in `appFacts` by the app for the build that carries that code. A device fact says what the module does, not what the app does with it (for `sealed.attest_before_send` the app chooses how long a checked router is reused).

```typescript
import { isFactLive } from '@recursiv/sdk/privacy'
const { data: capabilities } = await r.privacy.capabilities()
const showNoPushLine = isFactLive('sealed.no_push', capabilities)
const showCheckedLine = isFactLive('sealed.attest_before_send', capabilities, { deviceFacts: ['sealed.attest_before_send'] })
```
- `r.sealed` web frame routes (unreleased; server switch `config().web`, SEALED_GATEWAY_WEB) — `frameToken()` → `{ token, expiresAt, expiresIn?, origin }` (`expiresIn`: whole seconds it lives from the answer, the gateway's `expires_in`): a short-lived `sft_` credential for the Sealed frame, minted from the member's own app key (never an API key; accepted only from `origin`, only on the frame's routes, never to mint another). `me()` → `{ user_id, privacy, content, data }` (GET /sealed/me; `data` repeats the fields so a `settings.getPreferences()` reader takes it unchanged; through a frame token `content.sealed_adult` is always false). `report({ reason, details? })` → `{ id, existing, details_kept }` (filed on the member's own account; `details` at most 2000 characters). All three are sent once, never retried, and throw AuthorizationError `sealed_web_off` while web Sealed is off (`isSealedWebOff(error)`). `@recursiv/sdk/sealed` carries only `HttpClient`, `SealedResource` and the errors, for the frame's bundle. `@recursiv/sdk/sealed-frame` (browser only) is protocol v1 for both sides: the message types, builders and validators (`parseSealedFrameHello`, `parseSealedHostMessage`, `parseSealedFrameMessage`, `parseSealedWipeRequest`; null for anything unknown, mistyped, outside its enum or over 4 KB), `mountSealedFrame({ container, frameOrigin, hostKind, scheme, layout, account, mintToken, onState, onNavigate, onTokenError? })` → `{ iframe, setTheme, setLayout, setAccount, signedOut, newChat, destroy }` (sandboxed iframe, hello + MessagePort on every load, window messages never read, one shared mint cached until 60 s before expiry, at least 30 s between mints whatever the browser clock says; `signedOut()` also runs the sign-out page and reloads a frame that has not said ready), and `wipeSealedFrame({ frameOrigin, account, timeoutMs? })` → `'wiped' | 'timeout'` for every sign-out path.

```typescript
import { mountSealedFrame, wipeSealedFrame } from '@recursiv/sdk/sealed-frame'
const frame = mountSealedFrame({ container, frameOrigin: 'https://sealed.minds.com', hostKind: 'minds', scheme: 'dark', layout: 'column', account: me.id, mintToken: () => r.sealed.frameToken(), onState: setSealedState, onNavigate: go })
// sign-out: await frame.signedOut()  (no frame mounted: await wipeSealedFrame({ frameOrigin, account: me.id }))
```
- `r.billing` — Usage tracking, checkout sessions, portal sessions, metered billing
- `r.appSubscriptions` — Project-scoped consumer plans: `checkout` (409 `subscription_exists` when the member already pays; 409 `subscription_paid_elsewhere` when they pay from another Stripe customer, which no plan change reaches, so show the message; 409 `subscription_billed_by_apple` when a live legacy Apple subscription already pays for the tier, so show the message), `status` (`cancelAtPeriodEnd` is true once the plan is set to end: show its end date, not a plan switch), `createPortalSession({ return_url, flow?: 'cancel' })` (`flow: 'cancel'` opens Stripe's cancel confirmation; 409 `no_subscription` when there is no plan to cancel), `previewTierChange({ tier })`, `changeTier({ tier, proration_date? })` (in-place, prorated, never a second subscription)
- `r.boosts` — Promoted posts (micro-USD): `create`, `mine`, `balance`, `pause`, `resume`, `cancel`, `recordEvent`, `stats(campaignId)` (views, clicks, click rate, cost per 1,000, daily series); a feed page's boosts to splice in with `slots({ surface: 'all', limit: page.length, exclude: ids })` (visitors: `publicSlots({ projectId, ... })`), then `spliceBoostSlots(page, res.data)`; buy credit with `topup({ amount_cents, return_url })` then `confirmTopup(sessionId)` (credits once); pay with tokens via `topupWithTokens({ tokens, request_id })` when `balance().meta.token_topup.available`; admin `listPendingReview`, `review`, `grant`
- `r.notifications` — The notification stream: `list({ category: 'social' })` (rows carry `actor`, `reaction_type` and a `post_preview` with the viewer's `user_reaction`/`reposted_by_viewer_id` and counts; an `agent_needs_input` row carries `answered`, true once you have written in the agent's thread since it asked, when its title reads "You answered <agent>"), `category: 'mentions'` (0.7.72) for a Mentions tab (mentions and replies only; `unreadCount` and `markAllAsRead` take it too), `unreadCount({ category })` for badges (`const { data } = await r.notifications.unreadCount({ category: 'social' })`), `markAsRead(id)`, `archive(id)` to dismiss, `markAllAsRead(category)` or `markAllAsRead({ category, organization_id })`, plus push token `registerToken`/`unregisterToken`. A push's `data.notificationId` is the row to mark read on tap. DMs are not in the stream.
- `r.uploads` — Legacy media upload URLs (prefer `r.storage` for new projects)
- `r.github` — GitHub integration (getRepository, getTree, getFileContent, getCommits, createFromTemplate)
- `r.deployments` — App deployment management plus protected API/frontend reservations (`reserveRelease`, `getRelease`, `advanceRelease`, `startRelease`, `finishRelease`, `recoverRelease`); see the [shared release guide](../../docs/deploy/shared-releases.md). Use `r.projects.deploy()` for ordinary app deploys.
- `r.integrations` — External service integrations and agent tool connections. Connections: `listConnections(orgId)`, `connect()`, `confirmConnection()`. Deterministic tool execution (no agent/LLM in the loop): `executeTool({ connection_id, tool, arguments })` — run a tool yourself with explicit args + pagination and get the raw result back (e.g. `{ tool: 'GMAIL_FETCH_EMAILS', arguments: { query, max_results } }`); use for reliable batch coverage, vs `agents.chat` for autonomous behavior. Tool approvals: `listPendingExecutions(conversationId)`, `approveExecution(id)`, `rejectExecution(id)` — handles both integration tools and brain/platform tools (provision_sandbox etc.); use these to unblock a permission-mode agent waiting on tool approval
- `r.email` — Email campaigns, batch sending, and transactional email. **Pass `category: 'transactional'`** for receipts, invites, confirmations and alerts: `r.email.send({ to, subject, html, category: 'transactional' })`. Without it the send is treated as marketing and held for anyone who has not given marketing consent. A send where every recipient was held throws `EmailNotSentError` (its message carries the reason). A `status: 'partial'` result lists each recipient's `status` and `reason` in `messages`.
- `r.webhooks` — Register inbound webhook endpoints: `register()`, `list()`, `delete()`. Webhook events execute handler code in project sandbox.
- `r.jobs` — Scheduled cron jobs: `create({ name, cron, handler_code })`, `list()`, `update()`, `delete()`. Handlers execute in project sandbox on schedule.
- `r.wallet` — Wallet, MINDS tokens (`getTokenBalance`, `getTokenLedger`; wei stays a string), USD payouts (`getPayouts`, `startPayoutOnboarding`, `payoutLoginLink`). Link a wallet the member holds (0.7.104; the server answers 404 `wallet_link_disabled` until it turns linking on): `const { data: n } = await r.wallet.createLinkNonce({ address, chainId: 8453, domain: 'minds.com', uri: 'https://minds.com' })`, have the wallet sign `n.message` (a message you build yourself must carry `n.statement` word for word), then `await r.wallet.linkWallet(n.message, signature)` (plain keys and smart wallets, EIP-1271/6492; a nonce works once; 409 `wallet_linked_to_another_account`; screened like a send: 451 blocked or unknown region, 403 `wallet_address_sanctioned`, 503 `sanctions_screening_unavailable`); `listLinkedWallets()`, `unlinkWallet(address, chain?)`. The Minds-held wallet (`getMyWallet`, `getBalance`, `send`) is for agents: a member gets `configured: false` with `reason: 'custodial_wallet_off_for_members'` and `send` answers 403.
- `r.freeTier` — Free tier limits and status

```typescript
const { data: subscription } = await r.appSubscriptions.status()
if (subscription.active) {
  const { data: portal } = await r.appSubscriptions.createPortalSession({ return_url: 'https://app.example.com/billing' })
  console.log(portal.url)
}
// Switch plan in place: preview, then change with the same proration date
const { data: quote } = await r.appSubscriptions.previewTierChange({ tier: 'pro' })
await r.appSubscriptions.changeTier({ tier: 'pro', proration_date: quote.prorationDate })
```
- `r.admin` — Admin operations (user management, stats, network settings); content reports: `listReports({ status? })`, `resolveReport(id)`, `dismissReport(id)` (project-bound keys see only their app's reports); a moderator's hold on one member's native network: `holdNativeNetwork(userId, network, { retract? })` (`locked`/`moderator_hold` at once: Minds stops acting for that identity there, though it takes back no credential the member holds; `retract` also takes down what they shared) and `liftNativeNetworkHold(userId, network)` (they are off; 404 `not_held`), with an admin key bound to the member's app
- `r.moderation` — Moderation actions. Staff (admin key), 0.7.74: `const { data: actions } = await r.moderation.list({ target_type: 'user', target_id: userId })` reads one target's recorded actions (`ModerationAction`: `id`, `target_type` incl. `source_item`, `action`, `label`, `reason`, `actor_id`, `actor_type`, `source_report_id`, `expires_at`, `reversed_at`, `created_at`), newest first, at most 100, inside the caller's network and a project-bound key's app; `list()` with no target reads the network's latest. Unban = reverse each ban still in force: `for (const a of actions.filter(a => a.action === 'ban' && !a.reversed_at)) await r.moderation.reverse(a.id)`; the target's state is derived again from what is still in force. `reverse` is sent once, never retried: 404 `action_not_found` (`NotFoundError`) means already reversed or not in the caller's scope; 409 `use_judgment_review` means a reviewed label override (change it with `r.judgments.review`). An older SDK has neither method. Also `apply`, `publicLog`, `mine`, `appeal`, `resolveAppeal`, and agent grants `listAgentGrants`, `grantAgent(agentId, 'shadow' | 'act')`, `revokeAgent`.
- `r.trust` — The signed trust log (0.7.96; both reads answer 404, `NotFoundError`, until the operator turns on `TRUST_LOG_PUBLIC_READS`). `r.trust.keys()` (keyless) lists every public key that ever signed it (`key_id`, `algorithm` `ed25519`, `public_key` base64 SPKI DER, `activated_at`, `retired_at`, `compromised_at`). `r.trust.mine({ before?, limit? })` (`users:read`) reads the caller's own signed events, newest first (their follows, blocks, mutes, hides, appeals, and a moderator's own decisions: `kind`, `actor`, `subject`, `payload`, `chain`, `seq`, `key_id`, `occurred_at`, and the server's check `verified`) with the `keys` that signed the page; page with `before: pagination.next_before`. On the public log, `r.moderation.publicLog(networkId)` then carries `trust_log` on each action (`status`: `verified` | `unverified` | `unsigned` | `unavailable`, and the signed `decision` and `reversal`: `chain`, `seq`, `key_id`, `algorithm`, `occurred_at`, `verified`) and on the page (`status` and the count of each). No read carries a hash or a signature (the v1 encoding signs the moderator and the subject unsalted, so one would let anyone test guesses of who acted on what): `verified` is the server's verdict.
- `r.judgments` (0.7.71) — Jev's labels of one post. `get({ kind: 'post' | 'network_post', id })`: switch on `data.view` — `'full'` for the post's author and staff (`judgments` with answers, `safety` verdict, `viral.withheld`; staff also `reviewer_ids`, `review_note`), `'summary'` for other members (`category`, `politics` band in words with its `judgment_id`; never a probability or cell). `data.status === 'unavailable'` (returned, not thrown): hide label actions. `getPublic(projectId, { kind, id })` on an anonymous client: `view: 'category'` only. `dispute(judgmentId, { question_key: 'placement', proposed: 'cm' | … | 'not_political', note? })` (safety: `question_key: 'safety'`, author only): the author's dispute is an appeal; a repeat answers `existing: true`. Staff: `review(judgmentId, { outcome: 'uphold' } | { outcome: 'override', proposed, note?, apply_to_shared? })`, sent once (never retried): a compass override answers 202 `{ status: 'awaiting_reviewer', agreeing, needed }` until a second reviewer (or an agreeing Jev re-judge) proposes the same; a safety override to `'none'` that would free other posts throws 409 `shared_words` (`isJudgmentSharedWordsError(e)`, `e.details.shared_posts`) until resent with `apply_to_shared: true`. Budgets (60 reads/hour, 25 of one author's posts, 20 disputes/day) throw `RateLimitError` with `scope: 'action'` at once. Example: `const { data } = await r.judgments.get({ kind: 'post', id }); if (data.status === 'ok' && data.view === 'summary' && data.politics) await r.judgments.dispute(data.politics.judgment_id, { question_key: 'placement', proposed: 'not_political' })`
- `r.inviteCodes` / `r.inviteCodesAdmin` — Invite code management
- `r.organizationSettings` / `r.organizationSecurity` — Org configuration
- `r.humanAsks` — An agent's ask for a person. `await r.humanAsks.create({ ask, organization_id, subject_type: 'member', subject_id: memberId, urgent: true })` links it to what it is about (member, post, report, boost, withdrawal or chat; both subject fields or neither). Admin queue: `const { data, meta } = await r.humanAsks.queue({ organization_id, limit: 50, offset: 0 })` lists every open ask oldest first with `age_minutes` (org owners and admins; `meta.has_more`); `r.humanAsks.dismiss(id)` and `r.humanAsks.reassign(id, { asked_of_user_id: personOrNull })` take an org owner or admin or the addressee, never an agent key (404 `human_ask_not_found` otherwise). Needs `commands:read` / `commands:write`.
- `r.audit` — An organization's audit log, owners and admins only (anyone else: 404). `const { data, next_cursor } = await r.audit.list(orgId, { limit: 50, outcome: 'failure' })` pages newest first (pass `cursor: next_cursor`; null on the last page); rows carry `created_at`, `actor_user_id`, `actor_type`, `event_type`, `action`, `outcome`, `resource_type`, `resource_id`, `metadata`. Filters: `from`, `to`, `event_type`, `action`, `actor_user_id`, `outcome`. `r.audit.export(orgId, { format: 'csv' | 'jsonl', from?, to? })` returns `{ data: { filename, content_type, content, row_count, truncated } }`: at most 90 days and 10,000 rows. Needs `organizations:read`.
- `r.settings` explicit starting choices (unreleased): `const { data: current } = await r.settings.getExperience(); const { data: saved } = await r.settings.updateExperience({ version: current.version, goals: ['explore'], interests: ['technology'] });` Open `saved.discovery?.href` for existing category results; this does not change whole-feed ranking or privacy. `undoExperience({ version: saved.version })` restores the last choices and refuses a stale version. Own project-bound member key only, `settings:read` / `settings:write`; goal ids: build, create, explore, connect, private_ai, earn. Categories are canonical browse ids; no chat text is saved.
- Native follows: `nativeFollowState({ accountId, protocol, nativeId })`, `prepareNativeFollow({ clientMutationId, accountId, protocol, nativeId, action: "follow" | "unfollow" })`, `submitNativeFollow(id, { approve: true, event? })`, `nativeFollowStatus(id)`. Show the acting identity and native following/requested/unfollowed state separately from the Minds feed subscription. Nostr must sign the complete review event without dropping other contacts; stale lists require a fresh review. Keep mutation IDs and reconcile ambiguous outcomes without replay. Requires current follow scopes and API `NATIVE_SOCIAL_FOLLOW_PROJECTS` plus source controls.
- Native reposts: `nativeRepostState({ accountId, protocol, nativeId })`, `prepareNativeRepost({ clientMutationId, accountId, protocol, nativeId, action: "repost" | "unrepost" })`, `submitNativeRepost(id, { approve: true, event? })`, `nativeRepostStatus(id)`. Requires `NATIVE_SOCIAL_REPOST_PROJECTS`, account capability and explicit approval; Nostr signs the exact review (kind 6 or own kind 5). Unknown attempts only reconcile. Bluesky connections need the new repost scope; ActivityPub uses write:statuses. Native likes: `nativeLikeState({ accountId, protocol, nativeId })`, `prepareNativeLike({ clientMutationId, accountId, protocol, nativeId, action: "like" | "unlike" })`, `submitNativeLike(id, { approve: true, event? })`, and `nativeLikeStatus(id)`. Display the selected account, source and action before approval. Only Nostr supplies `event`: sign the exact public `signing.event` in the review; never transmit a private key. Preserve mutation IDs on ambiguous responses and refresh unknown results instead of resending. Read capabilities before offering actions; old reply-only connections need reconnecting for likes. Nostr results describe the connected relay, not every public relay. The app-specific `NATIVE_SOCIAL_LIKE_PROJECTS` switch and source controls must be enabled on the API.
- Delegated social accounts: `r.protocols.nativeSocialAccounts()`, `startNativeSocialConnection({ protocol, identifier })`, `finishNativeSocialConnection({ protocol, state, code?, iss?, error? })`, `disconnectNativeSocialAccount(id)`. Example: `const { data } = await r.protocols.startNativeSocialConnection({ protocol: "bluesky", identifier: "alice.bsky.social" })`; open `data.authorizationUrl`, then complete with the same signed-in app user. Never log callback codes, send passwords, or auto-retry OAuth callbacks. Shared replies (off until schema/API deployment and live verification): `prepareNativeReply({ clientMutationId, text, parent: { protocol, nativeId, readRef? }, accountIds, media?, linkedPostAccountIds?, recoverFrom?: { batchId, deliveryIds } })`, `submitNativeReply(id, { approve: true, deliveryIds })`, `nativeReplyStatus(id)`, `nativeReplyHistory({ limit?, cursor? })`, `prepareNativeReplyRemoval(id, { deliveryIds })`, `removeNativeReply(id, { approve: true, removals })`. Review account, destination, `kind`, source, exact `wireText` and every reviewed `media` item with its alt text; connection is not publication approval. `media` takes the same `NativeMediaInput[]` as `prepareNativePost` and needs the account's `publish_media` capability. `linkedPostAccountIds` explicitly selects different-network standalone posts with a source link, never matching threaded replies or a same-network denial fallback. Preserve mutation IDs, show per-destination results and reconcile uncertain attempts without reposting. To review selected unsent or definitively rejected deliveries again, use recoverFrom with a new mutation ID, the same source/accounts and freshly reviewed text; preserve that ID on uncertain preparation. Only saved recoverable destinations qualify, current gates still apply, and replacedBy disables old sends atomically. Never restart unknown, accepted or published deliveries. The new preview still needs explicit approval. Saved delegated drafts/results: `const { data: history } = await r.protocols.nativeReplyHistory({ limit: 20 })`; use its opaque cursor for the next page and `nativeReplyStatus(item.id)` for details. This is a private read, not a write or provider refresh, and includes Nostr results marked type=nostr. Use nativeNostrReplyResult(item.id) to check that recorded event on its relay without signing or resending. Discard page state on owner/app changes. See README for examples and the callback, revocation and removal contracts.
- `r.protocols` — Private app safety: `sourceControls` returns current `enabled` plus paged saved choices; `setSourceControl`, `onSourceControlChange` and `reportSource` share app scope. Example: `const choices = new Map(); const stop = r.protocols.onSourceControlChange(change => choices.set(JSON.stringify([change.source, change.control]), change.enabled));` then `await r.protocols.setSourceControl({ source: { protocol: "bluesky", kind: "actor", nativeId: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa" }, control: "mute", enabled: true, scope: "minds" });` and call `stop(); choices.clear()` on account change/unmount. Notifications follow an exact server confirmation, never an uncertain response. These preferences and reports apply in Minds, not on the remote network. Open network ids (0.7.87, readers first): `import { SOCIAL_PROTOCOL_IDS, isSocialProtocolId } from '@recursiv/sdk'` lists every network a post, account or `SocialSourceRef` may name: bluesky, activitypub, nostr and farcaster (a Farcaster account by its FID, "3"; a cast by `<fid>:0x<40 lowercase hex>`). Listing an id serves nothing: read only what `publicNetworks()` lists, and skip an id this SDK does not know. Writes stay narrower: a native reply, follow, like or repost takes only `NATIVE_WRITE_PROTOCOLS` (bluesky, activitypub, nostr; `isNativeWriteProtocol(post.protocol)` before offering one), and a feed top's `networks` always names those three while a Farcaster lane may be absent (`networks.farcaster ?? []`). Keyless post links: `const visitor = new Recursiv({ anonymous: true, inheritEnvironmentApiKey: false }); const { data: thread } = await visitor.protocols.getSharedConversation(projectId, { protocol: 'nostr', post: publicEventId })`; `sharedNetworks(projectId)` lists public conversation capabilities. Only configured apps; app moderation and rate limits apply, no member state or write authority. Member public reading: `publicNetworks`, `searchPublicProfiles`, `getPublicProfile`, `getPublicAuthorFeed`, `getFollowingFeed`, `getPublicConversation`, `getPublicTrends`, `getPublicTrendFeed`; a Fediverse community a groups read lists under `open_network` (0.7.109): `const { data: page } = await r.protocols.getOpenGroupThreads({ group: entry.actor, limit: 20 })` reads its newest threads read-only (`page.group`, `page.items`); `limit` is 1 to 25, `compass: 'hide'` leaves out the threads in politics, and the next page passes `cursor: page.cursor` while it is set (404 while the app does not offer groups from other networks); private app subscriptions: `listSubscriptions`, `subscribeToProfile`, `unsubscribeFromProfile`, `onSubscriptionChange`. `getFollowingFeed` sources: a slow account is `late` (status `late`, or `ok` with `late: true` while its held first page is shown; older APIs say `unavailable` with `late: true`), never a failure: read the next page for its posts (`lateNetworks` names its network). Example after selecting a returned source post: `const { data: thread } = await r.protocols.getPublicConversation({ protocol: post.protocol, post: post.nativeId, readRef: post.readRef })`. Render `focus`, oldest-first `ancestors` and direct `replies`; `public_provider_window` never promises every reply, and `limited` marks known omissions. The author's own thread (0.7.81): `thread` holds the focus author's continuation below the post, oldest first (a "1/" post's 2/, 3/, 4/ ..., at most 20 parts, each held to the same moderation and member controls as a reply); its first part is not repeated in `replies`, so render `focus`, `thread`, then `replies` (`thread ?? []`: older APIs omit it, and a `replies: 'none'` read answers none). A card (a post shared into a chat, a link preview) asks for the post alone, 0.7.78: `getPublicConversation({ protocol, post, replies: 'none' })` (also `getSharedConversation` and `getConnectedSocialConversation`) answers `focus` with no `ancestors` or `replies` and `repliesStatus: 'not_requested'`; a Nostr note answers from one relay read instead of a whole thread's. An older API answers 400 `invalid_input`: read without it. Requires both `users:read` and `posts:read` on the current human app key. Protocol discovery/settings: `const { data: adapters } = await r.protocols.list()` returns bounded `{ id, name, icon, color, maturity, capabilities, limitations }` metadata; `supported` means implemented, not configured, healthy, authorized, or enabled. Methods: `list`, `status`, `listCandidates`, `getCandidate`, `search`, `getSettings`, `refresh`, `updateSettings`.
  - Native Nostr: `const { data: preview } = await r.protocols.prepareNativeNostr(identityId, { action: "publish", content: draft })`; review and sign the exact public event, then `submitNativeNostr(identityId, { intent: preview.intent, event, approve: true })`. Preparation/submission never auto-retry. After uncertainty, use `getNativeNostrPost(identityId, preview.postId ?? preview.eventId)` before a user-selected retry of the identical intent/event: deletion checks the original note's `postId`, publication checks `eventId`. Check `nativeNostrAccount()` enablement first; keys stay with the signer. For replies, after `nativeNostrAccount()` advertises `reply_text_note`, use `prepareNativeNostr(identityId, { action: "reply", content: draft, parentId: post.nativeId })`. Review returned parent/root/participants/relay and exact event, sign with the connected client signer, then `submitNativeNostr(identityId, { intent, event, approve: true })`. Requires users:read, posts:read and posts:write. Kind1 public notes only; reply enablement and shared UI/live proof remain pending. Do not inherit arbitrary notification tags or relay hints. Signing mutations never auto-retry; check `getNativeNostrPost(identityId, eventId)` after uncertainty before a user-selected identical-event retry.
  - Nostr signing (0.7.192): `nativeNostrAccount()` answers `signing: 'client'` (the member's own key: prepare, sign the exact event, submit) or `signing: 'server'` with `mode: 'managed'` (a key Minds holds: `prepareNativeNostr` is a side-effect-free preview; after the member approves, `prepareNativeNostr(id, { ...input, send: true })` signs, sends and returns `receipt`; a like/repost/follow review submits `{ approve: true }` with no `event`; `engage*` with `identity: 'native'` acts as it). A managed key's `enabled` follows the member's Nostr presence, not the app's Nostr write switches; for either key, like/repost/follow (and their undos) are listed only while the app's review route for them is on, so offer exactly the listed capabilities.
  - Native networks (0.7.89): read the current state of ActivityPub, AT Protocol and Nostr before offering setup or actions. `const { data } = await r.protocols.networks()` lists `{ network, state, reason, mode, handle, engageDefault }` (read-only; `ready` = set up on their first post or interaction, show "Will be set up when you first post or interact"). `activateNetwork(network)` = "Set up now" (`pending` + `retryAt` over budget; 409 `network_off` after the member's off switch). `setNetwork(network, { enabled: false, removePast: true })` turns it off and removes what was shared; `{ enabled: true }` turns it back on (403 `network_locked`, 409 `not_rolled_out`/`age_band_required`). Where a network is opt-in, a member who never turned it on reads `off`/`not_opted_in` (nothing sets them up; `activateNetwork` is 409 `network_off`) until `setNetwork(network, { enabled: true, consentVersion?, consentSource? })`, which records their consent (send those two only where `networks()` reads `recordsConsent: true` for the network, or after a `not_opted_in` refusal: a server without the level reports neither and answers 400 `invalid_input` to them). A member who set a Fediverse address up in Linked accounts before reads `on`/`legacy_opt_in`, and their tap acts as it. A turn-on also takes `autoShare` (`false` = address only: their posts with no `destinations`, as the API, MCP, the CLI and agents send, skip that network; omitted, `consentSource: 'engage'` is address only and any other shares), sent only where `networks()` reports `autoShare` (an account whose access to the app is not a membership cannot keep address only: 409 `auto_share_unrecorded`, nothing set up). `posts.create` answers `sharing_paused: [{ network, reason, retry_at }]` when the member's federated-post caps kept the post off a network (`hourly_sharing_limit`, `daily_sharing_limit`, `remote_mention_limit`): it is on Minds and is never sent there. No new identity for a 13-17 member (`locked`/`minor_network`, 403 `network_locked`) or an account under a week old with no verified email (`needs_action`/`account_too_new` with `availableAt`, 409); AT Protocol needs both (`needs_verified_email`, 409); an identity a member already has is left to them (on stays on; after an off they can turn it on again). Needs users:read (+ users:write to change). Each row lists `carries` (what the server sends there: `post`, `reply`, and `repost`/`quote` once it does; missing = `['post','reply']`). `networks({ post, action: 'reply'|'repost'|'quote' })` (`supportsPostReach`) answers the same rows with `reaches` and, when false, `reason` (`post_not_there`, `group`, `not_public`, `not_carried`, `sensitive`): where that reply, remind or quote of the post would go; 404 `post_not_found` for a post the member cannot see (+ posts:read). A linked outside account is a Settings choice, never a step in a main flow. Taking the managed Nostr key home: `exportNostrKey({ password } | { emailCode })` (code from `settings.requestConfirmationCode('nostr_key')`) returns the `nsec` (show once, never log); `nostrRebindChallenge()` then `rebindNostrKey(signedEvent)` proves the device holds the same key (mode `attached`); `deleteManagedNostrCopy(stepUp)` deletes Minds' copy (held for now: 409 `device_signing_unavailable`, copy kept; 409 `rebind_required` before the rebind; 409 `too_many_published` keeps it), after which Nostr actions are signed on the device and Minds' own notes still come down with takedowns it signed first. Never auto-retried.
  - Famous accounts (0.7.151): `const { data } = await r.protocols.getPublicPopularProfiles({ protocol: 'all', limit: 24 })` reads the reviewed famous accounts of AT Protocol, the Fediverse and Nostr in one ranking (most famous and recently active first: followers plus readers of the person's Wikipedia article, categories interleaved, politics at most one in four and rotated across sides), then the providers' own suggestions. Page with `cursor` for infinite scroll (it holds its list across an hourly refresh for a few hours; on 400 `invalid_input` start again); `null` is the end. `category` (one of `data.categories`) narrows the list; `compass: 'hide'` (the member's Hide politics) leaves political accounts out of any list. Items carry `category` on `protocol: 'all'`. A list the catalog leads says so: `provenance.ranking` is `famous_accounts` (provider named in plain words, `fame and recent activity`, with no company name, so an app can show it as is), and on a network's own list `provenance.sources` keeps the provider's own label and read time for the accounts after the catalog's. A `protocol: 'all'` cursor is also refused after a deploy changed the catalog. Needs users:read and posts:read; 503 until the app's index has built the list.
  - Hosted Bluesky account on the app's own PDS: `const { data } = await r.protocols.createHostedIdentity({ protocol: 'atproto', handle: 'alice', email })`. Only the label is sent; `data.handle` carries the domain and `data.password` is returned this once, never stored. Never auto-retried. Either the account is finished or it is removed again. `email` must be the member's own verified one (409 `needs_verified_email` = none yet, 409 `email_not_yours` = send their own); in an app that rolls native networks out (Minds), 403 `outbound_refused` = the rollout does not cover the member yet, 403 `network_locked` = a rule holds AT Protocol off for them, 409 `age_band_required` = answer the age question first, and the label must be the one their native setup would choose now (the first free of their username's label, its `-2` to `-50`, and that label with their tag). 409 `handle_unavailable` = choose another label (in Minds: the label is not the one native setup would choose, or the PDS holds it; offer "Set up now", `activateNetwork('atproto')`, instead), 409 `identity_conflict` = they already have one; 503 `handle_dns_unavailable`/`handle_unresolvable`/`handle_unverified` = operator setup, retry later unchanged.
  - One-tap engage (0.7.191): `engageLike|engageRepost|engageFollow({ protocol, nativeId, clientMutationId, action, identity?, accountId? })`, `engageReply({ clientMutationId, text, parent, media?, identity?, accountIds? })`, `engageQuote({ clientMutationId, text, quote, ... })`. Native: `{ identity: 'native', queued: false, delivery, actedAs }` or 202 `{ queued: true, interactionId, expiresAt, retryAt, actedAs }` (sent once the identity is set up; `pendingInteractions()` lists them). Linked: the review to submit as before, plus `identity: 'linked'`, `actedAs` and once `notice: 'engage_default_linked'`. `setEngageDefault(network, 'native' | 'linked')`. Refusals: 409 `native_network_off` (with `reason`), `linked_account_required`, `native_post_from_app` (a plain post is never native), 429 `too_many_pending`, 503 `native_network_unavailable` (reason `adapter_missing`: that network cannot send a tap natively yet; a linked account acts instead when there is one). Keep `clientMutationId` across retries; never auto-retried. Read back (0.7.202): `nativeInteractionState({ protocol, nativeId })` -> `{ liked, reposted, reaction, following: 'pending'|'accepted'|'rejected'|null }` and `nativeNotes({ protocol, limit?, cursor? })` -> `{ items: [{ id, kind: 'reply'|'quote', nativeId, text, mediaCount, createdAt, target: { nativeId, author } }], cursor }` (what the member's own identity did; ActivityPub only for now, else 503 `adapter_missing`).
  - AT Protocol password claim (0.7.191): the member's AT Protocol account is created with their verified email and Minds acts for them with a revocable app password (Minds still runs the PDS and holds the DID's only rotation key, so never tell members they can lock Minds out). `claimAtprotoPassword({ password } | { emailCode })` (emailCode from `POST /settings/confirmation-code` purpose `atproto_password`) has the PDS email a reset code; answers `{ handle, sentTo }` (masked). 403 `step_up_required`/`step_up_failed`, 404 `no_identity`, 409 `needs_verified_email`/`email_changed`, 429 `rate_limited`. Never auto-retried.
  - AT Protocol grant (0.7.191): presence `needs_action` reason `needs_atproto_grant` (an account made before Minds ran it natively) or `error` reason `app_password_revoked` -> `grantAtproto({ password })` with the AT account's password (main, or a non-privileged app password); Minds keeps only a new revocable app password. Answers `{ handle, presence }`. 403 `password_failed`, 400 `privileged_app_password`, 409 `identity_mismatch`, 404 `no_identity`, 429 `rate_limited`. Never auto-retried.
  - Anonymous discovery: `const visitor = new Recursiv({ anonymous: true, inheritEnvironmentApiKey: false }); const { data } = await visitor.protocols.getSharedTrends(projectId, { protocol: 'nostr', limit: 20, discovery: true })`. Use `sharedNetworks(projectId)` capabilities; open a returned topic with `getSharedTrendFeed(projectId, { protocol: 'bluesky', topic: trend.nativeId, cursor })`. Configured apps only; no account authority or writes. App moderation and per-IP/app rate limits apply. Categories and Jev layouts reuse cached judgments without initiating paid inference; handle partial categories and finite provider windows. Category depth: `r.posts.list({ category: 'science', sort: 'hot', discovery: true })` pages the hot window by offset and then by keyset (`meta.next` is `{ offset }`, `{ cursor }` or `null`; pass a cursor back as `cursor`); when a stage ends, `meta.fallover` lists the next feeds in order (`category_older`, `category_network`, `category` with `via`, `for_you`, `all`; `feed` with `ref` is declared in 0.7.60 but not sent yet, so skip kinds you cannot open). One call for a category's modules: `const { data } = await r.discovery.category({ category: 'science' })` returns `stories`, `network`, `clips`, `people`, `groups`, each `{ items, ms, reason? }`. Watch's Minds videos: `const { data, meta } = await r.discovery.videos({ limit: 12 })` returns public video posts in hot order from a list shared per app (rebuilt about once a minute), each re-checked per call for the viewer; page on `meta.next_cursor`. With no category about one row in four is an open-network clip (0.7.78): `isWatchNetworkClip(row)` tells `{ kind: 'social', id, post: SocialPost }` from a `Post`; open and react to it as the network's post (its `id` is never a Minds id).
  - Progressive Discover feed (0.7.71): `const feed = r.discovery.createProgressiveFeed({ networks, category, recommend, top: { ref: 'builtin:all' }, seen, seenClusters }); const round = await feed.next(part => draw(part))` opens one `createFeed` session per source (Minds with the radar and suggestions, one per network with `public_trends`) and hands each source's page on as a `DiscoveryPart` (`{ source, round, modules, composed?, mixed? }`) the moment it lands, instead of a page that waits for its slowest network (up to 15 s); a round waits `DISCOVERY_STRAGGLER_MS` past its first answer and rejects only when every source failed. The first load is held until Minds and one other network answered (or `FIRST_SCREEN_MS`, 2.5 s, after the first answer; `firstScreenMs: VISITOR_FIRST_SCREEN_MS` for a visitor) and arrives as one `composed: true` part from `composeFirstScreen`: the top's first post when it is a playable video, else (0.7.200) the most engaging post across the networks by `discoveryLeadScore` (engagement on a log scale against the whole batch's typical post, never its own network's median; a playable clip `DISCOVERY_VIDEO_BOOST` times, a picture `DISCOVERY_PICTURE_BOOST`; halving every `FIRST_SCREEN_LEAD_HALF_LIFE_HOURS`, 72 h; a Minds member's post only within `FIRST_SCREEN_MINDS_LEAD_SHARE`, 0.85, of the best open-network post; never a post nobody engaged with while an engaged one is on the screen, nor a column while a single post may lead: `firstScreenEngagedLead`), else, with no engagement anywhere, a picture lead from the best 8 by engagement (never a story, rail, video strip, column, `isSensitivePost` post or `linksAdultSite` porn link; 0.7.80: never a post with no picture or clip and no engagement while the screen holds one with either, which then leads: media and engagement, else media, else engagement, as `mergeDiscoveryArrival` leads a feed's top and the feed after a line), then every network's posts by engagement (`DiscoveryEngagementMerge`) with row 2 from another network than the lead's when one is left (`FIRST_SCREEN_NETWORK_ROWS`), a story as row 3 and a rail as row 5, nothing dropped. Merge later `mixed` parts with `mergeDiscoveryArrival(rows, arriving, reachedIds)`. `top`/`seen`/`seenClusters`/`bucket` reach every session; the top is read once per open. Also `retryFailed()`, `onStatus(listener)`, `setNetworks(catalog)`; settings `perSource`, `firstScreen`, `onLanded`. For you: `createProgressiveFeed({ createFeed: o => r.discovery.createPersonalFeed(o) }, options, { perSource: false })`. A session's `seen` now also leaves seen network posts out of trend pages, previews and topic pages; in a category a topic page with nothing new ends its topic and after `DISCOVERY_EMPTY_TOPIC_PAGES` (3) in a row the network's other topics are skipped. 0.7.84: a featured module carries `theme` only when its lead window was themed so and most of its own posts were judged into that category (a category feed's posts, by the read's category filter); a feed with no category titles every module by its kind alone ("Videos", not "Videos in Technology" over an unjudged Nostr clip). A post is shown once by every identity (`discoveryItemIdentities(item)`: its key, an open-network post's network id, and each media file by address and by content hash, so a second note carrying the same clip is the same post) across a session's pages, a progressive feed's sources (`withoutSeenItems` takes identities or keys), `mergeDiscoveryArrival` and gallery pooling; `withoutRepeatedDiscoveryItems(rows, shown)` does the same for an app's own rows.
  - Viral read (0.7.59; off until the server enables it for the app): `const { data } = await r.protocols.getPublicViral({ media: 'video', category: 'science', limit: 20 })` (member key, users:read + posts:read, never cached) or keyless `visitor.protocols.getSharedViral(projectId, { media: 'video', compass: 'hide' })` (visitors send compass `all` or `hide`, and a side or `mix` only where the catalog lists `compass_sides`). Params, all optional: `network` (all, minds, bluesky, activitypub, nostr), `category`, `media: 'video'`, `limit` 5/10/20/40, `cursor` (the last page's; a cursor whose 30-minute build expired ends the list), `compass`. Each item: `key` (stable; drop ones already shown), `protocol`, `post` (checking `protocol` narrows it: `ViralMindsCard` for minds, open at /post/:id; otherwise a `SocialPost`), `label` viral/rising/hot, `score`, `rank`, `category`, `velocity` (show counts with `countsReportedBy` as reported, never verified), `spread`. A visitor's read serves media only where the server cleared it, so even with `media: 'video'` some items arrive with the video withheld (empty `media`): `import { viralItemHasVideo } from '@recursiv/sdk'` and keep `data.items.filter(viralItemHasVideo)` before a vertical video player. `status` ok/building/screening/off: off resolves with no items, and `getSharedViral` also resolves an older API's 401 `missing_api_key` as off; `getPublicViral` throws every 401/403 (never off), so catch it and skip that step.
  - Public trends: require `public_trends` from `publicNetworks()`, then `getPublicTrends({ protocol, limit?, cursor?, compass?, media? })` (`compass: 'hide'` leaves out politics, 0.7.62; `media: 'video'`, 0.7.73, Bluesky: the network's own window of video posts, a `kind: posts` page paged by its cursor, no category or layout, 404 `unsupported_protocol` for a network without one, 400 on an API that predates it; keyless `getSharedTrends(projectId, { ..., media: 'video' })` holds only clips a visitor may see and counts the rest in `mediaFilter.withheld`); render `kind: topics` as source topics and `kind: posts` as source posts. With `trend_feed`, open only a returned current topic using `getPublicTrendFeed({ protocol, topic: trend.nativeId, limit?, cursor? })`. Show provider, observedAt and provider_ranked_window coverage; null rankingWindow is unknown, not a daily/global ranking. Preserve source order, canonical IDs and readRef, and opaque cursors. Topic catalogs do not paginate; Mastodon trends stop at 200 source positions. Both methods require users:read plus posts:read on the current human app key; Nostr trends are unsupported. Propagate errors; trend_unavailable means refresh the topic list. No ingestion or native writes.
  - One outlet count per story (0.7.71): a radar story (list, story read, archive), a World Today story (`outlets`, with `outlet_count` its total and `lane_mix` its lanes), a category strip story, a `feeds.top`/`feeds.stories` story and a search story carry `outlets: { total, mainstream, independent, other }`, the distinct outlets of the articles the story lists (an allow-listed outlet once, an unlisted host in `other`; the buckets sum to `total`). Show `outlets.total`; `sources.outlet` counts articles. `DiscoveryCluster.outletCount` reads it. An older server omits it.
  - Keyless category surface (0.7.165): `const { data } = await visitor.protocols.getSharedCategorySurface(projectId, { category: 'science', compass: 'hide' })` gives a signed-out category page its `stories`, `network` (open-network posts, with `by_protocol`) and `clips` in one read, the sections a member's `r.discovery.category()` reads from the same server cache, never `people` or `groups`. Every visitor floor runs again on each read (tier-1, held and blocked-instance items, safety and term floors, NSFW, media only where cleared for visitors: a post's pictures keep their `width` and `height`). `compass`: `all` or `hide` (Hide politics on all three, counted in `data.meta.compass_filter`); a side or Mix only where the app's catalog lists `compass_sides` for visitors (else a 400), answered with Everything's sections marked `unavailable`, since no section carries a placement. A short or failed section says why in `reason`. Send only `category` and `compass`: the answer is one per app, category and choice, so the edge may keep it 30 s.
  - Political stories (0.7.67): every radar story (`getPublicRadar`, `getSharedRadar`, a story read) and every World Today story (`r.curator.today()`) carries `political`: true when a quarter of its judged posts are politics, its theme or topic is politics, or its headline or summary names an election, a war or troop deployment, a court or justice, a legislature, or a party or politician. `compass: 'hide'` leaves those out whatever their theme; `r.curator.today({ compass: 'hide' })` does the same to the front page, the next story leads, and `meta.compass_filter` counts what was left out. A story from `r.feeds.stories()` or a `r.feeds.top()` lead carries `political` too, and both reads, and `r.curator.forYouWorld()`, leave political stories out under `compass: 'hide'` whatever their theme. An older server omits `political`: decide by `theme` as before.
  - Hide politics as a floor (0.7.72): the radar, `r.curator.today()`, `getPublicTrends`, keyless `visitor.protocols.getSharedTrends(projectId, { protocol, compass: 'hide' })` (visitors send `all` or `hide`, and a side or `mix` only where the catalog lists `compass_sides`, 0.7.116; an older API answers 400 to `compass` there), the viral read, `r.discovery.videos` and a visitor's Discover posts apply `compass: 'hide'` for every caller. Where the operator does not serve the caller the full filter, the answer's `meta.compass_filter` is `{ status: 'applied', basis: 'flags', ... }`: left out by the server's own `political` flags and browse categories, no judgment read. Treat `applied` with or without `basis` as filtered. Choose sides and Mix sides still answer `unavailable` until the operator serves them, and the catalog's `compass_filter` capability still says when to offer Politics in Filters; `compass_sides` (0.7.116) says the viewer may choose sides and Mix too (a visitor only where the operator serves visitors the whole filter).
  - Post language: a `SocialPost` may carry `language`, the lower-case primary subtag the post declares (`'de'`, `'en'`; Bluesky `langs[0]`, Mastodon `language`, a Nostr NIP-32 `ISO-639-1` label). It is absent when the post declares none (most Nostr notes) and on posts from the source index; it is never guessed and no post is dropped for it. Order by it (the viewer's language first, undeclared next), never filter on it.
  - Nostr mentions (0.7.143): a Nostr `SocialPost` (and its available `quote.post`) may carry `mentions`, the people its `text` names with NIP-27 references that the server can name: `{ pubkey, displayName, handle, references }`, at most eight, in the order the text first names them. Draw `@displayName` in place of each string in `references` (the exact `nostr:npub1…`/`nostr:nprofile1…` references in `text`), and open the person with `protocol: 'nostr'`, `actor: pubkey`. `handle` is their NIP-05 name once its domain confirmed it, else their npub. A person the server has not read, whose metadata hides them, or whom the app's moderation or the member's own blocks and mutes hide, is left out: show that reference as the text writes it. The server never follows an nprofile's relay hints. A quoted note's author is named by the newer of what the read relays hold and what the server last read of them (a key only when neither has any), so an author who hides themselves withholds the quote at once.
  - `listCandidates({ protocol?, limit?, cursor? })` and `getCandidate(id)` are read-only quarantine review, not published-post search. Both require `admin` scope, a project-bound key, a live admin role, and existing project-admin access. The key supplies app/network scope; neither method accepts another project or network. They never invoke refresh, change settings, or publish.
  - Lists return `{ data: ProtocolQuarantinedCandidate[], meta: { limit, has_more, next_cursor } }`; use the opaque `next_cursor`, not offset pagination. The API defaults `limit` to 20 and permits at most 50. Details return `{ data: ProtocolQuarantinedCandidate }`. Every candidate has `state: 'quarantined'` and `content_format: 'plain'`; render its bounded `content` as text, respect `content_truncated`, and distinguish upstream `published_at` from local `observed_at` / `created_at`.
  - Safe source IDs are preserved byte-exact. `external_id: null` means unsafe or malformed provenance was withheld, not an invented ID; `author.native_id` may likewise be absent or withheld. Preserve nulls in both list and detail views, and use the candidate's own `id` for `getCandidate`.
  - API authorization/validation/not-found/service errors propagate as normal SDK errors, including when the deployed API does not yet support these routes. Never substitute synthetic candidates or turn these failures into an empty queue. `getCandidate` rejects empty/whitespace and URL dot-segment IDs with `ValidationError` before sending; other IDs are encoded and validated by the server.
  - `ingestionHealth()` (0.7.71) reads `GET /protocols/ingestion/health` with no query (the API rejects one; scope comes from the key): `{ data: ProtocolIngestionHealthReport }` with `runtime` switches, `lanes` (per lane `jobs`, `current` open job with `position` { feed_index, term_index, page }, `pages_committed`, `consecutive_failures`, `lease_expired`, `waiting_since`, `starved_since`; `last_done_at`; 24-hour `activity` with `reasons`; `dead_letters` grouped by reason and position) and `circuits` (provider or fetch-host rows that are open, counting or killed). Same key and authority as `listCandidates` but no `content_intelligence_admin` binding. A section that did not answer is null and listed in `unavailable`: show it as unknown, not as zero. Errors throw.
- `r.inbox` — Notification feed
- `r.network` — Federation/network config
- `r.simulator` — Simulation/testing
- `r.dispatcher` — Task queue: `tasks()`, `create()`, `claimNext()`, `complete()`, `release()`, `stats()`, `signals()`, `outcomes()`, `staleItems()`, `stuckItems()`, `discoveries()`
- `r.dispatcher` (webhooks): `createWebhook()`, `listWebhooks()`, `updateWebhook()`, `deleteWebhook()`, `testWebhook()`, `webhookDeliveries()`, `cleanupWebhookLogs()`
- `r.goals` — Org goals that dispatcher tasks roll up into: `list()`, `get()`, `create()`, `update()`, `archive()`. Tasks link via `goal_id` on `r.dispatcher.create()/update()`; `tasks({ goal_id })` filters (use `'none'` for goal-less tasks).
- `r.linkPreview` — Open Graph card for a public link: `get(url)` answers `{ data: LinkPreview | null }` (null: no preview, show the plain link); keyless clients may call it. For a link in a chat message pass where it came from, `get(url, { messageId })` (or `{ conversationId }` before the message has an id), on a signed-in key with `chat:read`: the link is fetched only when it is in the named message and a person wrote that message, or when the caller wrote the same address in that conversation (a message, or the card link of a Minds post they shared there), else `{ data: null, refused: 'ai_link' }` with nothing fetched; 401 without a key, 404 for a message or conversation the caller cannot read. A `source` with no id rejects with `ValidationError` and sends nothing. Never pass `source` in an encrypted conversation: the server cannot read it, so every link would be refused; the app's own rule decides there.

```typescript
// Create a goal and group tasks under it (personal keys: pass organization_id)
const { data: goal } = await r.goals.create({ name: 'Ship the relaunch', organization_id: orgId })
await r.dispatcher.update(taskId, { goal_id: goal.id, organization_id: orgId })
const { data: goals } = await r.goals.list({ organization_id: orgId }) // includes task rollups
```

```typescript
// Create a webhook to receive dispatcher events
const { data: wh } = await r.dispatcher.createWebhook({ url: 'https://example.com/hooks', event_types: ['dispatcher:task_completed'] })
// wh.secret — HMAC-SHA256 signing secret (shown once)

// List, update, test, delete
const { data: hooks } = await r.dispatcher.listWebhooks()
await r.dispatcher.updateWebhook(id, { active: false })
await r.dispatcher.testWebhook(id)
await r.dispatcher.deleteWebhook(id)
```

---

## KPIs (the metric ledger)

Every KPI a person sees, an agent reads from the same daily snapshots. Numbers carry a one-sentence definition, a status (`ok`, `partial`, `failed`), the value seven days earlier, and one `confidence` word for the whole read. A number that could not be counted is `null`, never `0`.

```typescript
// One tier, one scope. Access follows the tier: platform owners, network admins,
// organization members, project admins or the owning organization.
const { data } = await r.metrics.forOrg(orgId, { keys: ['activeIn28Days', 'revenueIn28Days'], seriesDays: 28 });
data.confidence;                       // 'ok' | 'partial' | 'stale' | 'unverified' | 'missing'
data.metrics.activeIn28Days.value;     // 312
data.metrics.activeIn28Days.weekBefore; // 288
data.metrics.activeIn28Days.definition; // 'Distinct product users who opened an app ... ending at as_of.'

await r.metrics.forProject(projectId);             // members, signups, active, posts, API health
await r.metrics.get('network', networkId);         // admins: users, retention, MRR, waitlist
await r.metrics.children('org', orgId);            // the org's projects with their headline number
await r.metrics.definitions('project');            // every key with its sentence, for a success metric
```

A task's `success_metric` can name a ledger key: `internal.project.activeIn7Days > 100`.

## Golden paths

### AI-native app (database + agent + storage + auth)
project-admin setup: `r.projects.create()` → `r.databases.ensure()` → `r.databases.getCredentials()` → `r.projects.executeCode()` (migrations) → `r.storage.ensureBucket()`; runtime: `r.auth.signUp()` → `r.databases.query()` → `r.agents.create()`

### Social/community platform
`r.auth.signUp()` → `r.communities.create()` → `r.posts.create()` → `r.tags.create()` → `r.chat.createGroup()` → `r.profiles.follow()`

### AI coding playground
`r.projects.create()` → `r.projects.createSandbox()` → `r.agents.create()` → `r.agents.chatStream()` → `r.projects.executeCode()` → `r.projects.deploy()`

### Autonomous agent with its own infra
`r.projects.create()` → `r.databases.ensure()` → `r.storage.ensureBucket()` → `r.agents.create()` → `r.agents.grantProjectAccess()` → `r.projects.executeCode()`

### White-label business app (BYOK)
project-admin setup: `r.databases.ensure()`; runtime: `r.auth.signUp()` → `r.databases.query()` → `r.email.send()` → `r.webhooks.register({ provider: 'stripe' })` → `r.jobs.create({ cron: '0 8 * * *' })`

---

## Response shapes

```typescript
{ data: T[], meta: { limit, offset, has_more } }  // list (PaginatedResponse)
{ data: T }                                         // single (SingleResponse)
{ data: { deleted: true } }                         // delete (DeleteResponse)
{ data: { success: true } }                         // success (SuccessResponse)
```

Pagination: pass `limit` and `offset`. Check `meta.has_more`.

---

## Error types

| Error | HTTP | When |
|-------|------|------|
| `AuthenticationError` | 401 | Missing or invalid API key |
| `AuthorizationError` | 403 | API key lacks required scope |
| `NotFoundError` | 404 | Resource doesn't exist or no access |
| `ValidationError` | 400 | Invalid input (check `error.details`) |
| `RateLimitError` | 429 | Rate limit hit (`retryAfter` seconds, `resetAt` Date, `scope`) |
| `ConflictError` | 409 | Resource already exists |

Auto-retry on 429/5xx built in (exponential backoff, default `maxRetries: 2`), except a 429 with `X-RateLimit-Scope: action` (one member action past its budget): never retried, `RateLimitError.scope === 'action'`, `resetAt` = when it reopens; show it on that action, do not pause the app. A read that holds its own deadline can ask once: `r.posts.list({ ...params, retry: false })` and `r.curator.forYou({ ...params, retry: false })` (0.7.59) throw the first 5xx or 429 with no retry and no `Retry-After` sleep; `retry` is never sent. It rides in the params so a reader that wraps `posts.list` and forwards its params keeps it. Discover's feed sessions (`discovery.createFeed`, `createPersonalFeed`, a `DiscoveryFeedSession` over your own `posts.list` wrapper) read Minds posts this way, as they read the open networks, and report a busy read in `failedSources`; a wrapper that rebuilds the params from chosen fields must copy `retry` too. Member actions with a per-member budget are sent once and never auto-retried: `reports.create`, `moderation.appeal` and `protocols.reportSource` throw the 429 at once (`RateLimitError`, `message` is member-facing, `retryAfter` = seconds until the window opens; a budget refusal carries `X-RateLimit-Scope: action` and no `Retry-After` header).

Automated report review: pass `actor_type: 'ai'` to both decisions, for example `await r.reports.dismiss(reportId, { actor_type: 'ai' })`; the API refuses human-only cases even with an admin credential. Deploy the supporting API before relying on this guard.

Sealed answer reports (0.7.152; deploy the supporting API before client adoption): `await r.reports.create({ target_type: 'sealed_answer', target_id: appProjectId, reason: 'harmful', details: 'The exchange the member chose to show staff' })`. Use a human-owned, non-agent project key with `posts:write` and its exact project id. This intake does not recheck live app membership; `/sealed/reports` additionally applies the gateway's membership guard. These queue items do not accuse the reporter or hold their unrelated posts/account deletion; a reviewer can close them without account enforcement. Older `user` reports remain account reports and are not reclassified. Existing native clients must adopt this target after the API/SDK rollout; source support alone does not fix them. Every answer request, including a join, spends the shared report budget. Read `data.id`, `data.existing` and `data.details_kept`: false means the reason was retained but the selected text did not fit in full; show a successful partial receipt, not a failure or automatic resend.

### Idempotency

The REST API (`/api/v1/*`) supports the `Idempotency-Key` header on POST/PUT/PATCH requests. Include a unique key per mutation to prevent duplicate side effects on retries. The key is scoped per-user and cached for 24 hours. Max key length: 256 characters. The SDK's built-in retry handles 429/5xx automatically, but idempotency keys protect against client-side retries too.

---

## Configuration

```typescript
const r = new Recursiv({
  apiKey: 'sk_live_...',                   // or set RECURSIV_API_KEY env var
  inheritEnvironmentApiKey: true,          // default; false guarantees keyless operation
  baseUrl: 'https://api.recursiv.io/api/v1',  // default
  timeout: 30000,                          // request timeout in ms
  maxRetries: 2,                           // auto-retry on 429/5xx
})

// Zero-arg works when RECURSIV_API_KEY is set
const r = new Recursiv()

// Anonymous sandbox (no API key required; inherits RECURSIV_API_KEY when set)
const r = new Recursiv({ anonymous: true })

// Guaranteed keyless public client, even inside a credentialed server process
const visitor = new Recursiv({ anonymous: true, inheritEnvironmentApiKey: false })

// Self-hosted
const r = new Recursiv({ baseUrl: 'https://my-instance.com/api/v1' })
```

---

## Common mistakes that break apps

```typescript
// ❌ WRONG: agents.chat() is async — does NOT return the agent's reply
const reply = await r.agents.chat(agentId, { message: 'Hello' })
console.log(reply.data.content) // undefined!

// ✅ RIGHT: use chatStream() for real-time responses
const stop = new AbortController()
const stream = r.agents.chatStream(personalAgentId, { message: 'Hello', turn: { safe: true, purpose: 'minds_eye' } }, { signal: stop.signal })
// stop.abort() cancels the reader and this safe turn's server run; partial work may still be charged.
// Native: agents.chatStreamText(id, input, { signal }). No signal preserves prior disconnect behavior.
for await (const chunk of stream) { process.stdout.write(chunk.delta ?? '') }

// ❌ WRONG: getCredentials takes name, not database_id
await r.databases.getCredentials({ database_id: db.id }) // ValidationError!

// ✅ RIGHT
await r.databases.getCredentials({ project_id: 'proj_xxx', name: 'my-db' })

// ❌ WRONG: missing organization_id
await r.agents.create({ name: 'Bot', model: 'anthropic/claude-sonnet-4' }) // fails

// ✅ RIGHT
await r.agents.create({ name: 'Bot', username: 'bot_1', model: 'anthropic/claude-sonnet-4',
  system_prompt: '...', organization_id: orgId })

// ❌ WRONG: assuming get() always returns the full group
const { data } = await r.communities.get('comm_xxx')
data.created_by.name // undefined on a private group you are not in

// ✅ RIGHT: a private group you're not in is a card (limited: true); hidden or missing is 404
try {
  const { data } = await r.communities.get('comm_xxx')
  if (data.limited) { /* show name + "Request to join" / membership_status 'pending' */ }
} catch (e) { if (e.status === 404) { /* hidden or doesn't exist */ } }
```

---

## Gotchas

1. **`agents.chatStream()` requires ReadableStream** (Node.js/browsers). For React Native, use `agents.chatStreamText()` which reads the full response then parses SSE events.
2. **`ensure` methods** (databases, storage) are idempotent for existing resources. Missing-resource creation requires project admin authority; pre-provision before regular `project_member` users mount the app.
3. **Do NOT use `r.posts` as a database.** Posts are for social content. Use `r.databases` for structured data.
4. **API keys need explicit scopes.** Missing scopes → `AuthorizationError` (403).
5. **`organization_id` is required** when creating agents and projects.
6. **`databases.getCredentials()`** takes `{ project_id, name }` — not `database_id`.
7. **`agents.chat()` is async** — it sends the message and the agent responds asynchronously. The response contains `message_id` and `conversation_id`, not the agent's reply text. Use `chatStream()` for real-time responses.
8. **Self-hosted:** pass `baseUrl` to constructor. Default is `https://api.recursiv.io/api/v1`.
9. **`r.memory` rejects secrets.** Facts containing patterns like `sk_`, `api_key=`, `password=`, or private keys are rejected on write. Store secrets in environment variables, not memory.
10. **Memory is network-scoped.** Facts and decisions are isolated per network (tenant). Two teams on different networks cannot see each other's memory.
11. **`r.memory.context()` has a token budget.** Default is 2000 tokens (~8000 chars). Pass `max_tokens` to control how much context is returned.

Nostr replies and linked posts are saved in the same `protocols.nativeReplyHistory()`
feed after signed submission. Items with `type: 'nostr'` use
`protocols.nativeNostrReplyResult(id)` for a read-only check of the saved event and
its author's deletion requests on the recorded relay. Other history items use
`nativeReplyStatus(id)`. Do not turn an unknown result into a fresh preparation or
publication; history stores no signature, signing key or intent. Keep the acting
user/app-bound result IDs and discard UI state after an account switch. The last
read-back observation is separate from retained publication/deletion evidence.

Standalone public text posts: `prepareNativePost({ clientMutationId, text, accountIds })` → review → `submitNativePost(id, { approve: true, deliveryIds })`. Use `nativePostStatus(id)` / `nativePostHistory({limit,cursor})` for private durable outcomes and `prepareNativePostRemoval(id,{deliveryIds})` → `removeNativePost(id,{approve:true,removals:[{deliveryId,removalId}]})` for reviewed own-post removal. Check `publish_text`; no reply parent or audience override. Attach already-uploaded Minds images with `media: [{ url, alt?, width?, height?, mimeType? }]` (at most four JPEG/PNG/WebP/GIF, Minds-hosted HTTPS URLs only, a Mastodon GIF must be the only attachment) on accounts that also advertise `publish_media` — grants made before image scopes existed keep working for text and must be reconnected first. Always pass the member's own `alt`; an omitted one is sent empty, never invented. The receipt reports `media: { count, alt_missing }`. A photo-only post (no words) passes `text: ''` with at least one `media` item: Bluesky gets an empty text with the images, Mastodon a status with only the photos, each `alt` as its description; `''` without media or text of only spaces is refused, and replies always need text. Preserve mutation IDs, never create a new send to recover uncertainty.
Bluesky quote: accounts must advertise `quote`; call `prepareNativePost({clientMutationId,text,accountIds,quote:{protocol:'bluesky',nativeId:sourceAtUri}})`, review each returned quote/account/comment, then approve via the same submit method. The server binds the source CID and rechecks permissions before sending. Mastodon quote (0.7.71): `quote:{protocol:'activitypub',nativeId:statusUri}`; the member's server must support quote posts (API version 7) and allow it, else `quote_not_supported` / `reply_not_allowed`, never a link. Nostr quote: `prepareNativeNostr(id,{action:'publish',content,quote:{protocol:'nostr',nativeId:eventId}})` adds NIP-18 `q`/`p` tags and a `nostr:nevent` line; sign and submit as usual. No cross-network quote conversion. Public reads expose one filtered `post.quote` (`available` with `post`, or `unavailable` without source details). Available quotes may include `embeddedReferences`: exact standalone source-reference lines in the unchanged outer `text`. Omit them only when the quoted original is actually visible; retain them for unavailable or locally hidden quotes. Nostr references are decoded and matched by the server, without following relay hints.

Public post search (API/SDK 0.7.35): `const { data: page } = await r.protocols.searchPublicPosts({ protocol: 'nostr', query: 'open social', limit: 10 })`. Bluesky/ActivityPub require a selected `accountId` from `nativeSocialAccounts()` with `post_search`; older Bluesky grants must reconnect with consent. Open their results with `getConnectedSocialConversation({ protocol, accountId: page.readerAccountId, post: item.nativeId, readRef: item.readRef })` and pass the same accountId to `reportSource` for post reports. Nostr uses `getPublicConversation`. Pages report provider/observedAt and bounded coverage; no invented exhaustive or global search. Keep cursors paired with the exact owner, query, account, limit and connection revision. No writes, credentials or new ingestion are part of search.

Topic browsing can request `getPublicTrends({ protocol: "bluesky", includePreviews: true })`. Optional `SocialTrend.preview` is a real image-bearing post from that topic, never a generated illustration. The server samples at most eight posts for each of ten topics, with three concurrent reads and a shared 2.5-second deadline; missing images leave usable text topics. App moderation and user source controls filter previews on every request. Bluesky CDN image attachments, quote-with-media images, and unlabeled link-preview thumbnails are supported; omitted content retains the source link.

## Public media privacy

Private incoming reading choices (deploy supporting API first): `const {data}=await r.settings.getContentControls(); await r.settings.updateContentControls({version:data.version,hidden_networks:['nostr']});` Requires the member's own project-bound key. Re-read on 409 `stale_version`; mutations are not automatically retried. These choices filter supported post feed/list/search reads, not outbound identities or explicit direct-link access. Top-level category/master values are saved intent; render actual `effective` values and only the category actions advertised by `capabilities.category_filters`. Null effective values mean unavailable, never an active filter. A locked action or disabled master opt-out is not implemented safety customization. Optional constructor `surface:'web'|'android'|'ios'` requires the API's `x-recursiv-surface` CORS support before adoption. Missing/unknown platforms cannot loosen safety settings; no category choice overrides moderation or illegal-content floors. Restoring an incoming source is permitted on every platform and age band without loosening any safety rule.

App appearance (deploy the supporting API first): `const { data } = await r.settings.getAppAppearance(); await r.settings.updateAppAppearance({ expected_revision: data.revision, changes: { theme: 'dark', interfaceSound: false } });` Requires the member's own project-bound key; no user/project IDs in the body. Defaults are System, All Glass, Hyperminimal and Illuminated (the yellow bulb). New APIs return `values.customLogo` (null if absent); older APIs omit it. Upload a private static PNG with one patch `{ customLogo: pngDataUri, logoVariant: 'custom' }`: exactly 512×512 or 1024×256, source and sanitized PNG at most 128 KiB. Unsupported formats, animation, malformed/empty pixels and wrong dimensions are refused. Clear it with `customLogo: null`; Custom falls back to Wordmark. A 409 requires a fresh read and merge of pending explicit changes; hydration/no-op saves do not advance revision. Global `updateAppearance` is unchanged.

`await r.media.sourceApprovals({ projectId, sources: [{ host: 'www.youtube-nocookie.com', purpose: 'player' }] })` reads only cached judgments for a registered app. Respect `enabled`, `enforce`, exact `owned_hosts` and expiry; unknown/stale provider results remain pending. Static images/icons stay relayed. A judgment permits only its exact host and purpose, and does not establish downstream player hosts or tenant ownership.

`await r.linkPreview.get(url, { messageId }, { projectId })` opts a signed-in chat preview into expiring opaque image/icon URLs. Keep previews in a source/member-bound memory cache, refresh before `media_expires_at`, clear on sign-out, and never fall back to a bare private chat URL. Existing two-argument calls preserve their wire behavior.

AI privacy (0.7.197): `const {data: state}=await r.settings.getAiPreferences(); if(state.enforced.memory_facts) await r.settings.updateAiMemoryPreferences({memory_facts:false,version:state.version});` Personal hosts: `const {data}=await r.settings.getAiProviderRoutes();` display each route's disclosure and sources, then only after the member chooses it call `setAiProviderRoute({route_id:route.id,terms_version:route.version,terms_digest:route.digest,version:data.version})`. Clear with `route_id:null`; unknown, expired or mismatched terms never broaden routing. Until the operator sets `AI_PERSONAL_PROVIDER_ROUTES_ENABLED`, `routes` is empty and `can_choose_broader` false: offer no host choice then.

Private AI fact erasure (0.7.197): show the count from `r.settings.getPrivateAiMemoryState()`, then after the member confirms call `r.settings.clearPrivateAiMemory({confirmed:true,version:state.version})`; saving turns off and attributable private facts are erased together. Re-read choices/count after success. Chats, shared records and ambiguous app-less history remain.

Publication previews: `r.posts.publicationAssist({project_id, content, source_revision})` returns reviewable title/description suggestions without writing. Apply only if source_revision still matches the draft. It respects the network AI stop and requires posts:write plus project access. `publication_metadata.thumbnailSourceUrl` names the attached source of an attached thumbnail derivative, which remains safety-checked but is excluded from the gallery.

Content language: on a compatible API, `r.protocols.getPublicTrends({ protocol: 'nostr', preferredLanguage: 'de' })` (and public/shared trend-feed counterparts) prefers declared matches within the selected page without dropping other/unknown languages. The app resolves its saved account/device preference. `preferContentLanguage(items, 'de', post => post.publication_metadata?.language)` applies stable local recommendation ordering; avoid on following/search/date sorts. Source-index rows have no language yet.

Rendered discovery: `r.discovery.createProgressiveFeed({ networks, preferredLanguage: 'de' })` carries the choice through source sessions and final composition locally, without sending a new API field. Custom renderers pass `{ preferredLanguage }` to `composeFirstScreen` and argument six to `mergeDiscoveryArrival`; custom comparators use `discoveryModuleLanguageRank` after top/tier and before score. `createFeed` and `createPersonalFeed` accept the same choice.

Explicit member covers: read `r.settings.getContentControls()` WITHOUT new headers first; only a cover-capable application with `data.capabilities.cover_protocol === 'd18-v1'` may call `r.setContentPolicy({protocol:'d18-v1',surface:'web'})`, then reread controls. Never automatically opt in a generic SDK client. Verify `readContentSensitivity` and SHA256 of `contentSensitivityDigestInput(post)` with platform crypto before mounting content; malformed, mismatched or pending metadata covers the whole post. Metadata absent means legacy rules. `r.setContentPolicy(null)` clears negotiation without replacing credentials or auth/Sealed resources. Master and category choices are separate calls; master-off initially sets media/CW Warn and hate/order Show, master-on restores defaults. Hate has no Warn; profanity ordering follows the master, with no separate dial. Actual native labels and per-response v3 qualification constrain available actions; no global safe-off promise.

Human safety review (current own app staff key, supporting API required): `const {data}=await r.judgments.getSafetyReviewQueue({filter:'threat',limit:10});` then deliberately answer all three binary labels using `r.judgments.reviewSafety(item.judgment_id,{content_digest:item.content_digest,answers:{hate:0,threat:1,spam:0}})`. The answers above are an example, not defaults. A review preserves the original model row and records human provenance for current words. It creates no report/removal and calls no model. Reads/mutations are not retried automatically; refresh on 409. Content-control PATCH additionally requires a committed metadata-only audit receipt: disabled admission/failure returns 503 and rolls back the preference. Deployment flags, qualified rollback and audit-consumer delivery remain owner release gates.
