# @recursiv/sdk

**Infrastructure for AI agents and the apps that use them.** Databases, deploy, file storage, AI agents with memory, auth, and social primitives. One SDK. Zero dependencies.

## Install

```bash
npm install @recursiv/sdk
```

Node.js >= 18. ESM only (`import` works on 18+; `require()` needs Node >= 22, which can require ES modules). Zero runtime dependencies; realtime and the Next.js helpers each declare one optional peer, installed only if you use them.

## 60-second quickstart

```typescript
import { Recursiv } from '@recursiv/sdk'

const r = new Recursiv() // reads RECURSIV_API_KEY from env

// Provision a database
const { data: db } = await r.databases.ensure({ name: 'my-app', project_id: 'proj_1' })
const { data: creds } = await r.databases.getCredentials({ project_id: 'proj_1', name: 'my-app' })
console.log(creds.connection_string) // postgresql://...

// Create an AI agent
const { data: agent } = await r.agents.create({
  name: 'Assistant',
  username: 'assistant_1',
  model: 'anthropic/claude-sonnet-4',
  system_prompt: 'You are a helpful assistant.',
  organization_id: 'org_xxx',
})

// Stream agent responses
for await (const chunk of r.agents.chatStream(agent.id, { message: 'Hello!' })) {
  process.stdout.write(chunk.delta ?? '')
}
```

## What can you build?

| App type | Recursiv gives you | Example |
|----------|-------------------|---------|
| **AI-native app** | Database + AI agent + file storage + auth | Home maintenance tracker, AI CRM, smart inventory |
| **Autonomous agent** | Agent with its own Postgres, memory, and code execution | Research agent, data pipeline agent, ops bot |
| **Social platform** | Posts, communities, chat, profiles, follow graph | Team forum, community hub, social network |
| **Code playground** | Sandboxes, deploy, AI coding assistant, live preview | Vibe coding tool, learning platform, code editor |
| **Any app that needs a backend** | Auth + database + storage + billing | Skip Firebase/Supabase — one SDK covers it all |

## Choose the right primitive

| Your app needs... | Use this | Not this |
|---|---|---|
| Structured data (users, records, tasks) | `r.databases` | `r.posts` with JSON blobs |
| Social content, feeds, discussions | `r.posts` + `r.communities` | `r.databases` for feeds |
| File uploads (photos, docs, media) | `r.storage` | `r.uploads` (legacy) |
| User auth and API keys | `r.auth` | Raw fetch to auth endpoints |
| AI agent with a model | `r.agents` | Direct LLM API calls |
| Measure agents (evals, accuracy, cost) + audit trail | `r.evidence` | Ad-hoc logging |
| Run code in a sandbox | `r.projects.executeCode()` | External sandbox services |
| Deploy to production | `r.projects.deploy()` | Manual CI/CD |

## API overview

### Infrastructure
| Resource | Key methods |
|----------|------------|
| `r.knowledgeSources` | `notes({ project_id, note_id?, reference_url?, query?, limit? })` — source-attributed Community Notes whose current revision has human admission and verified per-use rights. Keyless for registered public apps; no live AI call. Upstream status is separate from Minds admission. Requires the supporting API (unreleased). |
| `r.knowledgeSources.localEvaluationNotes` | Same selectors over an explicit bounded local sample. Requires a keyless client with a loopback HTTP `baseUrl` and `inheritEnvironmentApiKey: false`. Returns `LocalKnowledgeEvaluationResponse` with `mode: 'local_evaluation'` and `admission.public_display: false`; no production route or approval. |
| `r.databases` | `ensure`, `create`, `list`, `getCredentials`, `query` |
| `r.envVars` | `set`, `list`, `delete` (values write-only; secrets masked on read) |
| `r.projects` | `create`, `deploy`, `executeCode`, `createSandbox`, `stopSandbox`, `deploymentLogs` |
| `r.personalBuilds` | `listProjects`, `prepare`, `get`, `admission`, `execute`, `previewEntry`, `stop`; explicit reviewed `approvals` / `approve` / `reject`; bounded `saveVersion`, read-only `saveVersionStatus`; immutable `publicationCandidate`, `publish`, `publicationStatus`. New-project `prepare` optionally accepts `new_project_budget: { daily_limit_usd: 1, enforced: true }` (above zero, at most $1; omit `project_id`), setting only its daily model-spend ceiling without funding, dispatch or provisioning. Omit the budget to keep a new draft unbudgeted; existing project budgets cannot be changed here. Staging pilot only, explicit human session bearer and server-approved owner/network/project/repository binding (disabled by default); paid personal admission, no app-key broadening. Requires the supporting API/package rollout. |
| `r.deployments` | Operator release coordination: `reserveRelease` (optional initial-run `coordinator_identity_token` after compatible API rollout), `getRelease`, `advanceRelease`, `startRelease`, `finishRelease`, `recoverRelease`; follow the [shared release guide](../../docs/deploy/shared-releases.md) |
| `r.storage` | `ensureBucket`, `getUploadUrl`, `getDownloadUrl`, `listItems`, `deleteObject` |
| `r.telemetry` | `productCounts` — app-bound first-party aggregate counts; reviewed event names and counts only, retained at most 30 days |
| `r.sandbox` | `execute` (anonymous, no API key needed) |

