# 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 } from '@recursiv/sdk'
const r = new Recursiv() // reads RECURSIV_API_KEY from env
```

## Decision rules — pick the right resource

| 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 |
| File storage (photos, docs, media) | `r.storage` (buckets, presigned URLs) | `r.uploads` (legacy) |
| 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 |

**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`.

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.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`

### 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: 'home_bot_' + Date.now(),
  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
})

// 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`, `conversations`, `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: `gatePrompt({ messages, model? })`, `execute({ prompt, current_screen?, org_slug?, model?, locale?, attachments? })`

### 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')
```

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

---

## 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' },
  session.token,
)
// key: { key, id, name, prefix, lastFourChars, scopes, createdAt }

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

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

**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' },
);

// 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.

```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();

// 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' })
```

Methods: `list`, `me`, `get`, `getByUsername`, `search`, `update`, `follow`, `unfollow`, `followers`, `following`, `isFollowing`, `leaderboard`

---

## Social Primitives

### 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`, `deleteConversation`, `reactToMessage`, `editMessage`, `deleteMessage`, `markAsRead`, `unreadCount`

### r.realtime — WebSocket Chat Client

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

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

// 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()
```

Events: `onMessage`, `onMessageEdit`, `onMessageDelete`, `onTyping`, `onAgentThinking`

#### 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

```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 })
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`, `react`, `unreact`

### r.communities

```typescript
const { data: c } = await r.communities.create({ name: 'Denver Devs', slug: 'denver-devs', privacy: 'public' })
await r.communities.join(c.id)
```

Methods: `list`, `get`, `members`, `create`, `join`, `leave`

### 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`, `deleteConversation`, `reactToMessage`, `editMessage`, `deleteMessage`, `markAsRead`, `unreadCount`

### 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.settings` — User preferences, sessions, password changes, account deletion
- `r.billing` — Usage tracking, checkout sessions, portal sessions, metered billing
- `r.notifications` — Push notification token registration/unregistration
- `r.uploads` — Legacy media upload URLs (prefer `r.storage` for new projects)
- `r.github` — GitHub integration (getRepository, getTree, getFileContent, getCommits, createFromTemplate)
- `r.deployments` — Deployment management (prefer `r.projects.deploy()` for new projects)
- `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 (`r.email.send({ to, subject, html })`)
- `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` — Credits/wallet management
- `r.freeTier` — Free tier limits and status
- `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)
- `r.inviteCodes` / `r.inviteCodesAdmin` — Invite code management
- `r.organizationSettings` / `r.organizationSecurity` — Org configuration
- `r.protocols` — Protocol definitions
- `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()`

```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)
```

---

## 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 (`error.retryAfter` seconds) |
| `ConflictError` | 409 | Resource already exists |

Auto-retry on 429/5xx built in (exponential backoff, default `maxRetries: 2`).

### 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
  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 needed)
const r = new Recursiv({ anonymous: true })

// 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 stream = r.agents.chatStream(agentId, { message: 'Hello' })
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: not handling private communities
await r.communities.get('comm_xxx') // 404 if private and not a member

// ✅ RIGHT
try { await r.communities.get('comm_xxx') }
catch (e) { if (e.status === 404) { /* private 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.