### AI Agents
| Resource | Key methods |
|----------|------------|
| `r.agents` | `create`, `update`, `chat`, `chatStream`, `stopChat` (0.7.221: stop the reply being written in a one-on-one chat; its partial text is saved with `metadata.ai.stopped`; await it before aborting the stream), `retryChatStream`, `grantProjectAccess`, `conversations` (each with a `name`), `createConversation` ("New chat" with your own personal agent; send its first message with `chatStream` and its `conversation_id`), `discover` (the app's agent directory: server search and sort, keyless-readable) |
| `r.e2ee` | `status`, `registerDevice`, `devices`, `revokeDevice` (`{ cascade }` to also revoke devices approved through it; 409 `has_dependents` otherwise), `requestResetCode` and `resetAccount` (reset encrypted chat with an emailed code where `status().accountReset`), `peerChanges` (contacts whose main device a reset replaced since a time), `publishKeyPackages`, `keyPackageStatus`, `claimKeyPackage`, `appendEvent` (`trust_change: true`: after a contact's reset, 409 `peer_not_joined` until this account added their new device), `events`, `acknowledge`, `conversations`, `requestStart` and `cancelStartRequest` (ask the other person to encrypt a chat when they have no device yet: a message with `metadata.kind` `e2ee_start_request`; the live ones are `ConversationDetail.encryption_requests`); device linking by scan: `createLink`, `link`, `scannedLink`, `approveLink`, `completeLink`, `linkProgress`, `cancelLink` (flag-gated E2EE v2 transport; its doorbell is `r.realtime.onE2eeEvent`, which carries a small message's stored ciphertext to the owner's own sockets; link and device changes arrive on `r.realtime.onE2eeLink` and `onE2eeDevices`, a contact's reset on `onE2eePeer`) |
| `r.brain` | `sendMessage` |
| `r.commands` | `execute`, `gatePrompt` |
| `r.projectBrain` | `tasks`, `decisions`, `milestones`, `completeTask`, `usage`, `getSettings`, `updateSettings` (owner-enabled daily budgets) |
| `r.metrics` | `get`, `forOrg`, `forProject`, `children`, `definitions` — the KPI ledger per tier (platform, network, org, project): numbers with definitions, status, and confidence |

### Identity & Auth
| Resource | Key methods |
|----------|------------|
| `r.auth` | `exchangeCustomerAppCode` (platform-hosted sign-in, project key only); `signUp`, `signIn`, `signInWithUsername`, `getSession`, `signOut`, `createApiKey`, `forgetPassword`, `resetPassword`; two-factor: `enableTwoFactor`, `verifyTwoFactor`, `disableTwoFactor`, `regenerateTwoFactorBackupCodes`, `requestTwoFactorEmailCode`, `completeTwoFactorSignIn`; OAuth consent: `exchangeSessionForCookie`, `getOAuthClientInfo`; cutover: `legacyHandoff` (a legacy Minds session for a session here; throws `LegacyHandoffError`) (session calls use explicit Bearer auth with a native/server Cookie fallback) |
| `@recursiv/sdk/next` | `createRecursivAuth` — cookie-session server auth for Next.js App Router (see below) |
| `r.users` | `me`, `get` |
| `r.organizations` | `create`, `members`, `addMember`, `invite` |
| `r.humanAsks` | `create`, `list`, `queue`, `dismiss`, `reassign` — an agent's ask for a person, optionally linked to the member, post, report, Boost, withdrawal or chat it is about (`subject_type`, `subject_id`) and marked `urgent`; `queue` lists every open ask of the organization oldest first for its owners and admins; `dismiss` and `reassign` take an org owner or admin or the addressee, never an agent key. Deploy the supporting API before client adoption. |
| `r.audit` | `list`, `export` — an organization's audit log for its owners and admins (newest first, cursor pages; CSV or JSONL export of up to 90 days and 10,000 rows) |
| `r.profiles` | `me`, `get`, `search`, `mentions`, `follow`, `unfollow`, `followers`/`following` (rows carry `is_following`, `follows_you`), `followingIds`, `block`, `unblock`, `blocked`, `mute`, `unmute`, `muted` |

### Social
| Resource | Key methods |
|----------|------------|
| `r.posts` | `publicationCapabilities` (deployed publishing contract), `publicationAssist` (explicit draft suggestions), `create` (optional `title` / `publication_metadata`), `update`, `list`, `publicList({ projectId, limit?, offset? })` (keyless newest native public posts; camelCase fields, no ranking or pagination metadata), `get`, `getMany(ids)` (up to 25 posts by id per request, no thread; a `Map` of each id's post or `NotFoundError`; 0.7.77), `resolveLegacy(guids)` (legacy Minds post guids to `{ guid, id }` for posts the member may open, up to 200 per request; 0.7.206), `liked`, `bookmarked`, `bookmark`, `unbookmark`, `search`, `replies`, `react` |
| `r.search` | `query` (blended search in sections; a thin answer steps down the search ladder, each item labelled `via`, the answer's `ladder` says how); `history`: `list`, `add`, `remove`, `clear`, `merge` — the member's recent searches and the people, groups and categories they opened from search, synced across devices (0.7.199, where `network.getConfig()` advertises `capabilities.search_history`). A visitor's search posts (`publicDiscovery.search`, `PublicSearchPage`) may carry `picture` (`SearchPicture`, 0.7.162): `kind`, `textHeavy`, `tileQuality` (0-3) and an optional `focal` point, layout hints from a background read of pictures the floors cleared, absent until judged and never a safety signal; on the `deep` stage `picture.showsQuery` (0.7.190) says whether the picture itself shows the query, absent unless the operator turned on `SEARCH_PICTURE_SUBJECT`. Both answers may carry `video_lead` (`SearchVideoLeadEntry[]`, 0.7.173): every clip in the order to lead and play it, the most about the words first, then the freshest, a Minds member's clip winning a tie |
| `r.bookmarks` | `save`, `unsave`, `posts`, `list`, `keys`, `merge` — the member's saved posts, open-network posts and articles, synced across devices; `collections`: `list`, `create`, `update`, `remove`, `add`, `removeItem`, `items`, `posts` — private named collections of saves (0.7.68, where `network.getConfig()` advertises `capabilities.bookmark_collections`) |
| `r.feeds` | `top` (what the member is most likely to engage with, rotated by what they saw, with open-network lanes and the lead story), `stories` (the story tail), `publicTop` (a visitor's top, keyless and edge-cacheable), `firehose` (0.7.195: the member's live stream of the most engaged, viral and breaking posts, never repeated in a session) |
| `r.alive` | `tick({ followingSince?, posts?, thread? })` (0.7.193; the member's own app key, `users:read`; 404 `alive_disabled` until the operator sets `ALIVE_TICK_ENABLED`): whether anyone the member follows posted since the newest row they hold (`following.fresh`), the current counts of up to 30 posts on screen they may see, the new replies under the open post (their own left out), and `nextAfterMs` (when to tick next). Asked once; at most 4 a minute |
| `r.communities` | `create`, `join`, `search`, `members` |
| `r.chat` | `send`, `dm`, `createGroup` (`encrypted: true` for an end-to-end encrypted group, 0.7.59), `messages` (cursor paging), `acceptRequest`, `declineRequest`, `mute` / `unmute` (the caller's own push mute of one conversation, served as `muted_until`, 0.7.196), `setPushLevel` (a group chat's pushes: `'mentions'`, the default, for replies to the caller and @mentions of them, or `'all'`, served as `push_level`, 0.7.196), `leave`, `deleteConversation`; a private group's admin: `addMembers`, `removeMember`, `updateGroup` (0.7.59); photos and voice notes: `uploadAttachment`, `signAttachments` (private chat storage, 0.7.82) |
| `r.tags` | `create`, `list` |
| `r.signals` | `batch` (up to 100 engagement signals, such as views, dwell and hides, for the member's own ranking; `keepalive` for a page-leave flush), `record` (one signal) (0.7.71); `clearViewingHistory` ("Clear my viewing history"); typed `SignalMetadata`, an id per event so a retry is stored once, and `duplicates`/`limited`/`rejected` in the answer (0.7.93) |
| `r.privacy` | `capabilities` (the platform privacy facts the deployed API's build enforces, and its commit); pair with `@recursiv/sdk/privacy` (`PRIVACY_FACTS`, `isFactLive`, `liveFacts`) (unreleased) |
| `r.reports` | `create`, `list`, `resolve`, `dismiss`, `signAttachments`; automated reviewers pass `{ actor_type: 'ai' }` to both `resolve` and `dismiss` so human-only cases stay protected. 0.7.152 `sealed_answer` reports target the key's exact project id and need `posts:write` on a human-owned, non-agent project key. This intake does not recheck live app membership; the Sealed gateway additionally does. Review applies no account enforcement. Every answer request, including a join, spends report budget. `create` returns the report `id`, optional `existing`, and `details_kept` for an answer: false means its reason was kept but its text did not fit in full. Deploy supporting API before client adoption. |
| `r.sealed` | Sealed mode: `config`, `attestation`, `send`; for web Sealed's frame (unreleased): `frameToken` (a short-lived `sft_` credential for the frame), `me` (the member's own age view and Sealed adult setting), `report`; pair with `@recursiv/sdk/sealed` (the resource alone) and `@recursiv/sdk/sealed-frame` (below) |
| `r.curator` | `today` (World Today; a world story can carry `story_key` and `discussion`, its count across networks), `storyPosts` / `memberStoryPosts` (one page of a story's posts, keyless or under the member's key), `storyPostPages` (walk every page), `forYou`, `run`, `refreshIfStale`, `seedDeck` |
| `r.media` | Creative jobs: `capabilities`, `quote`, `createJob`, `listJobs`, `getJob`, `findJobByIntent`, `cancelJob`, `getJobAsset`, `deleteJob`. Member billing requires a confirmed quote and stable paid-intent ID; explicit operator pilot is separate. Private originals and explicit attachment; supporting API/configuration required. |
| `r.uploads` | `uploadMedia` — upload post/chat bytes end to end (long audio/video in parts), awaiting clearance when the API returns `scan_required`; `getMediaScanStatus(key)` (uploader's state), `listMediaScanHolds(projectId)` (live project-admin metadata; synthetic staging pilot, supporting API required); `startMediaMultipartUpload`, `signMediaMultipartParts`, `completeMediaMultipartUpload`, `abortMediaMultipartUpload` |
| `r.judgments` | Jev's labels of a post (0.7.71): `get({ kind, id })` (the author and staff get every judgment and the safety verdict; other members the category and the compass band in words; `status: 'unavailable'` is returned, not thrown), keyless `getPublic(projectId, { kind, id })` (the category only), `dispute(judgmentId, { question_key, proposed, note? })` (the author's dispute is an appeal; a repeat returns `existing: true`), staff `review(judgmentId, { outcome, proposed?, note?, apply_to_shared? })` (sent once; 202 `awaiting_reviewer` until a compass label's second reviewer, or an agreeing Jev re-judge; `isJudgmentSharedWordsError` for the 409) |
| `r.video` | `entitlement` (may the caller publish video, and how much is left), `createUpload`, `renewUpload` (the creator's fresh TUS credentials for the same video, with `createUpload`'s `resumeGrant`, so a resume past the hour continues it; 0.7.63), `getStatus`, `getPlaybackToken` |

Source builds advertise `r.uploads.supportsMediaRequestScope === true` before relying on
`uploadMedia`'s optional `requestScope: <T>(request: () => Promise<T>) => Promise<T>`.
Invoke the callback synchronously once, propagate its result and add no retries; every SDK
API operation, including later scan polls and multipart operations, re-enters that scope.
Source reads and signed PUTs still use `fetchImpl`; in-flight abort requires an existing
scope-aware transport. Omission preserves existing behavior. This hook is not in published 0.7.210.

### Platform
| Resource | Purpose |
|----------|---------|
| `r.settings` experience | `getExperience`, `updateExperience({ version, goals?, interests?, avoid_categories? })`, `undoExperience({ version })` — explicit per-app starting choices with a real category Discover link; requires the member's own project-bound key (unreleased). Does not change whole-feed ranking or privacy settings. |
| `r.settings` app appearance | `getAppAppearance()`, `updateAppAppearance({ expected_revision, changes })` — private account/project presentation with atomic revisions (deploy supporting API first). Defaults: System, All Glass, Hyperminimal, Illuminated (the yellow bulb). `customLogo` is a private static PNG data URI: exactly 512×512 or 1024×256, at most 128 KiB; check that the read response has the field before offering upload on older APIs. Save it with `logoVariant: 'custom'` in one patch, or clear with `customLogo: null`. A 409 needs a fresh read and merge. Global `updateAppearance` is unchanged. |
| `r.settings` content controls | `getContentControls()`, `updateContentControls({ version, hidden_networks })` — private member/app reading choices with revision checks. Hides incoming sources on supported feed/list/search reads, without changing identities, sharing or explicit direct-link access. Render category actions only from `capabilities.category_filters`; unsupported safety dials stay locked. A stale save requires a fresh read. Optional SDK `surface` sends `x-recursiv-surface` only to the API; deploy its CORS support before adopting that option. |
| `r.judgments` safety review | `getSafetyReviewQueue({ filter: 'threat' | 'all', limit?, cursor? })`, `reviewSafety(judgmentId, { content_digest, answers: { hate: 0 | 1, threat: 0 | 1, spam: 0 | 1 }, note? })` — own current human app staff only. Records all three labels for the exact current words; no report, removal or model call. Mutations are not retried; stale or already reviewed returns 409. |
| `r.settings` | AI memory (0.7.197): `getPrivateAiMemoryState`, `clearPrivateAiMemory` (confirmed action turns saving off and clears attributable private facts atomically; pass the preferences version), `getAiPreferences`, `updateAiMemoryPreferences` (offer only enforced keys); explicit reviewed personal AI hosts (0.7.197): `getAiProviderRoutes`, `setAiProviderRoute` (acknowledge exact terms, `route_id:null` restores collection denial; no routes and `can_choose_broader: false` until the operator sets `AI_PERSONAL_PROVIDER_ROUTES_ENABLED`). User preferences (including app-scoped content choices; per-kind notification settings in `notifications.channels`, set one kind with `updateNotifications({ channels: { post_reaction: { push: false } } })`, 0.7.72; quiet hours and the push pause with `updateNotifications({ quiet_hours: { start: '22:00', end: '07:00' }, time_zone, paused_until })`, read back as `notifications.quiet_hours` and `notifications.paused_until`, 0.7.196; message previews hidden from every push about a chat with `updateNotifications({ message_previews: false })`, read back as `notifications.message_previews`), sessions (`revokeOtherSessions` keeps this device), connected AI clients (`listConnectedApps`, `disconnectApp(client_id)`), password management, email change (`requestConfirmationCode` for accounts with no password), deactivation (`disableAccount({ password })`, 0.7.71; 404 on an API that does not serve it) |
| `r.billing` | Usage tracking, subscriptions, checkout |
| `r.appSubscriptions` | Consumer app plans: `checkout`, `status`, `createPortalSession`, `previewTierChange`, `changeTier`; member AI funding (disabled by default): `aiFunding`, `setAiPayg` for the member's balance and explicit capped paid-usage consent. Monetary microcents are decimal strings; $1 = 100,000,000. |
| `r.boosts` | Promoted posts: `create`, `mine`, `balance`, `pause`, `resume`, `cancel`, `recordEvent`, `stats`, `topup`, `confirmTopup`, `topupWithTokens`; a feed page's boosts `slots` / `publicSlots` (splice with `spliceBoostSlots`); admin `listPendingReview`, `review`, `grant` |
| `r.wallet` | Wallet, MINDS tokens (`getTokenBalance`, `getTokenLedger`), a wallet the member holds linked by signature (`createLinkNonce`, `linkWallet`, `listLinkedWallets`, `unlinkWallet`), USD payouts (`getPayouts`, `startPayoutOnboarding`, `payoutLoginLink`) |
| `r.notifications` | Notification stream (`list`, `unreadCount`, `markAsRead`, `archive`, `markAllAsRead`; `category: 'mentions'` for mentions and replies only, 0.7.72; `unreadCount` stops at 1,000 and sets `capped` when there may be more, 0.7.219) and push tokens |
| `r.github` | GitHub integration |
| `r.integrations` | External service connections |
| `r.admin` | User management, stats, content reports (`listReports`, `resolveReport`, `dismissReport`), a moderator's hold on one member's native network (`holdNativeNetwork(userId, network, { retract? })`, `liftNativeNetworkHold(userId, network)`; an admin key bound to the member's app) |
| `r.moderation` | Moderation actions: `publicLog`, `mine`, `appeal`; staff `apply`, `resolveAppeal`, `list({ target_type?, target_id? })` (one target's recorded actions, newest first, at most 100; none named = the network's latest; 0.7.74) and `reverse(actionId)` (sent once: a repeat answers 404 `action_not_found`; 0.7.74); agent grants `listAgentGrants`, `grantAgent`, `revokeAgent` |
| `r.trust` | The signed trust log (0.7.96; 404 until the operator turns on `TRUST_LOG_PUBLIC_READS`): keyless `keys()` (every key that ever signed it), `mine({ before?, limit? })` (`users:read`: the caller's own signed events with the server's check `verified`). `r.moderation.publicLog` then carries `trust_log` on each action (`status`, and where the signed decision and reversal sit: `chain`, `seq`, `key_id`, `occurred_at`, `verified`). No read carries a hash or a signature |
| `r.dispatcher` | Task queue, claims, signals, outcomes, webhooks |
| `r.goals` | Org goals with task rollups (group dispatcher tasks) |
| `r.media` | `sourceApprovals({ projectId, sources })` — cached public host/purpose judgments and exact owned hosts; no caller-triggered provider fetch or inference. Image/icon requests stay relayed; direct players use approved, unexpired decisions once enforcement is active |
| `r.linkPreview` | `get(url, source?, { projectId })` opts into expiring relayed image/icon capabilities; refresh before `media_expires_at`, and preserve source authorization. `get(url)` — a public link's Open Graph card (`data: null` when it has none). For a chat link pass `{ messageId }` or `{ conversationId }` 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 the caller wrote it in that conversation, else `refused: 'ai_link'`. A source with no id rejects (`ValidationError`). Not in encrypted chats: the server cannot read them, so leave `source` out there and apply the app's own rule |
| `r.protocols` | Private Minds safety: `sourceControls` (current enablement and saved choices; filter with `control`, each item may carry a `display` label), `setSourceControl`, `onSourceControlChange`, `reportSource`. Delegated accounts: `nativeSocialAccounts`, `startNativeSocialConnection`, `finishNativeSocialConnection`, `disconnectNativeSocialAccount`. Native follows: `nativeFollowStates` (every connected account's state for one source, one read), `nativeFollowState`, `prepareNativeFollow`, `submitNativeFollow`, `nativeFollowStatus` (native following or pending approval, distinct from a Minds feed subscription; preserve the complete signed Nostr list). Native reposts and undo: `nativeRepostState`, `prepareNativeRepost`, `submitNativeRepost`, `nativeRepostStatus` (public posts, explicit approval, connected account, no uncertain retries). Native likes and unlikes: `nativeLikeState`, `prepareNativeLike`, `submitNativeLike`, `nativeLikeStatus` (connected authority, app enablement and explicit approval; resume pending actions instead of duplicating them). Reviewed replies and optional linked posts: `prepareNativeReply`, `submitNativeReply`, `nativeReplyStatus`, `nativeReplyHistory`, `prepareNativeReplyRemoval`, `removeNativeReply` (require deployed API support and app enablement). Keyless shared post links: `sharedNetworks(projectId)`, `getSharedConversation(projectId, { protocol, post, readRef?, replies?: 'none' })` (`replies: 'none'`, 0.7.78: the post alone for a card, with `repliesStatus: 'not_requested'`; `getPublicConversation` and `getConnectedSocialConversation` take it too). Member public reading: `searchPublicPosts` (selected account required for Bluesky/ActivityPub; public Nostr search), `getConnectedSocialConversation` (preserve result readerAccountId/readRef), `publicNetworks`, `searchPublicProfiles`, `getPublicProfile`, `getPublicAuthorFeed`, `getFollowingFeed`, `getPublicConversation`, `getPublicTrends`, `getPublicTrendFeed`; a Fediverse community's newest threads, read-only (0.7.109): `getOpenGroupThreads({ group, limit?, cursor?, compass? })`, `group` being the `actor` of a groups read's `open_network` entry; radar stories: `getPublicRadarStory` (one story by id with its posts; one that left the radar within its minimum lifetime, or within the last half hour, still answers live with `liveUntil` and the story that continues it; one that has left for longer comes with its archived copy and the live story it continues as; the id may be a World Today edition story's, and the answer then names it in `editionStory` under the story's radar id; a story a World Today story seeded carries `volume`, the first page of the posts that story counts across Minds and the open networks, whose `cursor` goes on with `curator.storyPosts` or `curator.memberStoryPosts`), keyless `getSharedRadarStory(projectId, { cluster })` and `getSharedRadarPosts(projectId, { cluster })` (keyless reads carry images and videos only from outlets and members marked `visitorMedia`; signed-in reads keep all media, so a share card uses only those); keyless famous accounts (0.7.220): `getSharedPopularProfiles(projectId, { protocol, limit?, cursor?, category?, compass? })`, the members' `getPublicPopularProfiles` list in the same ranking for a signed-out page, under the app's moderation with no adult accounts and nothing of any viewer (no `subscription`, no `seed`), cacheable for 5 minutes (an older API answers 401 `missing_api_key`); keyless category surface (0.7.165): `getSharedCategorySurface(projectId, { category, compass? })`, a category's `stories`, `network` and `clips` for a signed-out page in one read under every visitor floor (`compass` `all` or `hide`, or a side or Mix where the visitor catalog lists `compass_sides`, answered `unavailable`; never people or groups); the Viral read (fastest-moving posts across Bluesky, the Fediverse, Nostr and Minds, each against its own network's pace; 0.7.59): `getPublicViral({ network?, category?, media?: 'video', limit?: 5 | 10 | 20 | 40, cursor?, compass? })` under the member's key and keyless `getSharedViral(projectId, params)` (visitors: `compass` `all` or `hide` only; a visitor's `media: 'video'` read can carry items whose video the server withheld, so filter with the exported `viralItemHasVideo` before a video player; `item.post` narrows on `item.protocol`). `status: 'off'` resolves with no items until the app enables the read, and `getSharedViral` also resolves an older API's 401 `missing_api_key` as off; `getPublicViral` throws every 401 and 403, so a session failure is never read as off; private app subscriptions: `listSubscriptions`, `subscribeToProfile`, `unsubscribeFromProfile`, `onSubscriptionChange`. `list` returns bounded adapter `maturity`, `limitations`, and exhaustive `supported`/`planned`/`unsupported` implementation capabilities (not provider health or enablement); settings, candidate refresh/status, search, and read-only quarantined candidate review via `listCandidates` / `getCandidate` |

Full reference: see [llm.md](./llm.md) (ships with this package) or the type definitions in `dist/`.

### Quarantined protocol candidates

`r.protocols.listCandidates({ protocol?, limit?, cursor? })` and
`r.protocols.getCandidate(id)` read unpublished candidates, not feed posts.
Both require an `admin`-scoped, project-bound key, a live admin role, and
existing project-admin access. App/network scope is not a caller parameter.
These GET methods do not collect content, update settings, or publish anything.

Lists return `{ data, meta: { limit, has_more, next_cursor } }` with no offset;
the API defaults to 20 rows and permits at most 50. Details return `{ data }`.
Render candidate `content` as plain text and respect
`content_truncated`. Safe source IDs are preserved byte-exact. A null
`external_id` means unsafe or malformed provenance was withheld; an author's
`native_id` may likewise be absent or withheld. Do not invent replacement IDs.
API failures, including routes absent from an older
deployment, throw the normal SDK errors; do not present them as an empty queue.

### Ingestion health (0.7.71)

`r.protocols.ingestionHealth()` reads `GET /protocols/ingestion/health`: counts-only
health for the key's app, so an operator can see whether each ingestion lane reaches
done or dies part way without SQL. It needs the same key and authority as the
candidate reads, but not the `content_intelligence_admin` binding. It sends no query
(the API rejects one). Per lane: `jobs` counts, the open job (`current`: its
`position`, `pages_committed`, `consecutive_failures`, `lease_expired`,
`starved_since`), `last_done_at`, 24-hour `activity` by reason, and `dead_letters`
by reason and position; plus open or counting `circuits`. A section that does not
answer reads as null and is named in `unavailable`; errors throw.

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

## Projects & deploy

```typescript
// Deploy to production
const { data: deployment } = await r.projects.deploy('proj_1', {
  branch: 'main',
  type: 'production',
})

// Execute code in a sandbox
const { data: result } = await r.projects.executeCode('proj_1', {
  code: 'console.log("hello")',
  language: 'typescript',
})
console.log(result.output) // "hello\n"

// Get deployment logs
const { data: logs } = await r.projects.deploymentLogs('proj_1', deployment.id)

// Start/stop sandboxes
await r.projects.createSandbox('proj_1')
await r.projects.stopSandbox('proj_1')
```

Shared API/frontend releases use `r.deployments` with a project-bound operator key carrying `projects:read` and `projects:write`. Read an existing reservation with `await r.deployments.getRelease(releaseId, projectId)`. Follow the [shared release guide](../../docs/deploy/shared-releases.md) for phase transitions, health proof and recovery; uncertain operations keep ownership held.

## AI agents

```typescript
// Create an agent
const { data: agent } = await r.agents.create({
  name: 'Research Bot',
  username: 'researcher',
  model: 'anthropic/claude-sonnet-4',
  system_prompt: 'You help users find information.',
  tool_mode: 'autonomous',
  organization_id: 'org_xxx',
})

// Chat (async — agent responds asynchronously)
const { data: reply } = await r.agents.chat(agent.id, {
  message: 'What are the latest trends in AI?',
})
// reply: { message_id, conversation_id, content, created_at }

// Stream (token-by-token)
for await (const chunk of r.agents.chatStream(agent.id, {
  message: 'Tell me more about transformer architectures',
})) {
  process.stdout.write(chunk.delta ?? '')
}

// A cancellable safe ask: personalAgentId is the member's existing personal agent.
// No tools or memory, in their app-scoped Asks thread.
// Call stop.abort() on Close/Stop. The server may keep the partial reply and charge for work already done.
const stop = new AbortController()
for await (const chunk of r.agents.chatStream(personalAgentId,
  { message: 'Explain this post', turn: { safe: true, purpose: 'minds_eye' } }, { signal: stop.signal })) {
  showText(chunk.delta ?? '')
}
// React Native: chatStreamText(personalAgentId, input, { signal: stop.signal }).
// agents.supportsMindsEye verifies client support only; older servers reject purpose before storing a turn.
// Minds Eye selects Grok within existing app limits; it never changes the saved model or falls back to a different model.
// A retry uses the original ask's saved purpose; supplying a different turn purpose cannot change or relabel it.
// With no signal, existing stream/disconnect behavior is unchanged.

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

## Social primitives

```typescript
// Posts
// Title/metadata publishing checks the serving API's capability before any write.
// Native metadata fields: version:1, shareTitle, description, thumbnailUrl,
// media:[{url,alt,caption}], transcript, language. Null clears; omitted fields stay.
const { data: post } = await r.posts.create({
  content: '# Shipped!\n\nNew deploy is live.',
  content_format: 'markdown',
  community_id: 'comm_abc',
})

// Post/chat media: the SDK obtains the signed URL, PUTs the bytes, checks
// every response, and awaits any required scan clearance before returning the public URL.
const mediaUrl = await r.uploads.uploadMedia({
  blob: imageFile,
  contentType: imageFile.type,
})

// Chat
const { data: dm } = await r.chat.dm({ user_id: 'user_abc' })
await r.chat.send({ conversation_id: dm.id, content: 'Hello!' })

// Communities
const { data: community } = await r.communities.create({
  name: 'TypeScript Devs',
  slug: 'ts-devs',
  privacy: 'public',
})
```

## Real-time Chat (React / React Native)

The SDK provides a ready-to-use WebSocket hook for building chat applications without REST polling.

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

const r = new Recursiv()

function ChatRoom({ conversationId }) {
  const { isConnected, error, sendTyping, sendMessage } = useChat(r, {
    conversationId,
    onMessage: (msg) => {
      console.log('New message received:', msg.text)
    },
    onTyping: (evt) => {
      console.log(`${evt.userName} is typing...`)
    },
    onAgentThinking: (evt) => {
      console.log(`Agent ${evt.agentName} status: ${evt.status}`)
    }
  })

  // Automatically connects, joins room, and listens to events!
  
  return (
    <div>
      {isConnected ? '🟢 Connected' : '🔴 Disconnected'}
      <button onClick={() => sendMessage('Hello world!')}>Send</button>
    </div>
  )
}
```

## Customer-app password auth

On a shared Recursiv API hostname, pass the customer app's project when signing
in and minting a per-user key. The SDK forwards that project on the password
sign-in request so the server resolves same-email users in the app's network.

```typescript
const anonymous = new Recursiv({ anonymous: true, baseUrl })
const { apiKey, user } = await anonymous.auth.signInAndCreateKey(
  { email, password },
  {
    name: 'my-app',
    scopes: ['posts:read'],
    projectId: 'prj_xxx',
    expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString(),
    consumeSession: true,
  },
)
```

`consumeSession: true` atomically retires the temporary login session as the
API key is minted. Use it when the customer app stores and authenticates only
with the returned API key; omit it for flows that still need the cookie session.
`createApiKey(input, sessionToken)` requires a signed-in session. Its optional `expiresAt` must be in the future and at most one year away. The creation receipt includes the stored `projectId`, `networkId` and `expiresAt`; validate these bindings before storing an operator key, and keep the returned key out of logs.

## Next.js server auth (`@recursiv/sdk/next`)

Cookie-session helpers for the App Router (Next 14 and 15). Each user signs in once, gets a **project-scoped per-user API key** in an httpOnly cookie, and every request acts as that user — no platform key on the server.

This subpath uses the optional `server-only` peer to keep its exports out of Client Components. Install it alongside the SDK in Next.js apps: `npm install server-only`.

```typescript
// src/lib/recursiv.ts (server-only module)
import 'server-only';
import { createRecursivAuth } from '@recursiv/sdk/next';

export const auth = createRecursivAuth(); // RECURSIV_PROJECT_ID from env

// src/actions/auth.ts ('use server')
export async function signIn(input: { email: string; password: string }) {
  const { user } = await auth.signIn(input); // mints key + sets session cookie
  return user;
}

// any server component or route handler
const sdk = await auth.getSdk(); // Recursiv acting as the signed-in user
const { data: me } = await sdk.users.me();
```

Route handlers building their own response pass a cookie writer, and the cookie contract (name, lifetime, attributes) is fully configurable:

```typescript
const auth = createRecursivAuth({ cookie: { name: 'myapp_session', maxAge: 60 * 60 * 24 * 90 } });

export async function POST(req: NextRequest) {
  const res = NextResponse.json({ ok: true });
  await auth.verifyOtp(await req.json(), { response: res.cookies });
  return res;
}
```

Server-side only — the `server-only` guard fails the build if it's ever imported into a client component. Keep it out of `middleware.ts` as well (edge bundle size); gate routes with a plain cookie-presence check on a shared constant.

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

Two pure functions for asking an assistant about a post: no network, clock, randomness or Node-only API, so a server, a React Native phone and a web app build the same model input from the same data (unreleased).

```typescript
import { buildSubjectBundle, renderBundleForModel } from '@recursiv/sdk/assistant'

const { bundle, refused, excluded } = buildSubjectBundle({
  mode: 'standard',                       // or 'sealed'
  asker: { id: me.id, blocked_ids, muted_ids }, // a server also passes blocked_by_ids
  post, parent, quoted, replies,          // data you already hold; nothing is fetched
})
if (!bundle) return showUnavailable()     // make no model call; never show the asker `audit`
// boundary: fresh per call, e.g. 32 hex digits from crypto.getRandomValues
const { system, user, references } = renderBundleForModel(bundle, 'explain', { boundary })
```

- `buildSubjectBundle` leaves out posts and replies whose authors turned asks off (`ai_ask_allowed`: `'all'`, `'sealed_only'` read only in Sealed, `'off'`), authors the asker blocked or muted and authors who blocked the asker, known-minor authors (unless the asker is the author), posts under a child-safety hold and posts a moderator suppressed. Pictures go as alt text and the stored caption only, never bytes or addresses. Hidden text (zero-width, bidi and tag characters, HTML comments and hidden elements, invisible markdown) is stripped, and the top 20 replies and every field are capped. Every safety flag fails closed, and an id list it cannot read throws.
- `known_minor`, `child_safety_hold`, `assistant_suppressed`, media `held: true` and `blocked_by_ids` are server-side inputs: never send them to another member's client (leave held media out of that payload, and the post's stored caption, `ai_caption`, whenever any of its media is held: the caption may describe the held picture, and a client builder cannot see media it was never sent). A client builder passes each post's `assist_readable` (`'all'`, `'sealed_only'`, `'none'`), the server's verdict for that viewer, which does not say why. The one exception is a picture's `held: false`, the payload's "not held" mark beside `checked_at` (below).
- `refused` and `excluded` are what the asker may be told: blocks, minors, holds and suppression all read `'unavailable'`, so they never say who blocked the asker, whose account is a minor's or that a post is held. `audit` holds the detail for the server's log only.
- `renderBundleForModel(bundle, intent, { boundary, language? })` spotlights the bundle for `explain`, `summarise`, `fact_context`, `translate` or `describe`: the content sits between two lines carrying your per-call random boundary, every member-written line starts with `| `, each item is labelled with its id and handle, and `references` lists the only ids, handles and addresses an answer may use (never a picture address; write them only as plain links, never render an image the model wrote). Render only bundles built from your own reads.

#### Post pictures as pictures

A post picture's `checked_at` is the time this read found it passed Minds' current checks (recursiv#5012): visibility, holds and adult labels. Where the server's media-safety floor is on (CONTENT_MEDIA_SAFETY_ENABLED), one of those labels is a vision model's stored verdict that the picture is not suggestive; no image classifier is run for `checked_at` itself. No hash bank (NCMEC, StopNCII) and no CSAM classifier is among the checks.

Pass each media item's `id`, the payload's `checked_at` and its `held: false` mark into `buildSubjectBundle`, then list the candidates, run your own checks on every one of them, and render with the ones that passed:

```typescript
import { type BundlePicture, bundlePictures, renderBundleForModel } from '@recursiv/sdk/assistant'

const max = Math.max(0, 3 - phonePictures.length) // 3 pictures per message in all; the composer caps phone pictures at 3
const listed = bundlePictures(bundle, 'explain', { now: Date.now(), max })
// Your checks load each listed picture from your image cache (never fetched), prepare it as sealed-full-scope-v1 2.2
// says (longest side at most 1536 px, re-encoded as JPEG, metadata stripped), check the prepared bytes, and return the
// pictures that passed, each with the prepared bytes they checked. Send those bytes: a second read of the cache could
// return a picture nobody checked, and the raw cached file still carries its metadata.
const passed: { picture: BundlePicture; prepared_jpeg: string }[] = await runYourPictureChecks(listed)
const same = (a: BundlePicture, b: BundlePicture) =>
  a.item_id === b.item_id && a.media_id === b.media_id && a.number === b.number
const { system, user_parts, pictures } = renderBundleForModel(bundle, 'explain', {
  boundary,
  pictures: {
    now: Date.now(), // a fresh clock: a picture that went stale during your checks goes as alt text
    max,
    allowed: passed.map((x) => x.picture),
    cached: (p) => passed.find((x) => same(x.picture, p))?.prepared_jpeg ?? null,
  },
})
// user_parts: the opening line and the content's text, one { type: 'image_url', image_url: { url: 'data:image/jpeg;base64,…' } }
// per picture, then the closing line and the task. Send `system` and `user_parts`: with a picture attached, `user` and
// `text` name it but cannot carry it.
```

- A picture goes as a picture only when it is on the asked-about post, its parent or its quote (never a reply's), its input says `held: false` exactly (2.1: "checked within the last 24 hours and not held"; absent or null is not enough, since a phone cannot see why media is held), its `checked_at` is under 24 hours old by `now` (up to 5 minutes ahead still counts), it has a plain media id, it is on `allowed`, and `cached` returns the base64 of a JPEG (no line breaks): the prepared bytes your checks passed (shrunk, re-encoded and stripped of metadata before the checks), never a second read of the cache. The SDK checks only that the bytes look like a JPEG; it cannot tell a prepared picture from a raw one. At most `max` (3 when absent, never more), the asked-about post first, and none for `translate`. Anything else, including a missing or unreadable `checked_at`, goes as alt text and the stored caption only, exactly as without `pictures`.
- The renderer re-checks each approved picture at its own `now` and attaches nothing that is not on `allowed`: a picture that went stale between the two calls, or that your checks left out, goes as alt text and no other picture takes its place. Read the clock again for the render call: a later `now` can only take pictures away.
- The pictures sit inside the delimited content block, after its text. `references` never holds a picture's address or bytes. The content says which picture is attached ("picture 1 is attached: image 1 of 1"), and the instructions tell the model that words in a picture are data and never to say who a person in a picture is.

#### What a Sealed message may carry

`sealedTurnCaps(input)` is the "never all three" rule for Sealed (something about the member, someone else's content, a way out): one pure function the Sealed tab, the post sheet, the encrypted-chat ask and Both all decide through.

```typescript
import { sealedTurnCaps } from '@recursiv/sdk/assistant'

const caps = sealedTurnCaps({
  mode: 'sealed',                      // or 'both'
  search: true,                        // "Search the web" on for this chat
  others_content: ['public_post'],     // required; also 'members_only_post', 'chat_messages', 'encrypted_chat'; [] = own words
  temporary: false,                    // required: a temporary chat?
  searched_earlier: false,             // required: did an earlier message in this chat search?
  phone_pictures_earlier: false,       // required: did an earlier message in this chat carry a phone picture to Sealed?
  earlier_messages: true,              // required: does the chat have earlier messages or answers?
  memory: true,                        // Settings switch
  memory_in_chat: true,                // the header chip: counts only in the member's own chat
  memory_tick: false,                  // "Use what George remembers": the only thing that counts with others' content
  about_you: false,
  phone_pictures: 0,                   // required: pictures from the phone on this message, 0 to 3
  page_opens_limited: false,           // Tinfoil ask 3; leave false until a server switch says otherwise
})
// caps: { search, history, memory, about_you, phone_pictures, suggest_memory, reasons: ['search.off_subject'] }
```

- `others_content`, `phone_pictures`, `temporary`, `searched_earlier`, `phone_pictures_earlier` and `earlier_messages` are required: left out or null, they throw rather than read as "none" (so a searching message never drops the chat so far without its `search.question_only` line, or a picture without its `search.off_mix` line). `phone_pictures` is 0 to 3 (3 pictures per message in all); more throws, so cap them in the composer.
- `mode: 'both'` with `'encrypted_chat'` in `others_content` throws: an encrypted-chat ask is Sealed only (G21), and Both's Standard half would put the decrypted messages on Minds and the AI company. Offer Sealed alone on that surface.
- A message that searches never carries memory, About you or a picture from the phone; those stay and search turns off (`search.off_mix`). Someone else's public post (in the message or earlier in the chat) stops search until `page_opens_limited` (`search.off_subject`); members-only posts and picked chat messages never search (`search.off_members`), nor do encrypted-chat messages (`search.e2ee`). A message that searches carries only the question (and, after ask 3, the post it asks about): `history` is false, with `search.question_only` when the chat has earlier messages. Both never searches (`both.no_search`) and never carries a phone picture (`both.no_photo`). An encrypted-chat ask carries no phone picture either (one message of words; no line, since that surface has no Photo item).
- Memory goes only when on and on for this chat: the chip in the member's own chat, and only the tick with someone else's content (the chip alone never counts there). Never in a temporary chat or with encrypted-chat messages; About you follows the same rules without needing memory on. `suggest_memory` is false whenever the message holds anyone else's words, searches, carries a picture from the phone (it may be a screenshot of someone else's words), follows a search or a phone picture earlier in the chat, or is temporary. `reasons` are copy ids for what the member turned on that this message leaves off.


### Fixed election and crisis cards

Before a model answers, check the member's own words for a fixed card. Pure, no model call, the same card on a server and a phone (unreleased):

```typescript
import { fixedCardAnswer, matchFixedCard } from '@recursiv/sdk/assistant'

const match = matchFixedCard(question, { country: 'US', locale: 'en-US' }) // country: ISO 3166-1 alpha-2, if known
if (match) {
  show(match.card)                                  // { kind, id, title, lines, phones, links, as_of }
  if (fixedCardAnswer(match.kind, Date.now()) === 'card_only') return // election before 2026-11-04T12:00Z: no model call
}
```

- `crisis`: self-harm or suicide risk (first person, plans, means, worry about someone else) or immediate danger. The card gives the country's crisis line and emergency number, or the generic card (the US line, labelled, and findahelpline.com). Danger from someone else, or a medical emergency, leads with the emergency number (the police first where that is a separate number, as in Brazil, Chile and Peru: id `crisis.XX.danger`); worry about someone else gets a line addressed to the helper (`crisis.XX.other`). It always shows first; the turn may go on.
- Matching runs in time linear in the message. Past 20,000 characters (after invisible ones are dropped), the start and the end are read.
- `election`: only clear logistics (how, where or when to vote, registering, deadlines, polling places, mail or absentee ballots, voter ID, checking registration or a ballot). Never candidates, results, polls, fraud claims or votes on a post or poll. The US card points to vote.gov and CanIVote.org and the state election office; elsewhere the country's election authority, or a generic line.
- English and Spanish. Every number and address has a cited source and an `as_of` date (`CRISIS_LINES`, `ELECTION_SITES`); a country with no checked entry gets the generic card, never a guessed number. `fixedCardFor(kind, options)` gives a card without a message.

### Sealed price consent

`sealed.config().billing` positively names `legacy` or `member` billing. For `member`,
display the fixed message/search prices and obtain explicit acceptance before calling
`sealed.send({ ...sealedRequest, pricingVersion: config.billing.pricing_version })`.
Never automatically accept a config read as consent. Missing/stale acceptance refuses
before forwarding; safety checks remain included. The version is sent only to the
gateway, outside the encrypted payload, and is never forwarded to the enclave.
Publish/adopt this transport after the backend serves the explicit billing mode;
publishing the SDK does not enable billing or approve prices.

## Sealed frame (`@recursiv/sdk/sealed-frame`)

Web Sealed runs in its own frame, served from its own origin (https://sealed.minds.com), so the page that embeds it can't read it. This browser-only subpath is protocol v1 for both sides: the host page uses `mountSealedFrame()` and `wipeSealedFrame()`, and the frame uses the same message types, builders and validators.

```typescript
import { mountSealedFrame, wipeSealedFrame } from '@recursiv/sdk/sealed-frame'

const frame = mountSealedFrame({
  container,                                  // size it with CSS; the frame never reports its height
  frameOrigin: 'https://sealed.minds.com',
  hostKind: 'minds',                          // or 'build'
  scheme: 'dark',
  layout: 'column',                           // or 'workspace'
  account: member.id,                         // null when signed out: the frame wipes this browser's Sealed data
  mintToken: () => r.sealed.frameToken(),     // called only when the frame asks, at most once per token life
  onState: (state) => setSealedState(state),  // { state: 'ready' } or { state: 'unavailable', reason }
  onNavigate: (to) => go(to),                 // 'plans' | 'settings_ai' | 'sign_in' | 'get_app'
})

frame.setTheme('light')
await frame.signedOut()                       // 'wiped' | 'timeout' (1.5 s)
frame.destroy()

// Any sign-out path, with or without a frame on screen:
await wipeSealedFrame({ frameOrigin: 'https://sealed.minds.com', account: member.id })
```

- The iframe is sandboxed (`allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox`), may only write to the clipboard, sends no referrer and is never `credentialless`.
- On every load the host posts `sealed/hello` to the frame origin only with a MessagePort, and then reads that port only: a window message is never read, whatever its origin or source.
- Every message is validated: an unknown type, a missing or extra field, a value outside its enum or pattern, or anything over 4 KB is dropped. Nothing the member types or reads ever crosses.
- Tokens: one shared mint in flight, a token reused until 60 s before it expires, at least 30 s between two mints whatever the browser's clock says, and a failed mint held back 2 s doubling to 60 s (`onTokenError` gets the error; `isSealedWebOff(error)` means web Sealed is off). The cache belongs to one mount, so keep one mount while the page shows Sealed.
- `signedOut()` always also runs the sign-out page, which records the wipe first; a frame that has had its hello but not said `ready` is reloaded, so its next hello is signed out.
- The frame must not use `<form>` submission: the sandbox has no `allow-forms` (the frame CSP sets `form-action 'none'`), so an embedded form never fires `submit`. Handle Enter and the send button with key and click handlers.

`@recursiv/sdk/sealed` exports `HttpClient`, `SealedResource` and the errors and nothing else, for a bundle that must hold only Sealed.

## Error handling

```typescript
import {
  Recursiv,
  AuthenticationError,  // 401 — missing or invalid API key
  AuthorizationError,   // 403 — API key lacks required scope
  NotFoundError,        // 404
  ValidationError,      // 400 — check error.details
  RateLimitError,       // 429 — includes retryAfter, resetAt, scope, upgradeUrl
  ConflictError,        // 409
} from '@recursiv/sdk'

try {
  await r.projects.deploy('proj_1', { branch: 'main' })
} catch (err) {
  if (err instanceof RateLimitError) {
    console.log(`Retry after ${err.retryAfter}s`)
  }
}
```

Auto-retry is built in. 429 and 5xx responses retry with exponential backoff (configurable via `maxRetries`, default 2). A 429 with `X-RateLimit-Scope: action` refuses one member action past its budget and is never retried: its `RateLimitError` has `scope: 'action'` and `resetAt` (a `Date`, when that action's budget reopens). A read that holds its own deadline can ask once with `retry: false` in its params: `r.posts.list({ ...params, retry: false })` and `r.curator.forYou({ ...params, retry: false })` throw the first 5xx or 429 with no retry and no `Retry-After` sleep, and never send `retry` to the server.

## Pagination

```typescript
const page1 = await r.posts.list({ limit: 20 })
if (page1.meta.has_more) {
  const page2 = await r.posts.list({ limit: 20, offset: 20 })
}
```

## Response shapes

```typescript
{ data: T[], meta: { limit, offset, has_more } }  // list
{ data: T }                                         // single
{ data: { deleted: true } }                         // delete
{ data: { success: true } }                         // success
```

## Works everywhere

| Environment | Status | Notes |
|-------------|--------|-------|
| Node.js >= 18 | Full support | ESM only (`require()` needs Node >= 22). Uses native fetch. |
| Next.js | Full support | Server components, server actions, and route handlers. Use `@recursiv/sdk/next` for cookie-session auth (Next 14 and 15). |
| React (Vite, CRA) | Full support | Bundle-friendly, zero dependencies. Realtime needs the optional `socket.io-client` peer. |
| React Native / Expo | Supported with caveats | `chatStream()` requires manual SSE handling. See [React Native guide](./docs/guide-react-native.md). |
| Deno | Full support | ESM native, fetch native |
| Bun | Full support | ESM native, fetch native |
| Browser (direct) | Full support | Uses native fetch. CORS must be configured for your domain. |

## AI assistant reference

This package includes [`llm.md`](./llm.md) — a complete reference designed for AI coding assistants (Claude, Cursor, Copilot). It covers all resources with decision rules, working examples, and known gotchas. Your AI assistant will read it automatically when it encounters this SDK.

## Types

All request and response types are exported:

```typescript
import type {
  Project, Deployment, DeployInput, ExecuteCodeInput,
  Agent, StreamChunk, AgentChatInput,
  Post, Community, Message, Conversation,
  PaginatedResponse, SingleResponse,
} from '@recursiv/sdk'
```

## Guides

- [Build an AI-native app](./docs/guide-ai-app.md) — Database + agent + storage + auth
- [Build a social platform](./docs/guide-social.md) — Posts, communities, chat, profiles
- [Build a code playground](./docs/guide-vibe-coding.md) — Sandboxes, AI coding, deploy
- [Give an agent its own infrastructure](./docs/guide-autonomous-agent.md) — Database + memory + code execution
- [Mobile / React Native setup](./docs/guide-react-native.md) — Expo, streaming workarounds, auth flow
- [Error reference](./docs/errors.md) — Every error type, what causes it, how to fix it

## Links

- [npm](https://www.npmjs.com/package/@recursiv/sdk)
- [API Docs](https://docs.recursiv.io)
- [GitHub](https://github.com/recursivlabs/recursiv)
- [Website](https://recursiv.io)

## License

FSL-1.1-ALv2 — source-available, converts to Apache 2.0 after 2 years.

### Public source trends

Check `publicNetworks()` for `public_trends` before calling
`getPublicTrends({ protocol, limit: 10, cursor })`. The response is a discriminated
union: `kind: 'topics'` contains Bluesky topics; `kind: 'posts'` contains public
ActivityPub posts ranked by mastodon.social. Preserve provider order and display
`provider`, `observedAt`, and `coverage: 'provider_ranked_window'`. A null
`rankingWindow` means the provider has not supplied an exact ranking interval.

For a network with `trend_feed`, open a returned topic with
`getPublicTrendFeed({ protocol, topic: topic.nativeId, limit: 10, cursor })`.
The service rechecks current topic availability before each page; a disappeared
topic returns `trend_unavailable` rather than an empty feed. Keep canonical post
IDs and provider `readRef` when opening `getPublicConversation`. Cursors are
opaque; topic catalogs have no pagination and the Mastodon post window stops at
200 source positions. Both reads require `users:read` and `posts:read` on the
current human project-bound app key. Nostr does not advertise trends. Provider
failures propagate as SDK errors, and neither method ingests or publishes posts.

A clip player scoped to one network asks for its video window instead (0.7.73):
`getPublicTrends({ protocol: 'bluesky', limit: 25, media: 'video', cursor })`, or keyless
`getSharedTrends(projectId, { protocol: 'bluesky', limit: 25, media: 'video', cursor })`.
The answer is a `kind: 'posts'` page holding only posts that carry a video (Bluesky: What's
Hot's videos, one provider request a page), paged by its opaque cursor until it is `null`;
a page may be empty while its cursor goes on. It takes no `category` and judges no layout;
`compass: 'hide'` (0.7.72) leaves the political clips out of it as it does from trends.
A signed-out read holds only clips whose video the visitor may see, and counts the rest in
`mediaFilter.withheld`. A network without a video window answers 404 `unsupported_protocol`;
an API that predates `media` answers 400 `invalid_input`, so fall back to its trends.

### Native networks

Every eligible member is on ActivityPub, AT Protocol and Nostr by rule; an identity is
set up lazily, on their first public post, their first interaction on that network, or
"Set up now". `protocols.networks()` reads each network's `state` (`ready`, `on`,
`pending`, `off`, `error`, `needs_action`, `locked`) with its `reason` and `handle`, and
never sets anything up. `protocols.activateNetwork('atproto')` sets one up now (over the
setup budget it answers `pending` with `retryAt`). `protocols.setNetwork('activitypub',
{ enabled: false, removePast: true })` is the member's off switch, and
`setNetwork(network, { enabled: true })` turns it back on with the same identity.

Where an app's network is opt-in, a member who never turned it on reads `off` with reason
`not_opted_in`, and nothing sets them up until they do: `setNetwork(network, { enabled: true,
consentVersion, consentSource })` is their turn-on, recorded with what they agreed to and
where. Send those two only where `networks()` reads `recordsConsent: true` for the network, or
after a `not_opted_in` refusal: a server without the opt-in level reports neither, and answers
400 `invalid_input` to them. A member who set a Fediverse address up in Linked accounts before
reads `on` with reason `legacy_opt_in`, and their one-tap actions act as it.

A turn-on also records whether the member's posts that name no `destinations` (the API, MCP,
the CLI, agents) go there: `autoShare: false` is "address only", for a like's "Set up and
like" or the composer's "Just this post"; omitted, a turn-on with `consentSource: 'engage'`
is address only and any other shares them. Send it only where `networks()` reports `autoShare`
for the network. An account whose access to the app is not a membership (the app's owner, an
organization's owner or member) cannot keep address only: that turn-on is 409
`auto_share_unrecorded` and sets nothing up. When the member's federated-post caps keep a new
post off a network, it stays on Minds and `posts.create` answers
`sharing_paused: [{ network, reason, retry_at }]` (`hourly_sharing_limit`,
`daily_sharing_limit` or `remote_mention_limit`).

No new identity is set up for a 13-17 member (`locked`, reason `minor_network`), or for an account
under a week old with no verified email (`needs_action`, reason `account_too_new`, with `availableAt`,
when it is a week old). AT Protocol needs both the week and a verified email (`needs_verified_email`).
An identity a member already has is left to them: it stays on, and after an off they can turn it on
again. A turn-on they hold is refused 403 `network_locked` or 409 `account_too_new` /
`needs_verified_email`. A moderator's hold reads `locked` with reason `moderator_hold`, and the member
cannot turn the network on or off until it is lifted; `{ enabled: false, removePast: true }` still
takes down what they shared there.

```ts
const { data } = await r.protocols.networks();
for (const network of data.networks) {
  if (network.state === 'ready') show(network.network, 'Will be set up when you first post or interact');
}
await r.protocols.setNetwork('nostr', { enabled: false, removePast: true });
const activitypub = data.networks.find((network) => network.network === 'activitypub');
await r.protocols.setNetwork('activitypub', activitypub?.recordsConsent
  ? { enabled: true, consentVersion: 'fediverse-1', consentSource: 'settings' }
  : { enabled: true });
```

Each row's `carries` lists what the server sends to that network (`post`, `reply`, and `repost` or `quote` once
it sends those there; a row without it, from an older server, means `['post', 'reply']`). Before a reply, remind
or quote, `protocols.networks({ post, action })` (`supportsPostReach`) answers where it would go: the same rows,
each with `reaches` and, when false, a `reason` (`post_not_there`, `group`, `not_public`, `not_carried`,
`sensitive`). A post the member cannot see is 404 `post_not_found`, as a missing one is.

```ts
const { data: reach } = await r.protocols.networks({ post: postId, action: 'repost' });
const also = reach.networks.filter((row) => row.reaches).map((row) => row.network); // e.g. ['activitypub']
```

One-tap actions act as the member's own identity on that network by default (0.7.191). `engageLike`,
`engageRepost`, `engageFollow`, `engageReply` and `engageQuote` take `identity?: 'native' | 'linked'`. A
native answer is sent (`queued: false`, with the network's `delivery`) or, while the identity is still
being set up, queued (202, `queued: true`, sent in order once it is on; `pendingInteractions()` lists
them). A linked answer is the review to submit, as `prepareNativeLike` always returned. Every answer
says who acted (`actedAs`). A member who linked an account before the cutover keeps acting as it until they
choose otherwise with `setEngageDefault(network, 'native')`; the first such answer carries
`notice: 'engage_default_linked'`. An account linked later is a choice: `setEngageDefault(network, 'linked')`.
Keep the same `clientMutationId` across retries: a retry is answered from the first tap, never sent twice
(once that tap expired unsent, with `delivery.code` `interaction_expired`; a new tap takes a new id). A native
reply's or quote's `media` takes only the member's own Minds uploads, as the linked flows do.

```ts
const { data } = await r.protocols.engageLike({ protocol: 'bluesky', nativeId: post.nativeId, clientMutationId, action: 'like' });
if (data.identity === 'native') showActedAs(data.actedAs, data.queued ? 'Sending when your account is ready' : null);
else await r.protocols.submitNativeLike(data.id, { approve: true });
```

What the member's own identity did is read back the same way (0.7.202): `nativeInteractionState({ protocol, nativeId })`
answers `liked`, `reposted`, `reaction` and `following` (`pending` until the account answers, `accepted`, `rejected`)
for one post or account, and `nativeNotes({ protocol, limit?, cursor? })` lists the replies and quotes they wrote
there, newest first, each with the post it answers. Both read only what that identity recorded (ActivityPub keeps
it; another network answers 503 `native_network_unavailable`, reason `adapter_missing`).

```ts
const { data: state } = await r.protocols.nativeInteractionState({ protocol: 'activitypub', nativeId: post.nativeId });
setLiked(state.liked);
const { data: notes } = await r.protocols.nativeNotes({ protocol: 'activitypub', limit: 20 });
```

A member's AT Protocol account is created on the PDS Minds runs, with their verified email (0.7.191); Minds acts for
them with a revocable app password named "Minds". `claimAtprotoPassword({ password })` (or `{ emailCode }` from
`POST /settings/confirmation-code` with purpose `atproto_password`, for an account with no password) has the PDS
email a reset code to that address, so the member can sign in from any AT Protocol app and revoke that app password
there. Revoking it stops Minds acting as them through it, not Minds' control: Minds runs the PDS, so it can still reset
the account's password or deactivate it, and the PDS's rotation key, which Minds holds, is the only key on the DID.
Do not tell members they can lock Minds out or leave without Minds.
A member without a verified email reads `needs_action` with reason `needs_verified_email` on AT Protocol.

```ts
const { data } = await r.protocols.claimAtprotoPassword({ password });
show(`We sent a reset code for ${data.handle} to ${data.sentTo}`);
```

AT Protocol reads `needs_action` with reason `needs_atproto_grant` for an account made before Minds ran it natively,
and `error` with `app_password_revoked` after the member revoked Minds' app password. `grantAtproto({ password })`
(0.7.191), with that account's password (or a non-privileged app password the member made), lets Minds act as it again:
Minds keeps only a new revocable app password, and answers the handle and the presence after the grant.

```ts
const { data } = await r.protocols.grantAtproto({ password: atPassword });
if (data.presence.state === 'on') show(`Minds acts as ${data.handle} again`);
```

A member can take their Minds-held Nostr key home, in three steps of their own:
`protocols.exportNostrKey({ password })` returns it as an `nsec` (an account with no password
sends `{ emailCode }` from `settings.requestConfirmationCode('nostr_key')`); after they
import it into their signer, `nostrRebindChallenge()` and `rebindNostrKey(signedEvent)`
prove the device holds the same key; then `deleteManagedNostrCopy({ password })` deletes
Minds' copy, and every later Nostr action is signed on their device. What Minds published
with the key still comes down when they delete a post or their account (Minds signs those
takedowns before the copy goes; 409 `too_many_published` keeps the copy when there is too
much). Deleting Minds' copy is held for now: it answers 409 `device_signing_unavailable`
until members' devices can sign, and keeps the copy. Show the `nsec` to the member alone and never log it. None of these is retried
automatically.

### Native Nostr signing

A member's Nostr key is either their own, signed on their device, or one Minds holds for them (0.7.192).
`nativeNostrAccount()` says which: `signing: 'client'` is the flow below; `signing: 'server'` (with
`mode: 'managed'`) means Minds signs. Then `prepareNativeNostr` is the preview to show (nothing is signed
or sent), and `prepareNativeNostr(id, { ...input, send: true })` once the member approves signs and sends
in that call and answers with the `receipt` (nothing to submit). A like, repost or follow review is submitted with
`{ approve: true }` and no `event`, and `engageLike`, `engageReply`, `engageFollow` and the rest with
`identity: 'native'` act as that key in one tap. For a key Minds holds, a like or repost Minds is still sending (the
relay has not taken it yet) reads as liked or reposted with `acknowledged: false`, and an unlike or unrepost removes it.

Use `protocols.nativeNostrAccount()` to check the app's explicit native-write
capability. For an enabled connected key, prepare a text post with
`prepareNativeNostr(identityId, { action: 'publish', content })`, show its
identity, relay and text, and ask the client signer to sign the returned event.
Submit only the public event with `submitNativeNostr(identityId, { intent, event,
approve: true })`. Preserve that exact event on uncertain retries. Check
`getNativeNostrPost(identityId, eventId)` for relay visibility. An owned note can
prepare `{ action: 'delete', postId }`; deletion is a signed request, not a
promise of erasure across all relays. Keys are never sent to this SDK service.
Preparation and submission never retry automatically, even when `maxRetries` is
configured. After an uncertain submission, check
`getNativeNostrPost(identityId, preview.postId ?? preview.eventId)`: deletion uses
the original note's `postId`, while publication uses the new `eventId`. Any
user-selected retry must keep the same intent and signed event.

When the deployed API advertises `reply_text_note`, the same method can prepare
`{ action: 'reply', content: draftText, parentId: selectedPost.nativeId }`. Review
the returned parent, root, participants, relay and exact event before asking the
signer to sign. The API constructs verified NIP-10 references; callers cannot
inject tags, participant lists, relay URLs or signing keys. Reply prepare/submit
also require `posts:read`. This capability remains off until the shared reply UI
and live delivery are verified. Only public kind-1 notes are supported; additional
participant selection is unfinished. `textTruncated` labels an abbreviated source
preview. Preparation and submission never automatically retry; check the event ID
after an uncertain result before choosing a retry of the identical signed event.

### A Bluesky account on the app's own PDS

`createHostedIdentity` asks the app's own PDS to issue a Bluesky account for the
signed-in member. Only the label is sent; the app picks the domain.

```ts
const { data: identity } = await r.protocols.createHostedIdentity({
  protocol: 'atproto', handle: 'alice', email: 'alice@example.com',
})
// identity.handle is e.g. 'alice.pds.minds.com'. identity.password exists only in
// this response: show it to the member once and store it nowhere.
```

The email must be the member's own verified one: none is `needs_verified_email`
(409), another address `email_not_yours` (409). In an app that rolls native
networks out (Minds), only a member the AT Protocol rollout covers may ask
(`outbound_refused`, 403) and only one the native-network rules admit
(`network_locked`, 403; `age_band_required`, 409), for the label their own native
setup would choose now (the first free one of their username's label, its `-2` to
`-50`, and that label with their tag).

The server either finishes the account or removes it again, so a failure never
leaves one half made. The call is never retried automatically. `handle_unavailable`
(409) means choose another label, except in an app that rolls native networks out,
where only the label native setup would choose is accepted and the member uses
"Set up now" (`activateNetwork('atproto')`) instead; `identity_conflict` (409)
means they already have one; the 503 codes `handle_dns_unavailable`,
`handle_unresolvable` and `handle_unverified` are operator setup and succeed
unchanged once it is done.

### Delegated Bluesky and ActivityPub accounts

These methods require the same signed-in human app key throughout. The API must
enable the app and deploy the authorization schema before use.

```ts
const { data: connection } = await r.protocols.startNativeSocialConnection({
  protocol: 'bluesky', identifier: 'alice.bsky.social',
})
// Navigate to connection.authorizationUrl. On the configured app callback:
const { data: account } = await r.protocols.finishNativeSocialConnection({
  protocol: 'bluesky', state, code, iss,
})
const { data: accounts } = await r.protocols.nativeSocialAccounts()
await r.protocols.disconnectNativeSocialAccount(account.id)
```

ActivityPub uses an operator-approved HTTPS server origin as `identifier` and
requires Mastodon-compatible OAuth metadata with S256 PKCE. The server configures
the exact callback path `/social/connect/callback/:protocol`; the app must remove
its query from browser history immediately and never log codes. No password or
native token is sent through these SDK methods. Start and callback are single-use
requests and are never automatically retried. If a callback result is uncertain,
refresh the account list before starting again.

In a native app, use the operator-configured native callback instead of the web
one when `nativeSocialAccounts()` lists the protocol in `nativeRedirects`:

```ts
const { data: start } = await r.protocols.startNativeSocialConnection({
  protocol: 'bluesky', identifier: 'alice.bsky.social', redirect: 'native',
})
const result = await WebBrowser.openAuthSessionAsync(start.authorizationUrl, start.callbackUrl)
// In the native callback route, read state, code, iss (or error) from result.url:
await r.protocols.finishNativeSocialConnection({ protocol: 'bluesky', state, code, iss })
```

Connection does not approve publication. The account's `capabilities` lists only
implemented actions, currently empty for these adapters. Local disconnect takes
effect even when `providerRevocation` is `unconfirmed`; the user can also revoke
Minds from their network's authorized-app settings.

### One reviewed reply across selected accounts

The shared reply API is off by default. Deploy its required schema/API and finish
live authorization and delivery verification before enabling it. This example
prepares a preview; it does not publish anything:

```ts
const { data: preview } = await r.protocols.prepareNativeReply({
  clientMutationId: crypto.randomUUID(), text: draftText,
  parent: { protocol: 'bluesky', nativeId: selectedPost.nativeId },
  accountIds: [blueskyAccount.id, activityPubAccount.id],
  linkedPostAccountIds: [activityPubAccount.id],
  // Optional, needs each account's `publish_media` capability:
  media: [{ url: uploadedImageUrl, alt: memberWrittenAltText }],
})
// Review each delivery's account, protocol, kind, parent, media and exact wireText.
// After the user approves selected delivery IDs:
await r.protocols.submitNativeReply(preview.id, { approve: true, deliveryIds: approvedDeliveryIds })
```

Use `linkedPostAccountIds` only after the user selects a standalone post with the
source link on that different network. It is not a matching threaded reply, and
a denied same-network reply never falls back automatically. Verified cross-network
thread mappings are not implemented here. Nostr uses the connected client signer
described above. Preserve the mutation
ID while recovering an uncertain preparation; read `nativeReplyStatus(preview.id)` to
show each destination's result. Repeated submit reconciles an attempted delivery
without publishing it again. Removal uses a fresh `prepareNativeReplyRemoval`
preview and explicit `removeNativeReply` approval for the selected own posts.

For a selected unsent or definitively rejected destination, the same prepare
method accepts `recoverFrom: { batchId: preview.id, deliveryIds: selectedIds }`
with a **new** mutation ID, the same source/accounts and freshly reviewed text.
Preserve that new ID if preparation is uncertain. The server creates the fresh
review and disables only those old destinations atomically; `replacedBy` points
to the new batch. `recoverable` describes saved eligibility, while current account,
source and safety checks still apply. Sending, unknown, accepted or published
destinations cannot be resent this way. The fresh preview still needs explicit
approval; completed destinations retain their outcomes.

`nativeReplyHistory` pages through one private history containing Bluesky/ActivityPub
drafts and delivery results, plus Nostr replies and linked posts once submitted. It also includes unsent or expired preparations. The
summary contains a bounded preview of the user's own text and source references,
not old remote parent text or approval material. Opening a result with
`nativeReplyStatus(id)` does not send anything. Reading remains available when
new replies are disabled; it does not refresh credentials or contact a network.
Nostr items have `type: "nostr"`. `nativeNostrReplyResult(id)` checks the saved event
on its recorded relay without signing or resending. It requires the same connected
identity and preserves historical publication/deletion evidence separately from
`lastReadBack`. A relay absence is not proof of global deletion. Signatures and
intents are never retained in history.

```ts
const { data: history } = await r.protocols.nativeReplyHistory({ limit: 20 })
// Read a saved result without submitting it.
const firstResult = history.items[0]
if (firstResult) {
  if ('type' in firstResult && firstResult.type === 'nostr') {
    await r.protocols.nativeNostrReplyResult(firstResult.id)
  } else await r.protocols.nativeReplyStatus(firstResult.id)
}
if (history.cursor) {
  const { data: next } = await r.protocols.nativeReplyHistory({ limit: 20, cursor: history.cursor })
  console.log(next.items.length)
}
```

Keep the cursor opaque and discard it when the app or signed-in user changes.
History order is fixed by creation time, so later delivery updates do not move
older entries across page boundaries. Reopen each result for its current saved
state and obtain a fresh review before a new write.

### Public protocol post links

Visitors can read a public conversation in an explicitly configured app without signing in:

```ts
const visitor = new Recursiv({
  anonymous: true,
  inheritEnvironmentApiKey: false,
});
const { data: networks } = await visitor.protocols.sharedNetworks(projectId);
const { data: conversation } = await visitor.protocols.getSharedConversation(projectId, {
  protocol: 'nostr', post: publicEventId,
});
```

These reads apply app moderation, provider public-visibility/deletion checks and bounded
per-IP/app budgets. They return no subscriptions, personal safety preferences, account
connections or signing authority. Missing configuration or unavailable safety checks fail
closed. Signed-in members continue using `getPublicConversation` to apply personal
blocks/mutes as well. All reply and account endpoints still require authentication.

Standalone public publication uses `protocols.prepareNativePost({ clientMutationId, text, accountIds, media? })`, then explicitly approved `submitNativePost`. Keep the same mutation ID after uncertain preparation; previously attempted deliveries are reconciled without resending. `nativePostStatus` and paginated `nativePostHistory` expose private app/user-owned outcomes. Review current own posts with `prepareNativePostRemoval`, then approve exact removal IDs through `removeNativePost`. Check connected-account `publish_text` capabilities; only explicitly enabled apps may publish. Text is sent unchanged, public only, with each provider’s actual limits. Optional `media` is a `NativeMediaInput[]` of at most four already-uploaded Minds images (`{ url, alt?, width?, height?, mimeType? }`, JPEG/PNG/WebP/GIF, Minds-hosted HTTPS URLs only, a Mastodon GIF must be the only attachment). It additionally requires the account's `publish_media` capability; accounts connected before image permissions existed must reconnect. Pass the member's own `alt` — an omitted one is sent as an empty description, never an invented one — and read `receipt.media` (`{ count, alt_missing }`) after sending. These methods still do not accept a reply parent or caller-supplied authority.

To delete a post everywhere, link its network copies when you cross-post: pass `crossPostOf: post.id` (the member's own post in this app, from `sdk.posts`) to `prepareNativePost` and to `prepareNativeNostr(id, { action: 'publish', content, crossPostOf })`. Later, `nativePostHistory({ crossPostOf: post.id })` lists exactly that post's copies, each with `crossPostOf` set: delegated items are removed with `prepareNativePostRemoval`/`removeNativePost`, and `type: 'nostr'` items (original notes, which this SDK's history lists; the REST route returns them only with `include=nostr` or `crossPostOf`, so older apps keep the delegated-only shape) with the Nostr signing flow (`prepareNativeNostr(identityId, { action: 'delete', postId: eventId })`). Another member's post, or one from another app, answers `not_found`; copies prepared without `crossPostOf` stay unlinked.

For Bluesky accounts advertising `quote`, prepare the same publication with `quote: { protocol: 'bluesky', nativeId: sourceAtUri }`. The server resolves the exact source CID using each connected account, checks quote permission and Minds safety, and rechecks before writing. Review each delivery’s `quote` alongside the account and comment before submitting. Changed or unavailable sources cannot publish; uncertain deliveries reconcile the original record key. Mastodon accounts advertising `quote` (0.7.71) take `quote: { protocol: 'activitypub', nativeId: statusUri }`: the member's server must create quote posts (Mastodon API version 7, sent as `quoted_status_id`) and allow this account to quote the status, or prepare answers `quote_not_supported` / `reply_not_allowed`, never a plain link. A Nostr quote is `prepareNativeNostr(identityId, { action: 'publish', content, quote: { protocol: 'nostr', nativeId: eventId } })` (accounts advertising `quote`): the event carries NIP-18 `q` and `p` tags and a `nostr:nevent` line after the text, for the member's signer to sign as usual. Public post reads include at most one filtered `quote` with `state: 'available'` and `post`, or `state: 'unavailable'` without source content. 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.

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.

### Continuous public discovery

Create one `sdk.discovery.createFeed({ networks, category, source, learning })`
per signed-in viewer and filter. Pass the app-advertised network catalog, then call
`next()` as the reader approaches the end. Each page contains safe json-render
module specs and native or protocol post objects. Preserve their existing source
authority and interactive controls. `retryFailed()` explicitly retries unavailable
sources; create a new session to refresh exhausted source windows. A topics network
(Bluesky) is read one topic page at a time; in a category the catalog's previews are not
judged to be in it, so a read walks into the topics at once, and walks past a topic the
provider no longer lists (`trend_unavailable`) or one with nothing new, up
to five topic pages a read, so a page reaches a topic that carries posts. In a category a
topic page that shows nothing new ends its topic (the provider's cursor is not followed),
after three such pages in a row (`DISCOVERY_EMPTY_TOPIC_PAGES`) the network's other topics
are passed over without a call, and the network's source-index stream (`idx:tf:` cursors)
is started once and ends on its third page in a row with nothing new. A network read
that fails for a passing reason (past the 15 s page deadline, a dropped connection, a 429
or a 5xx) leaves the network out of that page and the next, named in `retryingSources`
until a later page asks it again (from the page after, when its turn comes), up to two
times in a row. Any other failure, or one past that, marks the source failed
(`failedSources`) until `retryFailed()`. The Minds read is asked once and is never
retried this way: any failure of it is in `failedSources` on that page.

`sdk.discovery.createPersonalFeed({ networks, category?, learning?, recommend? })`
builds the same kind of session for a member's For you tab: its Minds slot reads
`sdk.curator.forYou({ surface: 'discover', discovery: true, cursor })`, which ranks
fresher and past the member's follows, pages a stored ranking by `meta.next_cursor`,
and says whether the member is personalized yet (`meta.personalized`). With a
`category` (the member's first), the session also reads open-network posts from it;
without, it is Minds only. It never carries the radar.

### Progressive Discover feed

`sdk.discovery.createProgressiveFeed(options, settings?)` reads the same feed without
waiting for its slowest network (a session's page waits for every source, up to 15 s). It
opens one `createFeed` session per source (Minds with the story radar and suggestions, and
one per network with `public_trends`), and `next(onPart)` hands each source's page on as a
`DiscoveryPart` (`{ source, round, modules, composed?, mixed? }`) the moment it lands; the
promise resolves with the round's summary (`hasMore`, `failedSources`, `retryingSources`,
`fallover`) and rejects only when every source it read failed. A round waits
`DISCOVERY_STRAGGLER_MS` (3 s) past its first answer; a source still reading then lands
later, and `onStatus(listener)` says so. `setNetworks(catalog)` takes in a network the feed
did not have (a feed opened before the catalog answered) and stops reading one the catalog
dropped.

The first load is held until Minds and one other network have answered, or
`FIRST_SCREEN_MS` (2.5 s, a member's; pass `firstScreenMs: VISITOR_FIRST_SCREEN_MS`, 0.8 s,
for a visitor) after the first answer, and arrives as one part with `composed: true`, built
by `composeFirstScreen`:

- it leads with the top's first post when that is a video that can play; else (0.7.200) with
  the most engaging post across the networks (`firstScreenEngagedLead`): each post's
  engagement on a log scale against the whole batch's typical post (`discoveryLeadScore`,
  never its own network's median), a playable clip counting `DISCOVERY_VIDEO_BOOST` times
  and a picture `DISCOVERY_PICTURE_BOOST`, halving every `FIRST_SCREEN_LEAD_HALF_LIFE_HOURS`
  (72 h); a Minds member's post leads only within `FIRST_SCREEN_MINDS_LEAD_SHARE` (0.85) of
  the best open-network post, a post nobody engaged with never while an engaged one is on the
  screen, and a column never while a single post may. With no engagement anywhere, a post
  that opens on a picture or video (`moduleOpensOnPicture`) from the best
  `FIRST_SCREEN_LEAD_WINDOW` (8) by engagement leads. A story, a suggestion rail, a video strip,
  a conversation or thread (`isColumnModule`), a sensitive Minds post (`isSensitivePost`)
  or an open-network post that links a porn site (`linksAdultSite`) never leads;
- the posts then follow by engagement, every network's together (`DiscoveryEngagementMerge`:
  normalised per network, decayed by age, video and pictures first, no network more than
  8 of any 20 rows or 3 in a row, a Minds member's post at least every sixth row); posts by
  `name@host` accounts in Minds' lane count as ActivityPub's (`mindsPostNetwork`);
- the row under the lead is the best post from another network while one of the same standing
  is left (`FIRST_SCREEN_NETWORK_ROWS`), so a screen that shows two rows is never one network's;
- a story goes in as row 3 (`FIRST_SCREEN_STORY_SLOT`) and a rail as row 5
  (`FIRST_SCREEN_RAIL_SLOT`); galleries are pooled into one; nothing is dropped.

Later parts over every network carry `mixed: true`: merge them below what the reader has
seen with `mergeDiscoveryArrival(rows, arriving, reachedIds)`. `top`, `seen`, `seenClusters`
and `bucket` reach every session; the top is read once per open (one session token), and
not asked again for five minutes after it answers 404. Settings: `perSource: false` keeps
a feed that picks its own networks whole (For you: pass
`{ createFeed: o => sdk.discovery.createPersonalFeed(o) }` to the standalone
`createProgressiveFeed(factory, options, { perSource: false })`), `firstScreen: false` hands
every part on as it lands, and `onLanded(source, failed)` reports each landing. A client
that moves clips out of a composed part recomposes the rest with
`composeFirstScreen([{ modules }], { keepLead: true })`. `withoutSeenItems` and
`readFalloverSteps` are the rules the feed applies across sources and to `fallover`.

### For You: the world by the member's interests

`sdk.curator.forYouWorld({ part?, session?, snapshot?, compass? })` reads the For You overview
for the signed-in member, with their own key of the app. `stories` are world stories (Today,
the radar and the viral read) matched to the member's interests with breadth: at least four
themes and two breaking or general stories in the first eight, at most two per theme, and a
story shown three times without an open rests for a week. `items` are the member's For You
picks interleaved with the most engaging posts of their top interests (half or more on their
interests, no interest over 40%, videos weighted up), and `blocks` lay the page out like All:
`stories`, `lead_video`, `clips`, `posts`, `people`, `groups`, `topics`, `viral` and
`categories`, never the same type twice in a row, each naming the refs its views should send.
Every story and item carries `reasons` (`interest:<category>`, `followed:@<handle>`, `breaking`,
`general`, `for_you`, `engaging`, `breadth`). An open-network item carries its `card` (text,
author, media and counts, no URL on its network) to draw it from; a Minds item's is null (read
the post by id). `part: 'stories'` and `part: 'items'` read the
two halves on their own, so an app can draw each as it lands; a part=items answer keeps the
stories rail as a `deferred` block. `meta.interests` are category ids for chips (never put them
in a URL), `meta.partial` names a source that missed its deadline, and `meta.foryou_cursor`
continues the same ranking with `curator.forYou({ cursor })`. 404 while the app's operator has
it off; a 503 `for_you_world_unavailable` carries Retry-After.

### The top of a feed

`sdk.feeds.top({ ref, limit?, session?, compass? })` answers the top of a feed for the
signed-in member, read with their own key of the app (`ref`: `builtin:all`,
`category:<id>`, `following`, `watch` or `story:<cluster id>`): `items` (the posts most
likely to be engaged with, often video, rotated by what the member has seen), `networks`
(Bluesky, Fediverse and Nostr lanes of up to six posts, each with a `card` to draw and no
URL on its network), `lead` (the story the feed should open with) and `meta` (`short`,
`safety`, whether the order used impressions). Every item's `target` is in the app: a
post id, `/social/post/<protocol>/<id>`, or a story id. `sdk.feeds.stories({ after?, limit? })`
is the story tail from the same ranker. `sdk.feeds.publicTop({ projectId, ref?, limit?, compass? })`
is a visitor's top (safe items only, the same for every visitor in one 15-minute bucket),
read with no credential so the edge can hold it. Each answers 404 while the app's operator
has it off. Send `block: 'top'` and the item's position with a visible view of a top item.

`sdk.feeds.firehose({ session, limit?, compass?, network? })` (0.7.195) is the member's live
stream: the next items of the most engaged, viral and breaking posts of Minds and the open
networks, re-checked for the member on the server and never sent twice in one `session`. Each
item carries `network`, `state` (`breaking`, `viral` or null), `publishedAt`, `chosenAt`, an
in-app `target` and, for an open-network post, a `card`. Reveal them one at a time and read
again no sooner than `meta.refillAfterMs`; remove the refs in `retract` wherever you hold them.
404 while the app's operator has it off; 429 and 503 carry Retry-After. A Mix or Choose sides `compass`
spends one of the member's hourly sided Politics reads at most once per `session` and choice in ten
minutes, and answers 429 `compass_rate_limited` once those are spent. Since 0.7.208 `network` may be
`farcaster`: the newest casts of reviewed Farcaster channels, for signed-in members only, while the
server reads Farcaster in time order (`meta.networks.farcaster` is present only then, `unavailable`
while its read is failing).

A feed session opens with it when asked: `createFeed({ networks, top: { ref, session? }, seen,
seenClusters?, bucket? })` (or `new DiscoveryFeedSession(..., { top: { ref, read, post? }, seen })`
with your own readers). The top's read starts with the first page's reads, and the top holds
the page at most 1.5 s from its start, the reads of its items' posts included; a top that is
off, fails or is late leaves the session exactly as it is without one. The radar's story reads
its posts as soon as the radar answers, whatever the top does. When it answers, page 0 opens with the story it leads with, then its items (each item
carries `top: { ref, position, block }`, a lane entry also `lane`), and its lanes stand in
for the networks' first reads. Minds items the first hot page does not carry are read by id
once, within the same 1.5 s (`top.post`, or `GET /posts/:id` without retries). `seen` (Minds post ids and
`<protocol>/<nativeId>` refs the member already saw) leaves those posts out of the hot pages
and out of the networks' trend pages, topic previews and topic pages (the top's own lanes
stay), and no hot page repeats a top item; a hot page left under five posts walks on, up to three
more pages, and the feed's `fallover` still reports when the ranking ends. Without impressions
in the top's order, the member's seen top items follow the unseen ones. An item's
`top.position` is its place in the whole top, so sessions that each place their own
network's part never share a place. `seenClusters` (`Map<id, { n, clicked }>`) skips a story
shown three times without an open, the server's lead included,
and a visitor's `bucket` rotates page 0's story among the breaking ones
(`pickRadarCluster` is the same rule on its own). With none of these options a session is
unchanged.

Both take a Politics choice, `compass` (`all`, `mix`, `hide`, or cells in the order
`lo,co,ro,lm,cm,rm,ll,cl,rl`, optionally `np`), and send it with every Minds read
(`posts.list` and `curator.forYou` take it too). Each such page says what it did in
`meta.compass_filter` (`status` `applied` or `unavailable`, and counts only), and each session
page carries its Minds read's answer as `page.compass` (`unavailable`: the page is unfiltered). Only Minds
posts are filtered, so a view that leaves posts out reads best with `source: 'minds'`.
The catalog lists `compass_filter` on every network when the filter is served to the viewer, and `compass_sides`
with it (0.7.116) when the viewer may choose sides and Mix too: a visitor's catalog lists it where the operator serves
visitors the whole filter; without it, offer a visitor Hide politics only.
Hide politics (`compass: 'hide'`) also applies on its own, with or without compass judgments on the server, to
`sdk.discovery.videos`, `protocols.getPublicTrends` and the radar (`getPublicRadar`, keyless `getSharedRadar`; 0.7.62):
it leaves out what is categorised politics (a story not themed yet, or `mixed`, too) and says what it did in
`meta.compass_filter`. These reads answer a side or Mix unfiltered, marked `unavailable`. Every radar story and every
World Today story (`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. Hide politics leaves those out whatever their theme, on the radar and on
`curator.today({ compass: 'hide' })`, where the next story then leads. The stories of `feeds.stories()` and the lead of
`feeds.top()` carry `political` too (0.7.67), and those reads and `curator.forYouWorld()` leave political stories out
under Hide politics.

From 0.7.72 Hide politics on those reads that need no compass judgment (the radar, `curator.today()`,
`getPublicTrends` and keyless `getSharedTrends({ ..., compass: 'hide' })`, the viral read, `sdk.discovery.videos` and a
visitor's Discover posts) applies for every caller, whether or not the operator serves them the full filter: where it
does not, Hide is the floor (the server's own `political` flags and browse categories, no judgment read) and
`meta.compass_filter` says `status: 'applied'` with `basis: 'flags'`. Choose sides, Mix sides and the catalog's
`compass_filter` and `compass_sides` capabilities still follow the operator's audience.

Every story names one outlet count (0.7.71): radar stories, World Today stories, category strip stories, feed-top and search stories carry `outlets: { total, mainstream, independent, other }`, the distinct outlets of the articles the story lists (buckets sum to `total`). Show `outlets.total`; `sources.outlet` counts articles, not outlets.

A World Today story's discussion across networks (0.7.69; servers with World Story Volume on): `sdk.curator.today()`
gives each world story the server indexed a `story_key` and, when the reader's pool holds a post, a `discussion`:
`total`, `people`, `by_network` (`minds`, `bluesky`, `activitypub`, `nostr`), `capped` (the pool reached 1,000: show
"1,000+") and up to two open-network `previews`; `meta.story_volume` says how the pools stand. Without them (an older
server, or the feature off) show the story as before. The posts behind the count:
`sdk.curator.storyPosts({ storyKey, network?, sort?: 'top' | 'latest', cursor?, limit? })` keyless (a visitor's view)
or `sdk.curator.memberStoryPosts(...)` under the member's key (their own blocks, mutes and hidden posts leave each
page), and `for await (const page of sdk.curator.storyPostPages({ storyKey }, { reader: 'member' }))` walks every
page. Each item is `{ kind: 'minds', post: Post }` or `{ kind: 'social', post: SocialPost }` (narrow on `kind`; open
a social post inside the app, never link out); `text_only` means show its words only. A post removed since the build is
counted in the page's `withheld`, never replaced, so the pages' items plus `withheld` add up to the page's `matched`:
`discussion.total` for `network: 'all'`, that network's `discussion.by_network` count for one network (`discussion`
always counts the whole pool). A cursor whose build is gone answers `status: 'expired'`: start again from the first page.

`sdk.discovery.recommendations({ kind, category?, limit?, session?, exclude? })` is
the app's one recommender for suggestion rails: `kind` is `member`, `group`, `tag`,
`network_account` or `story`, and `category` is `all` or a browse category id. It
suggests only active or warm entities that pass the server's gates (no link feeds,
bursts, mirrored `name@host` feeds, single-poster groups or unsafe names), leaves out
what the viewer follows, joined, blocked or muted, and says why a list is empty in
`meta.reason`. Call `sdk.discovery.recordImpressions({ kind, keys, event })` with
`shown` when suggestions are on screen and `engaged` on a tap, follow or join: three
showings without a tap rest a suggestion for fourteen days, and engaging clears it.
Keep one `session` token per app session so a rail does not reshuffle on every render.

`sdk.discovery.places({ limit? })` (0.7.216) is the same recommender's "mine" mode, for a
Recent list under Create: only ties the member already has. `data.rows` (at most 12) puts
needs-you first (join requests in groups they own or admin, `need: 'requests'`; unread mentions
and replies, `need: 'mentions'`), then chats with unread messages (a name and the count,
never a message; an encrypted chat has `name: null`, so name it as your Chat list does;
leave out chats the member archived or muted on the device, as your Chat badge does),
then the groups with news since the member last opened them, the people they reply to,
remind, vote on and tap, the categories they open and the searches they repeat. Every
`href` is an in-app route, and a row's counts (`unread`, `pending`, `new_posts`) stop at 99:
show 99 as "99+". `data.arrival` counts what came with a returning legacy member
(their own follows, groups, chat rooms and posts) within 30 days of their first 2.0
session; `data.next_step` is the first action-ladder rung they have not done. Record
`shown` for the habit rows on screen (never for chats), `engaged` when one is opened and
`removed` for "Remove from recent" with `recordImpressions`, whose `kind` also takes
`category` and `search`: three sessions shown without a tap rest a row fourteen days,
removing rests it thirty. Category and search rows do not rest yet: their writes answer
`{ recorded: 0, reason: 'unavailable' }` until the server's table takes those kinds, so
hide "Remove from recent" on them (or expect them back on the next read). It needs the member's own key of the app and answers 404
(`places_disabled`) until the operator turns places on for the app.

A category feed never ends at an empty page. `sdk.posts.list({ category, sort: 'hot' })`
(or `score`, or the default chronological order) pages the window of the category's
newest judged posts, then continues by keyset through the whole indexed
history: every page's `meta.next` is `{ offset }`, `{ cursor }` or `null`, and when a
stage ends `meta.fallover` lists where to go, in order: `category_older` (the keyset
cursor `next` also carries), `category_network` (the same category on the open
networks), the member's next categories (`via` names the order they came from), `for_you`
and `all`. A `feed` step (`ref`, the next feed's ref; 0.7.60) is declared but not sent yet:
skip a kind your app cannot open. A `DiscoveryFeedSession` follows the cursor itself and
reports the Minds feed's `fallover` on its pages, leaving out any step this SDK does not
know or a malformed one. `sdk.discovery.category({ category, session? })` answers a
category's surface in one call: `stories`, `network` and `clips` (each shared per app and
category, refreshed after 30 s, kept up to 300 s and warmed as the warmer reaches the category, then filtered for the viewer on every call: the cached safety verdicts of story members, network posts and clips again, the term list, the viewer's blocks and mutes over clips, and the member's own hidden sources over network posts and story members) and the
viewer's `people` and `groups`; a section that timed out, failed or is off is empty with a
`reason` for that request only (a failure is never cached, so asking again retries it), and one this
key may not read is empty with `refused` (`stories` and `network` need the member's own app
key with `users:read`; `people` and `groups` need `users:read`). `sdk.discovery.videos({ category?, limit?, cursor?, offset?, compass? })`
is Watch's Minds read: the app's public video posts in hot order, from one list the server shares among every viewer of
the app and rebuilds about once a minute, each post checked again on every call under the public floors and the viewer's
blocks and mutes, in the `Post` shape with the viewer's own `user_reaction` and `reposted_by_viewer_id` (page on
`meta.next_cursor`; a feed session's Minds slot can read it as its `list`). With no category, about one row in four is
an open-network clip (0.7.78): `{ kind: 'social', id, post }` (`WatchNetworkClip`, `isWatchNetworkClip(row)`), its `post`
a `SocialPost` cleared for visitors; a feed session hands it on as a `social` item under the network's own key. A plain category page
(`posts.list({ category })` with no other filter) reads on past a slice the safety floors
thinned, up to six reads, until it holds `limit` posts or its candidates end: `meta.scanned`
is how many it examined (the next offset is `offset + scanned`), and the stage ends on the
page that reaches its end, with `next` and `fallover`, rather than after a trail of empty
pages. In a category, Discover's read of Bluesky (`getPublicTrends` with `category` and
`discovery: true`) is the network's posts judged into the category from the source index,
as a page of posts with an `idx:tf:` cursor (pass it back to `getPublicTrends`), not the
topic catalog, which ignores the category; with the index off the catalog is answered as
before. A Bluesky topic feed in a category whose topic is gone, or whose page holds nothing
in the category, is served the network's indexed posts in it (`sourceIndex.reason` of `gone`
or `empty`) with an `idx:tf:` cursor that continues in the index; the provider's deeper pages
of such a topic are not read. In a category, a network's feed ends when its source does (a null
cursor) or on the third page in a row that shows no posts: an `idx:` cursor carries that count,
so pass it back unchanged; a provider's own cursor continues until the provider ends it. While a
category is read from the index, the server reads one Bluesky catalog topic a minute into it in
the background. When the index cannot answer (busy, or its safety cache unreadable), the page
is what the provider answered: the empty page, or the gone topic's 404; only an `idx:tf:` page
answers 503 `unavailable`, and that ends the index continuation, not the network. The app
contract: a `trend_unavailable` 404, an empty topic page or a failed `idx:tf:` page never
disables a network for the session; move to the next topic, start the `idx:tf:` stream once per network and session
(every such topic answers the same index stream; after a failed page it may start again),
and pass cursors back unchanged. `DiscoveryFeedSession` does this for you.

`sdk.posts.categories()` answers the app's categories in the order this member
should see them. `meta.order` is `personal`, `popular` or `static`; `meta.reason`
says why an answer is not personal (`low_signal`, `deadline`, `requested`,
`experiment_off`), and `meta.order_id` changes only when the order does. The order
is private to the member; show it as returned rather than sorting it again.

Optional `DiscoveryLearning` consumes real visible impressions and explicit
engagement/hide outcomes. Persist its count-only snapshot per viewer; never share
a session or learning state across accounts. It starts conservatively and does
not imply measured retention improvement.

For the CLI, `recursiv posts suggest --project-id <id> --draft-file ./draft.txt` sends an explicitly chosen UTF-8 draft to the configured AI provider and prints reviewable JSON. This is a billed AI call, not a publish. Use `--post-id <id>` for an existing post so owner and safety checks apply.

Ranked open-network discovery accepts `preferredLanguage` on `getPublicTrends`, `getPublicTrendFeed`, `getSharedTrends` and `getSharedTrendFeed`. Pass the account's content-language choice (or the device language for a visitor). Matches move first within each page; unknown and other languages stay visible in their original relative order. Providers and their shared caches never receive the preference. Existing servers may refuse the new optional parameter; deploy compatible API support before sending it. `preferContentLanguage(items, language, languageOf?)` provides the same stable page ordering locally, including author-declared native `publication_metadata.language`; it is for recommendations, never search, following or explicit date sorts. Source-index rows currently carry no language and stay unknown.

For rendered discovery, pass `preferredLanguage` to `discovery.createFeed`, `createPersonalFeed` or `createProgressiveFeed` (the progressive settings also accept it). The SDK carries it through session rows and final engagement composition without a new API parameter. `composeFirstScreen(parts, { preferredLanguage })` and the optional sixth argument of `mergeDiscoveryArrival` preserve it through client composition; custom comparators use `discoveryModuleLanguageRank(module, preferredLanguage)` after pinned-top and quality tier, before engagement score. Top, story and recommendation placements remain owned by their existing rules.

Member content covers require explicit application support: first read `settings.getContentControls()` with the current client. Only after `capabilities.cover_protocol === 'd18-v1'` and every material cover consumer is implemented, call `sdk.setContentPolicy({ protocol: 'd18-v1', surface: 'web' })`, then reread controls. `setContentPolicy(null)` withdraws negotiation without replacing auth or Sealed clients. Default clients send no new headers; negotiated headers go only to the bounded member GET allowlist. Validate `readContentSensitivity`, verify SHA256 of `contentSensitivityDigestInput(post)` using the platform crypto API before mounting children, and cover the whole post while verification is pending or fails. Absent metadata retains legacy behavior.

Content-control saves require the supporting API's durable `security.content_controls_changed` outbox admission and audit consumer. An unavailable/disabled receipt returns 503 and saves nothing; a private test pack or source support does not establish production activation. See the platform's network-content-controls release conditions.
