# FluxyChat > Realtime rooms on Cloudflare Workers (Durable Objects + D1). Chat, presence, Yjs, agents, and HTTP ingest share one room Durable Object. MIT self-host or hosted beta. FluxyChat is a tenant room on a Durable Object. Map roomId to a deal, board, classroom, or dispatch view. Humans and invokeAgent share the chat timeline. Feeds are agent and workflow logs, not chat. Cloudflare Think is an Agent class. Document CRDT products are the file. We are the room. FluxyChat is a room layer for your product. Public rooms: FluxyRealtimeProvider publishableKey (pk_; POST /tokens/anonymous) or FluxyChatClient.joinPublicRoomAsGuest (stable guestKey in localStorage). Private rooms: mint a member JWT with POST /auth/token and header X-Fluxy-Api-Key (fc_ keys are server-only; pk_ returns 403). Scaffold with npx @fluxy-chat/create-fluxy-chat@latest (the unscoped create-fluxy-chat package is not ours). Open two browser tabs for cursors, presence, or Yjs. Named errors: FluxyNotMemberError, FluxyTokenExpiredError, FluxyAnonymousNotAllowedError. Message quota: persisted chat + non-ephemeral client_event; cursors do not count. Presence is sendCursor / liveCursors / presence_patch (WebSocket type cursor). Large rooms switch presenceKind to aggregate above 250 unique users. Derived late-joiner JSON is setDerivedState (not a CRDT, 16 KiB). Visibility is visibility/visibleTo on send (kernel, not UI-only). Broadcast is sendClientEvent; prefix client-ephemeral-* skips webhooks. Pointers on client_event warn in development. Storage is FluxyYjsProvider plus useStorage from @fluxy-chat/sdk/yjs. Nest it under FluxyRealtimeProvider or pass token/authTokenProvider. Feeds are /rooms/:id/feeds, not chat messages. Comment pins are /comment-threads (useThreads). Chat nested replies are parentId / useThread / GET /rooms/:id/threads. Room agents use invokeAgent. Copilots use RegisterAiKnowledge and AiChat (they do not write the timeline). Hosted onPublish overlay: PUT /admin/projects/:id/publish-config (CLI: pnpm fluxy:deploy) including rooms templates and extension slots. Inbox socket: GET /ws/inbox (connectInbox). Weekend demo: GET /public/demo-credentials when PUBLIC_DEMO_PUBLISHABLE_KEY is set. FluxyRealtimeProvider takes workerUrl plus publishableKey, authTokenProvider, or connectUrl (not token/config.baseUrl). Nest useChat under it. useChat and useLiveCursors share sessionScope app (one JSON WebSocket per room). Pass a distinct sessionScope for a second widget on the same room. Yjs opens a second binary WebSocket on the same /ws/room/:id route. Spec: /docs/core/wire-protocol. IoT and fleet ingest HTTP and fan out server_event names iot.reading and fleet.gps_update. Set iotAutoAgentId on publish-config to invoke an agent without @mention. Geofences are GET/POST /fleet/geofences (listFleetGeofences), not a location SDK package. useLocation consumes fleet tracks. Games use /games/* plus game.tick after startMatch. Voice stage is joinVoiceStage signaling. Cross-org negotiation is REST /cross-org. Omnichannel lives in console Bridges with per-vendor OAuth and signing secrets. RCS uses RCS_OUTBOUND_URL plus RCS_WEBHOOK_SECRET. Voice clone/translation posts to /voice-ai/clone-translate, which calls VOICE_CLONE_URL on your media box. Voice P95 tables are SLO targets from a unit bench, not fleet measurements. Hosted is beta. Pin npm versions. Vue/Svelte packages are best-effort vs React. ## Docs - [Docs home](https://docs.fluxychat.com/docs): Start here. Hosted, self-host, or SDK-only. - [Status and limits](https://docs.fluxychat.com/docs/learn/status-and-limits): What ships, what is labs, what is not claimed. - [Concepts](https://docs.fluxychat.com/docs/concepts): Projects, rooms, presence, broadcast, storage, feeds, threads, chat. - [Choose your path](https://docs.fluxychat.com/docs/getting-started/choose-your-path): Hosted CLI, your Worker, or a few lines of SDK. - [What to build](https://docs.fluxychat.com/docs/getting-started/what-to-build): Product idea to gallery example. - [Gallery](https://docs.fluxychat.com/docs/getting-started/gallery): Copy-paste Vite apps. deal-room and negotiation-room: this URL and ?seat=counsel. - [CLI and examples](https://docs.fluxychat.com/docs/getting-started/for-coding-agents): create-fluxy-chat flags, env vars, JWT mint. Skill: npx skills add AlessandroFare/fluxychat --skill fluxy-chat-room. - [Quickstart](https://docs.fluxychat.com/docs/getting-started/quickstart): pk_ in the browser, then member JWT. - [Wire protocol](https://docs.fluxychat.com/docs/core/wire-protocol): v1 frames and non-goals. - [Client setup](https://docs.fluxychat.com/docs/getting-started/client-setup): React, vanilla, React Native. - [Self-hosting](https://docs.fluxychat.com/docs/getting-started/self-hosting): Worker on your Cloudflare account. - [useChat](https://docs.fluxychat.com/docs/core/use-chat): Timeline, agents, most room APIs. - [Presence](https://docs.fluxychat.com/docs/core/presence-typing): Who is here, cursors, selections. - [Broadcast](https://docs.fluxychat.com/docs/core/broadcast): Sparse one-shot events. - [Storage](https://docs.fluxychat.com/docs/core/storage): Yjs, Tiptap, whiteboard. - [Comments](https://docs.fluxychat.com/docs/core/comments): Pinned threads. - [Chat reply threads](https://docs.fluxychat.com/docs/core/nested-threads): useThread on parentId. Same room socket. - [Feeds](https://docs.fluxychat.com/docs/core/feeds): Activity logs. - [Copilots](https://docs.fluxychat.com/docs/core/copilots): Side-panel AI. - [Notifications](https://docs.fluxychat.com/docs/core/notifications): Inbox and daily digest. - [Voice](https://docs.fluxychat.com/docs/core/voice-huddles): Clips, stage signaling, clone proxy. - [Platform modules](https://docs.fluxychat.com/docs/features/platform-status): IoT, fleet, game, RCS, Bridges, commerce, federation. - [Platform overview](https://docs.fluxychat.com/docs/platform): Console modules on one Worker. - [FluxyEdu](https://docs.fluxychat.com/docs/platform/edu): Polls, breakouts, attendance. Video is Cloudflare Realtime SFU. - [Chatbot builder](https://docs.fluxychat.com/docs/platform/chatbot-builder): Trigger-action workflows on /api/workflows. - [Marketplace](https://docs.fluxychat.com/docs/platform/marketplace): Agent templates and MCP apps. - [Web3 rooms](https://docs.fluxychat.com/docs/platform/web3): Worker SIWE mint (/auth/wallet + fc_). Token gates stay on your server. - [Collab](https://docs.fluxychat.com/docs/platform/collab): Yjs on the room. Excalidraw is a local renderer. - [Spatial](https://docs.fluxychat.com/docs/platform/spatial-digital-twin): Scenes, entities, MCP grants. - [Voice AI](https://docs.fluxychat.com/docs/platform/voice): STT/TTS. Huddle media is Cloudflare Realtime SFU. - [Auth JWT](https://docs.fluxychat.com/docs/guides/auth-jwt): Mint tokens from your backend. - [Publishable keys](https://docs.fluxychat.com/docs/guides/publishable-keys): pk_ in the browser, fc_ on the server. - [Polls](https://docs.fluxychat.com/docs/core/polls): Timeline polls and anonymous ballots. - [Voice load report](https://docs.fluxychat.com/docs/operations/voice-load-test-report): SLO targets (unit bench), not fleet P95. ## Examples - [live-cursors](https://docs.fluxychat.com/docs/getting-started/gallery): Presence pointers. - [live-cursors-chat](https://docs.fluxychat.com/docs/getting-started/gallery): Cursors plus chat. - [javascript-live-cursors](https://docs.fluxychat.com/docs/getting-started/gallery): Vanilla JS pointers. - [tiptap-room](https://docs.fluxychat.com/docs/getting-started/gallery): Collaborative editor. - [whiteboard](https://docs.fluxychat.com/docs/getting-started/gallery): Y.Array strokes plus cursors. - [draw](https://docs.fluxychat.com/docs/getting-started/gallery): Ephemeral stamps. - [comments-board](https://docs.fluxychat.com/docs/getting-started/gallery): Contextual pins. - [polls](https://docs.fluxychat.com/docs/getting-started/gallery): createPoll / votePoll. POST /polls isAnonymous for ballots. - [war-room](https://docs.fluxychat.com/docs/getting-started/gallery): Humans and invokeAgent. - [deal-room](https://docs.fluxychat.com/docs/getting-started/gallery): Decisions and markdown export. - [iot-panel](https://docs.fluxychat.com/docs/getting-started/gallery): HTTP ingest, iot.reading. - [fleet-panel](https://docs.fluxychat.com/docs/getting-started/gallery): GPS ingest, fleet.gps_update. - [game-tick](https://docs.fluxychat.com/docs/getting-started/gallery): Lobby, ticks, leaderboard. - [voice-stage](https://docs.fluxychat.com/docs/getting-started/gallery): Speaker roster signaling. ## API - [HTTP reference](https://docs.fluxychat.com/docs/api-reference): Worker REST. - [OpenAPI YAML](https://docs.fluxychat.com/openapi.yaml): Machine-readable routes. - [@fluxy-chat/sdk](https://docs.fluxychat.com/docs/packages/sdk): Client, REST, Yjs, verticals. - [@fluxy-chat/react](https://docs.fluxychat.com/docs/packages/react): Provider and hooks. - [@fluxy-chat/ui](https://docs.fluxychat.com/docs/packages): Cursors, Thread, AiChat. - [npm sdk](https://www.npmjs.com/package/@fluxy-chat/sdk): Published client. - [npm react](https://www.npmjs.com/package/@fluxy-chat/react): Published hooks. - [npm ui-kit](https://www.npmjs.com/package/@fluxy-chat/ui-kit): FluxyChatWidget, FluxyInboxPanel, guest plus pk_. - [npm vue](https://www.npmjs.com/package/@fluxy-chat/vue): Vue 3 composables. - [npm svelte](https://www.npmjs.com/package/@fluxy-chat/svelte): Svelte 5 stores. - [npm create-fluxy-chat](https://www.npmjs.com/package/@fluxy-chat/create-fluxy-chat): Scaffold CLI. ## Optional - [GitHub](https://github.com/AlessandroFare/fluxychat): Source, MIT. - [Hosted app](https://fluxychat.com): Console and playground. - [Pricing](https://fluxychat.com/pricing): Hosted plans. Open beta. Pin versions. - [Status](https://fluxychat.com/status): Worker /health. Not a fleet SLO. - [Trust](https://fluxychat.com/trust): DPA, subprocessors, security.txt. Not SOC 2. - [Import ChatGPT JSON](https://fluxychat.com/migrate-chatgpt): File you downloaded. Cap 400. - [Subprocessors](https://fluxychat.com/subprocessors): Cloudflare, Clerk, Stripe, LLM, Vercel. - [Cookbook](https://docs.fluxychat.com/docs/cookbook): JWT, RAG, offline. - [Integration kit](https://docs.fluxychat.com/docs/guides/integration-kit): Entity rooms, signed inbound webhooks. - [Public share](https://docs.fluxychat.com/docs/guides/public-share): Read-only URL for type=public rooms. - [Import transcript](https://docs.fluxychat.com/docs/guides/import-transcript): ChatGPT/Claude export JSON. - [Room tickets](https://docs.fluxychat.com/docs/guides/room-tickets): GitHub/Linear/Jira with your env tokens. - [Shared-room agent defaults](https://docs.fluxychat.com/docs/guides/security/shared-room-agent-defaults): Two-key HITL. - [Room Decisions](https://docs.fluxychat.com/docs/guides/room-decisions): Floor, route, NL policy. - [@fluxy-chat/auth](https://docs.fluxychat.com/docs/packages/auth): Mint helper. fc_ on the server. --- # Testing in FluxyChat monorepo (/docs/TESTING) Testing in FluxyChat monorepo [#testing-in-fluxychat-monorepo] What runs when you invoke tests from the repo root and how to run focused suites locally. Root commands [#root-commands] | Command | What runs | | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pnpm test` | Everything: packages (unit), worker + pool, worker e2e, ai-agent, dashboard | | `pnpm test:packages` | Unit tests for the 12 packages wired into this command (protocol, sdk, react, vue, svelte, ui, config, agent, auth, react-native-sdk, chat-adapter-fluxychat, cloudflare-agents) | | `pnpm test:ai-agent` | AI agent service unit tests (`apps/ai-agent`) | | `pnpm test:e2e:smoke` | Dashboard Playwright smoke (`*.smoke.spec.ts`) — no worker/JWT | | `pnpm run check:bundle-size` | Gzip report for SDK entrypoints (`bundle-size-report.json`) | | `pnpm run check:publish-manifest` | Packed tarball has no `workspace:` ranges; exports resolve | | `pnpm run smoke:create-fluxy-chat` | Scaffold smoke for `create-fluxy-chat` CLI | | `pnpm run smoke:typecheck-templates` | Scaffold every `create-fluxy-chat` template and typecheck it (nightly drift check) | | `pnpm --filter @fluxy-chat/worker test:pool` | workerd pool tests: alarm queues + hibernation registry (`@cloudflare/vitest-plugin`) | CI (`.github/workflows/ci.yml`) also runs docs build, pricing/tenant/openapi checks, and integrated E2E on a separate job when configured. Per-package unit tests [#per-package-unit-tests] | Package | Command | Focus | | ----------------------- | ----------------------------------------------------- | ------------------------------------------------------ | | `@fluxy-chat/protocol` | `pnpm --filter @fluxy-chat/protocol test` | WS frame parsing, event registries, conformance | | `@fluxy-chat/sdk` | `pnpm --filter @fluxy-chat/sdk test` | Client, hooks, cards, structured errors, testing utils | | `@fluxy-chat/react` | `pnpm --filter @fluxy-chat/react test` | React hooks re-exports | | `@fluxy-chat/ui` | `pnpm --filter @fluxy-chat/ui test` | Message list, input, safe-url | | `@fluxy-chat/config` | `pnpm --filter @fluxy-chat/config test` | Shared config helpers | | `@fluxy-chat/agent` | `pnpm --filter @fluxy-chat/agent test` | Agent runtime helpers | | `@fluxy-chat/dashboard` | `pnpm --filter @fluxy-chat/dashboard exec vitest run` | Console nav, feature flags, lib helpers | Worker and docs site do not have root `pnpm test` entries; use package filters: ```bash pnpm --filter @fluxychat/worker typecheck pnpm run docs:build ``` Dashboard E2E (Playwright) [#dashboard-e2e-playwright] **Smoke** (default in CI, no secrets): ```bash pnpm test:e2e:smoke ``` Covers onboarding UI, inbox shell, portal-parity weak-network smoke, landing, billing shell, status page. **Integrated** (local worker + dashboard + admin JWT): ```bash # Terminal 1 pnpm --filter @fluxychat/worker dev # Terminal 2 E2E_ADMIN_JWT= pnpm --filter @fluxy-chat/dashboard test:e2e:integrated ``` Integrated specs: onboarding full path, inbox feed, portal-parity send + offline recovery. Set `PLAYWRIGHT_SKIP_WEBSERVER=1` if dashboard is already running on port 3000. SDK integration testing [#sdk-integration-testing] Use `@fluxy-chat/sdk/testing` in Vitest — see [Testing integrations](/docs/guides/testing-integration) on the docs site. Conformance / protocol [#conformance--protocol] `packages/protocol/src/conformance-synthetic.test.ts` validates synthetic worker↔client frames against `protocol-events.json`. Run after changing `event-types.ts`. Environment hints [#environment-hints] `pnpm run check:env` prints missing vars for local dev (Worker URL, Clerk, VAPID, etc.) without failing CI. --- # Concepts (/docs/concepts) FluxyChat is a room on Cloudflare: one Durable Object plus D1. Map `roomId` to a deal, a classroom, a board, a dispatch view. Chat and presence share a JSON WebSocket. Yjs uses a second binary connection to the same object. Your auth and data model stay yours. Member JWTs (or a public-room guest session) open the socket. Hosted is beta. Self-host is MIT on your Cloudflare account. Cloudflare Think treats the agent as the unit of compute. Document collab products treat the file as the unit. We treat the room as the unit: humans and `invokeAgent` write the same chat timeline. Copilot UI (`AiChat`) stays off that timeline. Building blocks [#building-blocks] | Concept | FluxyChat | | ---------- | ------------------------------------------------------------------------------------------------------------ | | Project | Tenant. API keys (`fc_…`, server-only), rooms, agents, quotas. | | Room | One Durable Object. Chat JSON WebSocket; Yjs is a second binary connection on the same `/ws/room/:id` route. | | Primitives | Presence, Broadcast, Storage, Feeds, Threads, Chat, Polls, Derived, Visibility. | | Users | Humans (member JWT or guest) and AI (copilot, room peer, workflow). | | Features | Comments, multiplayer editors, notifications, copilots, AI collaboration. | | Platform | Worker, dashboard, `@fluxy-chat/sdk`, `react`, `ui`, `ui-kit`, `vue`, `svelte`. | Primitives (pick the right one) [#primitives-pick-the-right-one] | Primitive | Means | API | Stored? | | -------------- | ---------------------------------------------------- | ------------------------------------------------------------------- | ------------------------ | | **Presence** | Now: who is here, cursors, selections, `agentStatus` | `sendCursor`, `useMyPresence` / `presence_patch`, `presenceMembers` | No | | **Broadcast** | Pulse: one-shot signals | `sendClientEvent` / `useBroadcastEvent` | No | | **Storage** | The document | `FluxyYjsProvider`, `useStorage`, `useMutation`, LiveFile | Yes (Yjs on the room DO) | | **Feeds** | Activity / agent / n8n logs | `useFeeds`, `POST /rooms/:id/feeds` | Yes (D1, ≠ chat) | | **Threads** | Contextual comments | `useThreads`, `/comment-threads` | Yes | | **Chat** | Timeline + nested replies | `useChat`, `useThread`, `parentId` | Yes | | **Polls** | Ballots on the timeline (and `/polls` records) | `createPoll` / `votePoll`, `POST /polls` `isAnonymous` | Yes | | **Derived** | Late-joiner JSON bag (not a CRDT) | `setDerivedState` / `derivedState` | Yes (DO storage) | | **Visibility** | Who may see a chat line | `visibility` / `visibleTo` on send | Yes (D1) | Do **not** put 60 Hz pointers on Broadcast. Do **not** mix Feeds with `messages`. Do **not** mix comment pins (`useThreads`) with chat `parentId` replies (`useThread`). Do **not** hide private lines only in the UI. Set `visibility` on send. Wire limits and v1 non-goals: [Wire protocol](/docs/core/wire-protocol). Two kinds of AI [#two-kinds-of-ai] | Kind | API | Writes | | -------------------- | -------------------------------------------------- | ---------------------------- | | Copilot (side panel) | `RegisterAiKnowledge` + `useAiChat` + `` | Local UI only (keyless mock) | | Room peer | `invokeAgent` on `useChat` | Chat `messages` | | Workflow | API key `POST …/feeds/…/messages` | Feed + `server_event` | Auth [#auth] Browser: **`publishableKey` (`pk_`) on `FluxyRealtimeProvider`** (anonymous JWT via `POST /tokens/anonymous`), **member JWT**, or `FluxyChatClient.joinPublicRoomAsGuest(workerUrl, publicRoomId)` (stable `guestKey` in localStorage). Guest writes are on by default; set `PUBLIC_GUEST_READ_ONLY=true` to lock.\ Server: project API key (`fc_…`) mints member JWTs (`POST /auth/token`). `pk_` is rejected there (`403`). Never put `fc_…` in the client. Verticals on the same bus [#verticals-on-the-same-bus] IoT, fleet, game ticks, voice stage, deal quorum: all `server_event` or chat on the same room WebSocket. [Gallery](/docs/getting-started/gallery) has a copy-paste app for each. Those modules are optional. The product is the room. [Status and limits](/docs/learn/status-and-limits). Next: [Getting started](/docs/getting-started) · [CLI and examples](/docs/getting-started/for-coding-agents) --- # FluxyChat Docs (/docs) FluxyChat is the room you put in the product. One Durable Object plus D1. People and agents share that room. Map `roomId` to a document, board, deal, classroom, or dispatch view. Auth stays yours. Chat and presence use a JSON WebSocket. Yjs uses a second binary connection to the same object. That is the design, not a shortcut. Start with `publishableKey` on `FluxyRealtimeProvider`, or `npx @fluxy-chat/create-fluxy-chat@latest`. Then [Concepts](/docs/concepts) or [What to build](/docs/getting-started/what-to-build). Collaboration features [#collaboration-features] Packages [#packages] What you need [#what-you-need] | Piece | Who sets it | | ------------------------ | -------------------------------------------------------------------------------------------------- | | Worker URL | Hosted API or your `workers.dev` | | Public room | `FluxyRealtimeProvider` + `publishableKey` (`POST /tokens/anonymous`). Widget `guest` still works. | | Project API key (`fc_…`) | Server only. Mints member JWTs. | | Member JWT | Private rooms, roles, production. | | LLM keys | Worker secrets. Never the browser. | Try [fluxychat.com](https://fluxychat.com). Self-host: `pnpm install && pnpm run self-host && pnpm --filter @fluxy-chat/worker dev`. --- # API Reference (/docs/api-reference) Every route below is served by your Worker (`openapi.docs.yaml`). Expand **HTTP API** in the sidebar for tag groups (Auth, Messages, Rooms, Agents, Admin, …). Each page includes method badges and a try-it curl panel. WebSocket room sockets and the user channel are documented under [Wire protocol](/docs/architecture/response-envelope-extension), not in this OpenAPI tree. --- # Audit remediation (internal) (/docs/audit/REMEDIATION) This remediation tracker is for FluxyChat contributors only. It is not part of the public product documentation. For security and compliance guidance, see [SOC 2 readiness checklist](/docs/guides/enterprise/soc2-readiness-checklist) and [Agent tool exfiltration](/docs/security/agent-tool-exfiltration). --- # Production due diligence audit (internal) (/docs/audit/production-due-diligence-2026-06-15) This audit report is maintained for the core team and is not part of the public product documentation. For integrators evaluating production readiness, use: * [Platform roadmap status](/docs/features/platform-status) * [Production setup](/docs/operations/production-setup) * [SOC 2 readiness checklist](/docs/guides/enterprise/soc2-readiness-checklist) --- # Chat only (/docs/chat-only) Chat only [#chat-only] Minimal path for **in-app chat**: install the SDK, mint a JWT, wire `useChat` and optional `useInbox`. Skip stream, IoT, fleet, and spatial modules until you need them. Start here [#start-here] 1. [Chat-only quickstart](/docs/getting-started/chat-only-quickstart) — install, JWT, first message 2. [Scaffold with React](/docs/packages/react) — `npx @fluxy-chat/create-fluxy-chat@latest my-chat --template react` 3. [Inbox & notifications](/docs/guides/chat/inbox-notifications) — `useInbox`, badges, mark-read Compare & checklist [#compare--checklist] * [Feature parity checklist](/docs/guides/feature-parity-checklist) — hosted vs self-host, what the JS SDK covers * [Messages API](/docs/core/use-chat) — REST + WebSocket events When you need more [#when-you-need-more] Expand into [How-to guides](/docs/guides), [Platform](/docs/platform), or [Features](/docs/features) from the main docs nav. --- # Architecture (/docs/architecture) FluxyChat is a Cloudflare Worker plus Durable Objects and D1. Clients hold a member JWT and open a WebSocket to a room. * [Platform expansion](/docs/architecture/platform-expansion-layer) * [Response envelope](/docs/architecture/response-envelope-extension) * [Worker splitting](/docs/architecture/worker-splitting-plan) --- # Platform expansion layer (internal) (/docs/architecture/platform-expansion-layer) This page is for FluxyChat contributors. End users should use the public guides linked below. * [SDK reference](/docs/packages/sdk) * [Adapter pattern](/docs/guides/adapter-pattern) * [Unified Chat API](/docs/guides/unified-chat-api) --- # Response envelope extension (internal) (/docs/architecture/response-envelope-extension) This page documents internal API envelope conventions for contributors. Public API behavior is covered in the [SDK reference](/docs/packages/sdk) and [Dashboard integration](/docs/reference/dashboard-integration). --- # Vertical platform expansion (internal) (/docs/architecture/vertical-platform-expansion) This architecture document is maintained in the repository for the core team. It is not part of the public product documentation. If you are building on FluxyChat verticals, start here instead: * [FluxyEdu quickstart](/docs/guides/fluxy-edu-quickstart) * [Decision Rooms](/docs/guides/decision-rooms) * [Telephony handoff](/docs/guides/telephony-handoff) * [Announcement channels](/docs/guides/announcement-channels) * [Self-hosting](/docs/getting-started/self-hosting) --- # Worker splitting plan (internal) (/docs/architecture/worker-splitting-plan) This planning document lives in the repository for operators scaling self-hosted deployments. Integrators do not need it for day-to-day integration. See [Production setup](/docs/operations/production-setup) and [Observability](/docs/operations/observability) for operational docs. --- # Cookbook: Auth / Token / JWT (role-based) (/docs/cookbook/auth-jwt) Cookbook: Auth / Token / JWT (role-based) [#cookbook-auth--token--jwt-role-based] Fluxychat uses two credential forms: * **API key** (`X-Fluxy-Api-Key`): server-to-server, identifies the **tenant/project**. * **JWT** (`Authorization: Bearer ...`): client-to-worker/SDK, contains `sub` (userId), `tid` (projectId), `roles`, `exp`. Practical rule: * **Your app** keeps the API key on the backend and **mints JWTs** for clients (never expose the API key in the browser). Useful variables [#useful-variables] ```bash export FLUXY_BASE_URL="http://127.0.0.1\:8787" export FLUXY_API_KEY="fc_..." ``` 1\) Mint JWT (server-side) [#1-mint-jwt-server-side] Endpoint: `POST /auth/token` ```bash curl -sS -X POST "$FLUXY_BASE_URL/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "userId": "alice", "roles": ["member"], "ttlSeconds": 3600 }' ``` Response: * `token`: JWT * `expiresIn`: seconds * `claims`: echo of main claims 2\) Roles: what they unlock (quick map) [#2-roles-what-they-unlock-quick-map] Roles live in the JWT `roles` claim. * **member**: basic chat (send/edit/delete own message, read receipts, reactions) * **moderator**: admin/moderation actions (e.g. mute/ban, webhook replay) where allowed * **admin**: standard admin ops (alert rules, webhooks, projects…) unless restricted * **owner**: superset of `admin` (for more sensitive operations) Note: different admin endpoints require specific roles. In general: * `/admin/alerts/rules`: **owner/admin** * `/admin/projects*`: **owner/admin** * `/admin/mute|ban|unmute|unban|announcement`: **owner/admin/moderator** * `/admin/audit/events`: **owner/admin** 3\) Role-based examples [#3-role-based-examples] 3.1 JWT for a `member` user [#31-jwt-for-a-member-user] ```bash curl -sS -X POST "$FLUXY_BASE_URL/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "userId": "customer_123", "roles": ["member"], "ttlSeconds": 3600 }' ``` 3.2 JWT for `moderator` [#32-jwt-for-moderator] ```bash curl -sS -X POST "$FLUXY_BASE_URL/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "userId": "mod_1", "roles": ["moderator"], "ttlSeconds": 3600 }' ``` 3.3 JWT for `admin` [#33-jwt-for-admin] ```bash curl -sS -X POST "$FLUXY_BASE_URL/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "userId": "admin_1", "roles": ["admin"], "ttlSeconds": 3600 }' ``` 4\) REST calls with JWT [#4-rest-calls-with-jwt] Send message [#send-message] ```bash export JWT="" export ROOM_ID="" curl -sS -X POST "$FLUXY_BASE_URL/messages" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "'"$ROOM_ID"'", "content": "hello" }' ``` Admin mute (moderator/admin/owner) [#admin-mute-moderatoradminowner] ```bash export ADMIN_JWT="" curl -sS -X POST "$FLUXY_BASE_URL/admin/mute" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "'"$ROOM_ID"'", "userId": "customer_123", "reason": "spam", "durationSeconds": 600 }' ``` 5\) WebSocket auth (client-side) [#5-websocket-auth-client-side] Format: * `GET /ws/room/:roomId?token=<JWT>` * membership check enforced ```js const wsUrl = `${baseUrl.replace("http", "ws")}/ws/room/${roomId}?token=${encodeURIComponent(jwt)}` const ws = new WebSocket(wsUrl) ``` 6\) Next.js snippet (Route Handler) to mint JWT [#6-nextjs-snippet-route-handler-to-mint-jwt] Conceptual example: your app receives a user session, then calls Fluxychat `/auth/token` with your API key. ```ts import { NextResponse } from "next/server"; export async function POST(request: Request) { const body = await request.json().catch(() => null); const userId = body?.userId; if (!userId) return NextResponse.json({ error: "userId required" }, { status: 400 }); const res = await fetch(`${process.env.FLUXY_BASE_URL}/auth/token`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fluxy-Api-Key": process.env.FLUXY_API_KEY!, }, body: JSON.stringify({ userId, roles: ["member"], ttlSeconds: 3600 }), }); const json = await res.json(); return NextResponse.json(json, { status: res.status }); } ``` 7\) Common failure modes [#7-common-failure-modes] * **401 invalid api key** ([40102](/docs/errors/invalid_api_key)): API key does not resolve a valid project (or is revoked) * **401 token expired** ([40100](/docs/errors/token_expired)): `exp` passed — mint a new JWT (shorter TTL and rotation in your app) * **403 forbidden** ([40302](/docs/errors/forbidden)): token role insufficient for admin endpoint * **403 WS** ([40300 not\_member](/docs/errors/not_member)): user is not a room member (membership check) Every refusal above has a numeric code in the [error catalog](/docs/errors) — branch on the identifier, not on the human-readable message. --- # Cookbook: Node bot that streams into a room (/docs/cookbook/bot-streaming-fluxy-message-stream) Cookbook: Node bot that streams into a room [#cookbook-node-bot-that-streams-into-a-room] Use `FluxyMessageStream` from `@fluxy-chat/sdk` when your bot runs **outside** the Worker (Node script, Cloudflare Worker cron, etc.) but should publish the same streaming UX as built-in agents: one message row, `streaming: true` deltas, then a final edit. The Worker Durable Object handles persistence and broadcasts `message` / `edit` events to WebSocket clients. Prerequisites [#prerequisites] * Member JWT for a user that is a **member** of the room (or admin JWT with room access). * Room id (e.g. `assistant:general`). * Agent id string used as `userId` on stream frames (typically your bot’s `bots.id`). Install [#install] ```bash pnpm add @fluxy-chat/sdk ``` Minimal Node script [#minimal-node-script] ```typescript import { FluxyChatClient, FluxyMessageStream } from "@fluxy-chat/sdk"; const BASE_URL = process.env.FLUXY_BASE_URL ?? "https://api.fluxychat.com"; const MEMBER_JWT = process.env.FLUXY_MEMBER_JWT!; const ROOM_ID = "assistant\:general"; const AGENT_ID = process.env.FLUXY_AGENT_ID!; // bots.id from POST /agents async function main() { const client = new FluxyChatClient({ baseUrl: BASE_URL, userId: "bot-runner", token: MEMBER_JWT, }); const connection = client.connectRoom(ROOM_ID, { replayHistoryOnReconnect: false, historyLimit: 0, }); await new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error("connect timeout")), 15_000); const unsub = connection.addEventListener("message", (ev) => { if (ev.type === "history" || ev.type === "presence") { clearTimeout(timeout); resolve(); } }); connection.connect(); void unsub; }); const stream = new FluxyMessageStream(connection, AGENT_ID, { flushIntervalMs: 120, parentId: null, // or a message id for reply-to }); const chunks = ["Hello ", "from ", "your Node bot."]; for (const chunk of chunks) { stream.push(chunk); await new Promise((r) => setTimeout(r, 200)); } stream.end(); connection.close(); } main().catch((err) => { console.error(err); process.exit(1); }); ``` Wire protocol (what the SDK sends) [#wire-protocol-what-the-sdk-sends] `FluxyMessageStream` emits WebSocket JSON frames understood by the room DO: | Phase | `type` | `op` | Notes | | ----- | -------- | ------- | --------------------------------------------------------- | | Start | `stream` | `start` | `userId`, `content` (initial buffer), optional `parentId` | | Delta | `stream` | `delta` | `messageId`, `content` (full text so far) | | End | `stream` | `end` | Final content; clears `streaming` on the row | | Abort | `stream` | `abort` | Drops in-flight stream | The DO responds with `stream` / `op: "started"` and `id` so the SDK can attach `messageId` before deltas. Reply-to [#reply-to] Pass `parentId` in `FluxyMessageStreamOptions` to thread under an existing message (same as REST `replyTo` / chat `parent_id`). When to use REST invoke instead [#when-to-use-rest-invoke-instead] * You want the Worker **agent runtime** (tools, context fetch, billing, run rows): use `POST /agents/:id/invoke` or `@mention` in chat. * You only need **custom streaming text** from your own LLM loop: `FluxyMessageStream` is the right tool. Related [#related] * [Assistant room use case](/docs/use-cases/assistant-room) * [Dashboard integration](/docs/reference/dashboard-integration) — `useChat` replay modes --- # Connection status (/docs/cookbook/connection-status) Connection status [#connection-status] `room.status()` (same as `room.status.current()`) maps the socket onto attach names: attaching, attached, suspended, failed, detached. `subscribe` fires `{ current, previous, retryIn, error }` on each change. `retryIn` is set in milliseconds while the client is reconnecting or suspended. ```tsx const room = client.room("lobby"); const { current, change } = useRoomStatus(room); const { currentStatus, retryIn } = useChatConnection(room.connection); return (

{current} · socket {currentStatus} {retryIn ? ` · retry in ${retryIn}ms` : ""}

); ``` Full page: [Room status](/docs/rooms/status). Close reasons map to the [error catalog](/docs/errors): auth refusals ([token\_expired](/docs/errors/token_expired), [not\_member](/docs/errors/not_member)) are terminal, network drops ([connection\_failed](/docs/errors/connection_failed)) are not. --- # Cookbook (/docs/cookbook) Short recipes. The [Rooms](/docs/rooms) section is the feature map. Use a [how-to](/docs/guides) when you need the long path. --- # Knowledge Base + RAG agent (/docs/cookbook/kb-rag-agent) Knowledge Base + RAG agent [#knowledge-base--rag-agent] Connect Notion, Confluence, or Google Drive to an in-room Fluxy agent using `@fluxy-chat/sdk` knowledge-base helpers and Worker agent invoke. Overview [#overview] | Piece | Role | | ------------------------- | ------------------------------------------------------------ | | `createKnowledgeBase()` | In-memory index (dev) or swap for Vectorize/D1 in production | | `addSource()` | Register Notion/Confluence/GDrive connector config | | `ingestDocument()` | Chunk + index page content | | `buildRagContext()` | Top-k chunks → prompt prefix for the agent | | `POST /agents/:id/invoke` | Run the agent with RAG-augmented system prompt | 1\. Register sources [#1-register-sources] ```ts import { createKnowledgeBase } from "@fluxy-chat/sdk"; const kb = createKnowledgeBase(); kb.addSource({ type: "notion", name: "Product wiki", connectionConfig: { integrationToken: process.env.NOTION_TOKEN!, databaseId: process.env.NOTION_DB_ID!, }, enabled: true, syncIntervalMs: 3600_000, }); kb.addSource({ type: "confluence", name: "Runbooks", connectionConfig: { baseUrl: "https://acme.atlassian.net/wiki", email: process.env.CONFLUENCE_EMAIL!, apiToken: process.env.CONFLUENCE_TOKEN!, }, enabled: true, syncIntervalMs: 7200_000, }); ``` Store secrets in Worker secrets / your backend — never in the browser. 2\. Sync documents [#2-sync-documents] Pull pages from each provider on a cron or webhook, then ingest: ```ts async function syncNotionPage(sourceId: string, title: string, markdown: string, url: string) { kb.ingestDocument(sourceId, { title, content: markdown, url, metadata: { provider: "notion" }, }); } ``` For Google Drive, export Docs as plain text or Markdown before `ingestDocument`. Chunk size defaults to 500 characters; tune per embedding model context window. 3\. Build RAG context on each user message [#3-build-rag-context-on-each-user-message] ```ts function augmentPrompt(userMessage: string): string { const { synthesizedPrompt, results } = kb.buildRagContext({ text: userMessage, maxResults: 5, minScore: 0.4, }); if (results.length === 0) return userMessage; return `${synthesizedPrompt}\n\n---\nUser question: ${userMessage}`; } ``` `synthesizedPrompt` lists cited chunks with titles and URLs for the model to ground answers. 4\. Wire to Fluxy agent invoke [#4-wire-to-fluxy-agent-invoke] ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl, userId: "support-bot", token: serviceJwt }); export async function answerWithKb(roomId: string, userMessage: string) { const prompt = augmentPrompt(userMessage); await client.invokeAgentRest(agentId, roomId, prompt); } ``` In the dashboard, bind the agent to the support room under **Agents** → enable tools only if the KB miss rate is high. 5\. Production hardening [#5-production-hardening] | Concern | Approach | | ---------- | ------------------------------------------------------------------------------------------------------------------ | | Embeddings | Replace stub cosine in `createKnowledgeBase()` with Workers AI or external embeddings | | Storage | D1 is required. Optional Vectorize: bind `VECTORIZE` + Workers AI; see `createVectorRetriever` / room memory `?q=` | | Freshness | Notion webhooks / Confluence polling cron via Worker `scheduled` | | PII | Redact emails/phones before ingest; tenant-scoped source lists | | Citations | Post a `Card` with doc links when `results.length > 0` | 6\. Verify locally [#6-verify-locally] 1. `pnpm --filter @fluxychat/worker dev` 2. Ingest a sample markdown doc via a small script calling `kb.ingestDocument` 3. Ask the agent a question only answerable from that doc 4. Confirm the reply cites the chunk title/URL See also [#see-also] * [Custom tools](/docs/guides/ai-agents/tool-approval-hmac) — expose `search_kb` as an agent tool instead of pre-prompt injection * [Agent memory](/docs/guides/ai-agents/agent-memory) — long-term customer context alongside KB * [AI agents + handoff](/docs/guides/ai-agents/handoff) — escalate to human when confidence is low --- # Component locks (/docs/cookbook/locks) Component locks [#component-locks] Use this when two people must not edit the same field. Not Yjs. One holder per `lockId`. TTL defaults to 30s; the same owner may refresh. ```ts const room = client.room("board"); room.locks.subscribe((event) => { if (event.lockId === "slide-1" && event.held) { console.log("held by", event.owner); } }); room.attach(); room.locks.acquire("slide-1", { ttlMs: 30_000 }); room.locks.release("slide-1"); ``` A second user receives `held: true` and `acquired: false`. Locks drop when the holder leaves the room. `useLocks()` on `FluxyRoomProvider` wraps acquire/release and keeps the latest lock frame. `useLock("slide-1")` is the holder for one id. --- # Message history (/docs/cookbook/message-history) Message history [#message-history] `room.messages.history()` loads REST pages. Default order is newest first. A full page means `hasNext()` is true; `next()` walks older rows with the `before` cursor. `subscribe()` is live frames only. `historyBeforeSubscribe()` fills the gap before the listener was attached. ```ts const room = client.room("lobby"); const sub = room.messages.subscribe((event) => { if (event.type === "message.created") console.log(event.message.content); }); room.attach(); const page = await sub.historyBeforeSubscribe({ limit: 50 }); for (const message of page.items) { console.log(message.content); } if (page.hasNext()) await page.next(); const one = await room.messages.get(9); const versions = await room.messages.getVersions(9); await room.messages.update(9, "edited"); await room.messages.delete(9); await room.messages.reactions.send(9, "👍"); ``` `useMessages()` on `FluxyRoomProvider` exposes the same send/update/delete helpers plus the latest live frame. `room.messages.reactions.subscribe` is each add/remove frame, not an Ably summary. --- # Message templates (/docs/cookbook/message-templates) Message templates [#message-templates] Project-scoped templates with `\{\{variable\}\}` substitution for system/bot messages. Admin API (JWT with `admin` or `owner` role) [#admin-api-jwt-with-admin-or-owner-role] | Method | Path | Description | | ------ | ------------------- | ------------------------------------------------------ | | GET | `/templates` | List templates | | POST | `/templates` | Create `\{ name, body \}` | | GET | `/templates/:id` | Retrieve | | PATCH | `/templates/:id` | Update | | DELETE | `/templates/:id` | Delete | | POST | `/templates/render` | Preview `\{ templateId, vars \}` or `\{ body, vars \}` | Send via REST [#send-via-rest] ```bash curl -X POST "$WORKER_URL/messages" \ -H "Authorization: Bearer $MEMBER_JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "support-1", "templateId": "tpl_...", "templateVars": { "name": "Jane", "ticketId": "42" } }' ``` `content` is optional when `templateId` is set (rendered server-side). SDK [#sdk] ```ts import { renderMessageTemplate } from "@fluxy-chat/sdk"; const preview = renderMessageTemplate("Hi {{name}}", { name: "Jane" }); await client.createMessage(roomId, "", null, undefined, clientMessageId, { templateId: "tpl_...", templateVars: { name: "Jane", ticketId: "42" }, }); ``` Member preferences [#member-preferences] ```bash curl -X PATCH "$WORKER_URL/rooms/$ROOM_ID/members/me/preferences" \ -H "Authorization: Bearer $MEMBER_JWT" \ -H "Content-Type: application/json" \ -d '{"notifyEnabled": true, "preferences": {"locale": "en-GB"}}' ``` `GET /rooms/:id/members` returns `notifyEnabled` and `preferences` per member. --- # Live occupancy (/docs/cookbook/occupancy) Live occupancy [#live-occupancy] The Room Durable Object broadcasts `occupancy` on join and leave: `connections` (sockets) and `presenceMembers` (unique users). ```tsx const { store } = useChat({ roomId: "lobby" }); const { connections, presenceMembers } = useOccupancy(store); return (

{connections} sockets · {presenceMembers} people

); ``` Inside `FluxyRoomProvider`, `useOccupancy()` reads the bound room. Pass the store when you are on `useChat` instead. Without React: ```ts const room = client.room("lobby"); room.occupancy.subscribe((event) => { const { connections, presenceMembers } = event.occupancy; console.log(event.type, connections, presenceMembers); }); room.attach(); const snapshot = await room.occupancy.get(); ``` `get()` hits `GET /rooms/:id/live`. `current()` is the last realtime frame, or `null` before the first event. `current.connections` is the same number. `occupancy.enableEvents: false` throws `feature_not_enabled` on subscribe and on `current()`. Full page: [Rooms / Occupancy](/docs/rooms/occupancy). --- # Offline notify: in-app chat (FluxyChat) + SMS/WhatsApp (Sent.dm) (/docs/cookbook/offline-notify-sent-dm) Offline notify: in-app chat (FluxyChat) + SMS/WhatsApp (Sent.dm) [#offline-notify-in-app-chat-fluxychat--smswhatsapp-sentdm] Use **FluxyChat** when the user is in your product (WebSocket + in-app notifications). Use **[Sent.dm](https://sent.dm)** when they are offline and you need transactional SMS or WhatsApp — same mental model as pairing a chat API with a telco API (see `/compare`). Inspired by the Apache-2.0 `sent-dm-typescript` SDK in \`/docs (multi-channel fan-out, templates, delivery activity log). **No Sent code is vendored into FluxyChat**; you run this in your own Worker or backend. Architecture [#architecture] ```mermaid sequenceDiagram participant User participant FluxyChat as FluxyChat Worker participant Hook as Your webhook consumer participant Sent as Sent.dm API User->>FluxyChat: POST message (or WS) FluxyChat->>FluxyChat: persist + broadcast FluxyChat->>Hook: webhook message.created Hook->>FluxyChat: GET presence / read receipts (optional) alt recipient offline Hook->>Sent: POST /v3/messages (template) Sent-->>User: SMS / WhatsApp end ``` 1\. Register a project webhook [#1-register-a-project-webhook] In the operator console (or `POST /webhooks`), subscribe to at least: * `message.created` — new message persisted * Optionally `mention.created` if you add a custom automation; today mentions are in the message payload and in-app notifications. Store the signing secret; verify `X-Fluxy-Signature` on your consumer (see [`webhook-delivery.js`](../../apps/worker/src/lib/webhook-delivery.js)). Built-in option (FluxyChat Worker) [#built-in-option-fluxychat-worker] When these env vars are set on the Worker, mention and DM recipients can receive SMS without a separate webhook service: | Variable | Purpose | | ------------------------------- | -------------------------------------------------------------------------------------- | | `OFFLINE_SMS_ENABLED=true` | Turn on automation | | `SENT_DM_API_KEY` | Sent.dm API key | | `SENT_DM_PROFILE_ID` | Sent profile id (`x-profile-id`) | | `OFFLINE_SMS_TEMPLATE_NAME` | Template name (default `chat_notify`) | | `OFFLINE_SMS_IDLE_MINUTES` | Skip SMS if user read the room within N minutes (default 5) | | `OFFLINE_SMS_PER_USER_PER_HOUR` | Cap SMS per user (default 6) | | `OFFLINE_SMS_MEDIA_ENABLED` | Include attachment `media_url` in template params (default on; set `false` to disable) | **User opt-in** — store phone on the room member profile (no GPL import; your app controls consent): ```http PATCH /rooms/{roomId}/members/me/preferences Authorization: Bearer Content-Type: application/json { "preferences": { "smsE164": "+14155551234", "smsOptIn": true } } ``` Register a Sent.dm template `chat_notify` with parameters: `sender`, `preview`, `room_id`, and optionally `media_url`, `media_name`, and `media_type` (`image`, `video`, or `document`) for MMS or WhatsApp media. Define a media template variable in Sent.dm pointing at `media_url`. Implementation: [`offline-notify-sent.js`](../../apps/worker/src/lib/offline-notify-sent.js) (hooked from `schedulePostMessageAutomations`). *** 2\. Decide “offline” (custom webhook path) [#2-decide-offline-custom-webhook-path] Pick one or combine: | Signal | Source | Notes | | -------------------------- | -------------------------- | ------------------------------------------------------ | | Not connected to room WS | Your app / last-seen table | FluxyChat does not expose global presence across rooms | | No recent read receipt | `read_receipts` in D1 | Good for “hasn’t opened this DM/thread” | | In-app notification unread | `GET /notifications` | User has inbox row but hasn’t acked | | Quiet hours / user prefs | Your profile store | Don’t SMS at night | **Chatsemble-style pattern (GPL, concepts only):** org-scoped rooms + email for invites. FluxyChat equivalent: **in-app notifications** for mentions/DMs + **your** email/SMS bridge via webhooks — see [`chatsemble-concepts.md`](//docs). 3\. Webhook consumer (Worker sketch) [#3-webhook-consumer-worker-sketch] Deploy a separate route or Worker that: 1. Verifies the FluxyChat webhook signature. 2. Parses `message.created` (room id, author, content snippet, mentions). 3. Resolves recipient phone numbers from **your** user profile DB (never log full numbers in shared logs). 4. Skips if the recipient is considered “online” in your app. 5. Calls Sent.dm with a **template** (transactional; register templates in Sent dashboard). ```ts // Minimal fetch example (no SDK required). Run in YOUR worker, not FluxyChat core. const SENT_API_KEY = env.SENT_DM_API_KEY; const SENT_PROFILE_ID = env.SENT_PROFILE_ID; async function notifyOfflineSms({ toE164, templateName, parameters }) { const res = await fetch("https://api.sent.dm/v3/messages", { method: "POST", headers: { Authorization: `Bearer ${SENT_API_KEY}`, "Content-Type": "application/json", "x-profile-id": SENT_PROFILE_ID, "Idempotency-Key": crypto.randomUUID(), }, body: JSON.stringify({ channel: ["sms"], to: [toE164], template: { name: templateName, parameters, }, }), }); if (!res.ok) throw new Error(`sent_dm_${res.status}`); return res.json(); } ``` With the official SDK (`npm install @sentdm/sentdm`): ```ts import Sent from "@sentdm/sentdm"; const sent = new Sent({ apiKey: env.SENT_DM_API_KEY }); const { data } = await sent.messages.send({ channel: ["sms", "whatsapp"], to: ["+14155551234"], template: { name: "chat_mention", parameters: { sender: "Alex", preview: "Hey — can you review…" }, }, "x-profile-id": env.SENT_PROFILE_ID, }); // data contains per-recipient message ids — track delivery via webhooks or GET /v3/messages/{id} ``` 4\. Template content [#4-template-content] Keep SMS short; deep-link into your app: * `sender` — display name * `preview` — first 80 chars of message (strip HTML) * `room_url` — `https://app.example.com/rooms/\{roomId\}` * `media_url` — first image (or video/document) attachment URL; relative `/attachments/*` paths are resolved with `PUBLIC_APP_URL` * `media_name` — file name for the attachment * `media_type` — `image`, `video`, or `document` (Sent.dm channel adaptation) Register templates in Sent.dm; avoid free-form body for production (compliance + deliverability). 5\. Delivery debugging [#5-delivery-debugging] Sent.dm exposes: * `GET /v3/messages/\{id\}` — status * `GET /v3/messages/\{id\}/activities` — lifecycle (accepted → sent → delivered / failed) Log FluxyChat `webhook_deliveries` id alongside Sent message id in your support tooling. 6\. Security & compliance [#6-security--compliance] * Minimize PII in webhook logs; redact message bodies in Sent parameters when possible. * Opt-in SMS per region (TCPA, GDPR). Store `sms_opt_in` on the user profile. * Rate-limit outbound SMS per user (Sent profile limits + your own caps). * Never expose `SENT_DM_API_KEY` to the browser — only server/Worker. * **US production:** follow the [US SMS compliance playbook](/docs/operations/us-sms-compliance-playbook) (10DLC, STOP/HELP, opt-out webhook mirror via `sent_dm_contacts`). Related [#related] * [Public demo hardening](/docs/cookbook/public-demo-hardening) — Turnstile + origin allowlist for guest demos * [In-app notifications](../../apps/worker/src/lib/in-app-notifications.js) — mention/DM rows in D1 * [Transport fallback](/docs/cookbook/transport-fallback) — WS → SSE when mobile backgrounded * [Compare: telco vs in-app](https://fluxychat.com/compare) — positioning --- # Presence avatars (/docs/cookbook/presence-avatars) Presence avatars [#presence-avatars] `useSelf` / `useOthers` / `useLeavers` split the roster. Leavers stay visible for two minutes after `member_left`, then drop. ```tsx const { store } = useChat({ roomId: "lobby" }); const self = useSelf(store, userId); const others = useOthers(store, userId); const leavers = useLeavers(store); const avatars = usePresenceAvatars(store, userId); ``` UI location (which slide or field) lives on `presence_patch.uiLocation`. `useLocations()` follows that. GPS stays on `location_update` / `useLocation`. `room.presence.enter(data)` / `update(data)` send that patch. Joining the occupancy set is `attach()`, not a second enter call. `usePresenceListener()` refreshes `presence.get()` on enter/leave patches. `presence.leave()` hides you from `presenceMembers` and keeps the socket open. --- # Public demo & guest token hardening (/docs/cookbook/public-demo-hardening) Public demo & guest token hardening [#public-demo--guest-token-hardening] The dashboard route `/demo` and Worker `GET|POST /demo/session` mint short-lived guest JWTs for a shared room. Without guards, bots can burn quota and pollute the demo room. This checklist covers Turnstile, origin allowlists, rate limits, and guest-token hardening for public demo rooms. Checklist [#checklist] | Layer | Env / config | Status in FluxyChat | | -------------------------- | --------------------------------------------------------- | --------------------------------------------------- | | Disable by default | `DEMO_ENABLED` not `true` | ✅ 404 when off | | Dedicated demo project key | `DEMO_API_KEY` + `DEMO_ROOM_ID` | ✅ not platform default project | | IP rate limit | `RATE_LIMIT_DEMO_SESSIONS_PER_MINUTE` | ✅ `checkAndConsumeIpRateLimit` scope `demo-session` | | Origin allowlist | `DEMO_ALLOWED_ORIGINS` | ✅ `Origin` / `Referer` match | | Turnstile | `TURNSTILE_SECRET_KEY` + `NEXT_PUBLIC_TURNSTILE_SITE_KEY` | ✅ POST `/demo/session` with `turnstileToken` | | Read-only demo | `DEMO_READ_ONLY=true` | ✅ UI + no send | | Short JWT TTL | `DEMO_TOKEN_TTL_SECONDS` (300–3600) | ✅ default 1800 | | Auth token mint RL | `RATE_LIMIT_AUTH_TOKEN_PER_MINUTE` | ✅ `/auth/token` per IP + key fingerprint | | WS connect RL | `RATE_LIMIT_WS_CONNECTIONS_PER_MINUTE` | ✅ optional per-IP | Turnstile (production demo) [#turnstile-production-demo] **Worker** (`wrangler secret put`): ```bash TURNSTILE_SECRET_KEY=... DEMO_ALLOWED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com DEMO_ENABLED=true # GET blocked when Turnstile is on (use POST from dashboard) # DEMO_ALLOW_GET_WITHOUT_TURNSTILE=true # local only — not for prod ``` **Dashboard** (Vercel env at build time): ```bash NEXT_PUBLIC_TURNSTILE_SITE_KEY=... ``` Flow: 1. User opens `/demo`. 2. Turnstile widget renders; on success the app `POST`s `\{ "turnstileToken": "..." \}` to `/demo/session`. 3. Worker verifies via Cloudflare `siteverify`, then mints JWT. Local dev without Turnstile: omit both keys — `GET /demo/session` still works. Origin allowlist [#origin-allowlist] Set `DEMO_ALLOWED_ORIGINS` to the exact origins that host your demo UI (comma-separated). Requests without a matching `Origin` or `Referer` receive `403 demo_origin_forbidden`. Leave unset in local dev (`localhost` flows often omit `Origin` on same-origin fetches from the Next app — configure `http://localhost:3000` in production-like staging). Rate limits [#rate-limits] | Variable | Default | Applies to | | -------------------------------------- | ------- | ------------------------------------------ | | `RATE_LIMIT_DEMO_SESSIONS_PER_MINUTE` | 20 | `/demo/session` per IP | | `RATE_LIMIT_AUTH_TOKEN_PER_MINUTE` | 30 | `POST /auth/token` per IP + api key prefix | | `RATE_LIMIT_WS_CONNECTIONS_PER_MINUTE` | 0 (off) | WebSocket upgrade per IP | Uses `IP_RATE_LIMITER` DO when bound, else `RATE_LIMIT_KV`. Audit script (manual) [#audit-script-manual] 1. Confirm `DEMO_ENABLED` is false on production until intentionally enabled. 2. Confirm demo API key is scoped to a throwaway project, not production tenant data. 3. Enable Turnstile + origins before linking `/demo` from marketing pages. 4. Monitor `rate_limit_exceeded` logs and demo room message volume. 5. Set `DEMO_READ_ONLY=true` for marketing embeds that should not accept writes. Related [#related] * [Offline notify (Sent.dm)](/docs/cookbook/offline-notify-sent-dm) * [`.dev.vars.example`](../../apps/worker/.dev.vars.example) * [Research: free4chat abuse layers](//docs) --- # FluxyRealtimeProvider (browser-only) (/docs/cookbook/realtime-provider) FluxyRealtimeProvider (browser-only) [#fluxyrealtimeprovider-browser-only] `FluxyRealtimeProvider` owns a `FluxyChatClient`. Put it in a Client Component (`"use client"`). Do not import it from a Server Component. It calls `client.close()` when the tree unmounts, and when the guest or JWT client instance is replaced (token refresh). That tears down every tracked room socket. Next.js Strict Mode remounts once in development; you may see a brief extra connect. That is expected. ```tsx "use client"; import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; export function ChatShell({ workerUrl, jwt }: { workerUrl: string; jwt: string }) { return ( ); } function Room() { const { messages } = useChat({ roomId: "lobby" }); return
    {messages.map((m) =>
  • {m.content}
  • )}
; } ``` `FluxyRoomProvider` attaches the room on mount and detaches when the last provider unmounts. Child hooks (`useTyping`, `useMessages`, `usePresence`, `usePresenceListener`, `useOccupancy`, `useLocks`, `useCursors`, `useMembers`, `useRoom`) read that room from context. `useChatClient()` returns `{ clientId, client }` from the realtime provider. `room.objects` is the shared JSON bag on the room (`derived_set`). Same job as a LiveObjects map on the channel, on our wire. Release a cached room with `client.rooms.release(name)` (same as Ably `rooms.get` / `release`). `client.room(name)` still works. ```tsx ``` For attach without auto-connect (CHA-GP2): `useChat({ roomId, autoConnect: false })` then `client.room(roomId).attach()`. Room-only import (no IoT/edu barrel): `@fluxy-chat/sdk/room`. Demo scaffold: `?room=` pins the room. `?debug=1` prints the last 24 inbound frames. --- # Room reactions (/docs/cookbook/room-reactions) Room reactions [#room-reactions] `room.reactions.send(name)` broadcasts a `room_reaction` frame. Peers receive it once. The Room Durable Object does not write it to D1. This is not a message reaction. Message reactions attach to a `messageId`. ```tsx const room = client.room("lobby"); room.attach(); room.reactions.subscribe((event) => { console.log(event.reaction.userId, event.reaction.name); }); return ; ``` --- # Room history to AI messages (/docs/cookbook/room-to-ai-messages) Room history → AI messages [#room-history--ai-messages] Use `FluxyChatClient.toAiMessagesFromRoom()` to feed in-room chat history into agents, RAG pipelines, or Vercel AI SDK `generateText` / `streamText` calls. Basic usage [#basic-usage] ```typescript import { FluxyChatClient } from "@fluxy-chat/sdk"; import { generateText } from "ai"; const client = new FluxyChatClient({ baseUrl: process.env.FLUXY_WORKER_URL!, userId: "agent-bot", token: memberJwt, }); const messages = await client.toAiMessagesFromRoom("support-room-1", { limit: 30, includeSystem: false, }); const result = await generateText({ model: openai("gpt-4o-mini"), system: "Summarize the conversation for the next human agent.", messages, }); await client.createMessage("support-room-1", result.text); ``` Options [#options] | Option | Type | Description | | --------------------- | ------- | ------------------------------------------------------ | | `limit` | number | Max messages to fetch (default 50) | | `includeSystem` | boolean | Include system-role messages | | `mapUserDisplayNames` | boolean | Prefix user messages with display names when available | Agent invoke pattern [#agent-invoke-pattern] ```typescript import { createTelemetryManager, createConsoleTelemetryIntegration } from "@fluxy-chat/sdk"; const telemetry = createTelemetryManager({ functionId: "room-summarizer" }); telemetry.register(createConsoleTelemetryIntegration()); const history = await client.toAiMessagesFromRoom(roomId); // Pass history to your @fluxy-chat/agent runAgentLoop or external LLM ``` Related [#related] * [KB + RAG agent](/docs/cookbook/kb-rag-agent) — retrieval over knowledge base * [AI agents handoff](/docs/guides/ai-agents/handoff) — human takeover from in-room AI * [Unified reasoning](/docs/guides/unified-reasoning) — cross-provider thinking controls --- # Transport fallback (WebSocket → SSE → polling) (/docs/cookbook/transport-fallback) Transport fallback (WebSocket → SSE → polling) [#transport-fallback-websocket--sse--polling] `useChat` and `createFluxyRoomSession` automatically degrade transport when the room WebSocket cannot stay connected. Order [#order] 1. **WebSocket** — `FluxyChatRoomConnection` with exponential backoff reconnect (default 6 attempts in `useChat`). 2. **SSE** — `GET /rooms/:id/stream` when reconnect attempts are exhausted and a member JWT is present. 3. **Polling** — REST `GET /api/messages` every 4s if SSE is unavailable. When WebSocket reconnects, SSE/polling stops and live delivery resumes on the socket. UI [#ui] Use `connectionState` from the SDK (not raw `connectionStatus` alone): ```tsx const { connectionState } = useChat({ roomId }); if (connectionState.status === "reconnecting" && connectionState.nextRetryAt) { const seconds = Math.max( 0, Math.ceil((new Date(connectionState.nextRetryAt).getTime() - Date.now()) / 1000), ); return Reconnecting in {seconds}s…; } if (connectionState.transport === "sse") { return Live updates via SSE; } if (connectionState.status === "degraded-http" || connectionState.transport === "polling") { return Live socket blocked. Updating over HTTP.; } ``` Corporate proxies and some browser extensions block WebSockets. CORS must allow your app origin on the Worker. Custom domains need the same CORS list as `127.0.0.1`. There is no screenshot in this page; the status string above is what you show in the product. Vanilla (no React) [#vanilla-no-react] ```ts import { createFluxyRoomSession } from "@fluxy-chat/sdk"; const { store, stop } = createFluxyRoomSession({ roomId: "my-room", client, }); store.subscribe((state) => { console.log(state.connectionState); }); // later: stop(); ``` Related [#related] * [`packages/sdk/src/room-session.ts`](../../packages/sdk/src/room-session.ts) — fallback implementation * [`packages/sdk/README.md`](/docs/packages/sdk) — optimistic sends + `retryMessage` --- # Typing indicator (/docs/cookbook/typing) Typing indicator [#typing-indicator] `room.typing.keystroke()` sends a `typing` frame. Call it on each keypress; the SDK throttles to 2s and stops after 10s of silence. `stop()` sends idle immediately. `useChat({ roomId }).setTyping` is the same wire event. ```tsx const room = client.room("lobby"); room.attach(); room.typing.subscribe((event) => { console.log([...event.currentlyTyping], event.change); }); return ( room.typing.keystroke()} onBlur={() => room.typing.stop()} /> ); ``` Do not persist typing. Do not put pointer motion on `client_event`. Use `sendCursor` for that. --- # AI Agents (/docs/core/agents) Agents are configured on the Worker (dashboard or admin API). Clients **invoke** them. There is no `client.createAgent()` in the SDK. Configure on the Worker [#configure-on-the-worker] Create agents with admin JWT: ```bash curl -X POST "$FLUXY_BASE_URL/agents" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "Assistant", "handle": "assistant", "provider": "openai", "model": "gpt-4o-mini", "capabilities": ["chat"] }' ``` Agents with a **handle** (e.g. `@assistant`) auto-invoke when users mention them in a room message. Invoke from useChat [#invoke-from-usechat] ```tsx const { invokeAgent, stopAgentStream } = useChat({ roomId }); await invokeAgent("What is our refund policy?", { agentId: "agt_…" }); // Token edits land on the chat row (`streaming: true`). Stop keeps text already shown. stopAgentStream(); ``` Invoke via REST [#invoke-via-rest] ```ts await client.invokeAgentRest(agentId, roomId, "Summarize the last 10 messages"); ``` Requires member JWT on the client. Schedule (Cloudflare Agents `schedule()` HOW) [#schedule-cloudflare-agents-schedule-how] One-shot delay or 5-field UTC cron on the **room** Durable Object — not a second Agent DO. ```ts await client.scheduleAgent(roomId, { agentId, kind: "delay", delayMs: 60_000, prompt: "Standup recap" }); await client.scheduleAgent(roomId, { agentId, kind: "cron", cron: "0 9 * * 1-5", prompt: "Daily briefing" }); await client.scheduleAgent(roomId, { agentId, kind: "at", runAt: Date.now() + 120_000, prompt: "Later" }); await client.scheduleAgent(roomId, { agentId, kind: "interval", intervalMs: 60_000, prompt: "Heartbeat" }); await client.getAgentSchedule(roomId, scheduleId); const pending = await client.listAgentSchedules(roomId); await client.cancelAgentSchedule(roomId, pending[0].id); ``` Several agents in one room [#several-agents-in-one-room] `invokeAgent` can run more than one agent on the same `roomId`. Each call counts against the project's monthly `agent_invokes` quota (Free includes 5k). Handles (`@assistant`) auto-invoke from mentions and count the same way. Four concurrent agents (a restaurant floor, a war room) is a product pattern, not a second protocol. Watch quota and rate limits in the operator console. One turn at a time per room [#one-turn-at-a-time-per-room] Every room-bound turn — REST/SDK `invokeAgent`, `@handle` auto-invoke, agent schedules — runs on the same per-room agent instance, FIFO: the next turn starts when the current one finishes, so two turns never stream into one room at the same time. Concurrent callers wait their turn (queue of 8): * `POST /agents/:id/invoke` past the queue answers `429 { "error": "turn_queue_full" }` with `Retry-After` (default 5s). * A mention past the queue is dropped and logged (`agent.mention_turn_queue_full`) — the message gets no agent reply. Self-host without the `AGENT` binding runs invokes inline in the request (no turn queue). Handoff [#handoff] Check whether a human should take over: ```ts const handoff = await client.getRoomHandoff(roomId); // { shouldHandoff, reason?, suggestedAssignee? } ``` Streaming [#streaming] When the provider supports it, agent replies stream as message edits over WebSocket (`streaming: true` on the chat row). `stopAgentStream()` sends `{ type: "stream", op: "stop" }` on the room socket. The Worker finalizes that chat row with text already shown and aborts the in-flight LLM `fetch`. Tool calls show as cards when `toolExecuteUrl` is set. That is not Stream’s `ai_indicator.*` protocol, and it is not Cloudflare Think fiber recover after eviction. If the room Durable Object hibernates while the model is still generating, that LLM call does not resume. Reconnect still loads messages that already hit D1. Think’s object is the agent. Ours is the room. Next steps [#next-steps] * [Copilots](/docs/core/copilots) (side panel, not this timeline) * [Feeds](/docs/core/feeds) (workflow logs) * [Agent platform](/docs/platform/agent-platform) * [Handoff guide](/docs/guides/ai-agents/handoff) * [Use case: Assistant room](/docs/use-cases/assistant-room) --- # AI collaboration (/docs/core/ai-collaboration) Three writers, one room: | Role | API | Writes | | --------- | --------------------------------- | ------------------------- | | Copilot | `useAiChat` / `` | Local panel only | | Room peer | `invokeAgent` | Chat `messages` | | Workflow | `POST /rooms/:id/feeds` + API key | Feed log + `server_event` | n8n / LangChain / a Worker cron uses the **project API key** (server-only): ```bash curl -X POST "$WORKER/rooms/$ROOM/feeds/$FEED/messages" \ -H "X-Fluxy-Api-Key: fc_…" \ -H "Content-Type: application/json" \ -d '{"body":"deploy ok","metadata":{"source":"n8n","status":"ok"}}' ``` Optional: the same process can mint a short-lived member JWT and send `presence_patch` `{ "agentStatus": "running" }` on the room WebSocket so UIs show `useOthers()` status. Do not use `client_event` for that. This is not MQTT, not a copilot transcript, and not HIPAA. --- # Broadcast (/docs/core/broadcast) Broadcast is a **pulse**. Use it for “someone clicked stamp”, “slide changed”, “nudge the peer”. It is **not** stored. It is **not** for pointers. React [#react] ```tsx const { sendClientEvent, lastClientEvent } = useChat({ roomId, replay: "request" }); sendClientEvent("client-ephemeral-dot", { x, y, color: "#2563eb" }); ``` `useBroadcastEvent(store)` is the same send helper on a room store. Prefix **`client-ephemeral-*`** skips webhooks. Other `client_event` names are rate-limited (**10/min**) and may fire webhooks. vs Presence vs Storage [#vs-presence-vs-storage] | Need | Use | | -------------------------------------- | ----------------------------------------- | | Mouse / live selection | `sendCursor` / `presence_patch` | | Shared document / strokes that persist | Yjs `useStorage` / `--example whiteboard` | | One-shot “boop” | `sendClientEvent` | Scaffold: `--example draw` (stamps). Persistent ink: `--example whiteboard`. See [Presence](/docs/core/presence-typing) and [Storage](/docs/core/storage). --- # Comments & threads (/docs/core/comments) Pins on a canvas (`x`, `y`, a quote) live in `/comment-threads`. Chat replies are `parentId` on the message log. See [chat reply threads](/docs/core/nested-threads). REST [#rest] ``` GET /rooms/:roomId/comment-threads POST /rooms/:roomId/comment-threads { body, metadata } POST /rooms/:roomId/comment-threads/:id/comments { body } PATCH /rooms/:roomId/comment-threads/:id/comments/:commentId { body } DELETE /rooms/:roomId/comment-threads/:id/comments/:commentId PATCH /rooms/:roomId/comment-threads/:id { resolved, metadata } DELETE /rooms/:roomId/comment-threads/:id POST /rooms/:roomId/comment-threads/:id/comments/:commentId/reactions { emoji } DELETE /rooms/:roomId/comment-threads/:id/comments/:commentId/reactions { emoji } ``` Fan-out names: `comment.thread`, `comment.created`, `comment.updated`, `comment.deleted`, `comment.thread.updated`, `comment.thread.deleted`, `comment.reaction`. Edit/delete a comment is the author. Delete a thread is the creator. `useThreads` also has `searchThreads`, `editThreadMetadata`, `markThreadAsUnresolved`, `addReaction` / `removeReaction`. React [#react] ```tsx import { useThreads } from "@fluxy-chat/react"; import { CommentPin, FloatingComposer, Thread } from "@fluxy-chat/ui"; const { threads, createThread, createComment, markThreadAsResolved, markThreadAsUnresolved, deleteThread, deleteComment, editComment, searchThreads } = useThreads({ roomId }); await createThread({ body: "Check this", metadata: { x: 120, y: 80 } }); ``` Render pins with ``, overlay ``, and `` for replies/resolve/edit/delete. Scaffold: `--example comments-board`. `markThreadAsUnresolved` is Liveblocks-shaped (`resolved: false`). Inbox: merge `commentEventToInboxItem` into `useInbox().onItem`, then ``. Daily email digest includes yesterday's thread comments (enable `DAILY_DIGEST_ENABLED`; see [Notifications](/docs/core/notifications)). This is **not** the chat log. Do not store 60 Hz pointers here — those are presence (`sendCursor` / `presence_patch`). --- # Connection state (/docs/core/connection-state) `FluxyChatClient` and `useChat` expose structured connection state, not a boolean. Status values [#status-values] | Status | Meaning | | --------------- | ---------------------------------------------------------------------- | | `connecting` | First WebSocket handshake | | `connected` | Live on WebSocket | | `reconnecting` | Socket dropped, backoff retry in progress | | `suspended` | Long outage; the client still retries (`retryIn` on the status change) | | `failed` | Auth or max attempts; the client stops until you attach again | | `degraded-http` | Socket down, HTTP publish still works (`canPublishViaHttp`) | | `degraded` | Unhealthy, not the HTTP fallback path | | `disconnected` | Not connected (manual disconnect or fatal error) | Legacy `sse` and `polling` statuses normalize to `degraded-http`. `connectionState.transport` still tells you `sse` vs `polling`. Transport fallback [#transport-fallback] When WebSocket reconnect attempts are exhausted, the SDK degrades automatically: 1. **WebSocket**: primary (`/ws/room/:roomId?token=…`) 2. **SSE**: `GET /rooms/:id/stream` with member JWT 3. **Polling**: `GET /api/messages` every \~4s When WebSocket recovers, SSE/polling stops. ```tsx const { connectionState } = useChat({ roomId, client }); if (connectionState.status === "reconnecting" && connectionState.nextRetryAt) { const seconds = Math.max( 0, Math.ceil((new Date(connectionState.nextRetryAt).getTime() - Date.now()) / 1000), ); return Reconnecting in {seconds}s; } if (connectionState.status === "degraded-http" && connectionState.canPublishViaHttp) { return Live socket down. Sends still go over HTTP.; } ``` Client events [#client-events] ```ts client.on("connectionStateChange", (state) => { console.log(state.status, state.transport); }); await client.connect(); await client.disconnect(); ``` JWT refresh: `client.setToken(next)` (alias `updateToken`). Reconnect rooms if `sub` changed. If the live socket is blocked (corporate proxy, strict CSP), the UI should read `connectionState.status === "degraded-http"` and `canPublishViaHttp`. Sends still go over HTTP. This is not a second product; it is the same room. Per-room attach labels (`attached`, `suspended`, `failed`) are on `room.status()`. See [Room status](/docs/rooms/status). Related [#related] * [Room status](/docs/rooms/status) * [Wire protocol](/docs/core/wire-protocol) * [Transport fallback](/docs/cookbook/transport-fallback) --- # AI copilots (/docs/core/copilots) **Copilot** (``) is a side panel that reads registered app state. **Room agent** (`invokeAgent`) is a peer on the chat timeline. Do not mix them. React (keyless mock) [#react-keyless-mock] No LLM key required. The mock replies with your last message plus `RegisterAiKnowledge` / `RegisterAiTool`. It does **not** insert `messages` rows. ```tsx import { FluxyAiCopilotProvider, RegisterAiKnowledge, RegisterAiTool, useAiChat, } from "@fluxy-chat/react"; import { AiChat } from "@fluxy-chat/ui"; function CopilotPanel() { const { messages, sending, sendMessage } = useAiChat(); return ; } ``` Room-peer agents still use `invokeAgent` from `useChat`. Workflows write **feeds**, not this panel. Presence [#presence] Workflows / agents can set ephemeral `agentStatus` via `useUpdateMyPresence({ agentStatus: "running" })` (`presence_patch`). Not stored. --- # Feeds (/docs/core/feeds) Chat is `messages`. **Feeds** are a separate D1 log: agent traces, n8n/LangChain steps, automation. Do not POST feed items as chat messages. REST [#rest] ``` GET /rooms/:roomId/feeds POST /rooms/:roomId/feeds { name, kind } GET /rooms/:roomId/feeds/:feedId/messages POST /rooms/:roomId/feeds/:feedId/messages { body, metadata } ``` `kind`: `activity` | `agent` | `automation`. Metadata allowlist: `source`, `agentId`, `status`. Auth: **member JWT** (`canAccessRoom`) **or** project API key (`X-Fluxy-Api-Key`). API keys stay on the server (n8n, workers). Fan-out: `server_event` names `feed.created`, `feed.message`. There is no PATCH. Status changes are a new row (`createMessage` again with `metadata.status`). React [#react] ```tsx import { useFeeds, useFeedMessages } from "@fluxy-chat/react"; import { FeedMessage } from "@fluxy-chat/ui"; const { feeds, createFeed } = useFeeds({ roomId }); await createFeed({ name: "Agent traces", kind: "agent" }); const { messages, createMessage } = useFeedMessages({ roomId, feedId }); await createMessage({ body: "run started", metadata: { source: "n8n" } }); ``` Node / workflow (API key, not a browser JWT): ```ts const client = new FluxyChatClient({ baseUrl, apiKey: process.env.FLUXY_API_KEY, userId: "workflow" }); const feed = await client.createFeed(roomId, { name: "n8n", kind: "automation" }); await client.createFeedMessage(roomId, feed.id, { body: "step ok", metadata: { source: "n8n" } }); ``` --- # Inbox (/docs/core/inbox) Inbox model [#inbox-model] FluxyChat separates three concepts that are easy to conflate: | Concept | What it is | SDK / API | | --------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------- | | **Items feed** | Flat list of inbox rows (mentions, unread rooms, snoozed, follow-ups) | `useInbox().items` | | **Counter** | Global badge: number of rooms with unread messages | `useInbox().counter` | | **Unseen** | Rows in the current view that need attention (mentions + unread) | `useInbox().unseen` | | **Channel watermark** | Per-room “how far you read” in chat history | `markReadRest(roomId, messageId)` / `markReadLatest` in `useChat` | The **inbox** tracks *noticing* (mentions, unread rooms, snooze, follow-ups). Process human steps can show up as `opsTasks` on the Worker summary. The console Inbox panel loads the same list from `/ops/inbox`.\ The **room channel** tracks *reading* (last read message id inside a room). Clearing inbox unread does not automatically advance the room watermark unless you call mark-read. Nest `useInbox` under `FluxyRealtimeProvider` (same as `useChat`). Omit `client` when the provider owns the session. Member JWT required; guest/`pk_` inbox is empty. Quick start [#quick-start] ```tsx import { FluxyRealtimeProvider, useInbox } from "@fluxy-chat/react"; export function App({ workerUrl, memberJwt }: { workerUrl: string; memberJwt: string }) { return ( ); } function InboxSidebar() { const { items, counter, unseen, unreadInboxNotificationsCount, status, markInboxNotificationAsRead, markAllInboxNotificationsAsRead, } = useInbox({ pollIntervalMs: 30_000, realtime: true }); return (

Inbox {counter > 0 ? `(${counter})` : ""}

{status === "loading" &&

Loading…

}
); } ``` Item kinds [#item-kinds] Each row in `items` is a `FluxyInboxItem`: | `kind` | Source in REST summary | Typical use | | ----------- | ---------------------- | --------------------------------------------------------------- | | `mention` | `summary.mentions` | @you in a room | | `unread` | `summary.unreadRooms` | Room has messages after your watermark | | `snooze` | `summary.snoozedRooms` | Room hidden until `snoozedUntil` | | `follow_up` | `summary.followUps` | Operator reminder you created | | `thread` | `summary.threads` | Chat reply tree you participate in (`threadId` is a message id) | Items are built from `GET /inbox` and merged with realtime pushes on the **user channel** WebSocket (`onItem`). Counter vs unseen [#counter-vs-unseen] * `counter` — `summary.counts.unreadRooms` (or length of unread room list). Use for nav badges. * `unseen` — count of `mention` + `unread` rows in the current `items` feed (respects client `query` filter). ```tsx useInbox({ query: { unread: true } }); // narrows REST snapshot client-side ``` Mark read (room channel) [#mark-read-room-channel] Liveblocks names on `useInbox`: `markInboxNotificationAsRead(item.id)`, `markAllInboxNotificationsAsRead()`, `deleteInboxNotification(item.id)`, `unreadInboxNotificationsCount`. Those call `markReadRest` using the item payload (`messageId` / `lastMessage` / `firstUnreadMessageId`). ```tsx await markInboxNotificationAsRead(item.id); await markAllInboxNotificationsAsRead(); ``` In chat UI, `useChat({ readOn: "mount" })` or `markReadLatest: true` sends read receipts when the user opens a room. REST [#rest] | Method | Path | Description | | ------------------ | ----------------------------- | ------------------------------------------------------------- | | GET | `/inbox` | Inbox summary (mentions, unread, snoozed, follow-ups, counts) | | GET | `/inbox/agent` | HITL / askHuman rows for the current approver | | POST | `/inbox/agent/:id` | accept, ignore, edit, reply | | PUT | `/inbox/rooms/:roomId/snooze` | Snooze a room | | PUT / GET / DELETE | `/inbox/rooms/:roomId/mute` | Stream `channel.mute()` — skip `inbox_updated` | | POST | `/inbox/follow-ups` | Schedule follow-up | | POST | `/rooms/:roomId/read` | Advance read watermark `{ messageId }` | | POST | `/rooms/:roomId/unread` | Rewind watermark from `{ messageId }` | Requires authenticated member JWT (same as chat). Canned macros and CSAT live on the same Worker (Chatwoot HOW, not a Zendesk SKU): ```ts const created = await client.createCannedResponse({ shortcut: "hi", title: "Hi", body: "Hello" }); await client.updateCannedResponse(created.id, { body: "Hello there" }); const macros = await client.listCannedResponses(); await client.useCannedResponse(macros[0].id); await client.deleteCannedResponse(created.id); await client.triggerCsat(roomId); const survey = await client.getPendingCsat(roomId); if (survey) await client.respondCsat(survey.id, 5); ``` Realtime [#realtime] When `realtime: true` (default when authenticated), `useInbox` opens **`GET /ws/inbox?token=`** (`client.connectInbox()`). Handshake is `inbox_subscription_succeeded`. The same User Durable Object also serves `/ws/user/:userId`; inbox sockets only receive `inbox_updated` / `inbox_item`. Server pushes merge into `items` and call `onItem` once per new row. Console [#console] The dashboard **Inbox** page (`/inbox`) shows the items feed, sidebar badge via `useInbox().counter`, live `onItem` banner, **Mark read** / **Mark all read**, and the approvals inbox (HITL plus askHuman). Related [#related] * [Notifications](/docs/core/notifications) * [User channel](/docs/core/user-channel) * [Team chat use case](/docs/use-cases/team-chat) * [SDK playground](/playground) --- # Core SDK (/docs/core) One room WebSocket. Install: ```bash npm install @fluxy-chat/sdk @fluxy-chat/react @fluxy-chat/ui zustand ``` React 18+, zustand 5+. Yjs editors also need `yjs` and `@fluxy-chat/sdk/yjs`. Read [Concepts](/docs/concepts) before mixing primitives. Provider (required for hooks) [#provider-required-for-hooks] ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; ``` `FluxyYjsProvider` takes **`token`**, not `authTokenProvider`. Do not pass `token=` to `FluxyRealtimeProvider`. Topics [#topics] | Guide | Primitive | | ----------------------------------------------- | --------------------------------------------------- | | [Rooms](/docs/rooms) | attach, messages, occupancy, typing, locks, cursors | | [useChat](/docs/core/use-chat) | Chat timeline, agents, most room APIs | | [Read receipts](/docs/core/read-receipts) | Unread counts and mark-read | | [Presence & typing](/docs/core/presence-typing) | Now (cursors, selections) | | [Broadcast](/docs/core/broadcast) | Pulse (`sendClientEvent`) | | [Storage](/docs/core/storage) | Yjs document, Tiptap, whiteboard | | [Comments](/docs/core/comments) | Contextual pins | | [Chat reply threads](/docs/core/nested-threads) | `parentId` lens | | [Feeds](/docs/core/feeds) | Activity logs | | [Copilots](/docs/core/copilots) | Side-panel AI | | [AI collaboration](/docs/core/ai-collaboration) | Workflows → feeds | | [Agents](/docs/core/agents) | `invokeAgent` | | [Inbox](/docs/core/inbox) | Mentions, unread, thread/comment | | [Notifications](/docs/core/notifications) | Push + email digest | | [Rooms](/docs/rooms) | attach, occupancy, typing, locks, cursors | | [Connection state](/docs/core/connection-state) | WS / SSE / poll | | [Voice](/docs/core/voice-huddles) | Clips + stage signaling | Minimal client (no React) [#minimal-client-no-react] ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: "https://your-worker.workers.dev", userId: "alice", token: memberJwt, }); await client.sendMessage("general", "Hello!"); ``` --- # Message middleware (/docs/core/message-middleware) FluxyChat does not expose a `client.use()` message pipeline in the browser SDK. Middleware patterns split between **Worker-side** processing and **LLM middleware** for agents. Worker-side [#worker-side] Worker-side validation, templates, moderation, and rate limits run before Durable Object broadcast. Declarative **publish middleware** lives in `fluxy.config` (`onPublish` allow/block/mask) via [`@fluxy-chat/config`](/docs/packages/config), bundled as `apps/worker/fluxy.config.js`. That is the FluxyChat equivalent of a one-file server rules deploy. You still ship it with the Worker, not a second CLI. LLM middleware (agents) [#llm-middleware-agents] The SDK exports LLM middleware helpers for composing provider calls on the server: ```ts import { composeMiddlewares } from "@fluxy-chat/sdk"; // Used in custom agent/tool servers, not in browser clients ``` Agent tool execution flows through `toolExecuteUrl` on the agent profile. Client patterns [#client-patterns] For client-side filtering (analytics, UI transforms), subscribe to `useChat` messages: ```tsx const { messages } = useChat({ roomId, client }); const visible = messages.filter((m) => !m.deletedAt); ``` For send-time validation, validate in your UI before calling `sendMessage`. Templates [#templates] Server-rendered template messages bypass free-text middleware: ```ts await client.createMessage(roomId, "", null, undefined, clientMessageId, { templateId: "tpl_welcome", templateVars: { name: "Jane" }, }); ``` See [Message templates](/docs/cookbook/message-templates) and [Moderation](/docs/features/moderation-console). --- # Chat reply threads (/docs/core/nested-threads) A chat thread is a reply to a message. We store that as `parentId` on the same `messages` row you already have. The thread id is the parent message id. There is no second room and no second socket. If you want Figma-style pins on a canvas, that is still [`useThreads`](/docs/core/comments) and `/comment-threads`. Different table, different hook. Mixing the two will hurt. REST accepts `replyTo`, `parentId`, or `threadParentId`. Same field. Lens (`useThread`) [#lens-usethread] ```tsx import { useChat, useThread } from "@fluxy-chat/react"; function Room({ roomId }: { roomId: string }) { const chat = useChat({ roomId }); const thread = useThread({ roomId, threadParentId: 42 }); return ( <>
    {chat.messages.map((m) => (
  1. {m.content}
  2. ))}
    {thread.messages.map((m) => (
  1. {m.content}
  2. ))}
); } ``` Put both hooks under `FluxyRealtimeProvider`. They share the room store and the JSON WebSocket (`sessionScope` defaults to `app`). Without the provider, pass the same `sessionScope` string on both or you get two stores and a quiet thread. The lens lists **direct** replies only (`parentId === threadParentId`). A reply to a reply is its own thread: `useThread({ threadParentId: reply.id })`. `sendMessage` on the lens fills in `replyTo` for you. Eight hops from the root is the cap. Past that, `ThreadDepthExceededError` (`code: "blocked"`, `reason: "thread_depth_exceeded"`). Optimistic send rolls back. We do not fall through to the WebSocket. There is no `where()` filter on a thread in v1. Use the lens. `loadPrevious` hits `GET /api/messages?parentId=` for older replies the room page may have skipped. Registry [#registry] ``` GET /rooms/:roomId/threads?parent=&root=&cursor=&limit= ``` Empty `parent` (the default) lists root threads: a top-level message that already has at least one reply. `parent=` lists threads spawned from that message (children that have replies of their own). `root=` walks the tree and returns every thread whose root is that id. Page with the **`nextCursor` the server sent**. Do not build a cursor from message ids. If `hasMore` is true and `nextCursor` is missing, stop. Inventing a cursor from spawn order or ids will skip or loop pages. ```ts const page = await client.listRoomThreads(roomId, { limit: 20 }); const next = await page.next(); ``` `GET /threads` is the older "trees I participated in" list. Inbox uses that. It is not the room registry. Inbox [#inbox] `GET /inbox` adds a `threads` array (those participating trees). `useInbox().items` maps them to `kind: "thread"` with `threadId` and `rootThreadId`. Unread on a nested row does not increment the room row. Comment-pin events still use `kind: "thread"` via `commentEventToInboxItem`, but the id is the pin id string, not a numeric message id. Errors [#errors] | Class | `code` | `reason` | | -------------------------- | ------------------ | --------------------------- | | `ThreadDepthExceededError` | `blocked` | `thread_depth_exceeded` | | `ChatError` | `PARENT_NOT_FOUND` | parent missing in this room | --- # Notifications (/docs/core/notifications) Push and in-app notifications use Worker-configured VAPID keys and the user-channel WebSocket. Web push [#web-push] ```tsx import { useWebPush } from "@fluxy-chat/react"; import type { FluxyChatClient } from "@fluxy-chat/sdk"; function PushSettings({ client }: { client: FluxyChatClient }) { const { permission, requestPermissionAndSubscribe, unsubscribe } = useWebPush(client); if (permission === "unsupported") return null; return ( ); } ``` Configure VAPID keys in Worker secrets / `.dev.vars`: ```ini VAPID_PUBLIC_KEY=... VAPID_PRIVATE_KEY=... ``` See [Web push (VAPID)](/docs/core/web-push). User channel [#user-channel] `useNotifications` and `useUserChannel` subscribe to per-user realtime events (inbox refresh, mentions, system alerts): ```tsx import { useNotifications } from "@fluxy-chat/react"; useNotifications({ client, onEvent: (event) => console.log(event) }); ``` Delivery types [#delivery-types] | Channel | Mechanism | | ----------- | --------------------------------------- | | In-app | User channel WS + inbox | | Web push | Browser Push API + Worker delivery | | Email / SMS | Worker integrations (tenant-configured) | Member JWT required for subscription registration. Collab inbox kinds [#collab-inbox-kinds] `useInbox` items now include `thread`, `comment`, and `custom` besides mention/unread/follow\_up/snooze. Map `server_event` comment fan-out with `commentEventToInboxItem`. UI: `` from `@fluxy-chat/ui`. See [Comments & threads](/docs/core/comments). Daily email digest (collab + chat) [#daily-email-digest-collab--chat] Cron `runDailyDigest` (enable `DAILY_DIGEST_ENABLED=true`) emails yesterday's chat highlights **and** thread comments. Preferences: ``` GET /digest/preferences PATCH /digest/preferences { enabled, email, emailEnabled, webPushEnabled, inAppEnabled } ``` SDK: `client.getDigestPreferences()` / `client.updateDigestPreferences({ enabled: true, email })`. Delivery: Cloudflare Email binding or `RESEND_API_KEY`. From: `DIGEST_EMAIL_FROM` / `EMAIL_FROM`. Comments-only days still send (no chat messages required). --- # Polls (/docs/core/polls) Polls are stored on the room timeline (`createPoll` / `votePoll` on `@fluxy-chat/sdk`) and also as structured `/polls` records (`isAnonymous`, quorum via close). Chat-message poll (timeline) [#chat-message-poll-timeline] ```tsx const { messages } = useChat({ roomId, client }); await client.createPoll(roomId, { question: "Ship Friday?", options: ["Yes", "No"], allowMultiple: false, }); await client.votePoll(messageId, 0); ``` Anonymous ballot (`/polls`) [#anonymous-ballot-polls] `POST /polls` with `isAnonymous: true` stores votes without exposing voter ids in results. Use this for social-deduction and evaluator-only scoring. Close with `POST /polls/:id/close`. Typed polls (`pollType: "typed"`) start with no options. `voteTypedPoll` / `{ answer }` creates or reuses an option (BBB `pollSubmitUserTypedVote`). Private lines of chat (code only for the evaluator) still use `visibility` / `visibleTo` on `sendMessage`, not polls. Related [#related] * [Gallery `--example polls`](/docs/getting-started/gallery) * [Gallery `deal-room`](/docs/getting-started/gallery) * [useChat](/docs/core/use-chat) --- # Presence & typing (/docs/core/presence-typing) Presence and typing flow over the **room WebSocket** — no separate REST polling required. Typing with useChat [#typing-with-usechat] `useChat` exposes `setTyping(isTyping)` which sends a `typing` frame to the room Durable Object: ```tsx const { typingUsers, setTyping } = useChat({ roomId, client }); setTyping(true)} onBlur={() => setTyping(false)} />

{Object.entries(typingUsers) .filter(([, active]) => active) .map(([uid]) => uid) .join(", ")}{" "} typing…

``` Presence members [#presence-members] On connect, the room broadcasts `presence` events with member lists. The room store tracks `presenceMembers`: ```tsx const snapshot = useFluxyRoomStoreState(store); snapshot.presenceMembers.map((m) => m.userId); ``` Pass optional profile data when joining via WebSocket query (`presenceInfo` JSON) for richer avatars in the dashboard. Rooms with more than **250** unique users switch to **aggregate** presence: `presenceKind: "aggregate"`, `presenceCount`, and a sample of `presenceMembers` (24). Check `presenceKind` before rendering a full roster. Late-joiner derived state [#late-joiner-derived-state] Non-CRDT app state (score, turn, ETA) can live in a JSON bag on the room Durable Object. It is included on `subscription_succeeded` as `derived` so a late joiner paints before replaying the log. Replace the bag with `setDerivedState` from `useChat` (30/min, 16 KiB). Use Yjs storage when you need conflict-free document edits. ```tsx const { derivedState, setDerivedState } = useChat({ roomId, client }); setDerivedState({ score: 3, turn: "ada" }); ``` Live cursors (presence, not broadcast) [#live-cursors-presence-not-broadcast] Pointers use WebSocket `type: "cursor"` (up to 600/min, no D1, no webhooks). **Do not** send pointers as `client_event` (10/min + webhooks). ```tsx const { liveCursors, sendCursor, connected } = useChat({ roomId, replay: "request" }); function onPointerMove(e: React.PointerEvent) { const rect = e.currentTarget.getBoundingClientRect(); sendCursor({ x: e.clientX - rect.left, y: e.clientY - rect.top, label: "Ada", }); } ``` Scaffold: `npx @fluxy-chat/create-fluxy-chat@latest my-cursors --example live-cursors`. UI: `` (damped spring via `stepSpring`) / `` / `` from `@fluxy-chat/ui`. `prefers-reduced-motion` snaps without spring. Selections ride on `presence_patch` (same throttle as cursors, no D1, no webhooks): ```tsx const [, updateMyPresence] = useMyPresence(store); updateMyPresence({ selection: { x: 10, y: 20, x2: 80, y2: 40 } }); ``` `client_event` / `useBroadcastEvent` is for **sparse** signals (`client-ephemeral-*` skips webhooks). Not 60 Hz pointers. Intents [#intents] Typing intents support `composing`, `away`, `viewing_thread` — surfaced as `typingIntents` in the room store for advanced UX (thread focus indicators). See [Connection state](/docs/core/connection-state) for transport details. --- # Read receipts (/docs/core/read-receipts) FluxyChat tracks per-user read position per room in D1. Clients update via REST; other members see unread badges via inbox and room list. Mark read (SDK) [#mark-read-sdk] ```ts await client.markReadRest("general", latestMessageId); await client.markUnreadRest("general", firstUnreadId); ``` Or enable automatic read on mount: ```tsx useChat({ roomId, client, markReadLatest: true }); ``` Unread catch-up [#unread-catch-up] ```ts const { unreadCount, firstUnreadMessageId } = await client.getRoomCatchUp(roomId); ``` REST [#rest] | Method | Path | Description | | ------ | -------------------- | ------------------------------------------------- | | POST | `/rooms/{id}/read` | Body `{ messageId }` | | GET | `/rooms/{id}/unread` | Unread count + first unread id | | POST | `/rooms/{id}/unread` | Stream `markUnread` — rewind from `{ messageId }` | | GET | `/rooms?userId=` | Room list includes `unreadCount` per room | Read receipts sync to [Inbox](/docs/core/inbox) and the user channel (`inbox_updated` events). --- # Search (/docs/core/search) Search [#search] Search room history with `GET /search/messages` (FTS5-backed). When semantic search is enabled for your tenant, use hybrid mode for embedding + keyword results. ```ts const { results } = await client.searchMessages("deployment rollback", { roomId: "engineering", limit: 20, mode: "hybrid", // "fts" | "semantic" | "hybrid" }); for (const hit of results) { console.log(hit.snippet, hit.roomId, hit.createdAt); } ``` Semantic search (hybrid) [#semantic-search-hybrid] Per-tenant toggle in the dashboard at **Settings → Search** (`/settings/search`). | Step | Action | | ---- | -------------------------------------------------------------------------------- | | 1 | Worker: `SEMANTIC_SEARCH_ENABLED=true` + embeddings provider (`AI_EMBEDDINGS_*`) | | 2 | Apply migration `0164_semantic_search_settings.sql` | | 3 | Dashboard: enable semantic search → **Run backfill** | | 4 | Search on `/search` or the room Search panel in chat | SDK helpers: ```ts await client.getSemanticSearchSettings(); await client.backfillMessageEmbeddings({ roomId: "general" }); const { results } = await client.searchMessagesSemantic("onboarding flow", { roomId: "support" }); ``` Query parameters [#query-parameters] | Param | Description | | ------------- | ----------------------------- | | `q` | Search string (required) | | `roomId` | Limit to one room | | `from` / `to` | ISO date range | | `limit` | Max hits (default 20, max 50) | Requires member JWT with access to the scoped rooms. UI pattern [#ui-pattern] Debounce input, show snippets from `hit.snippet`, deep-link to `/rooms/{roomId}?message={id}` in your app router. See [API Reference](/docs/api-reference) → **Search**. --- # Storage (Yjs) (/docs/core/storage) Storage is the **document**: Yjs on the room Durable Object (`yjs-sync.js`). Do not invent a second CRDT. Presence is "now"; chat is the timeline; this is the file. Import from `@fluxy-chat/sdk/yjs` (or `@fluxy-chat/react/yjs`) so chat-only clients skip the yjs graph. React [#react] ```tsx import { FluxyYjsProvider, useStorage, useMutation, useUndo, useRedo, useYjsDoc, useAwareness, uploadLiveFile, } from "@fluxy-chat/sdk/yjs"; ``` Prefer nesting inside `FluxyRealtimeProvider` so you do not pass `token` twice. Standalone, `authTokenProvider` is accepted as an alias of `token`. `userId` is optional when the JWT has `sub`. ```tsx const title = useStorage((root) => String(root.title ?? "")); const setTitle = useMutation((storage, next: string) => { storage.set("title", next); }, []); ``` `useStorage` reads a JSON snapshot of the `storage` Y.Map. `useMutation` writes that map inside a Yjs transaction. Undo/redo is `Y.UndoManager` on the map + Tiptap fragment (`prosemirror`). Awareness (y-websocket HOW) is JSON on binary type `2`: `useAwareness()`, `setLocalAwareness` from `useYjsContext()`. `synced` is true after the first server sync frame. The provider opens a **binary** WebSocket on the same `/ws/room/:id` (replay off). Chat `useChat` stays JSON on its own socket. Same room DO, same persistence key. LiveFile [#livefile] Bytes go through existing `POST /upload` (`client.uploadFile`). Put a JSON ref on the CRDT, not a second blob store: ```ts const live = await uploadLiveFile(client, roomId, file); storage.set("hero", live); // { liveFile: true, id, name, mime, size, url } ``` Tiptap [#tiptap] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-doc --example tiptap-room ``` Pass `useYjsDoc()` into `@tiptap/extension-collaboration` with `field: "prosemirror"`. Disable StarterKit history; undo is Yjs. Lexical / BlockNote / CodeMirror wait until this example is copy-pasteable. Whiteboard [#whiteboard] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-board --example whiteboard ``` Strokes live on `Y.Array` inside `Y.Map("storage")` (`storage.set("strokes", new Y.Array())`). Cursors stay on `useChat().sendCursor`. Same room DO. The dashboard can render that doc with Excalidraw in the browser. Excalidraw is not a second backend. Agent suggestions [#agent-suggestions] `GET /rooms/:id/yjs/agent-suggestions` lists rows. `POST` writes a row (`comment` is the justification). Optional HITL tool `yjs.acceptSuggestion`. `POST .../accept` copies `value` onto `storage[storageKey]` and broadcasts a Yjs update. `POST .../reject` marks it rejected and denies HITL. SDK: `listYjsAgentSuggestions` / `proposeYjsAgentSuggestion` / `acceptYjsAgentSuggestion` / `rejectYjsAgentSuggestion`. Presence `agentStatus` is still the “bot is in the room” flag; this map is the edit proposal. --- # useChat (/docs/core/use-chat) `useChat` connects to a room through a shared `FluxyChatClient`. It handles history, optimistic sends, transport fallback, and agent invoke. ```tsx import { useChat } from "@fluxy-chat/react"; import { FluxyChatClient } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: process.env.NEXT_PUBLIC_FLUXY_BASE_URL!, userId: "alice", token: jwt, }); function ChatRoom({ roomId }: { roomId: string }) { const { messages, sendMessage, connectionState, loadMore, hasMore, isLoadingMore, retryMessage, invokeAgent, } = useChat({ roomId, client, markReadLatest: true }); return (

Status: {connectionState.status}

{messages.map((msg) => (
{msg.content} {msg.deliveryStatus === "failed" && ( )}
))} {hasMore && ( )}
); } ``` Options [#options] | Option | Type | Description | | ---------------- | ---------------------------------- | --------------------------------------------------------------------------------- | | `roomId` | `string` | Room to subscribe to | | `client` | `FluxyChatClient` | Connected client instance | | `markReadLatest` | `boolean` | Mark latest message read on mount/update | | `readOn` | `"mount" \| "visible" \| "manual"` | Read receipt timing | | `onAnyEvent` | `(event) => void` | Raw room WebSocket events (messages, typing, client\_event, …) | | `onServerEvent` | `(event) => void` | Worker vertical fan-out (`server_event`: polls, live, game, collab CRDT metadata) | Vertical `server_event` via useChat [#vertical-server_event-via-usechat] ```tsx useChat({ roomId, client, onServerEvent: ({ name, data, roomId: rid }) => { if (name === "poll.created") console.log(data.pollId); if (name === "collab.crdt_update") console.log("Yjs activity", data.byteLength); }, }); ``` For React-only subscription without message state, see `useServerEvents` from `@fluxy-chat/react`. With FluxyRealtimeProvider [#with-fluxyrealtimeprovider] When the provider owns the client, omit the explicit `client`: ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; ``` Nest `FluxyYjsProvider` **inside** `FluxyRealtimeProvider` (it reuses the client). Standalone, it accepts `token` or the same `authTokenProvider` string. Do not pass `config={{ baseUrl, token }}` to the realtime provider. Public rooms: `publishableKey` on `FluxyRealtimeProvider`, or `joinPublicRoomAsGuest`. See [Quickstart](/docs/getting-started/quickstart). One socket for chat and cursors [#one-socket-for-chat-and-cursors] Under `FluxyRealtimeProvider`, `useChat` and `useLiveCursors` share `sessionScope` `app`. One JSON WebSocket per room. Yjs is still a second binary connection if you mount `FluxyYjsProvider`. Two widgets on the same `roomId` (assistant panel + live chat) must pass different `sessionScope` values. Connection state [#connection-state] `connectionState` includes `status`, `transport` (`websocket` | `sse` | `polling`), and `nextRetryAt` during reconnect. See [Connection state](/docs/core/connection-state). Agents in-room [#agents-in-room] ```tsx const { invokeAgent } = useChat({ roomId }); await invokeAgent("Summarize this thread", { agentId: "agt_…" }); ``` Mention-based invoke (`@assistant …`) is handled by the Worker when agents have handles configured. Vanilla (no React) [#vanilla-no-react] ```ts import { createFluxyRoomSession } from "@fluxy-chat/sdk"; const { store, stop } = createFluxyRoomSession({ roomId: "general", client }); store.getState().sendMessage("hello"); // cleanup: stop(); ``` --- # User channel (/docs/core/user-channel) Besides room WebSockets, FluxyChat exposes a **user channel** — one socket per authenticated user for inbox updates, notification fan-out, and account-scoped events. React hook [#react-hook] ```tsx import { useUserChannel } from "@fluxy-chat/react"; function NotificationBridge({ client }: { client: FluxyChatClient }) { const { connected, lastEvent } = useUserChannel({ client, onEvent: (event) => { if (event.type === "inbox_updated") { // refresh sidebar } }, }); return {connected ? "Live" : "Offline"}; } ``` Vanilla client [#vanilla-client] After minting a JWT with `POST /auth/signin`, the response includes user channel paths. Connect with: ```ts const ws = client.connectUser(userId); ws.onmessage = (ev) => { const event = JSON.parse(ev.data); console.log(event.type, event); }; ``` When to use [#when-to-use] | Channel | Scope | Use for | | -------------- | ----------- | ------------------------------------------ | | Room WebSocket | Single room | Messages, typing, presence | | User channel | Account | Inbox, push triggers, global notifications | Pair with [`useInbox`](/docs/core/inbox) (`realtime: true`) and [`useNotifications`](/docs/core/notifications). HTTP APIs [#http-apis] | Endpoint | Purpose | | ------------------------------------------- | -------------------------------------- | | `POST /users/{userId}/events` | Push custom events to user channel | | `DELETE /users/{userId}/connections` | Force-disconnect all user sockets | | `GET/POST/DELETE /users/{userId}/watchlist` | Track rooms or users for notifications | Caller must be the user or project admin/owner. See [Wire protocol](/docs/architecture/response-envelope-extension) for event types. --- # Voice messages (/docs/core/voice-huddles) FluxyChat supports **async voice messages** (record → upload → optional AI transcription). There is no `useHuddle` hook in `@fluxy-chat/react` today — live WebRTC huddles are not part of the public SDK. Enable the feature on the Worker: ```ini FEATURE_VOICE_MESSAGES=true ``` Bind R2 for attachments (`ATTACHMENTS` in `wrangler.toml`). Upload from the client [#upload-from-the-client] `POST /messages/voice` accepts multipart form data with a member JWT (same auth as `POST /messages`): ```ts const form = new FormData(); form.append("audio", blob, "recording.webm"); form.append("roomId", roomId); form.append("durationMs", String(durationMs)); const res = await fetch(`${baseUrl}/messages/voice`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, body: form, }); const { messageId, audioUrl, transcriptionStatus } = await res.json(); // transcriptionStatus: "pending" → later "ready" via message_updated WS event ``` Supported formats: webm, ogg, mp3, m4a, wav. Size and duration limits return `413` when exceeded. Realtime updates [#realtime-updates] After upload, the Worker broadcasts a `message_updated` event when transcription completes. Subscribe via the room WebSocket or poll message history if the socket is down. Rate limits and quotas [#rate-limits-and-quotas] Voice uploads consume message quota and respect `RATE_LIMIT_VOICE_MESSAGES_PER_MINUTE` (default 10/min per user). Live voice / huddles [#live-voice--huddles] `joinVoiceStage` / `leaveVoiceStage` on `useChat` is **stage signaling** (speaker vs listener on the room WebSocket). Scaffold: `--example voice-stage`. It is not WebRTC audio. Console: [`/voice-ai`](/voice-ai). Media for huddles is LiveKit. Voice AI latency: [load report](/docs/operations/voice-load-test-report) and `GET /admin/voice-ai/stats`. Product SLO P95 ≤ 300ms is a target; treat tables as unit-bench until stats are populated. Async clips remain `POST /messages/voice`. --- # Web push (React) (/docs/core/web-push) `useWebPush` registers the browser Push API with the Worker VAPID keys and keeps subscriptions in sync. ```tsx import { useWebPush } from "@fluxy-chat/react"; function PushToggle({ client }: { client: FluxyChatClient }) { const { permission, subscriptions, isLoading, requestPermissionAndSubscribe, unsubscribe, } = useWebPush(client, { projectId: "default" }); if (permission === "unsupported") { return

Push not supported in this browser.

; } return ( ); } ``` Requirements [#requirements] 1. **Service worker** at `/sw.js` (or custom `swPath`) that handles `push` events. 2. Worker VAPID keys — auto-generated per project on first request. 3. Member JWT on the client. Server-side delivery [#server-side-delivery] The Worker sends push on offline paths (mentions, digests). Configure preferences with `PATCH /digest/preferences` (`webPushEnabled`). See [Web Push (VAPID) guide](/docs/core/web-push) for HTTP routes and manual subscription flow. --- # Wire protocol (v1) (/docs/core/wire-protocol) This page is the contract. Use it when you wire a client or review a competitor. One room, two sockets when you need Yjs [#one-room-two-sockets-when-you-need-yjs] A room is one Durable Object. Chat, presence, feeds, threads, `server_event`, and `derived` share a JSON WebSocket: ``` GET /ws/room/:roomId?token= ``` Yjs (`FluxyYjsProvider`) opens a second, binary WebSocket on the same route with replay off. Chat plus Tiptap means two connections to one object. JSON history and CRDT sync stay out of each other's way. Transport falls `websocket` to `sse` to `polling`. Reconnect exposes `connectionState.nextRetryAt`. Auth on the wire [#auth-on-the-wire] | Who | How | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Member | JWT in `?token=` (or `Authorization` on REST). Roles: `member` / `moderator` / `admin` / `owner`. | | Guest | `POST /tokens/anonymous` with `pk_` (provider `publishableKey`), or `POST /public/rooms/:id/guest-session` then the same `?token=`. Public rooms. Stable `guestKey` in localStorage on the guest-session path. | | Non-member | HTTP 403 or close `1008`. | Keep `fc_…` API keys on the server. Mint JWTs with `POST /auth/token`. Refresh with `client.setToken()` / `updateToken()`, or pass a function to `authTokenProvider`. Frames that match the job [#frames-that-match-the-job] | Job | Frame / API | Wrong primitive | | --------------------- | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | Pointers | `type: "cursor"` / `sendCursor` (up to 600/min; optional `presenceKey` layer, e.g. `"agent"`) | Broadcast at 60 Hz | | Roster | `presence_patch`, `presenceMembers` | Full roster above 250 users (`presenceKind` becomes `aggregate`) | | Chat | JSON messages + `clientMessageId` | Feeds or comment threads | | Ephemeral pulse | `client-ephemeral-*` (skips webhooks) | Persisting it | | Document | Binary Yjs on the second socket | A second CRDT backend | | REST inbox | `GET /inbox` | Liveblocks inbox | | Inbox socket | `GET /ws/inbox?token=` (`connectInbox`) | User-channel only | | Late-joiner JSON | `setDerivedState` / `derivedState` (16 KiB, 30/min) | Stuffing a graph into chat history | | Room extensions | `GET/PUT /rooms/:id/extensions` (`extension_snapshot`, max 5) | Eval on the shared Worker | | Private lines | `visibility` + `visibleTo` on send | Filtering only in the UI | | Agent on the timeline | `invokeAgent` | The keyless copilot panel (local UI only) | What this layer is for [#what-this-layer-is-for] The room is the product artifact: a deal, a board, a classroom, a dispatch view. You do not buy Ably for this combination. You do not buy Liveblocks unless the artifact is only a document. You do not buy Stream unless you need MAU-scale consumer chat and mobile moderation. Live audio is a media plane (LiveKit or an SFU). `voice-stage` is roster signaling. Devices POST JSON (`iot.reading`, `fleet.gps_update`). Game ticks are server-authoritative input. Publish rules live in your Worker / `fluxy.config` `onPublish`. REST companion [#rest-companion] History, uploads, geofences, and cross-org are HTTP. Routes: [openapi.yaml](https://docs.fluxychat.com/openapi.yaml) (`text/yaml`). --- # 40103 anonymous_not_allowed (/docs/errors/anonymous_not_allowed) 40103 — anonymous_not_allowed [#40103--anonymous_not_allowed] The room is not public: a `pk_` publishable key or a guest JWT cannot join. Terminal. **At a glance** — HTTP 401 · close 1008 `anonymous_not_allowed` · terminal · SDK `FluxyAnonymousNotAllowedError`. What to do [#what-to-do] * Connect with a member JWT minted for the user (`POST /auth/token`, roles `member`) instead of the guest path. * A public room accepts the `pk_` path; this room does not. Either join as a member or use a room configured for anonymous access. * The refusal is terminal — retrying the guest connection cannot succeed. Related [#related] * [40100 token\_expired](/docs/errors/token_expired) * [40108 auth\_refused](/docs/errors/auth_refused) --- # 40108 auth_refused (/docs/errors/auth_refused) 40108 — auth_refused [#40108--auth_refused] Catch-all auth refusal, set when a more specific identifier is not available. Terminal. **At a glance** — HTTP 401 · close 1008 (unmapped reason) · terminal · SDK `FluxyAuthError` (check `refusalCode`). What to do [#what-to-do] * Check the JWT `tid` (project), `sub` (user), and that the user is a member of the room. * The raw close reason often names the real refusal (`not_member`, `token_expired`, …) — branch on that first; `auth_refused` is the fallback. * `describeConnectionError()` resolves the catalog entry the SDK matched, and falls back to this one when nothing parsed. Related [#related] * [40100 token\_expired](/docs/errors/token_expired) * [40101 invalid\_token](/docs/errors/invalid_token) * [40300 not\_member](/docs/errors/not_member) * [10008 ws\_policy](/docs/errors/ws_policy) --- # 40301 banned (/docs/errors/banned) 40301 — banned [#40301--banned] This user is banned from the room. Terminal; do not retry the same identity. **At a glance** — HTTP 403 · close 1008 `banned` · terminal · SDK `FluxyAuthError` with `refusalCode: "banned"`. What to do [#what-to-do] * Stop reconnect attempts for this identity and surface a clear message instead. * Reconnect only after an unban (`/admin/unban`) or with a different user. * `describeConnectionError()` marks it terminal (`isTerminal: true`), so generic retry logic skips it automatically. Related [#related] * [40300 not\_member](/docs/errors/not_member) * [40302 forbidden](/docs/errors/forbidden) --- # 44000 channel_at_capacity (/docs/errors/channel_at_capacity) 44000 — channel_at_capacity [#44000--channel_at_capacity] The room hit its connection cap. Terminal for this attempt. **At a glance** — HTTP 429 · close 1008 `channel_at_capacity` · terminal for this attempt · SDK `FluxyAuthError` with `refusalCode: "channel_at_capacity"`. What to do [#what-to-do] * The credential is fine: wait and retry, or point the user at another room. * Retrying later can succeed once other clients disconnect — it is not an auth problem. * Do not treat it like `rate_limited`: the block is on the room's connections, not on request frequency. Related [#related] * [42900 rate\_limited](/docs/errors/rate_limited) --- # 50000 connection_failed (/docs/errors/connection_failed) 50000 — connection_failed [#50000--connection_failed] The WebSocket closed abnormally, or the network dropped. Not always terminal: the client retries, then gives up as `suspended` / `failed`. **At a glance** — no HTTP status · SDK `FluxyConnectionError` (`.code`, `.reason`) · reconnect with backoff. What to do [#what-to-do] * Let the SDK reconnect — it backs off exponentially (500 ms → 20 s cap) with jitter so clients do not stampede the same room. * Surface the status pill instead of an error toast while `retryIn` is set — see [Connection status](/docs/cookbook/connection-status). * Map the raw close code when you need to distinguish causes: 1005/1006 network, 1011–1014 server, 4000 heartbeat, 4001 moderator terminate. Related [#related] * [10000 send\_not\_open](/docs/errors/send_not_open) * [10200 discontinuity](/docs/errors/discontinuity) --- # 10200 discontinuity (/docs/errors/discontinuity) 10200 — discontinuity [#10200--discontinuity] Resume could not fill a hole in the realtime history — events between the last cursor and now are missing. Not terminal. **At a glance** — no HTTP status · the SDK emits a `discontinuity` event and jumps the cursor forward. What to do [#what-to-do] * If the UI must be exact, reload message history from REST instead of patching the gap in place. * Otherwise continue from the new cursor — the stream is live again after the jump. * Occasional discontinuities after long offline periods are expected; treat frequent ones as a signal, not noise. Related [#related] * [50000 connection\_failed](/docs/errors/connection_failed) --- # 40040 feature_not_enabled (/docs/errors/feature_not_enabled) 40040 — feature_not_enabled [#40040--feature_not_enabled] The client subscribed to a room feature that is off: occupancy, presence, or raw message reactions (`enableEvents: false` or `rawMessageReactions: false`). Not terminal. **At a glance** — HTTP 400 · terminal: no. What to do [#what-to-do] * Turn the room option on, or skip the subscribe on clients that do not need it. * REST `get()` still works with the feature off — only the realtime subscribe is refused. * Check the room options before mounting the feature's UI so the subscribe never fires in the first place. --- # 40302 forbidden (/docs/errors/forbidden) 40302 — forbidden [#40302--forbidden] A capability or role check failed — for example publishing on a spectator socket, or an admin route the token's roles do not cover. Terminal for that action. **At a glance** — HTTP 403 · close 1008 `Forbidden` · terminal · depends on the role/capability, not the connection. What to do [#what-to-do] * Check the JWT `roles` claim against what the action requires — the [Auth / JWT cookbook](/docs/cookbook/auth-jwt) maps roles to routes. * On the WebSocket, the SDK maps a `Forbidden` close to `FluxyNotMemberError`; the raw close reason keeps the server's wording. * This can be action-scoped rather than connection-scoped: a spectator stays connected but cannot publish. Related [#related] * [40300 not\_member](/docs/errors/not_member) * [40301 banned](/docs/errors/banned) * [10008 ws\_policy](/docs/errors/ws_policy) --- # Error codes (/docs/errors) Error codes [#error-codes] These codes sit on `FluxyErrorInfo.code`. The Worker still closes sockets with 1008 and a short reason (`token_expired`, `not_member`). The numeric code is for SDKs and docs. Registry: `packages/protocol/errors/catalog.json`. Do not invent codes in app copy. | Code | Identifier | HTTP | Terminal | | ----- | ------------------------------------------------------------- | ---- | -------- | | 40100 | [token\_expired](/docs/errors/token_expired) | 401 | yes | | 40101 | [invalid\_token](/docs/errors/invalid_token) | 401 | yes | | 40102 | [invalid\_api\_key](/docs/errors/invalid_api_key) | 401 | yes | | 40103 | [anonymous\_not\_allowed](/docs/errors/anonymous_not_allowed) | 401 | yes | | 40108 | [auth\_refused](/docs/errors/auth_refused) | 401 | yes | | 40300 | [not\_member](/docs/errors/not_member) | 403 | yes | | 40301 | [banned](/docs/errors/banned) | 403 | yes | | 40302 | [forbidden](/docs/errors/forbidden) | 403 | yes | | 42900 | [rate\_limited](/docs/errors/rate_limited) | 429 | no | | 44000 | [channel\_at\_capacity](/docs/errors/channel_at_capacity) | 429 | yes | | 10000 | [send\_not\_open](/docs/errors/send_not_open) | — | no | | 10008 | [ws\_policy](/docs/errors/ws_policy) | 403 | yes | | 40040 | [feature\_not\_enabled](/docs/errors/feature_not_enabled) | 400 | no | | 40041 | [resource\_disposed](/docs/errors/resource_disposed) | 400 | yes | | 40400 | [message\_not\_found](/docs/errors/message_not_found) | 404 | no | | 10200 | [discontinuity](/docs/errors/discontinuity) | — | no | | 50000 | [connection\_failed](/docs/errors/connection_failed) | — | no | Stable URL shape: `https://docs.fluxychat.com/errors/`. Branch on codes [#branch-on-codes] `toFluxyErrorInfo` normalizes any caught error to its catalog entry; `errorInfoIs` matches an identifier or a numeric code. `terminal` tells you whether retrying with the same credential is pointless. ```ts import { errorInfoIs, toFluxyErrorInfo } from "@fluxy-chat/sdk"; try { // any SDK call: REST request, token minting, connect follow-up } catch (cause) { const info = toFluxyErrorInfo(cause as Error, "send message"); info.code; // 40100 info.identifier; // "token_expired" info.statusCode; // 401 info.href; // this docs page for the code info.terminal; // stop retrying with the same credential? if (errorInfoIs(info, "token_expired") || errorInfoIs(info, 40100)) { // Mint a fresh member JWT and reconnect. } } ``` For WebSocket disconnects, the room connection's `onDisconnect` hands you a mapped `error`; `describeConnectionError()` turns it into user-facing copy with `isTerminal` and `isMemberIssue`. The [Auth / JWT cookbook](/docs/cookbook/auth-jwt) shows the common refusals in context. --- # 40102 invalid_api_key (/docs/errors/invalid_api_key) 40102 — invalid_api_key [#40102--invalid_api_key] `X-Fluxy-Api-Key` is missing, revoked, or not an `fc_` server key. `pk_` keys cannot mint member JWTs. **At a glance** — HTTP 401 · terminal for that request. What to do [#what-to-do] * Send the project's `fc_` key on the server-side call that needs it (`POST /auth/token`, admin routes, REST) — see the [Auth / JWT cookbook](/docs/cookbook/auth-jwt). * `pk_` publishable keys are for public rooms in the browser. They never mint JWTs. * If the key was rotated, update the server environment and retry. Related [#related] * [40100 token\_expired](/docs/errors/token_expired) * [40108 auth\_refused](/docs/errors/auth_refused) --- # 40101 invalid_token (/docs/errors/invalid_token) 40101 — invalid_token [#40101--invalid_token] The token string is malformed, or it is signed with the wrong secret. Terminal. **At a glance** — HTTP 401 · close 1008 `invalid_token` · terminal · SDK `FluxyTokenExpiredError` (the SDK folds `invalid_token` into the token-expired path). What to do [#what-to-do] * Check the JWT is signed with this project's secret and carries `tid`, `sub`, and `exp` — the same claims the [Auth / JWT cookbook](/docs/cookbook/auth-jwt) mints. * Re-mint the token; do not patch the string. * On the WebSocket you see close 1008 with reason `invalid_token`. Related [#related] * [40100 token\_expired](/docs/errors/token_expired) * [40102 invalid\_api\_key](/docs/errors/invalid_api_key) * [40108 auth\_refused](/docs/errors/auth_refused) --- # 40400 message_not_found (/docs/errors/message_not_found) 40400 — message_not_found [#40400--message_not_found] `GET /messages/:id` — or the versions / reactions for that id — found no row in this project, or the id was not a positive integer. Not terminal. **At a glance** — HTTP 404 · REST only. What to do [#what-to-do] * Check the id and the project scope: a message that exists in another project is a 404 here. * The id must be a positive integer; a malformed id is a 404, not a 400. * Nullable for UI: "not found" is a normal answer for detail endpoints, not an incident. --- # 40300 not_member (/docs/errors/not_member) 40300 — not_member [#40300--not_member] The user is authenticated but not a member of this room. Terminal until they are invited or join. **At a glance** — HTTP 403 · close 1008 `not_member` · terminal · SDK `FluxyNotMemberError`. What to do [#what-to-do] * Add the user to the room (invite / membership API), or connect with an identity that is already a member. * The SDK also maps a `Forbidden` close reason to `FluxyNotMemberError` — inspect the raw reason when you need to tell the two apart. * Do not auto-retry the same identity: reconnect fails until membership changes. Related [#related] * [40301 banned](/docs/errors/banned) * [40302 forbidden](/docs/errors/forbidden) * [40108 auth\_refused](/docs/errors/auth_refused) --- # 42900 rate_limited (/docs/errors/rate_limited) 42900 — rate_limited [#42900--rate_limited] Back off, then retry. Not terminal. **At a glance** — HTTP 429 · terminal: no · SDK `FluxyRateLimitError`. What to do [#what-to-do] * Wait the server's hint — REST responses carry `retryAfter`, or the `Retry-After` header — then retry. * In the SDK, catch `FluxyRateLimitError` and wait `retryAfterMs` before the next call. * Batch or throttle bulk sends instead of retrying in a tight loop. ```ts import { FluxyRateLimitError } from "@fluxy-chat/sdk"; try { await sendBatch(); } catch (err) { if (err instanceof FluxyRateLimitError) { await new Promise((resolve) => setTimeout(resolve, err.retryAfterMs)); // retry once, or hand the delay back to your queue } } ``` Related [#related] * [44000 channel\_at\_capacity](/docs/errors/channel_at_capacity) --- # 40041 resource_disposed (/docs/errors/resource_disposed) 40041 — resource_disposed [#40041--resource_disposed] `rooms.get` ran after `rooms.dispose()` / `client.close()`. The client is done. Terminal. **At a glance** — HTTP 400 · terminal · a client lifecycle error, not a network failure. What to do [#what-to-do] * Create a new `FluxyChatClient` instead of reusing the disposed one. * Terminal means retrying on the same client cannot succeed — the fix is a new client, not a retry. Related [#related] * [10000 send\_not\_open](/docs/errors/send_not_open) --- # 10000 send_not_open (/docs/errors/send_not_open) 10000 — send_not_open [#10000--send_not_open] Client-side: `sendJson` ran while the socket was not open. This is not a Worker close, and it is not terminal. **At a glance** — no HTTP status · SDK `FluxySendError`. What to do [#what-to-do] * Call `attach()` / `connect()` first, and wait for `connected` before sending. * Gate sends on the connection status (`attaching` → `attached`) — see [Connection status](/docs/cookbook/connection-status). * The SDK's guard message spells this out: "Cannot send: WebSocket is not open. Call connect() and wait until connected." Related [#related] * [50000 connection\_failed](/docs/errors/connection_failed) --- # 40100 token_expired (/docs/errors/token_expired) 40100 — token_expired [#40100--token_expired] The JWT is expired, or it is not a Fluxy member token. Terminal: stop retrying with the same credential. **At a glance** — HTTP 401 · close 1008 `token_expired` · terminal · SDK `FluxyTokenExpiredError`. What to do [#what-to-do] * Mint a new member JWT server-side (`POST /auth/token` with the `fc_` key) and reconnect with it. Never hand-craft or reuse another environment's token. * The SDK folds both `token_expired` and `invalid_token` closes into `FluxyTokenExpiredError`. * For long-lived clients, rotate before expiry with `scheduleSessionTokenRefresh` instead of reconnecting on failure. Related [#related] * [40101 invalid\_token](/docs/errors/invalid_token) * [40102 invalid\_api\_key](/docs/errors/invalid_api_key) * [40108 auth\_refused](/docs/errors/auth_refused) --- # 10008 ws_policy (/docs/errors/ws_policy) 10008 — ws_policy [#10008--ws_policy] A 1008 policy close whose reason did not match a named refusal identifier. Treat it as terminal until the reason is known. **At a glance** — close 1008 (unmapped reason) · terminal · SDK `FluxyAuthError` without a `refusalCode`. What to do [#what-to-do] * Log the raw close reason text — that is the whole point of this catch-all identifier. * Most 1008 closes are actually one of the named refusals; check [auth\_refused](/docs/errors/auth_refused), [not\_member](/docs/errors/not_member), and [token\_expired](/docs/errors/token_expired) first. * The Worker also uses 1008 for `protocol_unsupported` and bare `Unauthorized` / `Forbidden` reasons — those arrive here too. Related [#related] * [40108 auth\_refused](/docs/errors/auth_refused) * [40300 not\_member](/docs/errors/not_member) --- # A2A agent protocol (/docs/features/a2a-agents) A2A agent protocol [#a2a-agent-protocol] FluxyChat implements an A2A adapter: fetch external Agent Cards, validate HTTPS endpoints, and delegate tasks to remote agents while keeping room context on your Worker. Console [#console] **Agents → A2A** (`/agents/a2a`) 1. Register external agent base URL (Agent Card discovery). 2. Test delegation with a sample task payload. 3. View task status and responses in the task list. Complementary protocols [#complementary-protocols] | Protocol | Direction | | -------- | ------------------------ | | AG-UI | Agent to user UI in chat | | A2A | Agent to agent | | MCP | Agent to tools | Security [#security] * HTTPS-only Agent Card fetch. * SSRF blocks on internal IPs. * Optional `A2A_OUTBOUND_BEARER` for authenticated remote endpoints. API [#api] ```http GET /a2a/agent-cards POST /admin/a2a/agent-cards POST /a2a/rooms/:roomId/join POST /a2a/tasks GET /a2a/tasks/:taskId POST /a2a/tasks/:taskId/delegate ``` `POST /a2a/rooms/:roomId/join` with `{ "agentId": "…" }` adds a bot member and a room-scoped `agent_policy`. It does **not** stream the remote A2A endpoint into the room. Invoke the bot like any other agent. Agent Card JSON follows the [Linux Foundation A2A](https://github.com/a2aproject/A2A) spec. Related [#related] * [Cross-org rooms](/docs/features/cross-org-rooms) * [Ambient agents](/docs/features/ambient-agents) --- # Multi-agent debate (/docs/features/agent-debate) Multi-agent debate [#multi-agent-debate] Trigger a debate thread where multiple agents argue assigned perspectives. A moderator agent posts a synthesis when rounds complete. Console [#console] **Agents → Debate** (`/agents/debate`) 1. Seed default roles (optimist, skeptic, moderator) or create custom roles. 2. Configure trigger pattern (regex on user prompt), system prompt, and max rounds (default 2). 3. Run debate from console or trigger from chat when the pattern matches. In chat, debates render as grouped `agent_step` events in `DebateThreadPanel` with `participant_role: "debate"`. API [#api] ```http GET /admin/agent-debate/roles POST /admin/agent-debate/roles POST /admin/agent-debate/roles/seed PATCH /admin/agent-debate/roles/:roleId DELETE /admin/agent-debate/roles/:roleId GET /admin/agent-debate/sessions?roomId= POST /admin/agent-debate/run ``` Run body: `{ roomId, prompt, maxRounds? }`. Behaviour [#behaviour] * Token cost telemetry per debate session (`latencyMs`, step count). * Timeout produces a partial consensus message from the moderator role. * Events stream on the room WebSocket like normal agent steps. When to use [#when-to-use] High-stakes decisions, policy review, or UX where users benefit from seeing reasoning paths before the final answer. Related [#related] * [Agent observability](/docs/reference/observability-otel) * [Agent eval](/agents/eval) --- # Ambient agents (/docs/features/ambient-agents) Ambient agents [#ambient-agents] Ambient agents run when external events or room conditions match a policy: a keyword in a message, a webhook payload, a schedule, and so on. They do not need an explicit @mention. Console [#console] **Agents → Ambient** (`/agents/ambient`) Create policies with: | Field | Meaning | | ------------ | -------------------------------------------------- | | Trigger | `webhook`, `keyword`, `schedule`, … | | Max autonomy | How far the agent can act without human escalation | | Target room | Where to post results | | Agent ID | Which WorkflowAgent executes | Enable or disable policies without deleting configuration. Architecture [#architecture] ``` Webhook / room event → Worker policy engine (agent_policies) → WorkflowAgent → room message + audit log ``` API [#api] ```http GET /admin/ambient-agents/policies POST /admin/ambient-agents/policies PATCH /admin/ambient-agents/policies/:id DELETE /admin/ambient-agents/policies/:id POST /webhooks/ambient/:policyId ``` Guardrails [#guardrails] * Scoped permissions per policy. * Audit log on every autonomous action. * Escalation above configured risk threshold. Pair with [tool approvals](/docs/guides/tool-approvals) for sensitive tools. Related [#related] * [A2A agents](/docs/features/a2a-agents) * [AI agent handoff](/docs/reference/ai-agent-handoff) --- # Art. 50 transparency checklist (/docs/features/art-50-checklist) Art. 50 transparency checklist [#art-50-transparency-checklist] This is a **product mapping**, not a legal opinion. Regulation (EU) 2024/1689 Art. 50 interaction transparency applies from **2 August 2026** (no grace period). Art. 50(2) marking for systems already on the market has a grace window to **2 December 2026**. Confirm dates and scope with counsel. Hosted FluxyChat is beta. Self-host the MIT Cloudflare room layer if you need the code under your own account. What the software does [#what-the-software-does] | Control | Where | | --------------------------------------------------- | ----------------------------------------------------------------- | | `participantType: human \| ai` on protocol messages | Worker persist + WebSocket announce | | Visible **IA** badge on agent bubbles | `@fluxy-chat/ui` `MessageItem` | | First-contact notice (per project, default on) | Room banner + `metadata.firstContactInRoom` | | HMAC-signed machine-readable mark | `messages.metadata_json` | | Marks export | `GET /admin/eu-ai-act/art-50-marks` and console **Art. 50 marks** | | Prompt-side “I am an AI” suffix | Runtime policy when disclosure is on | | Gap assessment | `GET /admin/eu-ai-act/assessment` | HMAC is an **integrity** check for your export file. It is not secrecy and it is not a notified-body seal. Rotate `ART50_MARK_SECRET` and keep `ART50_MARK_SECRET_PREVIOUS` until old exports verify. Legal Art. 50 duties stay with the deployer of the agent, not with this HMAC. What stays on you [#what-stays-on-you] * Whether your use is in scope (chatbot vs other AI systems, deployers vs providers) * Copy for the first-contact notice in your jurisdiction and language * Training users not to treat agent output as a human operator * Deepfakes / synthetic media marking beyond in-room text (Art. 50(2) content) * EU database registration, FRIA, and notified-body work where required * Accessibility of the widget under the European Accessibility Act (separate from the AI Act; consumer services from 28 June 2025) Operator steps [#operator-steps] 1. Run D1 migration `0226_art50_message_marks.sql`. 2. Keep **Enforce AI disclosure** on for customer-facing rooms. 3. Keep **First-contact notice** on unless counsel says the room is out of scope. 4. Export marks after a test invoke and store them with your audit pack. 5. Read [EU AI Act readiness](/docs/features/eu-ai-act) for Art. 9–15 and Annex IV. Related [#related] * [EU AI Act readiness](/docs/features/eu-ai-act) * [GDPR](/docs/learn/gdpr-compliance) * [Chat SDK adapter (FluxyChat)](/docs/guides/chat-sdk-adapter) --- # Async decision quorum (/docs/features/async-decisions) Async decision quorum [#async-decision-quorum] Post a decision message that requires quorum from specific roles (e.g. 2 of 3 approvers within 48 hours). Progress updates live in the thread. In chat [#in-chat] 1. Open message menu → **Create decision** (or use the `Decision` UI component). 2. Set question, required roles, quorum count, and expiry. 3. Approvers tap **Acknowledge**. The progress bar updates server-side. 4. When quorum is met or time expires, state transitions to `approved` or `expired`. Console UI [#console-ui] The `Decision` component (`apps/dashboard/components/ui/decision.tsx`) renders quorum progress inline on decision messages. API [#api] ```http POST /rooms/:roomId/decisions POST /rooms/:roomId/decisions/:messageId/ack GET /rooms/:roomId/decisions/:messageId ``` SDK [#sdk] ```ts await client.createDecision(roomId, { question: "Ship v2 Friday?", requiredRoles: ["owner", "admin"], quorum: 2, expiresInHours: 48, }); await client.ackDecision(roomId, decisionMessageId); ``` Quorum is verified only on the server. Clients cannot bypass role checks. Related [#related] * [Message middleware](/docs/reference/message-middleware) --- # Channel structured forms (/docs/features/channel-forms) Channel structured forms [#channel-structured-forms] Define a form schema once. Deliver it on WhatsApp (interactive messages or Flows) or RCS (suggested replies). Answers arrive as a structured message in the FluxyChat room. Console [#console] **Bridges → Forms** (`/bridges/forms`) 1. Pick a room and recipient E.164 number. 2. Choose channel: WhatsApp or RCS. 3. Send structured form. The worker creates a delivery record and calls the channel adapter. 4. Copy inbound webhook URLs for Meta or RCS aggregator configuration. 5. Review recent deliveries (status, responses, timestamps). Field types [#field-types] | Type | Use | | -------- | -------------------------- | | `select` | Single choice from options | | `yes_no` | Boolean step | | `rating` | Numeric scale | | `text` | Free text | API [#api] ```http POST /channel-forms/dispatch GET /channel-forms/deliveries?roomId=&limit= POST /webhooks/channel-forms/whatsapp POST /webhooks/channel-forms/rcs ``` Dispatch body: `{ roomId, channel, recipientE164, schema?, formId?, channelConfigId? }`. WhatsApp [#whatsapp] Requires Meta Business API credentials. See [Optional integrations: WhatsApp](/docs/guides/ecosystem/optional-integrations#whatsapp-business-structured-forms). Set `WHATSAPP_*` env vars on the Worker (token, phone number ID, verify token). RCS [#rcs] Requires a paid RCS aggregator. See [Platform status](/docs/features/platform-status) for current RCS support. Dry-run [#dry-run] Without vendor credentials, submissions are stored locally for UI testing. Useful for schema iteration before going live. Related [#related] * [Bridges overview](/docs/guides/ecosystem/optional-integrations) * [Platform status](/docs/features/platform-status) --- # Chat cartography (/docs/features/chat-cartography) Chat cartography [#chat-cartography] Visualize a room's history as a 2D map of thematic clusters (from message embeddings). Zoom out for overview blobs. Zoom in to read messages in a cluster. Console [#console] **Cartography** (`/cartography`) 1. Select a room. 2. Generate or refresh map. The worker runs k-means on message embeddings and stores 2D coordinates. 3. Pan and zoom the canvas (`RoomCartographyMap`). 4. Click a cluster to list representative messages. API [#api] ```http GET /rooms/:roomId/cartography POST /rooms/:roomId/cartography/rebuild ``` Rebuild is rate-limited. Cached coords live in D1 (`room_cartography`). Requirements [#requirements] Message embeddings must exist. Enable [semantic search](/docs/core/search) and run backfill from **Settings → Search**. Honesty note [#honesty-note] Conversation maps show up in research papers from time to time. This is an exploratory UX for large rooms, not a replacement for keyword or semantic search. Related [#related] * [Search](/docs/core/search) * [Room sentiment](/docs/features/room-sentiment) --- # Counterfactual replay (/docs/features/counterfactual-replay) Counterfactual replay [#counterfactual-replay] On any agent tool call in chat, choose **Try alternative** to re-execute with edited parameters. Original and alternative results appear side by side. Console [#console] In the agent tool thread panel (`CounterfactualReplayPanel` / `CounterfactualCompare`): 1. Expand a completed tool call. 2. Edit JSON parameters. 3. Replay. The worker runs dry-run for side-effect tools. 4. Compare outputs in the two-column view. Requires agent runs stored with tool traces (default for WorkflowAgent). Guardrails [#guardrails] * Side-effect tools (send message, HTTP POST, etc.) run in dry-run mode. * Max one nested counterfactual level per run. * Stored in `agent_runs_counterfactual` (D1). API [#api] ```http POST /rooms/:roomId/agent-runs/:runId/counterfactual GET /rooms/:roomId/agent-runs/:runId/counterfactual ``` SDK [#sdk] ```ts const alt = await client.replayCounterfactual(roomId, { runId: originalRunId, toolCallId, modifiedParams: { query: "alternative search terms" }, }); ``` Related [#related] * [Agent observability](/docs/reference/observability-otel) * [Multi-agent debate](/docs/features/agent-debate) --- # Cross-org agent rooms (/docs/features/cross-org-rooms) Cross-org agent rooms [#cross-org-agent-rooms] Cross-org rooms let AI agents from two tenants collaborate in a neutral room with: * Verified agent identity (Agent Card / A2A) * Escrow-style commitments (`proposed` → `committed` | `rejected`) * Bilateral hash-chain audit * Mandatory human approval before binding commits Console [#console] **Agents → Cross-org** (`/agents/cross-org`) 1. Create room. Invite org B by project ID or invite code. 2. Post commitments (terms, deliverables, deadlines). 3. Counterparty responds with `countered` or acceptance path. 4. Human gate: each org approves before `committed`. 5. Export audit trail for compliance review. States [#states] ``` proposed → countered → pending_human_a | pending_human_b → committed | expired | rejected ``` Max negotiation rounds are configurable per room. API [#api] ```http POST /cross-org/rooms GET /cross-org/rooms/:roomId POST /cross-org/rooms/:roomId/commitments POST /cross-org/rooms/:roomId/commitments/:id/approve GET /cross-org/rooms/:roomId/audit ``` MVP scope [#mvp-scope] Neutral host on a single FluxyChat deployment (two projects, one worker). Full multi-deployment federation bridge is a later phase. Related [#related] * [A2A agents](/docs/features/a2a-agents) * [Audit chain](/docs/guides/enterprise/dlp-audit-export) * [Rehearsal rooms](/docs/features/rehearsal-rooms) --- # Empathy layer (voice) (/docs/features/empathy-layer) Empathy layer (voice) [#empathy-layer-voice] During voice sessions, optional prosody analysis (pitch, rate, pauses) on the client feeds a coarse emotion signal to the agent runtime. The agent adjusts tone and escalation hints. It never announces that the user sounds frustrated. Console [#console] **Voice AI** (`/voice-ai`): enable empathy per room in the settings panel. **Settings**: room-level empathy toggles stored in `room_empathy_settings`. Opt-in [#opt-in] * Per-room toggle in D1. * Raw prosody is not persisted. Only an aggregated signal with TTL in KV. * Low confidence means no prompt change. Client [#client] `useEmpathyProsody` hook sends: ```http POST /rooms/:roomId/empathy/signal ``` Body: coarse bucket (`calm`, `tense`, `elevated`) plus confidence, not raw audio. Agent runtime [#agent-runtime] When a signal is present, `agent-runtime` appends a short empathy block to the system prompt (adjust tone, offer pause) without exposing detection to the user. Related [#related] * [Voice stages](/docs/features/voice-stages) * [Voice AI pipeline](/docs/guides/voice-ai-pipeline) --- # EU AI Act readiness (/docs/features/eu-ai-act) EU AI Act readiness [#eu-ai-act-readiness] FluxyChat ships technical controls aligned with the [EU Artificial Intelligence Act](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX%3A32024R1689) (Regulation 2024/1689). This is not legal advice. Pair with your counsel for formal conformity assessment. Console: compliance hub [#console-compliance-hub] Open [EU AI Act](/ai-governance/eu-ai-act) in the dashboard (also under Trust → EU AI Act): | Feature | What it does | | ------------------- | --------------------------------------------------------------------- | | Gap assessment | Automated checklist with severity (critical / high / medium) | | Project settings | Provider identity, retention, disclosure and HITL enforcement toggles | | Agent profiles | Intended purpose, EU risk category, Annex III domain, oversight level | | Runtime enforcement | Blocks unacceptable/high-risk-without-conformity agents; forces HITL | | Annex IV export | JSON technical documentation for your conformity file | Risk categories [#risk-categories] | Category | Typical FluxyChat use | Runtime behaviour | | ------------ | ------------------------------------------ | ------------------------------------------------------- | | minimal | Internal FAQ bot, read-only tools | Standard logging | | limited | Customer support with disclosure | AI disclosure in system prompt and message metadata | | high | HR, credit, essential services (Annex III) | HITL on side-effect tools; conformity sign-off required | | unacceptable | Social scoring, prohibited practices | Blocked at runtime when enforcement enabled | Document each agent's intended purpose before production. Most team-chat agents are minimal or limited. Article mapping [#article-mapping] Art. 9: Risk management [#art-9-risk-management] * Per-agent profiles with intended purpose and Annex III category * Automated gap assessment (`GET /admin/eu-ai-act/assessment`) * Integration with [AI Governance](/ai-governance) model/prompt/tool registry Art. 10: Data governance [#art-10-data-governance] * [EU consent and DPA](/docs/features/eu-consent): banner and audit log * [Data residency](/settings/residency): pin project storage region * PII redaction via [LLM middleware](/middleware) and [room firmware](/docs/features/room-firmware) Art. 11: Technical documentation [#art-11-technical-documentation] * Annex IV export: `GET /admin/eu-ai-act/technical-documentation` * Includes agents, models, controls matrix, provider identity * Download from dashboard Annex IV export button Art. 12: Record-keeping [#art-12-record-keeping] * `agent_runs` table (tool traces, tokens, latency) * `eu_ai_act_audit_log` (settings changes, blocked runs, completions) * Configurable retention days in project settings (default 365) * [Run audits](/docs/guides/processes): JSONL or PDF evidence pack with the human decisions behind every write step * [Activities](/activities), [SOC 2](/soc2), OTel/Langfuse export Art. 13: Transparency [#art-13-transparency] * Agent `@mention` and streaming `agent_step` events * AI disclosure suffix in system prompt for limited/high-risk agents * Message metadata: `aiGenerated`, `aiDisclosure`, `euAiActRiskCategory` Art. 14: Human oversight [#art-14-human-oversight] * [Tool approvals](/docs/guides/tool-approvals): HITL before destructive tools * Automatic HITL for high-risk agents (`side_effect` or `all_tools` mode) * [Moderation console](/docs/features/moderation-console), [agent queue](/agent-queue), [async decisions](/docs/features/async-decisions) Art. 15: Accuracy and robustness [#art-15-accuracy-and-robustness] * [Agent eval](/agents/eval) datasets and OTel export * [Counterfactual replay](/docs/features/counterfactual-replay) * [Agents → Observability](/agents/observability) for drift monitoring Art. 43 / 50: Conformity and transparency [#art-43--50-conformity-and-transparency] * Conformity assessed checkbox on high-risk agent profiles (blocks run until set) * Provider legal name and contact in project settings * GPAI: register foundation models in AI Governance; use provider DPAs * **Art. 50 product surface:** `participantType`, IA badge, first-contact notice, HMAC marks, export. See the [Art. 50 checklist](/docs/features/art-50-checklist). Tools are not a legal guarantee. API reference [#api-reference] All routes require admin JWT. ```bash # Settings GET /admin/eu-ai-act/settings PATCH /admin/eu-ai-act/settings # Agent profiles GET /admin/eu-ai-act/agents PUT /admin/eu-ai-act/agents/{agentId} # Assessment & documentation GET /admin/eu-ai-act/assessment GET /admin/eu-ai-act/technical-documentation GET /admin/eu-ai-act/audit-log?limit=100 GET /admin/eu-ai-act/art-50-marks?roomId=optional ``` Example: register a high-risk agent profile: ```bash curl -X PUT "$WORKER/admin/eu-ai-act/agents/bot_hr" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "intendedPurpose": "Draft HR policy answers. Human reviews all outbound messages.", "euRiskCategory": "high", "annexIIICategory": "employment", "humanOversightLevel": "human_in_loop", "hitlMode": "all_tools", "requiresDisclosure": true, "conformityAssessed": true }' ``` Operator checklist (before go-live) [#operator-checklist-before-go-live] 1. Set provider legal name and contact in EU AI Act settings. 2. Inventory every agent: purpose, risk category, model ID. 3. Register models in AI Governance registry. 4. Enable tool approvals / HITL for high-risk agents. 5. Turn on EU consent and data residency if you have EU users. 6. Enable moderation and audit logging for customer-facing rooms. 7. Run gap assessment. Resolve all critical and high items. 8. Export Annex IV documentation and store with your conformity file. 9. Mark conformity assessed only after internal/legal review. 10. Configure OTel/Langfuse for incident review. What FluxyChat cannot do for you [#what-fluxychat-cannot-do-for-you] These remain organizational and legal obligations: * Formal conformity assessment body involvement (if required for your use case) * EU database registration as provider/deployer where applicable * Written human oversight policy signed by management * Fundamental rights impact assessment (FRIA) for high-risk public-sector deployers * Training data documentation for custom fine-tuned models Related [#related] * [AI Governance guide](/docs/guides/enterprise/ai-governance) * [GDPR compliance](/docs/learn/gdpr-compliance) * [SOC 2 runbook](/docs/guides/enterprise/soc2-hipaa-runbook) * [Platform status](/docs/features/platform-status) --- # EU consent and DPA (/docs/features/eu-consent) EU consent and DPA [#eu-consent-and-dpa] Rooms with EU members, or tenant policy requiring GDPR flows, show a consent banner on first join. Consent events append to an audit log for DPA evidence. Console [#console] **Settings → Consent** (`/settings/consent`) * Tenant default: require consent for all rooms or EU-flagged rooms only. * DPA version string and link URL shown in banner. * Export consent log (CSV/JSON) for audits. In chat [#in-chat] `EuConsentBanner` appears until the user acknowledges. Stored fields: user ID, consent version, timestamp. No extra tracking. API [#api] ```http GET /consent/settings PUT /consent/settings POST /rooms/:roomId/consent/ack GET /consent/audit?from=&to= ``` Pairs with [#pairs-with] * [Data residency](/docs/guides/enterprise/dlp-audit-export): region pinning (`/settings/residency`) * [Ephemeral messages](/docs/guides/ephemeral-messages): retention minimization Not legal advice. Configure banner text and DPA links with your counsel. Related [#related] * [GDPR compliance](/docs/learn/gdpr-compliance) * [Optional integrations](/docs/guides/ecosystem/optional-integrations) --- # Features overview (/docs/features/features-overview) Chat and realtime [#chat-and-realtime] | Feature | Documentation | | -------------------------- | ---------------------------------------------------------------------- | | WebSocket rooms + presence | [Pusher parity](/docs/reference/pusher-channels-parity) | | TypeScript / React SDK | [@fluxy-chat/sdk](/docs/packages/sdk) | | Semantic search | [Search](/docs/core/search) | | Smart catch-up digest | [Smart catch-up](/docs/features/smart-catch-up) | | Room sentiment | [Room sentiment](/docs/features/room-sentiment) | | Scheduled messages | [Scheduled messages](/docs/features/scheduled-messages) | | Async decisions | [Async decisions](/docs/features/async-decisions) | | Merge conflicts (CRDT) | [Merge conflicts](/docs/features/merge-conflicts) | | Slash commands | [Slash commands](/docs/guides/slash-commands) | | Ephemeral / retention | [Ephemeral messages](/docs/guides/ephemeral-messages) | | Public demo / embed | [Embed widget](/docs/reference/embed-widget) | | Public share URL | [Public share](/docs/guides/public-share) | | Import ChatGPT/Claude JSON | [Import transcript](/docs/guides/import-transcript) | | StackBlitz examples | [StackBlitz](/docs/guides/stackblitz-snippets) | | Custom domain | [Custom domain white-label](/docs/reference/custom-domain-white-label) | AI and agents [#ai-and-agents] | Feature | Documentation | | ---------------------------- | ------------------------------------------------------------- | | AI Gateway | [AI Gateway](/docs/reference/ai-gateway) | | Agent workspace (live steps) | [Workflow agent](/docs/guides/workflow-agent) | | Generative UI (AG-UI) | [Generative UI](/docs/guides/generative-ui) | | Counterfactual replay | [Counterfactual replay](/docs/features/counterfactual-replay) | | Multi-agent debate | [Agent debate](/docs/features/agent-debate) | | Ambient agents | [Ambient agents](/docs/features/ambient-agents) | | Rehearsal rooms | [Rehearsal rooms](/docs/features/rehearsal-rooms) | | Chat cartography | [Chat cartography](/docs/features/chat-cartography) | | Truth Market | [Truth Market](/docs/features/truth-market) | | A2A protocol | [A2A agents](/docs/features/a2a-agents) | | Cross-org agent rooms | [Cross-org rooms](/docs/features/cross-org-rooms) | | Empathy layer (voice) | [Empathy layer](/docs/features/empathy-layer) | | Voice stages | [Voice stages](/docs/features/voice-stages) | | Voice pipeline | [Voice AI pipeline](/docs/guides/voice-ai-pipeline) | | Agent handoff | [AI agent handoff](/docs/reference/ai-agent-handoff) | | Observability | [OpenTelemetry](/docs/reference/observability-otel) | | Room Decisions | [Room Decisions](/docs/guides/room-decisions) | | Art. 50 marks | [Art. 50 checklist](/docs/features/art-50-checklist) | Security and compliance [#security-and-compliance] | Feature | Documentation | | -------------------------- | --------------------------------------------------------------------------- | | Passkeys | [Passkeys](/docs/features/passkeys) | | Shared-room agent defaults | [Two-key HITL](/docs/guides/security/shared-room-agent-defaults) | | SSO / SAML | [SAML signature verification](/docs/security/saml-signature-verification) | | EU consent / DPA | [EU consent](/docs/features/eu-consent) | | Room firmware | [Room firmware](/docs/features/room-firmware) | | Moderation console | [Moderation console](/docs/features/moderation-console) | | Media pipeline | [Media pipeline](/docs/features/media-pipeline) | | SOC2 / HIPAA | [Enterprise SOC2/HIPAA runbook](/docs/guides/enterprise/soc2-hipaa-runbook) | | Audit / eDiscovery | [DLP audit export](/docs/guides/enterprise/dlp-audit-export) | Omnichannel and operations [#omnichannel-and-operations] | Feature | Documentation | | ------------------------------ | ---------------------------------------------------------------------- | | Channel forms (WhatsApp / RCS) | [Channel forms](/docs/features/channel-forms) | | Usage dashboard | [Usage dashboard](/docs/features/usage-dashboard) | | Unified inbox | [Dashboard integration](/docs/reference/dashboard-integration) | | Quiet hours | [Quiet hours notifications](/docs/reference/quiet-hours-notifications) | | External services | [Optional integrations](/docs/guides/ecosystem/optional-integrations) | | Entity rooms / HMAC ingest | [Integration kit](/docs/guides/integration-kit) | | GitHub/Linear/Jira from a room | [Room tickets](/docs/guides/room-tickets) | | React Native SDK | [React Native SDK](/docs/packages/react-native-sdk) | Not fully productized yet [#not-fully-productized-yet] See [Platform status](/docs/features/platform-status) for RCS, WebTransport, x402/AP2, omnichannel OAuth, IoT predictive layer, and voice clone translation. Related [#related] * [Platform modules](/docs/platform): stream, collab, game, IoT, fleet * [Core SDK](/docs/core): client APIs and hooks * [API reference](/docs/api-reference): REST endpoints on your Worker --- # Offline sync, federation, and merge conflicts (/docs/features/federation-merge-story) Offline sync, Matrix federation, and merge conflicts are related problems. FluxyChat handles them as one story instead of three disconnected features. The loop [#the-loop] ```mermaid sequenceDiagram participant Client participant DO as Room DO participant D1 participant Matrix Client->>Client: IndexedDB outbox while offline Client->>DO: reconnect and delta sync (syncStatus) DO->>D1: authoritative messages Note over Client: If two edits collide, open merge-conflict UI Client->>DO: resolve keep_a / keep_b / merge_both DO->>Matrix: optional outbound bridge ``` Pieces [#pieces] | Layer | What | Where | | ------------------ | ------------------------------------------- | ------------------------------------------------- | | Offline-first | WS events, pending send queue, `syncStatus` | `@fluxy-chat/sdk`, React Native outbox | | Authoritative room | Durable Object and D1 history | Worker Room DO | | Conflict UI | Side-by-side resolve when edits diverge | [Merge conflicts](/docs/features/merge-conflicts) | | Federation | Matrix appservice bridge in and out | Bridge routes and docs | Operator checklist [#operator-checklist] 1. Enable offline-first in the SDK (`offlineFirst: true`, default on web). 2. Show a connection banner when `syncStatus` is `offline` or `pending`. 3. Wire `MergeConflictPanel` (or your own UI) on `deliveryConflict` and the pending merge API. 4. For multi-org Matrix, configure the bridge and verify inbound traffic with the webhook emulator suite. How this compares [#how-this-compares] | Capability | Stream-style | Matrix-only | FluxyChat | | ------------- | ----------------------- | ------------ | ---------------------------------------- | | Offline queue | SDK local cache | Client cache | IndexedDB or RN outbox plus `syncStatus` | | Conflict UX | Usually last-write-wins | Room state | Explicit merge panel | | Federation | Limited | Native | Optional Matrix bridge | Related [#related] * [Merge conflicts (CRDT)](/docs/features/merge-conflicts) * [Edge room history](/docs/guides/realtime/edge-room-history) * [React Native quickstart](/docs/guides/ecosystem/react-native-quickstart) --- # FluxyStream (/docs/features/fluxystream) FluxyStream [#fluxystream] FluxyStream is FluxyChat's live broadcasting module. It combines WebRTC/RTMP ingest, Cloudflare Stream, HLS playback, realtime chat, AI moderation, and interactive audience features. Console [#console] | Route | Purpose | | ----------------------------- | ------------------------------------------ | | `/stream` | Live events list (live now and scheduled) | | `/stream/[eventId]` | Viewer: HLS player, chat, raise hand | | `/stream/[eventId]/broadcast` | Broadcaster: camera preview, go live / end | | `/stream/demo` | Interactive SDK feature demo | Architecture [#architecture] ``` OBS / WebRTC camera → Cloudflare Stream (RTMP/WHIP ingest) → HLS adaptive bitrate ↓ Cloudflare D1 (metadata, chat, viewers) ↓ Next.js Dashboard (viewer + broadcaster UI) ↓ FluxyChat SDK (polls, gifts, sentiment, commerce) ``` Key files [#key-files] | File | Description | | ----------------------------------------------- | ----------------------------------------------------------- | | `apps/worker/src/routes/live-streaming-http.js` | CRUD events, join/leave, chat, analytics, angles, gifts | | `apps/worker/src/lib/cloudflare-stream.js` | Cloudflare Stream API (live inputs) | | `packages/sdk/src/fluxy-stream.ts` | In-memory interactive features (polls, gifts, gamification) | Features [#features] Core: live broadcast, chat overlay, viewer count, AI moderation, polls, virtual gifts, recording/VOD, multi-camera angles, RTMP ingest, HLS adaptive bitrate, analytics. Interactive: stream-as-room (avatars, raise hand), sentiment dashboard, branching narrative voting, live commerce overlay, XP/badges leaderboard, AI co-host highlights. API (selected) [#api-selected] ```http POST /api/live/events GET /api/live/events/:id POST /api/live/events/:id/provision # Cloudflare Stream live input POST /api/live/events/:id/join POST /api/live/events/:id/messages GET /api/live/turn-credentials # WebRTC TURN (1h TTL) ``` Full route list lives in `live-streaming-http.js`. Environment [#environment] ```bash CLOUDFLARE_ACCOUNT_ID= CLOUDFLARE_STREAM_API_TOKEN= CLOUDFLARE_STREAM_CUSTOMER_CODE= # TURN relay (required for production WebRTC) TURN_SECRET= TURN_SERVERS=turn:turn.example.com:3478 # or Metered.ca: TURN_API_URL=https://api.metered.live/api/turn TURN_API_KEY= ``` Customization [#customization] * New gift type: extend `giftsCatalog` in `packages/sdk/src/fluxy-stream.ts`. * Default camera angles: call `stream.addAngle(label, streamUrl, isDefault)` in stream demo seed. * TURN provider: Coturn (`TURN_SECRET` + `TURN_SERVERS`) or Metered.ca (`TURN_API_URL` + `TURN_API_KEY`). Related [#related] * [Live streaming cookbook](/docs/cookbook): integration patterns * [Optional integrations](/docs/guides/ecosystem/optional-integrations): Stripe checkout for live commerce --- # Features (/docs/features) FluxyChat covers realtime chat, AI agents, vertical modules (stream, collab, IoT), and enterprise compliance. --- # Media pipeline (/docs/features/media-pipeline) Media pipeline [#media-pipeline] Every attachment upload passes through tenant size limits, optional ClamAV scan, and thumbnail jobs before messages reference the file. Console [#console] **Settings → Media** (`/settings/media`) | Setting | Purpose | | ------------------ | ------------------------------ | | Max file size | Reject oversized uploads early | | Allowed MIME types | Block unexpected content types | | Scan mode | `off`, `builtin`, `clamav` | Behaviour [#behaviour] 1. `POST /upload` stores the object in R2. 2. Async scan and thumbnail job queued. 3. Infected files blocked on send. Clean files get inline thumbnail URLs in messages. Built-in safety [#built-in-safety] EICAR test files are blocked even without ClamAV (`builtin` mode). Environment [#environment] | Variable | Purpose | | ------------------------ | ------------------------------- | | `MEDIA_PIPELINE_ENABLED` | Master toggle | | `CLAMAV_HTTP_URL` | Self-hosted ClamAV HTTP wrapper | | `MEDIA_MAX_BYTES` | Default max upload size | Optional ClamAV [#optional-clamav] Self-host an HTTP ClamAV wrapper. See [Optional integrations](/docs/guides/ecosystem/optional-integrations#clamav-media-virus-scan). Related [#related] * [Visual moderation](/docs/features/moderation-console) * [FluxyStream](/docs/features/fluxystream) --- # Merge conflicts (CRDT) (/docs/features/merge-conflicts) Merge conflicts (CRDT) [#merge-conflicts-crdt] When offline sync or federation produces two different contents for the same logical slot, FluxyChat surfaces a merge panel instead of silently picking a winner. In chat [#in-chat] The Merge conflict banner appears when `message-crdt-yjs` detects ambiguous candidates. Open `MergeConflictPanel` to compare side by side: * Keep version A * Keep version B * Merge both (concatenate with separator) Resolved content is broadcast to all connected clients. Console component [#console-component] `apps/dashboard/components/ui/merge-conflict-compare.tsx` is the two-column diff UI used from the room view when conflicts are pending. API [#api] ```http GET /rooms/:roomId/merge-conflicts?status=pending POST /rooms/:roomId/merge-conflicts/:id/resolve ``` Resolve body: `{ resolution: "keep_a" | "keep_b" | "merge_both" }`. SDK [#sdk] Conflict events arrive on the WebSocket as `deliveryConflict`. Subscribe and render your own resolve UI, or reuse the dashboard panel pattern. Related [#related] * [Connection state](/docs/core/connection-state): CRDT replay and offline sync --- # Moderation console (/docs/features/moderation-console) Moderation console [#moderation-console] Central moderation queue for AI-flagged and user-reported content. Moderators review, act, and audit history. Console [#console] **Moderation** (`/moderation`) | Section | Purpose | | ------------- | ------------------------------------------ | | Pending queue | AI flags and user reports awaiting review | | Stats | Queue depth, top categories, period totals | | Actions | Mute, ban, delete message, dismiss flag | | History | `moderation_events` audit trail | Use Room picker to scope queue to a specific room. AI moderation [#ai-moderation] Text and image flags enqueue automatically when enabled: | Variable | Purpose | | --------------------------- | ------------------------------------------------ | | `AI_MODERATION_ENABLED` | Text/content classification | | `VISUAL_MODERATION_ENABLED` | Frame capture and image moderation on live/video | Actions per severity: log only, mute user, delete message. Configured in worker moderation engine. Visual moderation [#visual-moderation] Dashboard helper `visual-moderation-client.ts` captures video/canvas frames for server-side scoring when visual moderation is on. Human-in-the-loop [#human-in-the-loop] Bulk approve/reject for HITL workflows. All actions are written to the audit log. API [#api] Moderation routes are under `/admin/moderation/*` and room-scoped moderation actions on message endpoints. See worker `post-message-automations.js` for enqueue logic. Related [#related] * [Tool approvals](/docs/guides/tool-approvals): agent-side moderation tools * [Security](/docs/guides/security) --- # Passkeys (WebAuthn) (/docs/features/passkeys) Passkeys (WebAuthn) [#passkeys-webauthn] Register passkeys for your operator account. Sign in with Face ID, Touch ID, or a security key instead of pasting JWTs manually. Console [#console] **Settings → Identity** (`/settings/identity`) 1. Register passkey → browser WebAuthn prompt. 2. List registered credentials (created date, device hint). 3. Remove stale credentials. SSO/SAML and SCIM provisioning live on the same Identity page. Flow [#flow] 1. `POST /webauthn/register/options` → browser credential creation. 2. `POST /webauthn/register/verify` → store credential in D1 (`webauthn_credentials`). 3. Login: `POST /webauthn/login/options` → `POST /webauthn/login/verify` → member JWT issued. Environment [#environment] | Variable | Example | Purpose | | ------------------ | ----------------------------- | --------------------------- | | `WEBAUTHN_RP_ID` | `console.example.com` | Relying party ID (hostname) | | `WEBAUTHN_ORIGIN` | `https://console.example.com` | Allowed origin | | `WEBAUTHN_ENABLED` | `true` | Master toggle | Must match the dashboard hostname exactly in production (no mismatch between Vercel preview and Worker config). Self-host [#self-host] Configure Worker env to match your dashboard URL. See [optional integrations](/docs/guides/ecosystem/optional-integrations) for hosted beta defaults. Related [#related] * [Session security](/docs/learn/session-security) * [Identity settings](/docs/guides/security) --- # Platform modules (/docs/features/platform-status) These sit on the same Worker as chat. Set secrets in `.dev.vars` or the hosted console. Hosted publish-config [#hosted-publish-config] Without forking the Worker, `PUT /admin/projects/:id/publish-config` (CLI `pnpm fluxy:deploy`) overlays `fluxy.config`: deny substrings, `guest_can_publish`, **`iotAutoAgentId`**, and **`rooms`** (anonymous, per-room deny, capabilities, kv/counter extension slots). When that agent id is set, HTTP ingest can invoke the room agent without an `@mention`. Self-host: keep callbacks in `fluxy.config.ts`; hosted never evals tenant JS. Omnichannel adapters [#omnichannel-adapters] Console path: **Bridges**. Each channel is a row in `channel_configs` (OAuth or bot token, webhook URL, signing secret). Slack, Discord, Telegram, Teams, WhatsApp, and the others in `cross-platform.js` share that table. 1. Create the vendor app (Slack app, Discord bot, …). 2. Paste tokens and the signing secret in Bridges. 3. Point the vendor webhook at your Worker. The web channel needs no vendor app. Structured replies: [Channel forms](/docs/features/channel-forms). IoT and fleet [#iot-and-fleet] Devices `POST` JSON. The room fans out `iot.reading` or `fleet.gps_update`. * Register and ingest: [IoT](/docs/platform/iot) * GPS: [Fleet](/docs/platform/fleet) * Health: `GET /iot/devices/:id/health` scores recent readings (mean, slope, alerts). * Geofence: Worker REST `GET/POST/PATCH/DELETE /fleet/geofences` plus `GET /fleet/geofence-events`. SDK: `listFleetGeofences` / `createFleetGeofence` / `updateFleetGeofence` / `deleteFleetGeofence` / `listFleetGeofenceEvents`. Current positions drop vehicles whose last ping is older than 10 minutes (Traccar status timeout). There is no separate “location SDK” package. The in-memory helpers on `createFluxyIoT()` are local rule helpers, not the fleet API. Game [#game] `createWorkerFluxyGameClient` covers matchmake, `joinLobby`, `listLobbies`, `listMatches`, `listParties`, `leaveLobby`, `startMatch`, `submitInput` (`game.tick` + `state`), `endMatch`, `game.lobby_updated` / `game.party_updated`. Leaderboard `?around=`, checkpoints (`deleteCheckpoint`), NPC, quests, tournaments (`joinTournament`). Checkpoint `federate` copies save state between rooms. Scaffold: `--example game-tick`. RCS [#rcs] Paid Twilio or MessageBird account. Set `RCS_OUTBOUND_URL`, `RCS_API_KEY`, and `RCS_WEBHOOK_SECRET`. Inbound webhooks must include an HMAC of the body (`X-RCS-Signature` hex SHA-256). Forms: [Channel forms](/docs/features/channel-forms). Voice clone and translation [#voice-clone-and-translation] Workers AI covers STT and TTS on `/voice-ai/transcribe` and `/voice-ai/speak`. Clone-quality output is `POST /voice-ai/clone-translate` with `{ audioBase64, targetLang, voiceId }`. The Worker forwards to `VOICE_CLONE_URL` (your GPU or VPS). Same member JWT as the rest of voice AI. Agent commerce [#agent-commerce] When a cross-org commitment reaches `committed`, the Worker writes a settlement. Default provider is `manual` (both sides confirm, you mark settled). Set `X402_FACILITATOR_URL` to post an x402 payment request and store `external_ref`. AP2 mandates are not a second protocol here: they ride the same settlement row. Federation [#federation] One FluxyChat deployment is the product: many orgs in `/cross-org` rooms, audit chain, human gates. To span two Workers, set `FLUXY_FEDERATION_PEER_URL` plus `FLUXY_FEDERATION_SECRET` and use game checkpoint `federate` or the cross-org peer forward. Both sides must share the secret. Related [#related] * [Features overview](/docs/features/features-overview) * [Channel forms](/docs/features/channel-forms) * [Voice](/docs/core/voice-huddles) --- # Rehearsal rooms (/docs/features/rehearsal-rooms) Rehearsal rooms [#rehearsal-rooms] Before a difficult negotiation or support escalation, open a rehearsal room: a temporary private room cloned from authorized context where an agent simulates the counterparty. It is not the real person. Console [#console] **Agents → Rehearsal** (`/agents/rehearsal`) 1. Pick a source room you already have access to. 2. Set an optional counterparty role (e.g. "skeptical buyer") and stated goal. 3. Start rehearsal. The worker creates an ephemeral room and copies an authorized message snapshot. 4. Open the rehearsal room from the session list. Default TTL is one hour. 5. Delete sessions manually or let them expire. Guardrails [#guardrails] * Only data you already have access to is copied. * A simulation disclaimer is shown in the UI and injected into the agent system prompt. * Outcomes are not written back to the production room unless you copy them manually. API [#api] ```http POST /rooms/:roomId/rehearsal GET /rehearsals?sourceRoomId=&limit= GET /rehearsals/:rehearsalId DELETE /rehearsals/:rehearsalId ``` Create body fields: `statedGoal`, `counterpartyRole`, `agentId`, `ttlSeconds`, `persistAfterSession`. Agent behaviour [#agent-behaviour] When an agent runs in a rehearsal room, `agent-runtime` appends a rehearsal system prompt so the model stays in character as a simulated counterparty. Related [#related] * [Cross-org rooms](/docs/features/cross-org-rooms): preparation before federated negotiations * [Multi-agent debate](/docs/features/agent-debate): structured multi-perspective reasoning --- # Room firmware (/docs/features/room-firmware) Room firmware [#room-firmware] Room firmware runs synchronous hooks on `message.create` before messages fan out to the room. Builtin modules ship today. Custom WASM is reserved for a future release. Console [#console] **Settings → Firmware** (`/settings/firmware`) 1. Select a room. 2. Enable modules and configure JSON config per module. 3. Save. Hooks apply on the next message in that room. | Module | Effect | | ------------ | ------------------------------------ | | `pii_veto` | Block messages matching PII patterns | | `rate_limit` | Per-user send throttle in room | | `denylist` | Block substring / regex matches | Rejected messages are audited in `room_firmware_audit`. API [#api] ```http GET /rooms/:roomId/firmware PUT /rooms/:roomId/firmware GET /rooms/:roomId/firmware/audit?limit= ``` Behaviour [#behaviour] * Fail-open on hook errors (message delivers; error logged). * Hooks run on REST send and Room DO WebSocket path. * Per-room config stored in D1 (`room_firmware`). Use for compliance rooms, negotiation term caps, or custom moderation without forking the Worker. Related [#related] * [Message middleware](/docs/reference/message-middleware) * [DLP settings](/docs/guides/security) --- # Room sentiment (/docs/features/room-sentiment) Room sentiment [#room-sentiment] Aggregate reaction sentiment and optional message classification into a mood timeline. Useful for community managers and team leads monitoring room health. Console [#console] **Search** (`/search`) with a room filter shows the Room sentiment panel: * Time buckets (positive / neutral / negative) * Current mood label * Trend over the selected window Component: `RoomSentimentPanel` in the dashboard. How it works [#how-it-works] 1. Collect emoji reactions and lightweight text signals from recent messages. 2. Bucket scores over configurable time windows. 3. Expose aggregates via REST. No extra client instrumentation required. API [#api] ```http GET /rooms/:roomId/sentiment?windowHours=24 ``` Member JWT required. Response: `{ buckets, currentMood, sampleSize }`. SDK [#sdk] ```ts const { buckets, currentMood } = await client.getRoomSentiment(roomId); ``` Related [#related] * [Smart catch-up](/docs/features/smart-catch-up): relevance-ranked digests * [Moderation console](/docs/features/moderation-console) --- # Scheduled messages (/docs/features/scheduled-messages) Scheduled messages [#scheduled-messages] Schedule a message to be delivered later. The composer stores content in D1 and the Room DO dispatches at `send_at` through the normal send path (same moderation, firmware, and fan-out rules as immediate sends). In chat [#in-chat] 1. Type your message in the composer. 2. Open **+** menu → **Schedule send** (`ScheduleSend` component). 3. Pick date/time and confirm. 4. View pending scheduled items in the panel. Cancel before delivery. Console [#console] Scheduled items appear in room context. No separate admin page required. API [#api] ```http POST /rooms/:roomId/scheduled-messages GET /rooms/:roomId/scheduled-messages DELETE /rooms/:roomId/scheduled-messages/:id ``` SDK [#sdk] ```ts await client.scheduleMessage(roomId, { content: "Reminder: standup in 5 minutes", sendAt: new Date(Date.now() + 3600_000).toISOString(), }); await client.cancelScheduledMessage(roomId, scheduledId); ``` Related [#related] * [Ephemeral messages](/docs/guides/ephemeral-messages) * [Room firmware](/docs/features/room-firmware) --- # Smart catch-up digest (/docs/features/smart-catch-up) Smart catch-up digest [#smart-catch-up-digest] When you return to a room, FluxyChat shows a catch-up banner with the most relevant updates: mentions, active threads, and semantically related topics. Not just the last N messages chronologically. Console [#console] 1. Open any room in **Rooms** after being away. 2. If new activity exists since your last-read watermark, `ChatCatchUpBanner` appears at the top with bullet highlights and an optional AI summary. 3. Dismiss the banner or jump to highlighted messages. How ranking works [#how-ranking-works] 1. Load messages since your watermark (`room-catch-up`). 2. Rank by mention of you, thread participation, and semantic similarity (when embeddings are on). 3. Optionally summarize top hits via Workers AI. Without semantic search, ranking falls back to mentions plus recency. API [#api] ```http GET /rooms/:roomId/catch-up?userId=... GET /rooms/:roomId/catch-up/smart ``` Smart digest response includes `summary`, `highlights[]`, and `since`. SDK [#sdk] ```ts const digest = await client.getRoomCatchUpDigest(roomId); // digest.summary, digest.highlights[], digest.since ``` Environment [#environment] | Variable | Purpose | | ------------------------- | ----------------------------------------- | | `SEMANTIC_SEARCH_ENABLED` | Enables embedding-based topic ranking | | `AI_*` | Workers AI for summary bullets (optional) | Configure semantic search under **Settings → Search** (`/settings/search`). Related [#related] * [Search](/docs/core/search) * [Thread summary](/docs/reference/thread-summary) --- # Truth Market (/docs/features/truth-market) Truth Market [#truth-market] When an agent makes a verifiable claim, it can stake internal credits. Other participants may dispute. Human arbitration resolves stake transfers. Console [#console] **Truth Market** (`/truth-market`) 1. Filter claims by room and state (`open`, `disputed`, `resolved`). 2. File claim: pick room, message (optional), stake amount, TTL. 3. Dispute: attach evidence text on open claims. 4. Resolve (admin): pick outcome and credit transfer. In chat, eligible agent messages can show stake and dispute actions when `TRUTH_MARKET_ENABLED` is on. MVP scope [#mvp-scope] Uses internal credits, not real money. Suitable for trust scoring and gamified fact-checking workflows. API [#api] ```http GET /truth-claims?roomId=&state= POST /truth-claims POST /truth-claims/:id/dispute POST /truth-claims/:id/resolve GET /truth-credits/:userId ``` Room-scoped shortcut: ```http POST /rooms/:roomId/truth-claims ``` Environment [#environment] | Variable | Default | Purpose | | ---------------------------------- | ------- | ------------------------- | | `TRUTH_MARKET_ENABLED` | off | Master toggle | | `TRUTH_MARKET_MIN_STAKE` | 1 | Minimum credits per claim | | `TRUTH_MARKET_MAX_STAKE` | 1000 | Maximum credits per claim | | `TRUTH_MARKET_DEFAULT_TTL_SECONDS` | 86400 | Claim expiry | Rules [#rules] * Min and max stake per claim (tenant-configurable via env). * Dispute spam rate limits on the worker. * Human arbitration default for ambiguous cases. Related [#related] * [AI governance](/docs/guides/ai-agents): agent accountability * [Moderation console](/docs/features/moderation-console) --- # Tenant usage and cost dashboard (/docs/features/usage-dashboard) Tenant usage and cost dashboard [#tenant-usage-and-cost-dashboard] See monthly usage, plan limits, storage totals, and a rough cost estimate for your project. Useful for billing conversations and capacity planning. This is not an invoice. Console [#console] **Settings → Usage** (`/settings/usage`) Displays: * Plan: name, billing status, monthly limits (messages, agent invokes, webhook deliveries). * This month: messages created, agent invokes, webhook deliveries. * Totals: all-time messages, rooms, MAU, attachment storage (GB). * Ops (30d): breakdown of worker operations. * Cost estimate: configurable rates times usage plus platform base (USD, disclaimer shown). API [#api] ```http GET /admin/tenant-usage ``` Response shape: `usage.plan`, `usage.monthlyUsage`, `usage.totals`, `usage.costEstimate`. Environment [#environment] | Variable | Purpose | | --------------------------------- | ------------------------------ | | `USAGE_COST_ENABLED` | Enable cost estimate block | | `USAGE_COST_PER_1K_MESSAGES_USD` | Rate for message volume | | `USAGE_COST_PER_AGENT_INVOKE_USD` | Rate per agent run | | `USAGE_COST_PER_GB_STORAGE_USD` | Storage monthly rate | | `USAGE_COST_PLATFORM_BASE_USD` | Fixed platform fee in estimate | Rates are estimates only. Configure them to match your internal unit economics. Related [#related] * [Billing overage policy](/docs/reference/billing-overage-policy) * [Optional integrations](/docs/guides/ecosystem/optional-integrations) --- # Voice stages (/docs/features/voice-stages) Voice stages [#voice-stages] Split voice participants into speakers and listeners. Only speakers publish audio by default. Listeners request to speak or are promoted by moderators. Console / in-room UI [#console--in-room-ui] **Voice AI** (`/voice-ai`) and the in-room Voice stage panel (`VoiceStagePanel`): * Toggle speaker / listener role * Request to speak queue for listeners * Moderator promote / demote * Active speaker highlight (Silero VAD) Active speaker [#active-speaker] `useVoiceStageVad` plus Silero VAD highlights who is speaking. Same pipeline as [voice AI](/docs/guides/voice-ai-pipeline). API [#api] ```http GET /rooms/:roomId/voice-stage POST /rooms/:roomId/voice-stage/join POST /rooms/:roomId/voice-stage/leave POST /rooms/:roomId/voice-stage/role POST /rooms/:roomId/voice-stage/mute POST /rooms/:roomId/voice-stage/request-speak POST /rooms/:roomId/voice/token ``` WS: `stage_join` / `leave` / `mute` / `request_speak` / `promote`. After reconnect the SDK re-sends the last `stage_join` (LiveKit Room reconnect HOW, signaling only). Media is not this API. Mint `getVoiceToken` (or `createVoiceTokenSource` to cache until expiry) then connect `livekit-client` yourself. `canPublish: false` / `canSubscribe: false` map to LiveKit JWT grants. Identity is the member JWT, not a spoofed `userId`. Environment [#environment] Voice pipeline env vars (`AI_*`, TURN) apply when WebRTC is used alongside stages. Ideal for AMAs, town halls, and large voice rooms without everyone unmuted. Related [#related] * [FluxyStream](/docs/features/fluxystream): live audience modes * [Empathy layer](/docs/features/empathy-layer): prosody hints --- # Chat-only quickstart (/docs/getting-started/chat-only-quickstart) Chat-only quickstart [#chat-only-quickstart] Use this path when you want **in-app chat only** — not stream, IoT, fleet, or spatial modules. 1\. Install [#1-install] ```bash pnpm add @fluxy-chat/sdk @fluxy-chat/react ``` Import chat hooks (keeps your bundle small): ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; ``` 2\. Client + JWT [#2-client--jwt] **Hosted (fastest):** sign up → **Onboarding** → copy Worker URL + member JWT. **Local:** from repo root: ```bash pnpm install && pnpm run first-message ``` 3\. Three lines to live chat [#3-three-lines-to-live-chat] ```tsx "use client"; import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; export function ChatPanel({ workerUrl, jwt, roomId, }: { workerUrl: string; jwt: string; roomId: string; }) { return ( ); } function Room({ roomId }: { roomId: string }) { const { messages, sendMessage, connectionState } = useChat({ roomId, markReadLatest: true, }); return ( <>

Status: {connectionState.status}

    {messages.map((m) => (
  • {m.content}
  • ))}
); } ``` 4\. Optional: AI agent in the same room [#4-optional-ai-agent-in-the-same-room] Mention an agent configured in the console: ```tsx await sendMessage("@assistant How can you help?"); ``` Streaming replies use the same WebSocket — see [Agents guide](/docs/core/agents). 5\. Inbox [#5-inbox] ```tsx import { useInbox } from "@fluxy-chat/react"; const { items, unreadCount, markRead } = useInbox({ client }); ``` Next steps [#next-steps] * [Full quickstart](/docs/getting-started/quickstart) — self-host, loadMore, reactions * [Feature parity checklist](/docs/guides/migrate-from-pusher) * [Compare vendors](https://fluxychat.com/compare) --- # Choose your path (/docs/getting-started/choose-your-path) You are wiring chat (and maybe an agent) into an app. Pick one: | Path | What you get | You run | | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | **Hosted** `npx @fluxy-chat/create-fluxy-chat@latest my-app --mode hosted -y` | Vite chat app. Clerk. Project + room + `@assistant` after login. | Nothing on Cloudflare. | | **Self-host** `npx @fluxy-chat/create-fluxy-chat@latest my-app --full --mode self-host` | Same Vite app, pointed at **your** Worker. Setup asks for Worker URL and secrets. | Worker on Cloudflare (or `wrangler dev` from a FluxyChat clone). | | `--template react` | Vite + `useChat`. You paste Worker URL and JWT. | Your Worker or hosted API. | | `--minimal` | Widget only. | Same. | | [fluxychat.com](https://fluxychat.com) | Browser playground / console. | Nothing. | Always use the scoped package: `@fluxy-chat/create-fluxy-chat`. Bare `npx create-fluxy-chat` 404s. Ten-minute guest room (chat + agent on one DO): [Shared AI room](/docs/guides/shared-ai-room-10-minutes). Hosted [#hosted] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-app --mode hosted -y cd my-app pnpm install pnpm setup:hosted pnpm dev ``` Localhost: 3-step tour, then Clerk, then chat. Second tab = realtime. Dashboard is a button, not the first screen. Self-host (your Worker) [#self-host-your-worker] You need the FluxyChat Worker running. Companies usually clone the repo once, deploy `apps/worker`, then point many apps at that URL. ```bash git clone https://github.com/AlessandroFare/fluxychat cd fluxychat pnpm install pnpm run self-host # paste Groq/OpenAI key when asked, or edit apps/worker/.dev.vars pnpm --filter @fluxy-chat/worker dev ``` In another terminal: ```bash npx @fluxy-chat/create-fluxy-chat@latest my-app --full --mode self-host cd my-app pnpm install pnpm setup:local pnpm dev ``` `pnpm setup:local` talks to `POST /dev/provision` on your Worker (`ALLOW_DEV_PROVISION=true` in `.dev.vars`). If the Worker is down, the script asks for the URL instead of dying silently. SDK only [#sdk-only] ```bash pnpm add @fluxy-chat/sdk @fluxy-chat/react ``` Then [client setup](/docs/getting-started/client-setup). JWT: [Auth JWT](/docs/guides/auth-jwt). Related [#related] * [create-fluxy-chat](/docs/guides/create-fluxy-chat) * [Self-host one command](/docs/guides/self-host-one-command) * [Client setup](/docs/getting-started/client-setup) --- # Client setup (/docs/getting-started/client-setup) FluxyChat clients talk to your Worker URL. Public rooms: `publishableKey` on `FluxyRealtimeProvider`, or `joinPublicRoomAsGuest`. Private rooms need a member JWT. `fc_` keys stay on the server. React is the client we document first. Vue and Svelte on npm are best-effort. React Native is on npm. Flutter, Swift, and KMP stay in-repo until pub.dev and CocoaPods. ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; function Room() { const { messages, sendMessage } = useChat({ roomId: "general" }); } ``` The room must be **public**. The SDK mints an anonymous guest JWT. Without a `pk_` (self-host + `PUBLIC_GUEST_ENABLED`): ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; const session = await FluxyChatClient.joinPublicRoomAsGuest(workerUrl, publicRoomId, { displayName: "Ada", }); ``` Production apps mint JWTs after sign-in ([Auth JWT](/docs/guides/auth-jwt)). ```bash pnpm add @fluxy-chat/react ``` ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; function App({ workerUrl, memberJwt }: { workerUrl: string; memberJwt: string }) { return ( ); } function Room({ roomId }: { roomId: string }) { const { messages, sendMessage, connectionState } = useChat({ roomId }); // render messages… } ``` `FluxyRealtimeProvider` takes `workerUrl` plus `publishableKey`, `authTokenProvider` (JWT string or function), or `connectUrl`. There is no `client` prop. See [@fluxy-chat/react](/docs/packages/react) and [useChat](/docs/core/use-chat). ```bash pnpm add @fluxy-chat/sdk ``` ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: "http://127.0.0.1:8787", userId: "alice", token: memberJwt, }); const conn = client.connectRoom("general"); conn.onMessage((msg) => console.log(msg)); await conn.send({ text: "Hello" }); ``` See [@fluxy-chat/sdk](/docs/packages/sdk) for connection state, inbox, and agents. ```bash pnpm add @fluxy-chat/sdk @fluxy-chat/react-native ``` Use the React Native package for WebSocket transport on iOS and Android. See [React Native SDK](/docs/packages/react-native-sdk) and the [Kotlin/Swift quickstart](/docs/guides/ecosystem/kotlin-swift-quickstart) for native bridges. Not on pub.dev. Path dependency from this repo: ```yaml dependencies: fluxychat_sdk: git: url: https://github.com/AlessandroFare/fluxychat.git path: packages/flutter-sdk ``` See [Flutter SDK](/docs/packages/flutter-sdk). Auth [#auth] Guest for public rooms (`publishableKey` or `joinPublicRoomAsGuest`). Member JWTs from your backend for everything else. Never embed `fc_…` in client bundles. Refresh with `client.setToken()` / `updateToken()`. See [Auth JWT](/docs/guides/auth-jwt). Common errors [#common-errors] | Error | Fix | | ------------------ | ------------------------------------------------------- | | `401 Unauthorized` | Token expired or wrong signing key. Mint a fresh JWT. | | `not a member` | Add the user to the room via REST or dashboard | | WebSocket blocked | Check CORS / custom domain; try HTTP long-poll fallback | More: [Troubleshooting](/docs/reference/troubleshooting). --- # CLI and examples (/docs/getting-started/for-coding-agents) Use the scoped CLI. Bare `npx create-fluxy-chat` is a different package and 404s. Hosted app [#hosted-app] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-app --mode hosted -y ``` That writes a Vite chat app. After `pnpm setup:hosted` you sign in on fluxychat.com. Coding agents: `npx skills add AlessandroFare/fluxychat --skill fluxy-chat-room` (gold room: mention, stream, whisper, feeds). Or skip the skill and scaffold `--example deal-room` below. Gallery [#gallery] Each example needs `VITE_FLUXYCHAT_WORKER_URL` plus a **`pk_`** (`VITE_FLUXYCHAT_PUBLISHABLE_KEY`), a **public** room id (guest), or a member JWT. Open two tabs for anything collaborative. Zero-backend public room: `FluxyRealtimeProvider` + `publishableKey` (`pk_`, `POST /tokens/anonymous`). Guest session still works: ```ts ``` ```bash npx @fluxy-chat/create-fluxy-chat@latest my-cursors --example live-cursors npx @fluxy-chat/create-fluxy-chat@latest my-cursors-chat --example live-cursors-chat npx @fluxy-chat/create-fluxy-chat@latest my-vanilla --example javascript-live-cursors npx @fluxy-chat/create-fluxy-chat@latest my-doc --example tiptap-room npx @fluxy-chat/create-fluxy-chat@latest my-board --example whiteboard npx @fluxy-chat/create-fluxy-chat@latest my-draw --example draw npx @fluxy-chat/create-fluxy-chat@latest my-comments --example comments-board npx @fluxy-chat/create-fluxy-chat@latest my-polls --example polls npx @fluxy-chat/create-fluxy-chat@latest my-war --example war-room npx @fluxy-chat/create-fluxy-chat@latest my-iot --example iot-panel npx @fluxy-chat/create-fluxy-chat@latest my-deal --example deal-room # Two tabs: this URL (buyer) and ?seat=counsel. Public guest room for whispers. npx @fluxy-chat/create-fluxy-chat@latest my-fleet --example fleet-panel npx @fluxy-chat/create-fluxy-chat@latest my-game --example game-tick npx @fluxy-chat/create-fluxy-chat@latest my-stage --example voice-stage ``` Cursors travel as WebSocket `type: "cursor"`. Tiptap and the whiteboard sync Yjs on the same room. See [What to build](/docs/getting-started/what-to-build) for the idea-to-example map. Three ways to run [#three-ways-to-run] | Path | Command | You provide | | --------- | ----------------------------------------------------------------------------------- | ---------------------------------- | | Hosted | `--mode hosted -y` | Clerk on fluxychat.com after setup | | Self-host | clone the repo, `pnpm --filter @fluxy-chat/worker dev` | Worker URL + project JWT | | SDK-only | `--template react` or `--example` from the [gallery](/docs/getting-started/gallery) | Worker URL + JWT or public room | Env vars (browser) [#env-vars-browser] * `VITE_FLUXYCHAT_WORKER_URL`: hosted API or `wrangler dev` * `VITE_FLUXYCHAT_PUBLISHABLE_KEY`: `pk_` on `FluxyRealtimeProvider` (public rooms) * `VITE_FLUXYCHAT_MEMBER_JWT` + `VITE_FLUXYCHAT_ROOM_ID`: member * `VITE_FLUXYCHAT_PUBLIC_ROOM_ID`: guest via `FluxyChatClient.joinPublicRoomAsGuest` Keep `fc_…` API keys on the server. One room session [#one-room-session] `useChat({ roomId })` is the room session: messages, presence, cursors (`sendCursor` / `liveCursors`), broadcast (`sendClientEvent`), agents (`invokeAgent`). Yjs is a second binary socket on the same Durable Object. For cursors only, `useLiveCursors({ roomId })`. Do not mount both unless they share `sessionScope`, or you open two sockets. | Need | API | | --------------------------------- | ------------------------------------------------------------------ | | Who is here, pointers, selections | `sendCursor`, `liveCursors`, `useMyPresence` / `presence_patch` | | One-shot stamps | `sendClientEvent` (`client-ephemeral-*` skips webhooks) | | Shared document | `useStorage` / `FluxyYjsProvider` (`@fluxy-chat/sdk/yjs`) | | Activity logs | `useFeeds`, `/rooms/:id/feeds` | | Side-panel assistant | `RegisterAiKnowledge` + `` | | Pinned review comments | `useThreads`, `/comment-threads` | | Chat timeline | `useChat` messages; replies use `parentId` | | Nested chat thread | `useThread({ threadParentId })`; registry `GET /rooms/:id/threads` | | Agent on the timeline | `invokeAgent` | JWT mint (server) [#jwt-mint-server] `POST {WORKER}/auth/token` with `X-Fluxy-Api-Key: fc_…` and body `{ userId, roles, ttlSeconds }`. Pass the JWT as `FluxyRealtimeProvider` `authTokenProvider`. Nest `FluxyYjsProvider` inside it, or pass `token` / `authTokenProvider`. Details: [Choose your path](/docs/getting-started/choose-your-path) and the auth cookbook. Open two tabs [#open-two-tabs] Cursors, presence, and chat need a second client on the same `roomId`. One tab is not a collab test. --- # Gallery examples (/docs/getting-started/gallery) Each template is a product shape, not a claim that FluxyChat is MQTT, netcode, or an SFU. The **Do not** column is the scope of that example. Open two tabs unless noted. Worker URL plus a `pk_` / public room id or a member JWT. ```bash npx @fluxy-chat/create-fluxy-chat@latest my-cursors --example live-cursors npx @fluxy-chat/create-fluxy-chat@latest my-cursors-chat --example live-cursors-chat npx @fluxy-chat/create-fluxy-chat@latest my-vanilla --example javascript-live-cursors npx @fluxy-chat/create-fluxy-chat@latest my-doc --example tiptap-room npx @fluxy-chat/create-fluxy-chat@latest my-war --example war-room npx @fluxy-chat/create-fluxy-chat@latest my-iot --example iot-panel npx @fluxy-chat/create-fluxy-chat@latest my-draw --example draw npx @fluxy-chat/create-fluxy-chat@latest my-deal --example deal-room npx @fluxy-chat/create-fluxy-chat@latest my-nda --example negotiation-room npx @fluxy-chat/create-fluxy-chat@latest my-room --example shared-ai-room npx @fluxy-chat/create-fluxy-chat@latest my-fleet --example fleet-panel npx @fluxy-chat/create-fluxy-chat@latest my-game --example game-tick npx @fluxy-chat/create-fluxy-chat@latest my-stage --example voice-stage npx @fluxy-chat/create-fluxy-chat@latest my-comments --example comments-board npx @fluxy-chat/create-fluxy-chat@latest my-polls --example polls npx @fluxy-chat/create-fluxy-chat@latest my-board --example whiteboard ``` | Example | Primitive | Scope (do not stretch) | | ------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `live-cursors` | `sendCursor` / `type: cursor` | Not `client_event` for pointers | | `live-cursors-chat` | cursors + `useChat` | One JSON socket. `?overlay=1` is OBS-transparent, not Overlayed Electron | | `javascript-live-cursors` | vanilla `connect` + `type: cursor` | React not required | | `tiptap-room` | Yjs `useStorage` + Collaboration | Not a second CRDT | | `war-room` | `useChat` + `invokeAgent` + `AvatarStack` | Same room WS. `scheduleAgent` is room-DO cron, not a CF Agents SKU | | `iot-panel` | HTTP ingest + `iot.reading` | Not MQTT. Hosted: `iotAutoAgentId` on publish-config invokes an agent without @mention. | | `draw` | cursors + `client-ephemeral-dot` | Not 60 Hz broadcast | | `deal-room` | quorum + `visibility` whisper + `invokeAgent` + feeds | Two tabs: `?seat=buyer` and `?seat=counsel`. Guest room for whispers (shared member JWT is one user). Traces are feeds, not chat. Cross-org is REST `/cross-org`. | | `negotiation-room` | same two-seat room + clause policy auto / ask / deny | Legal/procurement counterparties. HITL on **ask**. Not Harvey. Pin `rooms["nda-*"].makerChecker`. | | `shared-ai-room` | `pk_` guest widget + optional `invokeAgent` | First contact without console signup. Deploy `apps/worker` with wrangler; this template is the UI. | | `fleet-panel` | `POST /fleet/gps` then `fleet.gps_update` | Not MQTT. Geofences: `listFleetGeofences` | | `game-tick` | lobby + `game.tick` / `game.match_ended` | Authoritative input on the room, not Colyseus Schema | | `voice-stage` | `joinVoiceStage` signaling | Bring LiveKit for the media plane | | `comments-board` | `useThreads` + `FloatingComposer` | Not chat `parentId` as pins | | `polls` | `createPoll` / `votePoll` | Timeline polls. Anonymous ballots: `POST /polls` `isAnonymous` | | `whiteboard` | Yjs strokes + cursors + Comment pins | Yjs on the room DO, not a tldraw SKU | Health is not HIPAA. Stream WHIP/HLS needs Cloudflare Stream secrets; there is no gallery WHIP example yet. Voice numbers: [Voice load report](/docs/operations/voice-load-test-report). --- # Getting started (/docs/getting-started) You need a **Worker URL**. Public rooms: `FluxyRealtimeProvider` + `publishableKey`, or `joinPublicRoomAsGuest` / `FluxyChatWidget guest`. Production: mint a member JWT after sign-in. Hosted [#hosted] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-app --mode hosted -y cd my-app && pnpm install && pnpm setup:hosted && pnpm dev ``` Console: [fluxychat.com/dashboard](https://fluxychat.com/dashboard). Then open two tabs. Next [#next] * [One afternoon](/docs/getting-started/quickstart-afternoon): first live message in a room, fast * [Concepts](/docs/concepts): which primitive to use * [Rooms](/docs/rooms): attach, messages, presence, occupancy * [Connection state](/docs/core/connection-state): including `degraded-http` * [API reference](/docs/api-reference): REST --- # Local Development Guide (/docs/getting-started/local-development) Prerequisites [#prerequisites] | Tool | Minimum | Notes | | --------------------------------- | ---------------------- | -------------------------------------------------------------------- | | **Node.js** | 18.x (20+ recommended) | Required for all apps and scripts | | **pnpm** | 8.x | Monorepo package manager (`corepack enable && pnpm install -g pnpm`) | | **Git** | 2.x | | | **Cloudflare account** (optional) | — | Only needed for remote D1/R2 binding or deployment | | **Clerk account** (optional) | — | Only needed if you want auth UI; dashboard works without it | > **Without a Cloudflare account**, `wrangler dev` creates local D1/KV/R2 bindings automatically via Miniflare. You only need real bindings for production deployment. *** 1\. Clone & Install [#1-clone--install] ```bash git clone https://github.com/AlessandroFare/fluxychat.git cd fluxychat pnpm install ``` 2\. Environment Setup [#2-environment-setup] Run the automated setup script — it copies template files without overwriting existing ones: ```bash pnpm run dev:setup ``` This creates: * `apps/worker/.dev.vars` ← from `.dev.vars.example` * `apps/dashboard/.env.local` ← from `.env.example` Worker: `apps/worker/.dev.vars` [#worker-appsworkerdevvars] For basic local dev, you only need these entries: ```ini # Required for project provisioning ALLOW_DEV_PROVISION=true # Optional — enable hosted multi-tenant mode HOSTED_MULTI_TENANT=true FLUXY_PLATFORM_PROJECT_ID= # Optional — AI/LLM provider keys (uncomment what you use) # AI_API_KEY=sk-... # ANTHROPIC_API_KEY=sk-ant-... # OPENROUTER_API_KEY=sk-or-... # GROQ_API_KEY=gsk_... # DEEPSEEK_API_KEY=sk-... # OLLAMA_BASE_URL=http://localhost:11434 # for local models # Optional — feature flags FEATURE_VOICE_MESSAGES=true FEATURE_REPLY_SUGGESTIONS=true ``` The full template (`apps/worker/.dev.vars.example`) documents 100+ variables covering Stripe, rate limits, SMS OTP, push notifications, quotas, and more. Most default to sensible values — only set what you need. Dashboard: `apps/dashboard/.env.local` [#dashboard-appsdashboardenvlocal] ```ini # Point dashboard at your local worker NEXT_PUBLIC_FLUXYCHAT_WORKER_URL=http://127.0.0.1\:8787 # Optional — Clerk auth (omit for manual quickstart mode) # NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... # CLERK_SECRET_KEY=sk_test_... # NEXT_PUBLIC_CLERK_SIGN_UP_FALLBACK_REDIRECT_URL=/onboarding # Optional — console gate (skip for local dev) # CONSOLE_GATE_SECRET=your-secret-here ``` > **Without Clerk**: The dashboard runs in manual mode — you'll use the `/onboarding` flow to enter a Worker URL and API key directly. The `UserButton` and sign-in/sign-up buttons are hidden. AI Agent: `apps/ai-agent/.dev.vars` [#ai-agent-appsai-agentdevvars] Only needed if you want the AI agent service running alongside the worker: ```ini FLUXY_BASE_URL=http://127.0.0.1\:8787 JWT_SECRET=local-dev-secret # OPENAI_API_KEY=sk-... ``` Verify env readiness [#verify-env-readiness] ```bash pnpm run check:env ``` This runs `scripts/check-env-readiness.mjs` — a pre-flight checklist that catches missing or inconsistent values. *** 3\. Start Dev Servers [#3-start-dev-servers] All apps in parallel (recommended) [#all-apps-in-parallel-recommended] ```bash pnpm dev ``` This uses Turbo to run `dev` across `apps/*` in parallel: * **Worker** → `http://127.0.0.1:8787` (Wrangler + Miniflare) * **Dashboard** → `http://localhost:3000` * **AI Agent** → `http://127.0.0.1:8788` (Wrangler) Individual apps [#individual-apps] ```bash # Worker only cd apps/worker && pnpm dev # Dashboard only (needs worker running for API calls) cd apps/dashboard && pnpm dev # AI Agent only (needs worker running for webhooks) cd apps/ai-agent && pnpm dev ``` Build order [#build-order] Turbo handles this automatically for `pnpm build`, but if you build manually: ``` @fluxy-chat/protocol → @fluxy-chat/sdk → @fluxy-chat/ui → @fluxy-chat/agent → apps/dashboard ``` The dashboard's `build` script in `package.json` chains these for you. *** 4\. First Project & Message [#4-first-project--message] Option A: Dashboard onboarding (GUI) [#option-a-dashboard-onboarding-gui] 1. Open `http://localhost:3000/onboarding` 2. **With Clerk**: Sign up/in → the dashboard auto-connects 3. **Without Clerk**: Enter your Worker URL (`http://127.0.0.1:8787`) and click "Connect" 4. The onboarding wizard walks you through: * Project creation (auto-provisioned via `ALLOW_DEV_PROVISION=true`) * JWT minting (admin + member tokens) * First room creation * First message (celebrates with confetti when sent) Option B: Terminal quickstart (90 seconds) [#option-b-terminal-quickstart-90-seconds] ```bash pnpm run first-message ``` This script: 1. Starts a local Worker (inline Miniflare) 2. Provisions a project 3. Mints an admin JWT 4. Creates a room 5. Sends a message 6. Prints the JWT and room ID for SDK use Option C: Manual curl [#option-c-manual-curl] ```bash # Mint a project-scoped JWT curl -X POST "http://127.0.0.1\:8787/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: fc_your_api_key" \ -d '{"userId":"alice","roles":["admin"],"ttlSeconds":3600}' # Create a room curl -X POST "http://127.0.0.1\:8787/rooms" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"name":"general","isPublic":true}' # Send a message curl -X POST "http://127.0.0.1\:8787/rooms//messages" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"content":"Hello from local dev!"}' ``` *** 5\. Testing Realtime (WebSocket) [#5-testing-realtime-websocket] SDK hook [#sdk-hook] ```tsx import { FluxyChatClient, useChat } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: "http://127.0.0.1\:8787", userId: "alice", token: "", }); function ChatRoom() { const { messages, sendMessage } = useChat({ roomId: "general", client }); return (
{messages.map((m) => (
{m.content}
))} { if (e.key === "Enter") sendMessage(e.currentTarget.value); }} />
); } ``` Raw WebSocket test [#raw-websocket-test] ```bash # Connect to a room's WebSocket wscat -c "ws://127.0.0.1\:8787/rooms/general/ws?userId=alice&token=" ``` *** 6\. Testing Agents [#6-testing-agents] Create an agent [#create-an-agent] ```bash curl -X POST "http://127.0.0.1\:8787/agents" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "name": "Support Bot", "handle": "support", "provider": "openai", "model": "gpt-4o-mini", "capabilities": ["chat"], "systemPrompt": "You are a helpful support assistant." }' ``` Invoke via curl [#invoke-via-curl] ```bash curl -X POST "http://127.0.0.1\:8787/agents//invoke" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"roomId":"general","content":"What is FluxyChat?"}' ``` Via the dashboard [#via-the-dashboard] 1. Navigate to **Agents** in the sidebar 2. Click **Create agent** → fill in provider, model, system prompt 3. Open a room → type `@support ` to trigger the agent > **AI Agent Service**: For webhook-triggered agents (mention-based), ensure `apps/ai-agent` is running and its `.dev.vars` has the correct `FLUXY_BASE_URL` and `JWT_SECRET`. *** 7\. Common Tasks [#7-common-tasks] Run tests [#run-tests] ```bash # All packages pnpm test # Worker unit tests cd apps/worker && pnpm test # Dashboard unit tests cd apps/dashboard && pnpm test # Worker e2e tests (requires running worker) cd apps/worker && pnpm test:e2e # Dashboard e2e smoke tests (Playwright) cd apps/dashboard && pnpm test:e2e:smoke ``` Lint [#lint] ```bash pnpm lint ``` Smoke test the worker API [#smoke-test-the-worker-api] ```bash # Against a remote deployment cd apps/worker && pnpm smoke:remote -- --base-url https://your-worker.your-subdomain.workers.dev --admin-jwt # Bundled end-to-end (auth → room → message → GDPR) export TEST_API_KEY=fc_... pnpm smoke:bundled ``` Provisions / bootstrap [#provisions--bootstrap] ```bash # Create platform project (for hosted multi-tenant mode) pnpm run provision:bootstrap ``` *** 8\. Clerk Setup (Optional) [#8-clerk-setup-optional] If you want the full hosted experience with Clerk auth: 1. **Create a Clerk application** at [clerk.com](https://clerk.com) 2. Get your **Publishable Key** (`pk_test_...`) from Clerk Dashboard → API Keys 3. Get your **Secret Key** (`sk_test_...`) from the same page (server-only) 4. Add to `apps/dashboard/.env.local`: ```ini NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... NEXT_PUBLIC_CLERK_SIGN_UP_FALLBACK_REDIRECT_URL=/onboarding ``` 5. Restart the dashboard dev server > Clerk middleware in `apps/dashboard/middleware.ts` automatically activates when both keys are present. Without them, the middleware is a no-op and all routes are public. Clerk webhook (for auto-provisioning) [#clerk-webhook-for-auto-provisioning] To auto-create FluxyChat projects when users sign up: 1. In Clerk Dashboard → Webhooks → Add Endpoint 2. URL: `https://your-dashboard.com/api/webhooks/clerk` 3. Subscribe to `user.created` events 4. Copy the **Signing Secret** (`whsec_...`) to: ```ini CLERK_WEBHOOK_SIGNING_SECRET=whsec_... DASHBOARD_PUBLIC_URL=https://your-dashboard.com ``` *** 9\. Troubleshooting [#9-troubleshooting] | Symptom | Cause | Fix | | ---------------------------------------- | ----------------------------- | ----------------------------------------------------------------------- | | Worker 502 on startup | Miniflare D1 not initialized | `cd apps/worker && npx wrangler d1 migrations apply fluxychat --local` | | Dashboard "No active project" | JWT not in session | Go through `/onboarding` or set JWT in `localStorage` | | WebSocket connection refused | Worker not running | Ensure `pnpm dev` or `cd apps/worker && pnpm dev` is running | | Clerk sign-in loop | Missing redirect URLs | Set `NEXT_PUBLIC_CLERK_SIGN_UP_FALLBACK_REDIRECT_URL=/onboarding` | | `UserButton` invisible | Clerk not configured | Add `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` — or use manual quickstart mode | | Agent invoke timeout | No LLM API key in `.dev.vars` | Add `AI_API_KEY` or provider-specific key to `apps/worker/.dev.vars` | | Build error: `@fluxy-chat/sdk` not found | Packages not built | Run `pnpm build` from repo root (Turbo handles order) | | Voice messages not working | Feature flag off | Set `FEATURE_VOICE_MESSAGES=true` in `apps/worker/.dev.vars` | For more troubleshooting, see [Troubleshooting](/docs/reference/troubleshooting). *** 10\. Architecture Quick Reference [#10-architecture-quick-reference] ```mermaid flowchart TB subgraph dashboard["apps/dashboard — Next.js :3000"] landing["/landing"] onboarding["/onboarding"] console["/rooms · /agents · /admin"] landing --> onboarding onboarding --> console end subgraph worker["apps/worker — Cloudflare Worker :8787"] rest["REST API"] ws["WebSocket"] do["Durable Objects\n(Room, User, RateLimit)"] d1["D1 · KV · R2"] rest --> do ws --> do do --> d1 end subgraph agent["apps/ai-agent — Worker :8788"] llm["Mention webhooks → LLM → replies"] end console -->|"REST + WebSocket"| worker worker -->|"webhooks"| agent ``` Key ports [#key-ports] | Service | Port | Protocol | | --------- | ---- | --------------------------- | | Dashboard | 3000 | HTTP (Next.js) | | Worker | 8787 | HTTP + WebSocket (Wrangler) | | AI Agent | 8788 | HTTP (Wrangler) | --- # Ship in-app chat in one afternoon (/docs/getting-started/quickstart-afternoon) Ship in-app chat in one afternoon [#ship-in-app-chat-in-one-afternoon] Goal: first live message in a room using FluxyChat local Worker or hosted deployment. 0\. Zero-to-message (repo clone, ~90 seconds) [#0-zero-to-message-repo-clone-90-seconds] ```bash pnpm install pnpm run first-message ``` Uses `http://127.0.0.1:8787`, project `dev-local`, room `dev-local-general`. The script writes `FLUXY_CONSOLE_API_KEY` to `apps/worker/.dev.vars` when a new key is minted. 1\. Install in your app (2 min) [#1-install-in-your-app-2-min] ```bash pnpm add @fluxy-chat/sdk @fluxy-chat/react ``` 2\. Worker URL + JWT (10 min) [#2-worker-url--jwt-10-min] **Local dev:** use values printed by `pnpm run first-message`. **Hosted:** sign up at your dashboard → Quickstart → copy **member JWT** and **Worker URL**. **Self-host:** deploy `apps/worker`, run D1 migrations (`wrangler d1 migrations apply`), mint JWT via `POST /auth/token` with project API key. 3\. React hook (15 min) [#3-react-hook-15-min] ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; function Room({ roomId }: { roomId: string }) { const { messages, sendMessage, connectionState, sendReadReceipt, loadMore, } = useChat({ roomId, markReadLatest: true, }); return (

Status: {connectionState.status}

    {messages.map((m) => (
  • {m.content}
  • ))}
); } export function App({ workerUrl, jwt }: { workerUrl: string; jwt: string }) { return ( ); } ``` ```` ## 4. Rooms + unread (5 min) ```ts const rooms = await client.listRooms(); // each room may include unreadCount when using member JWT ```` 5\. In-app notifications (optional) [#5-in-app-notifications-optional] ```ts import { useNotifications } from "@fluxy-chat/react"; const { notifications, markRead, markAllRead } = useNotifications(client, { unreadOnly: true, }); ``` Mentions and DM messages create rows automatically (requires migration `0037_in_app_notifications.sql`). Next [#next] * [Message middleware](/docs/core/message-middleware) * [Transport fallback](/docs/cookbook/transport-fallback) * [Dashboard integration](/docs/reference/dashboard-integration) --- # Quickstart (/docs/getting-started/quickstart) First message [#first-message] Public room first. No backend. Member JWT when the room is private or you need roles. A. pk_ in the browser (about 30 seconds) [#a-pk_-in-the-browser-about-30-seconds] The room must be **public**. `pk_` identifies the project. The SDK mints an anonymous guest JWT (`POST /tokens/anonymous`). Writes are on unless the operator set `PUBLIC_GUEST_READ_ONLY`. ```bash pnpm add @fluxy-chat/react ``` ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; export function App() { return ( ); } function Room() { const { messages, sendMessage, connectionState } = useChat({ roomId: "general" }); return (

Status: {connectionState.status}

    {messages.map((m) => (
  • {m.content}
  • ))}
); } ``` No `useEffect`. No `joinPublicRoomAsGuest` in the app. `fc_` stays on the server. Self-host without a `pk_` row: `FluxyChatClient.joinPublicRoomAsGuest(workerUrl, publicRoomId)` still works when `PUBLIC_GUEST_ENABLED` is on. Drop-in widget: ```tsx import { FluxyChatWidget } from "@fluxy-chat/ui-kit"; ``` B. CLI (hosted) [#b-cli-hosted] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-app --mode hosted -y cd my-app pnpm install pnpm setup:hosted pnpm dev ``` Open [http://localhost:5173](http://localhost:5173), finish the tour, sign in. Mention `@assistant` in the room. Self-host instead? [Choose your path](/docs/getting-started/choose-your-path). C. Member JWT (private rooms, roles, production) [#c-member-jwt-private-rooms-roles-production] `FluxyRealtimeProvider` takes `workerUrl` plus `publishableKey`, `authTokenProvider`, or `connectUrl`. It does not take a `client` prop. Nest `FluxyYjsProvider` inside it so it reuses that client (`token` still works). Mint `jwt` on **your** server with `POST /auth/token` and a project API key (`fc_…`). Never put `fc_…` in the browser. See [Auth JWT](/docs/guides/auth-jwt). Local clone of this repo: `pnpm run first-message` prints a Worker URL and JWT for `dev-local-general`. Next [#next] * [Client setup](/docs/getting-started/client-setup) * [Publishable keys](/docs/guides/publishable-keys) * [Wire protocol](/docs/core/wire-protocol) * [Transport fallback](/docs/cookbook/transport-fallback) --- # Self-host cost (/docs/getting-started/self-host-cost) FluxyChat self-host is **$0 to us**. You pay Cloudflare for Workers, Durable Objects, D1, and (if you use them) R2 and AI. This is an order-of-magnitude note, not a quote. Read [Cloudflare Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/) and [Durable Objects pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/) for current numbers. What you actually run [#what-you-actually-run] * One Worker (HTTP + WebSocket upgrade) * One Durable Object per **active** room * D1 for messages, members, keys * Optional: R2 for attachments, a paid AI provider for `invokeAgent` Weekend / demo [#weekend--demo] The Workers free tier often covers a two-tab demo and a public room. Hibernating DOs are cheap when nobody is connected. Production (very rough) [#production-very-rough] Cost follows **WebSocket connections**, **DO requests**, and **D1 rows**, not "unlimited rooms" as a marketing line. A quiet B2B workspace (tens of rooms, not a ticker) is usually a small Workers bill. A consumer chat at Stream scale is a different product; do not self-host FluxyChat expecting that shape. Hosted FluxyChat Free is the no-card path if you do not want wrangler yet. Hosted is beta. Related [#related] * [Self-hosting](/docs/getting-started/self-hosting) * [Pricing](https://fluxychat.com/pricing) (hosted quotas; cursors do not count as messages) --- # Self-hosting (/docs/getting-started/self-hosting) Self-host means **you** run `apps/worker`. The Vite/React app is a client. It only needs the Worker URL and a member JWT. 1\. Bootstrap the Worker (from this repo) [#1-bootstrap-the-worker-from-this-repo] ```bash git clone https://github.com/AlessandroFare/fluxychat cd fluxychat pnpm install pnpm run self-host ``` The script copies `.dev.vars` templates and applies **local** D1 migrations. Put LLM keys in `apps/worker/.dev.vars` (`GROQ_API_KEY` or `OPENAI_API_KEY`). Agent model: `openai/gpt-oss-20b` on Groq (older `llama-3.1-8b-instant` is retired). ```bash pnpm --filter @fluxy-chat/worker dev ``` Smoke: `pnpm run first-message`. Longer notes: [Self-host one command](/docs/guides/self-host-one-command). 2\. Point an app at that Worker [#2-point-an-app-at-that-worker] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-app --full --mode self-host cd my-app pnpm setup:local pnpm dev ``` The CLI asks for Worker URL (default `http://127.0.0.1:8787`) and writes `.env`. `setup:local` calls `POST /dev/provision` so you get a project, JWT, room, and `@assistant`. 3\. Production [#3-production] From `apps/worker`: ```bash pnpm exec wrangler d1 migrations apply fluxychat --remote pnpm run deploy ``` Secrets via `wrangler secret put`: `JWT_SIGNING_KEY`, LLM keys, webhook HMAC. See [Production setup](/docs/operations/production-setup) and [Local development](/docs/getting-started/local-development). SSO [#sso] SAML is optional and sits on top of JWT rooms. [SAML SSO](/docs/security/saml-signature-verification). Related [#related] * [Client setup](/docs/getting-started/client-setup) * [Auth JWT](/docs/guides/auth-jwt) * [Dashboard integration](/docs/reference/dashboard-integration) --- # What to build (/docs/getting-started/what-to-build) Pick a row, scaffold the example, open two tabs. | You want | Primitive mix | Scaffold | | ------------------------------ | ------------------------------------------------ | ----------------------------------------- | | Live cursors / who is here | Presence | `--example live-cursors` | | Cursors + chat overlay | Presence + Chat | `--example live-cursors-chat` | | Vanilla JS pointers | Presence (`connect` + `type: cursor`) | `--example javascript-live-cursors` | | Google-Docs-style editor | Storage + Presence | `--example tiptap-room` | | Figma-like board | Storage `Y.Array` + Presence | `--example whiteboard` | | Stamp / ephemeral dots | Broadcast + Presence | `--example draw` | | Contextual review comments | Threads + UI `Thread` / `FloatingComposer` | `--example comments-board` | | Live polls / anonymous ballots | Chat `createPoll` / `votePoll` + `POST /polls` | `--example polls` | | Agent war room | Chat + `invokeAgent` + Presence | `--example war-room` | | Quorum / export deal | Chat decisions + whisper + `invokeAgent` + feeds | `--example deal-room` | | Two-party NDA / clause HITL | Same two-seat room; auto / ask / deny | `--example negotiation-room` | | Device telemetry panel | HTTP ingest + `server_event` | `--example iot-panel` | | GPS / fleet | `POST /fleet/gps` + `fleet.gps_update` | `--example fleet-panel` | | Match lobby ticks | Game HTTP + `game.tick` | `--example game-tick` | | Speaker / listener roster | `joinVoiceStage` | `--example voice-stage` | | n8n / LangChain log | Feeds + API key | [Feeds](/docs/core/feeds) | | Side-panel assistant | Copilot `` | [Copilots](/docs/core/copilots) | | Inbox + email catch-up | Inbox kinds + digest prefs | [Notifications](/docs/core/notifications) | Cross-org rooms use REST `/cross-org/…` on the Worker. Game ticks are server-authoritative inputs, not a full netcode stack. Voice stage is signaling. Clone-quality translation goes through `/voice-ai/clone-translate` to your media URL. Latency numbers: [voice report](/docs/operations/voice-load-test-report). --- # Adapter Error Hierarchy (/docs/guides/adapter-errors) Adapter Error Hierarchy [#adapter-error-hierarchy] FluxyChat's adapter error system provides a standardized error hierarchy for consistent error handling across all adapter implementations. Overview [#overview] All adapter errors extend `AdapterError`, which includes `adapter` (the platform name) and `code` (a machine-readable error code) fields. This lets you handle errors programmatically without parsing error messages. **Source:** `apps/worker/src/lib/errors.js` Error Classes [#error-classes] AdapterError (base) [#adaptererror-base] ```js import { AdapterError } from "@fluxy-chat/sdk"; try { await adapter.postMessage(threadId, text); } catch (err) { if (err instanceof AdapterError) { console.log(err.adapter); // "slack" console.log(err.code); // "RATE_LIMITED" } } ``` Full hierarchy [#full-hierarchy] | Class | Code | Key fields | When to use | | ----------------------- | ------------------- | ---------------------------- | -------------------------------- | | `AdapterError` | varies | `adapter`, `code` | Base class — catch-all | | `AdapterRateLimitError` | `RATE_LIMITED` | `retryAfter` (seconds) | Platform API rate limit hit | | `AuthenticationError` | `AUTH_FAILED` | — | Invalid or expired credentials | | `ResourceNotFoundError` | `NOT_FOUND` | `resourceType`, `resourceId` | Requested resource doesn't exist | | `PermissionError` | `PERMISSION_DENIED` | `action`, `requiredScope` | Bot lacks required permissions | | `ValidationError` | `VALIDATION_ERROR` | — | Invalid input data | | `NetworkError` | `NETWORK_ERROR` | `originalError` | Connectivity issues | | `AdapterNotFoundError` | `ADAPTER_NOT_FOUND` | — | Adapter slug not registered | | `ThreadNotFoundError` | `THREAD_NOT_FOUND` | `threadId` | Thread doesn't exist | | `MessageNotFoundError` | `MESSAGE_NOT_FOUND` | `messageId` | Message doesn't exist | Usage Examples [#usage-examples] Rate limit handling with backoff [#rate-limit-handling-with-backoff] ```js import { AdapterRateLimitError } from "@fluxy-chat/sdk"; try { await slackAdapter.postMessage(threadId, "Hello!"); } catch (err) { if (err instanceof AdapterRateLimitError) { console.log(`Rate limited by ${err.adapter}. Retry after ${err.retryAfter}s.`); await sleep(err.retryAfter * 1000); return retry(); } throw err; } ``` Permission errors with user feedback [#permission-errors-with-user-feedback] ```js import { PermissionError } from "@fluxy-chat/sdk"; try { await teamsAdapter.postMessage(threadId, "Hello!"); } catch (err) { if (err instanceof PermissionError) { // Show the user which scope is missing showPermissionError( `Cannot ${err.action} in ${err.adapter}`, err.requiredScope ); return; } throw err; } ``` Resource not found [#resource-not-found] ```js import { ResourceNotFoundError, ThreadNotFoundError } from "@fluxy-chat/sdk"; try { await adapter.fetchThread(threadId); } catch (err) { if (err instanceof ThreadNotFoundError) { console.log(`Thread ${err.threadId} not found in ${err.adapter}`); // Clean up local references return; } if (err instanceof ResourceNotFoundError) { console.log(`${err.resourceType} ${err.resourceId} not found`); return; } throw err; } ``` Network errors with original error [#network-errors-with-original-error] ```js import { NetworkError } from "@fluxy-chat/sdk"; try { await adapter.postMessage(threadId, text); } catch (err) { if (err instanceof NetworkError) { console.error(`Network error for ${err.adapter}:`, err.originalError); // Implement fallback or queue for later } } ``` Creating Custom Adapter Errors [#creating-custom-adapter-errors] When building a custom adapter, throw the appropriate error class: ```js import { AdapterRateLimitError, AuthenticationError, ValidationError, } from "@fluxy-chat/sdk"; class MyAdapter extends BaseAdapter { async postMessage(threadId, content) { if (!this.token) { throw new AuthenticationError(this.slug, "No OAuth token configured"); } if (!content) { throw new ValidationError(this.slug, "Content is required"); } const res = await fetch(this.apiUrl, { /* ... */ }); if (res.status === 429) { const retryAfter = parseInt(res.headers.get("Retry-After") || "60"); throw new AdapterRateLimitError(this.slug, retryAfter); } } } ``` Relationship to SDK Errors [#relationship-to-sdk-errors] The SDK also exports `ChatError`, `RateLimitError`, `LockError`, and `NotImplementedError` from the structured errors module. These are client-side errors for SDK operations, while the `Adapter*` errors are for adapter-level operations. See Also [#see-also] * [Unified Chat API](/docs/guides/unified-chat-api) — Top-level chat methods * [Adapter Lifecycle](/docs/guides/adapter-lifecycle) — disconnect, postEphemeral, rehydrateAttachment, waitUntil * [Adapter Pattern](/docs/guides/adapter-pattern) — Multi-platform adapter interface --- # Adapter Lifecycle & Operations (/docs/guides/adapter-lifecycle) Adapter Lifecycle & Operations [#adapter-lifecycle--operations] FluxyChat adapter lifecycle methods provide hooks for cleanup, ephemeral messaging, attachment rehydration, and portable background task tracking. Overview [#overview] Adapters in FluxyChat support optional lifecycle and operational methods beyond the core `postMessage`/`editMessage`/`deleteMessage` interface. These methods handle graceful shutdown, platform-specific ephemeral messaging, attachment handling after deserialization, and webhook background tasks. **Source:** `apps/worker/src/lib/adapter.js` `disconnect()` [#disconnect] Optional cleanup hook for closing connections and releasing resources on shutdown. ```js class SlackAdapter extends BaseAdapter { async disconnect() { if (this.ws) { this.ws.close(); this.ws = null; } console.log(`[${this.slug}] Disconnected`); } } ``` Bulk shutdown [#bulk-shutdown] Use `chat.shutdown()` to disconnect all registered adapters: ```js import { chat } from "@fluxy-chat/sdk"; const result = await chat.shutdown(); // { disconnected: ["web", "slack", "discord"], errors: [] } ``` This is useful for graceful Worker lifecycle management and testing cleanup. `postEphemeral(threadId, message, userId, options)` [#postephemeralthreadid-message-userid-options] Posts an ephemeral message visible only to a specific user. Falls back to DM when the platform doesn't support ephemeral messages natively. ```js // Slack supports ephemeral natively await slackAdapter.postEphemeral(threadId, "Only you can see this", "U123"); // Returns: { id: "msg-123", usedFallback: false } // Discord doesn't support ephemeral in the same way — falls back to DM await discordAdapter.postEphemeral(threadId, "Private note", "123456789"); // Returns: { id: "dm-msg-456", usedFallback: true } ``` The `fallbackToDM` option [#the-fallbacktodm-option] The `fallbackToDM` behavior is automatic. When a platform doesn't support ephemeral messages, the adapter opens a DM and posts there instead. The `usedFallback` flag in the result lets the caller know which path was taken: ```js const result = await adapter.postEphemeral(threadId, message, userId); if (result.usedFallback) { console.log("Sent as DM instead of ephemeral"); } ``` Overriding in a custom adapter [#overriding-in-a-custom-adapter] ```js class MyAdapter extends BaseAdapter { async _postEphemeralImpl(threadId, message, userId) { // Platform-specific ephemeral implementation const res = await fetch(this.apiUrl + "/ephemeral", { method: "POST", body: JSON.stringify({ threadId, message, userId }), }); const data = await res.json(); return { id: data.messageId }; } } ``` `postChannelMessage(channelId, message)` [#postchannelmessagechannelid-message] Posts a top-level message to a channel (not in a thread). This is distinct from `postMessage()` which posts into a specific thread. ```js // Post to a Slack channel (not as a thread reply) await slackAdapter.postChannelMessage("C123ABC", "Channel-wide announcement!"); ``` `rehydrateAttachment(attachment)` [#rehydrateattachmentattachment] Reconstructs `fetchData` closures after deserialization. Essential for queue/debounce strategies where attachments are serialized and processed later. ```js // When a message with attachments is queued (debounce strategy), // the attachment's fetchData closure is lost during JSON serialization. // rehydrateAttachment() restores it. class MyAdapter extends BaseAdapter { async rehydrateAttachment(attachment) { return { ...attachment, fetchData: async () => { // Re-fetch the file from the platform const res = await fetch(`${this.apiUrl}/files/${attachment.id}`); return res.blob(); }, }; } } ``` `waitUntil` pattern for webhooks [#waituntil-pattern-for-webhooks] Portable background task tracking for webhook handlers. On Cloudflare Workers, this maps to `ctx.waitUntil()`. On other runtimes, it can be a no-op or custom implementation. ```js class MyAdapter extends BaseAdapter { async handleWebhook(req, { waitUntil }) { const parsed = this.parseMessage(await req.json()); // Fire-and-forget background task waitUntil(this.syncUser(parsed.userId)); // Return immediately return parsed; } } ``` The `waitUntil` option is passed through the webhook handler options and allows adapters to schedule background work (analytics, logging, cache invalidation) without blocking the response. `fetchChannelMessages(channelId, options)` [#fetchchannelmessageschannelid-options] Fetches top-level channel messages (not thread replies). Enables moderation and analytics workflows. ```js const messages = await slackAdapter.fetchChannelMessages("C123ABC", { limit: 50, cursor: "next-cursor-token", }); // [{ id, content, userId, createdAt, threadId? }, ...] ``` `listThreads(channelId, options)` [#listthreadschannelid-options] Lists threads within a channel. Returns lightweight thread summaries for efficiency. ```js const threads = await slackAdapter.listThreads("C123ABC", { limit: 20, }); // [{ threadId, messageCount, lastReplyAt, authorId }, ...] ``` `getParticipants(threadId)` [#getparticipantsthreadid] Scans messages in a thread and returns deduplicated non-bot authors. ```js const participants = await adapter.getParticipants("slack\:C123:1234567890.123456"); // [{ userId: "U123", adapter: "slack" }, { userId: "U456", adapter: "slack" }] ``` `mentionUser(userId)` [#mentionuseruserid] Formats a platform-specific mention string. ```js slackAdapter.mentionUser("U123ABC"); // "<@U123ABC>" discordAdapter.mentionUser("123456789"); // "<@123456789>" webAdapter.mentionUser("alice"); // "@alice" ``` See Also [#see-also] * [Unified Chat API](/docs/guides/unified-chat-api) — `chat.thread()`, `chat.openDM()`, `chat.shutdown()` * [Adapter Errors](/docs/guides/adapter-errors) — Error handling for adapter operations * [Adapter Pattern](/docs/guides/adapter-pattern) — Core adapter interface --- # Multi-Platform Adapter Pattern (/docs/guides/adapter-pattern) Multi-Platform Adapter Pattern [#multi-platform-adapter-pattern] The Worker ships an `Adapter` interface and format converters. Console **Bridges** are paste-token rows: you create the Slack, Discord, Telegram, WhatsApp, or Teams app and point the webhook at the Worker. This is not a finished 14-channel helpdesk. Overview [#overview] The adapter pattern abstracts platform-specific concerns behind a common interface so you can add a channel without rewriting the room kernel. **Interfaces in this repo (not a desk SKU):** Web, Slack, Microsoft Teams, Discord, Telegram, WhatsApp, Google Chat, GitHub, Linear, Matrix, Resend (Email), IRC, Twitch, Line, and a generic API adapter. Gold path today is Bridges for Slack/Discord/Telegram/WhatsApp/Teams that you wire yourself. Adapter Interface [#adapter-interface] Every adapter implements: ```ts interface Adapter { handleWebhook(raw: Request): Promise; parseMessage(raw: TRawMessage): ParsedMessage; postMessage(threadId: string, content: string): Promise; editMessage(threadId: string, messageId: string, content: string): Promise; deleteMessage(threadId: string, messageId: string): Promise; stream(threadId: string, content: ReadableStream): Promise; encodeThreadId(parts: ThreadIdParts): string; decodeThreadId(threadId: string): ThreadIdParts; formatConverter: FormatConverter; lockScope: "thread" | "channel"; } ``` Format Converter [#format-converter] Each adapter includes a `FormatConverter` that translates between canonical mdast (Markdown Abstract Syntax Tree) and the platform's native format: * **Slack:** mrkdwn with Block Kit * **Teams:** Adaptive Cards * **Discord:** Markdown with embeds * **Telegram:** MarkdownV2 with inline keyboards * **WhatsApp:** Plain text with formatting shortcuts * **Web:** Full markdown rendering ```ts import { getAdapter } from "@fluxy-chat/sdk"; const slack = getAdapter("slack"); const threadId = slack.encodeThreadId({ channelId: "C123", ts: "1234" }); // "slack\:C123:1234" const parsed = slack.parseMessage(rawWebhookBody); await slack.postMessage(threadId, "Hello from FluxyChat!"); ``` WebAdapter [#webadapter] The `WebAdapter` wraps FluxyChat's native WebSocket + REST flow into the adapter interface. It's the default adapter and is registered at worker startup. ```ts import { getAdapter } from "@fluxy-chat/sdk"; const web = getAdapter("web"); const threadId = web.encodeThreadId({ userId: "alice", roomId: "general" }); // "web:alice\:general" ``` Adding a Custom Adapter [#adding-a-custom-adapter] ```ts import { BaseAdapter } from "@fluxy-chat/sdk"; class MyAdapter extends BaseAdapter { slug = "myapp" as const; async handleWebhook(req: Request) { /* ... */ } parseMessage(raw: MyRawMessage) { /* ... */ } async postMessage(threadId: string, content: string) { /* ... */ } // ... implement remaining methods } ``` Adapter Catalog [#adapter-catalog] The static adapter registry (`adapters-http.js`) provides metadata for discovery and onboarding UIs: ```ts import { listAdapters } from "@fluxy-chat/sdk"; const adapters = listAdapters(); // [{ slug: "web", name: "Web", packageName: "@fluxy-chat/adapter-web" }, ...] ``` Lock Scope [#lock-scope] Adapters declare whether they lock at the **thread** level (Slack, Discord) or **channel** level (WhatsApp, Telegram). This prevents concurrent message processing conflicts per platform's threading model. See Also [#see-also] * [Streaming Markdown Guide](/docs/guides/streaming-markdown) — How markdown renders during streaming * [Card Builder Guide](/docs/guides/card-builder) — Rich message elements across platforms --- # Room agent token cap (/docs/guides/agent-budget) Room agent token cap [#room-agent-token-cap] Each room can refuse new `invokeAgent` turns after a monthly token total from `agent_runs`. Set it from **Rooms → Advanced → Room insights** (owner or admin JWT) or: ```http GET /rooms/:roomId/agent-budget PUT /rooms/:roomId/agent-budget Authorization: Bearer Content-Type: application/json { "monthlyTokenBudget": 500000, "enabled": true } ``` `PUT` is owner/admin. `GET` is any room member. Empty cap means agents are uncapped. The USD line on the same panel is a Cloudflare Worker usage estimate for that room. It is not an invoice and it is not Stripe metering of your customers' customers. Optional: set `STRIPE_AGENT_METER_EVENT_NAME` plus `STRIPE_SECRET_KEY` so completed `invokeAgent` turns report token totals to **your** Stripe Billing Meter, keyed by `project_plans.stripe_customer_id`. That is usage for the FluxyChat tenant, not for their users. Dashboard [#dashboard] Collab project overview already showed this panel. It now also sits on **Rooms → Advanced**, so operators do not have to leave the rooms page. --- # Agent room broadcast (/docs/guides/agent-room-broadcast) Agent room broadcast [#agent-room-broadcast] Agents should speak **to the room** so every participant sees the same stream (Multiplayer AI / GargolasTech pattern). SDK default [#sdk-default] ```ts await client.createMessage(roomId, agentReply, { visibility: "room", }); ``` Do not use whisper unless the agent truly needs a private side channel. Ambient agents [#ambient-agents] Ambient and debate presets post to the room timeline by default. Check `apps/dashboard/app/agents/` presets before shipping a demo. UI badges [#ui-badges] Messages show **Room** when `visibility` is absent or `room`. Whisper and `role:*` scopes show their scope in the message metadata. MCP external agents [#mcp-external-agents] Room MCP `send_message` posts to the shared timeline and fans out on WebSocket. See [Room as MCP server](/docs/guides/room-as-mcp-server). --- # FluxyChat SDK — AI Agent Skill (/docs/guides/ai-sdk-skill) FluxyChat SDK — AI Agent Skill [#fluxychat-sdk--ai-agent-skill] Identity [#identity] You are coding with the FluxyChat SDK (`@fluxy-chat/sdk`). All imports from `@fluxy-chat/sdk` (subpath entries: `./react`, `./room`, `./chat`, `./testing`, `./core`, `./markdown`, and more). Core pattern: factory functions (`createXyz()`) returning interfaces with per-instance state. Modules [#modules] Core [#core] * **ThreadState** — `createThreadState()`: thread management with state merging * **Outbox** — `createMessageOutbox()`, `createOutboxProcessor()`: dedup and flush for outbound messages * **Transport** — `createWebSocketTransport()`, `createAdaptiveTransport()`, `createDurableTransport()`: WebSocket transport with backpressure * **Sync** — `delta-sync.ts`: CRDT-like state sync with patches Media & Voice [#media--voice] * **Voice pipeline** — `createVoicePipeline()`: mic→ASR→LLM→TTS→speaker 5-stage orchestrator with per-stage metrics * **Voice quality** — `createSloTracker()` (TTFA percentiles), `createNoiseProcessor()` (AEC/noise/gain), `createQualityCollector()` (snapshot breakdown) * **Turn detection** — `createTurnDetector()`: VAD energy gate + semantic EOT, dynamic endpointing * **Voice controls** — `createProsodyController()` (style/rate/pitch), `createDiarizer()` (speaker ID/overlap/correction) * **Call QA** — `createQaAnalyzer()`: topic/outcome/sentiment/compliance scoring with evidence spans * **Huddles** — `createHuddle()`: WebRTC join/leave, mute/unmute, screen share, captions, recording consent * **Video generation** — `createVideoGenerator()`: polling progress, cancel, multi-job tracking AI Tools [#ai-tools] * **Tool system** — `getPresetTools()`, `buildToolList()`, `createChatTools()`: preset tools with approval configs, tool overrides * **Dynamic tools** — `dynamicTool()`, `createDynamicToolRegistry()`: runtime tool registration * **Call options** — `callOptionsSchema()`, `prepareCall()`, `createAgentWithCallOptions()`: type-safe runtime config * **Workflow agent** — `createWorkflowAgent()`: LLM-powered multi-step agent * **Agent delegation** — `delegateToAgent()`: hand a task off to another agent * **Slash commands** — `createSlashCommandRegistry()`: /command parser * **Gamification** — `createGamification()`: XP/levels/badges/streaks * **Moderation** — `createModerationEngine()`, `evaluateModerationRules()`: profanity/spam/PII/content policies * **Rendering** — `ComponentRenderer`, `renderParts()`: pluggable component/message rendering Real-time Infrastructure [#real-time-infrastructure] * **Relay** — `createDecentralizedRelay()`: peer-to-peer relay * **Failover** — `createRegionalFailover()`: multi-region fallback * **Room** — `createFluxyRoomSession()`, `acquireFluxyRoomSession()`, `createRoomSequencer()`, `createBroadcastApi()` * **Delivery** — `createDeliverySemantics()`: at-most-once/at-least-once/exactly-once * **Streaming** — `createFluxyStream()`, `createResumableAgentStream()` * **Ephemeral** — `postEphemeral()`: post an ephemeral message (optional DM fallback) Enterprise/Security [#enterprisesecurity] * **Group cipher** — `createGroupCipher({ keyMaterial })`: AES-256-GCM with HKDF-SHA256 per-epoch keys and AAD binding. (`createMlsManager()` throws with migration text; it never performed the cryptography it claimed.) * **AI governance** — `createAiGovernance()`: model/prompt/tool registry, risk tiering, approvals * **eDiscovery** — `createEdiscoveryManager()`: legal hold, export, SHA-256 audit log * **DLP** — `createDlpDetector()`: PHI/PCI pattern scan, redact/block/flag * **CMK** — `createCmkManager()`: envelope encryption, key rotation/revocation, tenant-isolated audit * **Data residency** — `createResidencyValidator()`: region pinning, subprocessors, 8 region codes * **Policy engine (OPA)** — `createPolicyEngine()`: enforcing/shadow/disabled, rego-like matching * **MCP identity** — `createMcpIdentityManager()`: server registration, instructions, tool provenance * **Bot protection** — `createBotProtection()`: rate limits, raid mode, trust scoring * **Session replay** — `createSessionReplayManager()`: redacted timeline, consent, deterministic protocol * **Federation** — `createFederationBridge()`: Matrix/ActivityPub/DM bridges * **Feature flags** — `createFeatureFlagManager()`: tenant rollout, kill switch, metric guardrails * **Sandbox** — `createSandboxExecutor()`: isolated runs, quotas, timeouts, multi-runtime * **GUI sandbox** — `createGuiSandboxManager()`: iframe sandbox, CSP, capability grants Developer Experience [#developer-experience] * **Testing utils** — `createMockAdapter()`, `matchers` (Vitest custom) * **Telemetry** — `createTelemetryManager()`, `OpenTelemetryIntegration()`, `DevToolsTelemetryIntegration()` * **DevTools** — `createDevToolsStore()`, `createDevToolsInspector()` * **Deterministic models** — `createDeterministicLanguageModel()`: scripted output/chunks/errors * **Stream fixtures** — `streamFixtures`, `simulateStream()`: edge case stream patterns * **Error hierarchy** — `ChatError`, `RateLimitError`, `LockError`, `NotImplementedError` Patterns [#patterns] 1. Factory functions only (no class exports, no module-level state) 2. Each factory returns typed interface with per-instance mutable state 3. In-memory implementations — deployer wires real infrastructure (LiveKit, Redis, your provider, etc.) 4. Tests use `vi.fn()` mocks, no external services 5. Guide docs in `docs/guides/*.md` with usage examples Test Command [#test-command] ```bash cd packages/sdk && npx vitest run ``` 1,300+ tests across 200+ files. --- # AI Tool Presets (/docs/guides/ai-tool-presets) AI Tool Presets [#ai-tool-presets] `createChatTools()` generates a set of AI SDK-compatible tools for chat operations (fetching messages, posting, reactions, etc.) with preset-based filtering and approval controls. Usage [#usage] ```ts import { createChatTools } from "@fluxy-chat/sdk"; const chat: ChatBinding = { thread(id) { /* ... */ }, channel(id) { /* ... */ }, getUser(id) { /* ... */ }, openDM(id) { /* ... */ }, }; const tools = createChatTools({ chat, preset: "reader" }); // Pass to AI SDK const result = await streamText({ model: openai("gpt-4"), tools, }); ``` Presets [#presets] | Preset | Tools | Description | | ----------- | ----- | ---------------------------------------------- | | `reader` | 7 | Read-only: fetch messages, threads, users | | `messenger` | 10 | Read + post + reactions + typing | | `moderator` | 17 | Full set including edit, delete, subscriptions | Approval [#approval] Write tools (post, edit, delete, react, subscribe) default to `needsApproval: true`: ```ts createChatTools({ chat, preset: "messenger", requireApproval: { postMessage: false }, // override specific tools }); ``` Overrides [#overrides] Customize tool descriptions or other non-core fields: ```ts createChatTools({ chat, preset: "reader", overrides: { fetchMessages: { description: "Custom description" }, }, }); ``` Protected fields (`execute`, `parameters`) cannot be overridden. Tool Definitions [#tool-definitions] Each tool exports `description`, `parameters` (JSON Schema), `execute` function, and optional `needsApproval` flag. Compatible with Vercel AI SDK, OpenAI, Anthropic, and other tool-calling APIs. See Also [#see-also] * [Message-to-LLM Converter](/docs/guides/messages-to-ai) * [LLM Middleware](/docs/guides/llm-middleware) --- # Announcement channels (/docs/guides/announcement-channels) Announcement rooms work like a company-wide megaphone. Owners, admins, and moderators can post. Everyone else reads only, but they still get realtime updates, in-app notifications, and push when you have push configured. Create a channel [#create-a-channel] In the dashboard, go to **Rooms** and pick type **Announcement**, or call: ```http POST /rooms { "name": "Company news", "type": "announcement" } ``` Who can post [#who-can-post] `assertCanPostToRoom` blocks regular members. They get: ```json { "error": "announcement_read_only", "code": "announcement_read_only", "roomType": "announcement" } ``` HTTP status `403`. What members receive [#what-members-receive] When an admin posts successfully: 1. The room Durable Object broadcasts the message in realtime. 2. Every other member gets an in-app notification with `kind: "announcement"`. 3. Web, FCM, and APNs push run with higher priority (`topic: announcement`) through `maybePushNotifyOnMessage`. Announcement pushes still go out even if a member turned off routine message notifications. That is intentional for broadcast content. Related [#related] * [Notification controls](/docs/core/notifications) * [Quiet hours and notifications](/docs/reference/quiet-hours-notifications) --- # AST Markdown System (/docs/guides/ast-markdown) AST Markdown System [#ast-markdown-system] The markdown module provides a complete mdast (Markdown AST) system using unified/remark with GFM support. Builders [#builders] Create AST nodes programmatically: ```ts import { root, paragraph, text, strong, link } from "@fluxy-chat/sdk"; const ast = root([ paragraph([text("Hello "), strong([text("world")])]), paragraph([link("https://example.com", [text("click here")])]), ]); ``` Parse / Stringify [#parse--stringify] ```ts import { parseMarkdown, stringifyMarkdown } from "@fluxy-chat/sdk"; const ast = parseMarkdown("**bold** and *italic*"); const md = stringifyMarkdown(ast); // "**bold** and *italic*\n" ``` Plain Text [#plain-text] ```ts import { markdownToPlainText, toPlainText } from "@fluxy-chat/sdk"; markdownToPlainText("**bold** and *italic*"); // "bold and italic" toPlainText(ast); // "bold and italic" ``` Walk AST [#walk-ast] ```ts import { walkAst, isTextNode } from "@fluxy-chat/sdk"; walkAst(ast, (node) => { if (isTextNode(node)) { return { ...node, value: node.value.toUpperCase() }; } return node; }); ``` Type Guards [#type-guards] All 14 type guards available: `isTextNode`, `isParagraphNode`, `isStrongNode`, `isEmphasisNode`, `isDeleteNode`, `isInlineCodeNode`, `isCodeNode`, `isLinkNode`, `isBlockquoteNode`, `isListNode`, `isListItemNode`, `isTableNode`, `isTableRowNode`, `isTableCellNode`, `isHeadingNode`. --- # Asymmetric session profiles (/docs/guides/asymmetric-sessions) Asymmetric session profiles [#asymmetric-session-profiles] Built on [role-scoped visibility](/docs/guides/role-scoped-visibility). Store a profile on the room so dashboards and agents know which roles get private hints vs the public thread. API [#api] ```http GET /rooms/:roomId/session-profile PUT /rooms/:roomId/session-profile Authorization: Bearer ``` Example profile (interview eval): ```json { "profile": { "name": "interview_eval", "roles": { "evaluator": { "privateHints": true, "aiNotes": true, "panel": "notes" }, "member": { "privateHints": false, "aiNotes": false, "panel": "candidate" } } } } ``` Pair with messages sent using `visibility: "role:evaluator"`. Dashboard [#dashboard] **Rooms → Asymmetric session** applies the interview-eval pack in one click. Cookbook [#cookbook] [Interview eval template](/docs/guides/cookbook-interview-eval) walks through the full flow. --- # Audience score rollup (/docs/guides/audience-score) Audience score rollup [#audience-score-rollup] Roll up emoji reactions in a room over a sliding window. Useful for debate prep, live Q\&A, and audience scorecards (OratorIA / Vokaly patterns). API [#api] ```http GET /rooms/:roomId/audience-score?windowMinutes=15 Authorization: Bearer ``` Response: ```json { "score": 60, "positive": 8, "negative": 2, "total": 10, "windowMinutes": 15 } ``` Score is `(positive - negative) / total * 100`, clamped to 0–100. Dashboard [#dashboard] Open **Rooms → select room → Room intelligence** to refresh the score and run memory/graph extract alongside it. Template [#template] See [Audience score template](/docs/guides/cookbook-audience-score) for client-side tallying on stream rooms. --- # Authentication (JWT) (/docs/guides/auth-jwt) Authentication [#authentication] FluxyChat uses two credential forms: * **API key** (`X-Fluxy-Api-Key`): server-to-server, identifies the **tenant/project**. * **JWT** (`Authorization: Bearer …`): client-to-worker/SDK. Claims include `sub` (userId), `tid` (projectId), `roles`, `exp`. **Rule:** `fc_` stays on the server. Browsers may use **`pk_`** (publishable) for guest-session and anonymous tokens only. See [Publishable keys](/docs/guides/publishable-keys). Mint a member JWT (server-side) [#mint-a-member-jwt-server-side] ```bash export FLUXY_BASE_URL="http://127.0.0.1:8787" export FLUXY_API_KEY="fc_..." curl -sS -X POST "$FLUXY_BASE_URL/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{"userId":"alice","roles":["member"],"ttlSeconds":3600}' ``` Response includes `token`, `expiresIn`, and echoed `claims`. Roles [#roles] | Role | Typical access | | ----------- | ------------------------------------------------------- | | `member` | Send/edit own messages, reactions, read receipts, inbox | | `moderator` | Mute/ban, some admin routes | | `admin` | Webhooks, projects, alert rules | | `owner` | Sensitive tenant operations | Admin routes enforce role checks per endpoint. See OpenAPI docs for each route. Next.js Route Handler example [#nextjs-route-handler-example] Keep `fc_` on the server. `pk_` cannot mint member JWTs. ```ts import { createFluxyTokenRoute } from "@fluxy-chat/sdk"; import { auth } from "@clerk/nextjs/server"; // or Auth.js / Better Auth getSession export const POST = createFluxyTokenRoute({ workerUrl: process.env.FLUXY_BASE_URL!, apiKey: process.env.FLUXY_API_KEY!, getUserId: async () => (await auth()).userId, }); ``` Same helper with Clerk or Auth.js via `@fluxy-chat/auth` (still `fc_` on the server): ```ts import { auth } from "@clerk/nextjs/server"; import { createClerkFluxyTokenRoute } from "@fluxy-chat/auth"; export const POST = createClerkFluxyTokenRoute({ workerUrl: process.env.FLUXY_BASE_URL!, apiKey: process.env.FLUXY_API_KEY!, auth, }); ``` Auth.js / NextAuth: `createAuthJsFluxyTokenRoute({ …, auth })` with your `auth()` that returns `{ user: { id } }`. Better Auth / Lucia: `createBetterAuthFluxyTokenRoute` / `createLuciaFluxyTokenRoute` (same shape). Supabase: `createSupabaseFluxyTokenRoute({ getUser: () => supabase.auth.getUser() })`. Auth0-style `{ user: { sub } }`: `createOidcFluxyTokenRoute` (`auth0|1` is stored as `auth0_1`). Handmade: `createFluxyTokenRoute({ getUserId })` from `@fluxy-chat/auth` or the SDK. Same helper with a handmade `getUserId` if you are not on Clerk: ```ts import { NextResponse } from "next/server"; export async function POST(request: Request) { const body = await request.json().catch(() => null); const userId = body?.userId; if (!userId) return NextResponse.json({ error: "userId required" }, { status: 400 }); const res = await fetch(`${process.env.FLUXY_BASE_URL}/auth/token`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fluxy-Api-Key": process.env.FLUXY_API_KEY!, }, body: JSON.stringify({ userId, roles: ["member"], ttlSeconds: 3600 }), }); return NextResponse.json(await res.json(), { status: res.status }); } ``` Wire the returned JWT into `FluxyRealtimeProvider` or `FluxyChatClient({ token })`. WebSocket auth [#websocket-auth] ``` GET /ws/room/:roomId?token= ``` Membership is enforced: `403` / close `1008` when the user is not a room member. Token refresh [#token-refresh] `FluxyChatClient.setToken(next)` (alias `updateToken`) replaces the session JWT. Returns `true` when `sub` changed. Reconnect active rooms. When `exp` passes: 1. Mint a new JWT on your backend (`POST /auth/token`). 2. Call `client.setToken(jwt)`, or pass a **function** to `FluxyRealtimeProvider` `authTokenProvider` so it remints before expiry: ```tsx { const res = await fetch("/api/fluxy/token", { method: "POST" }); const data = (await res.json()) as { token: string }; return data.token; }} > {children} ``` Keep `FLUXY_API_KEY` (`fc_`) in the Route Handler only. Public rooms skip this path: `publishableKey` or `joinPublicRoomAsGuest`. Common errors [#common-errors] | Symptom | Cause | Fix | | ------------------------------- | ---------------------------- | ------------------------------ | | 401 invalid api key | Revoked or wrong project key | Rotate key in Projects console | | `FluxyTokenExpiredError` | JWT `exp` passed | Mint new JWT | | `FluxyNotMemberError` | User not in room | Add membership or join room | | `FluxyAnonymousNotAllowedError` | Room requires auth | Use member JWT | See [Troubleshooting integration](/docs/guides/troubleshooting-integration) for copy-paste fixes. Related [#related] * [Quickstart](/docs/getting-started/quickstart) * [Client setup](/docs/getting-started/client-setup) * [SDK playground](/playground) --- # Workflow automations (/docs/guides/automations) Open [**Automations**](/automations) in the dashboard or use `/api/workflows` on the Worker. Example rule [#example-rule] **When** a message contains `help` **then**: 1. Invoke agent `support-bot` 2. Notify the agent queue ```bash curl -X POST "$WORKER/api/workflows" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "Help keyword → agent", "triggerType": "message.created", "triggerConfig": { "contains": "help" }, "conditions": { "textContains": "help" }, "actions": [ { "type": "invoke_agent", "agentId": "support-bot" }, { "type": "notify", "channel": "agent-queue" } ] }' ``` Run manually [#run-manually] ```bash curl -X POST "$WORKER/api/workflows/wf_abc123/run" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{"triggerData":{"roomId":"room_demo","keyword":"help"}}' ``` SDK (in-process) [#sdk-in-process] For client-side prototyping: ```typescript import { createAutomationEngine } from "@fluxy-chat/sdk"; const engine = createAutomationEngine(); engine.addRule({ name: "Escalate urgent", trigger: { event: "message.sent", filters: { contains: "urgent" } }, actions: [{ type: "notify", params: { channel: "ops" } }], enabled: true, priority: 1, }); ``` Persist rules via Worker workflows for production. --- # Built with patterns (/docs/guides/built-with-patterns) Built with patterns [#built-with-patterns] Teams on weekend builds reused the same primitives: | Pattern | Example builds | | ---------------------------- | -------------------------------------- | | Agents as room peers | AI War Room, Multiplayer AI, Agentroom | | Agent vs agent negotiation | Altoke, AgentSync, Syncro | | Asymmetric visibility | ReclIA, Cable Rush | | Presence escalation | Aldaba, RestaurantFlow, SAMU | | IoT one channel | Nexora, jikan | | Live audience scoring | OratorIA, Vokaly Prep | | Knowledge / decision graph | Synapse, KUSKA | | Room exposed to external MCP | room (X-TAL) | FluxyChat ships docs and APIs for each row. Start from [Hackathon cookbooks](/docs/guides/hackathon-cookbooks). --- # Card Element Builder (/docs/guides/card-builder) Card Element Builder [#card-element-builder] FluxyChat's card builder lets you compose structured, interactive messages with buttons, tables, images, and sections. Overview [#overview] Cards go beyond plain text and markdown. They enable: * **Interactive buttons** for approvals, quick replies, and form submissions * **Structured layouts** with sections, dividers, and fields * **Tables** with headers and rows * **Images** with captions Element Types [#element-types] | Element | Description | | ------------ | ------------------------------------------------------ | | `Card` | Root container with optional title, subtitle, imageUrl | | `Text` | Text content (plain, bold, or muted) | | `Button` | Interactive button with action ID and optional style | | `LinkButton` | Button that opens a URL | | `Actions` | Horizontal button group container | | `Image` | Image with optional alt text | | `Divider` | Horizontal separator | | `Section` | Grouped content block | | `Field` | Label-value pair | | `Fields` | Grid of field pairs | | `Link` | Inline link with text and URL | | `Table` | Header + rows structured table | Function API [#function-api] ```ts import { Card, Text, Button, Actions, Divider, Section, Table, cardToMarkdown, cardToFallbackText } from "@fluxy-chat/sdk"; const card = Card({ title: "🎉 Welcome!", children: [ Text({ content: "Get started with FluxyChat" }), Divider(), Section({ children: [ Text({ content: "Choose an action:", style: "bold" }), Actions({ children: [ Button({ id: "create-room", label: "Create Room", style: "primary" }), LinkButton({ url: "https://docs.example.com", label: "Read Docs" }), ], }), ], }), ], }); // Render for different platforms const markdown = cardToMarkdown(card); const fallback = cardToFallbackText(card); ``` Fallback Text [#fallback-text] For platforms that can't render cards, `cardToFallbackText()` generates a plain-text representation: ```ts const text = cardToFallbackText(card); // **Title** // Subtitle // Content ``` Markdown Rendering [#markdown-rendering] `cardToMarkdown()` converts a card to markdown format: ```ts const md = cardToMarkdown(card); // # Title // ## Subtitle // Content ``` Type Guard [#type-guard] ```ts import { isCardElement } from "@fluxy-chat/sdk"; if (isCardElement(value)) { // value is CardElement console.log(value.title); } ``` See Also [#see-also] * [Adapter Pattern Guide](/docs/guides/adapter-pattern) — How cards render per platform * [AI Tool Presets Guide](/docs/guides/ai-tool-presets) — Approval gates for card interactions --- # Chat SDK adapter (/docs/guides/chat-sdk-adapter) Chat SDK adapter [#chat-sdk-adapter] Vercel Chat SDK lists **official** adapters under `@chat-adapter/*` and **vendor-official** adapters from the platform vendor. FluxyChat ships `chat-adapter-fluxychat` as a **community** package. `chat` is an optional peer; the factory still compiles without importing it. This is not a listing on chat-sdk.dev until a PR lands in [vercel/chat `apps/docs/adapters.json`](https://github.com/vercel/chat). Copy [`listing/adapters.entry.json`](https://github.com/AlessandroFare/fluxychat/blob/main/packages/chat-adapter-fluxychat/listing/adapters.entry.json) into that file. Pin `readme` to a commit SHA or tag. Publish `chat-adapter-fluxychat` to npm first. Liveblocks is vendor-official; we do not claim that tier. Capability list: [`PERMISSIONS.md`](https://github.com/AlessandroFare/fluxychat/blob/main/packages/chat-adapter-fluxychat/PERMISSIONS.md). Unsigned URL-loaded adapters are out. Install [#install] ```bash pnpm add chat-adapter-fluxychat @fluxy-chat/sdk ``` Thread ids look like `fluxychat:{roomId}`. `listThreads` maps `listRooms()` onto those ids. Still duck-typed: we do not import the `chat` package. ```ts import { createFluxyChatSdkAdapter, parseFluxyChatThreadId } from "chat-adapter-fluxychat"; const adapter = createFluxyChatSdkAdapter({ workerUrl: process.env.FLUXYCHAT_WORKER_URL!, token: process.env.FLUXYCHAT_BOT_JWT!, userId: "bot_support", }); const { roomId } = parseFluxyChatThreadId("fluxychat:deal-42"); await adapter.postMessage(`fluxychat:${roomId}`, "Hello from Chat SDK"); ``` State for `useChat` on Cloudflare still lives in the **room Durable Object + D1**, not in Redis. See [stream resumption](/docs/guides/stream-resumption). What this is not [#what-this-is-not] * Not an official `@chat-adapter/fluxychat` package * Not a replacement for [`FluxyRoomChatTransport`](/docs/guides/vercel-ai-sdk-chat-transport) (AI SDK UI transport) * Not listed until Vercel merges the catalog PR --- # Chat Singleton for Thread Deserialization (/docs/guides/chat-singleton) Chat Singleton for Thread Deserialization [#chat-singleton-for-thread-deserialization] FluxyChat's chat singleton provides a global registry so that `ThreadRef.fromJSON()` can resolve adapters without an explicit `Chat` instance being passed through every call. Overview [#overview] When serialized threads are stored in D1, KV, or passed through workflow engines, deserializing them back into usable `ThreadRef` objects requires access to the adapter registry. The singleton pattern avoids threading a `Chat` instance through every serialization boundary. **Source:** `apps/worker/src/lib/chat-singleton.js` Registration [#registration] Register a Chat instance at application startup. The first registered instance becomes the default. ```js import { registerChatInstance } from "@fluxy-chat/sdk"; // During worker initialization const api = createChatApi({ env, db, roomStub }); registerChatInstance("default", api); // Or register multiple instances (e.g., multi-tenant) registerChatInstance("project-123", projectApi); registerChatInstance("project-456", otherProjectApi); ``` Resolution [#resolution] Resolve an adapter [#resolve-an-adapter] ```js import { resolveAdapter } from "@fluxy-chat/sdk"; // Uses the default instance const slack = resolveAdapter("slack"); await slack.postMessage(threadId, "Hello!"); ``` Get a specific instance [#get-a-specific-instance] ```js import { getChatInstance } from "@fluxy-chat/sdk"; const api = getChatInstance("project-123"); const thread = api.thread("slack\:C123:1234567890.123456"); ``` Get the default instance [#get-the-default-instance] ```js import { getChatInstance } from "@fluxy-chat/sdk"; const api = getChatInstance(); // no name → default instance ``` Introspection [#introspection] ```js import { hasChatInstance, listChatInstances, getDefaultChatInstanceName, } from "@fluxy-chat/sdk"; console.log(hasChatInstance()); // true console.log(listChatInstances()); // ["default", "project-123"] console.log(getDefaultChatInstanceName()); // "default" ``` Changing the Default [#changing-the-default] ```js import { setDefaultChatInstance } from "@fluxy-chat/sdk"; // Switch the default to a different instance setDefaultChatInstance("project-456"); ``` Cleanup [#cleanup] ```js import { unregisterChatInstance, clearChatInstances } from "@fluxy-chat/sdk"; // Remove one instance unregisterChatInstance("project-123"); // If it was the default, the next remaining instance becomes default // Clear all (useful in tests) clearChatInstances(); ``` Use Case: D1 Round-Trip with Reviver [#use-case-d1-round-trip-with-reviver] The singleton enables the `reviver()` to deserialize threads from JSON stored in D1: ```js import { registerChatInstance, parseChatJSON } from "@fluxy-chat/sdk"; // 1. Register at startup registerChatInstance("default", createChatApi({ env, db })); // 2. Store a thread in D1 const thread = chat.thread("slack\:C123:1234567890.123456"); await db.prepare("INSERT INTO workflow_state (id, data) VALUES (?, ?)") .bind("wf-1", JSON.stringify(thread)) .run(); // 3. Retrieve and deserialize — no explicit Chat instance needed const row = await db.prepare("SELECT data FROM workflow_state WHERE id = ?").bind("wf-1").first(); const data = parseChatJSON(row.data); // data is a ThreadRef with adapterSlug resolved via the singleton ``` Multi-Tenant Pattern [#multi-tenant-pattern] For multi-tenant deployments, register one instance per project: ```js // On each request, set the default to the current project setDefaultChatInstance(`project-${request.projectId}`); // Now all singleton calls resolve to this project's adapters ``` See Also [#see-also] * [Unified Chat API](/docs/guides/unified-chat-api) — `chat.thread()`, `chat.openDM()`, `chat.getUser()` * [Postable Objects](/docs/guides/postable-objects) — Objects that can be posted to threads --- # Cloudflare Agents in a FluxyChat room (/docs/guides/cloudflare-agents-room) Cloudflare Agents put the **agent** in a Durable Object. FluxyChat puts **humans and invokeAgent** on a **room** Durable Object. Use both: keep your `AIChatAgent` for one-to-one tool loops, join the room as a user so other people see the same timeline. ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; export async function joinRoomFromCloudflareAgent(opts: { workerUrl: string; token: string; userId: string; roomId: string; }) { const client = new FluxyChatClient({ baseUrl: opts.workerUrl, userId: opts.userId, token: opts.token, }); client.connect(opts.roomId); return client; } ``` `packages/cloudflare-agents` re-exports this helper. It does not wrap `@cloudflare/ai-chat`. You still write the Agent class. Do not rebase the Room DO onto the Agents SDK. --- # Community decision simulation (/docs/guides/community-decision-simulation) Community decision simulation [#community-decision-simulation] KUSKA-style flow: the room proposes options, humans ack or vote, and optional graph extraction shows how arguments relate. This is **not** predictive ML. It is structured deliberation with audit. Building blocks [#building-blocks] | Piece | Guide | | ------------------------------ | ----------------------------------------------------------------------------------------------- | | N-of-M ack before risky action | [Critical action quorum](/docs/guides/critical-action-quorum) | | Live knowledge graph | Room `POST /rooms/:id/kg/extract` + [Room intelligence panel](/docs/guides/hackathon-cookbooks) | | Polls | SDK `createPoll` / `votePoll` on the same room | Demo flow [#demo-flow] 1. Post a decision proposal with `createDecision` (requires admin/owner acks). 2. Let members discuss in the open channel; agents broadcast summaries to the room. 3. Trigger graph extract after N messages to surface claims and contradictions. 4. Close with poll or quorum execute when threshold is met. Dashboard [#dashboard] Use **Rooms → Critical action quorum** and **Room intelligence** on the same room. Opt-out [#opt-out] Tenants can disable AI graph/memory extract via existing knowledge-graph and LLM policy flags. --- # Concurrency Strategies (/docs/guides/concurrency-strategies) Concurrency Strategies [#concurrency-strategies] `createConcurrencyStrategy()` provides 5 strategies for controlling concurrent execution of handlers (e.g., message sending, API calls) with queueing, debouncing, and burst support. Usage [#usage] ```ts import { createConcurrencyStrategy } from "@fluxy-chat/sdk"; const s = createConcurrencyStrategy({ strategy: "queue", maxQueueSize: 3 }); await s.enqueue("key1", async () => { // handler runs when it reaches the front of the queue return "done"; }); ``` Strategies [#strategies] | Strategy | Behavior | Best for | | ------------ | -------------------------------------------------------- | ------------------------------------- | | `concurrent` | Runs all handlers immediately, no limits | Idempotent, lightweight ops | | `drop` | Runs if idle, returns null if busy | Fire-and-forget with backpressure | | `queue` | Serial execution (FIFO), max 1 active | Ordered operations, rate-limited APIs | | `debounce` | Waits `debounceMs` of inactivity, then runs last handler | Search-as-you-type, save-on-change | | `burst` | Up to `maxConcurrent` handlers in parallel, queues rest | Batch processing with concurrency cap | Configuration [#configuration] ```ts interface ConcurrencyConfig { strategy: "concurrent" | "drop" | "queue" | "debounce" | "burst"; debounceMs?: number; // default 1500 (debounce only) maxConcurrent?: number; // default Infinity (burst only) maxQueueSize?: number; // default 10 (queue, burst) onQueueFull?: "drop-oldest" | "drop-newest"; // default "drop-oldest" queueEntryTtlMs?: number; // default 90000 (queue, burst) } ``` Queue Overflow [#queue-overflow] When the queue reaches `maxQueueSize`: * `drop-oldest`: removes the oldest queued entry (rejected with "Queue full — dropped oldest") and enqueues the new one * `drop-newest`: immediately rejects the new entry with "Queue full" Example: Debounced Search [#example-debounced-search] ```ts const search = createConcurrencyStrategy({ strategy: "debounce", debounceMs: 300 }); inputEl.addEventListener("input", () => { search.enqueue(inputEl.value, async () => { const results = await fetchSearch(inputEl.value); renderResults(results); }); }); ``` Example: Rate-Limited Upload [#example-rate-limited-upload] ```ts const uploader = createConcurrencyStrategy({ strategy: "queue", maxQueueSize: 5, onQueueFull: "drop-newest", }); files.forEach(file => { uploader.enqueue(file.name, () => uploadFile(file)); }); ``` Draining [#draining] `drain()` cancels all pending operations and resets the strategy to idle: ```ts await s.drain(); // resolves when active operations complete ``` --- # Audience score template (/docs/guides/cookbook-audience-score) Live audience scorecard [#live-audience-scorecard] Use stream reactions plus the server rollup endpoint: ```http GET /rooms/:roomId/audience-score?windowMinutes=15 ``` Or tally client-side on the last N messages: ```ts const score = messages .slice(-20) .reduce((sum, m) => sum + (m.reactions?.["👍"] ?? 0), 0); ``` For stream rooms, wire **Stream → Reactions** webhooks to a room `server_event` and let an agent post periodic score summaries to the channel. Pair with [Agent room broadcast](/docs/guides/agent-room-broadcast). --- # Fleet dispatch template (/docs/guides/cookbook-fleet-dispatch) Emergency / fleet dispatch demo [#emergency--fleet-dispatch-demo] Use **Fleet** vertical plus room coordination. 1. Create ops room `dispatch-central`. 2. Subscribe to GPS updates via FluxyFleet webhooks. 3. Fan out `location_update` events to the room WebSocket (built into Room DO). 4. Agents or humans ack assignments with [Critical action quorum](/docs/guides/critical-action-quorum). Dashboard: **Fleet** page for map view; room timeline for voice-style coordination. --- # Interview eval template (/docs/guides/cookbook-interview-eval) Interview eval template [#interview-eval-template] Candidate and evaluators share one live room. AI analysis stays on `role:evaluator` messages. Setup [#setup] 1. Create room `interview-{candidateId}`. 2. Add candidate as `member` or `guest`. 3. Add evaluators and AI agent with `room_members.role = evaluator`. Agent posts evaluator-only notes [#agent-posts-evaluator-only-notes] ```ts await client.createMessage(roomId, analysis, { visibility: "role:evaluator", }); ``` Candidate view [#candidate-view] Candidate JWT timeline shows public questions only. Evaluator dashboard shows public plus role-scoped notes. Docs [#docs] [Role-scoped visibility](/docs/guides/role-scoped-visibility) · [Room as MCP server](/docs/guides/room-as-mcp-server) for external Claude evaluator. --- # IoT telemetry starter (/docs/guides/cookbook-iot-telemetry) IoT telemetry [#iot-telemetry] Do **not** use MQTT. Post HTTP, listen on the room WebSocket. ```bash npx @fluxy-chat/create-fluxy-chat@latest my-iot --example iot-panel ``` ```bash curl -X POST "$WORKER/rooms/$ROOM/iot/events" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"deviceId":"sim-1","eventType":"telemetry","payload":{"temp":21}}' ``` ```tsx useChat({ roomId, onServerEvent: (ev) => { if (ev.name === "iot.reading") console.log(ev.data); }, }); ``` See [IoT](/docs/platform/iot). --- # Presence knock template (/docs/guides/cookbook-presence-knock) Presence knock template [#presence-knock-template] Agent waits for tier-1 human; cron nudges the next **online** person in the chain. ```http POST /rooms/support/presence-escalation ``` ```json { "escalationChain": ["on_call_l1", "on_call_l2", "duty_manager"], "nudgeIntervalSeconds": 180 } ``` When `on_call_l1` is offline but `on_call_l2` is in the room WebSocket presence set, the nudge targets L2. See [Presence-aware escalation](/docs/guides/presence-escalation). --- # Collaborative Editing (CRDT) (/docs/guides/crdt) Collaborative Editing (CRDT) [#collaborative-editing-crdt] Operation-based CRDT for shared document editing. ```ts import { createCrdt } from "@fluxy-chat/sdk"; ``` Document Operations [#document-operations] ```ts const crdt = createCrdt(); crdt.createDocument("doc-1", "hello"); crdt.applyOperation("doc-1", { userId: "u1", type: "insert", position: 5, value: " world" }); crdt.applyOperation("doc-1", { userId: "u1", type: "delete", position: 0, length: 1 }); ``` Snapshots & Merging [#snapshots--merging] ```ts const snap = crdt.createSnapshot("doc-1"); crdt.applySnapshot(snap); const applied = crdt.merge("doc-1", remoteOps); // idempotent merge ``` Awareness [#awareness] ```ts crdt.setAwareness("doc-1", { userId: "u1", cursorPosition: 3, lastActive: new Date().toISOString() }); const users = crdt.getAwareness("doc-1"); ``` --- # create-fluxy-chat CLI (/docs/guides/create-fluxy-chat) Always: ```bash npx @fluxy-chat/create-fluxy-chat@latest ``` Unscoped `npx create-fluxy-chat` is not our package. Chat app (what most people want) [#chat-app-what-most-people-want] ```bash # Hosted — Clerk, no wrangler npx @fluxy-chat/create-fluxy-chat@latest my-app --mode hosted -y # Your Worker npx @fluxy-chat/create-fluxy-chat@latest my-app --full --mode self-host ``` Then `cd my-app && pnpm install`. * Hosted: `pnpm setup:hosted && pnpm dev` * Self-host: start the Worker, then `pnpm setup:local && pnpm dev` The interactive CLI asks for Worker URL and optional Groq key when you pick self-host. It writes `.fluxy/worker.dev.vars` so you can paste secrets into `apps/worker/.dev.vars` after you clone the FluxyChat repo. Details: [Choose your path](/docs/getting-started/choose-your-path). Smaller templates [#smaller-templates] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-chat --template react npx @fluxy-chat/create-fluxy-chat@latest my-chat --minimal npx @fluxy-chat/create-fluxy-chat@latest my-hr --template hr-feedback npx @fluxy-chat/create-fluxy-chat@latest my-room --example shared-ai-room ``` React/minimal: copy `.env.example` and set Worker URL + JWT. [Auth JWT](/docs/guides/auth-jwt). Bot workers (Slack / Telegram / Discord) [#bot-workers-slack--telegram--discord] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-bot --adapter slack --pm pnpm npx @fluxy-chat/create-fluxy-chat@latest my-bot --adapter telegram --skip-install npx @fluxy-chat/create-fluxy-chat@latest my-bot -y --adapter discord npx @fluxy-chat/create-fluxy-chat@latest my-bot --adapter basic ``` These generate a small Cloudflare Worker (`src/index.ts`, `src/bot.ts`, `wrangler.toml`, `.dev.vars`). Fill `FLUXY_BASE_URL` and `FLUXY_API_KEY`, then `pnpm dev` / `pnpm deploy`. | Flag | Meaning | | ------------------------------------- | ----------------------------------------------------------------------------------------- | | `--mode hosted \| local \| self-host` | `self-host` is the same as `local` (your Worker) | | `--full` | Vite app + setup scripts | | `--adapter` / `--template` | `full`, `react`, `minimal`, `hr-feedback`, `basic`, `slack`, `telegram`, `discord`, `web` | | `-y` | Skip prompts | See also: [Unified chat API](/docs/guides/unified-chat-api), [SDK](/docs/packages/sdk). --- # Critical action quorum (/docs/guides/critical-action-quorum) Critical action quorum [#critical-action-quorum] Use **message decisions**: a room message that stays `pending` until enough role acks arrive (StrixX / Cable Rush pattern). Create with a message [#create-with-a-message] ```http POST /messages ``` ```json { "roomId": "ops", "content": "Approve production deploy v2.4.1?", "decision": { "content": "Deploy v2.4.1 to production", "requiredRoles": [ { "role": "admin", "count": 2 }, { "role": "owner", "count": 1 } ], "ttlSeconds": 3600 } } ``` Ack [#ack] ```http POST /messages/{messageId}/ack Authorization: Bearer ``` Each eligible member acks once. When quorum is met, state becomes `decided` and fans out on the room WebSocket. Timeout [#timeout] Cron expires pending decisions past TTL as `expired_no_quorum`. SDK [#sdk] Poll `GET /messages/{id}/decision` for progress arrays (`required`, `current`, `ackedBy`). --- # Cross-channel identity and journey (/docs/guides/cross-channel-identity) Unify the same user across **web, mobile, WhatsApp, SMS, voice, email, Slack, and Discord** with identity binding, profile merge, and journey history stored in CDP. Configure from [**Customers**](/customers) (Cross-channel section) or the admin API. Bind channel identity [#bind-channel-identity] Link a channel-specific user ID to a CDP customer profile: ```bash curl -X POST "$WORKER_URL/admin/cross-channel/bindings" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "customerId": "cp_abc123", "channel": "whatsapp", "channelUserId": "+15551234567" }' ``` Supported channels: `web`, `mobile`, `whatsapp`, `sms`, `voice`, `email`, `slack`, `discord`. Merge duplicate profiles [#merge-duplicate-profiles] ```bash curl -X POST "$WORKER_URL/admin/cross-channel/merge" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "primaryCustomerId": "cp_primary", "secondaryCustomerId": "cp_secondary" }' ``` Bindings and journey events from the secondary profile are moved to the primary. Journey history [#journey-history] Record and list touchpoints: ```bash curl -X POST "$WORKER_URL/admin/cross-channel/journey" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "customerId": "cp_abc123", "channel": "web", "step": "checkout_started", "metadata": {"cartValue": 99} }' curl "$WORKER_URL/admin/cross-channel/journey?customerId=cp_abc123" \ -H "Authorization: Bearer $ADMIN_JWT" ``` Unified customer view [#unified-customer-view] ```bash curl "$WORKER_URL/admin/cross-channel/customers/cp_abc123" \ -H "Authorization: Bearer $ADMIN_JWT" ``` Returns profile, bindings, journey, and linked channels. Related [#related] * [Customer data layer](/docs/guides/customer-data-segments) * [Slack/Discord bridge](/docs/guides/slack-discord-bridge) * Dashboard SDK demo: [**Cross-Channel**](/cross-channel) --- # Cross-org agent negotiation (/docs/guides/cross-org-negotiation) Cross-org agent negotiation [#cross-org-agent-negotiation] Use cross-org rooms and commitments for Altoke / AgentSync-style flows. Humans approve each round before agents continue. Create a cross-org room [#create-a-cross-org-room] ```http POST /cross-org/rooms ``` Body includes `orgAId`, `orgBId`, agent ids, and `maxRounds`. Propose terms [#propose-terms] ```http POST /cross-org/rooms/{id}/commitments ``` ```json { "terms": { "price": 1200, "currency": "USD", "deliveryDays": 14 }, "ttlSeconds": 86400 } ``` Counter or approve [#counter-or-approve] * `POST /cross-org/commitments/{id}/counter` with new `terms` * `POST /cross-org/commitments/{id}/confirm` from each org human States: `proposed` → `countered` → `awaiting_human_a` / `awaiting_human_b` → `approved` or `expired`. Dashboard [#dashboard] Try **Agents → Cross-org** and **Agents → A2A** in the console for live negotiation UI. Room timeline [#room-timeline] Commitment events fan out as room messages so both sides see the same negotiation stream. --- # Customer data layer and segments (/docs/guides/customer-data-segments) FluxyChat includes a **Customer Data Platform (CDP)** for profiles, events, and segments, plus a **broadcast segmentation** engine for targeted in-app campaigns. Manage everything from the dashboard [**Customers**](/customers) page or the REST APIs below. Customer profiles [#customer-profiles] Upsert a profile by external ID (your CRM user ID, auth subject, etc.): ```bash curl -X POST "$WORKER_URL/api/cdp/customers" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "externalId": "user_123", "email": "alex@example.com", "name": "Alex", "lifecycleStage": "customer" }' ``` List and search: ```bash curl "$WORKER_URL/api/cdp/customers?search=alex&limit=25" \ -H "Authorization: Bearer $ADMIN_JWT" ``` Track events: ```bash curl -X POST "$WORKER_URL/api/cdp/events" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "customerId": "cp_abc123", "eventType": "product", "eventName": "page_view", "properties": { "path": "/pricing" } }' ``` Segments [#segments] Create a CDP segment and add members: ```bash curl -X POST "$WORKER_URL/api/cdp/segments" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{"name":"Trial users","segmentType":"static"}' curl -X POST "$WORKER_URL/api/cdp/segments/csg_abc/members" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{"customerId":"cp_abc123"}' ``` Broadcast campaigns [#broadcast-campaigns] Use `/broadcast/*` for campaign lifecycle (draft → sending → sent): ```bash # Create segment curl -X POST "$WORKER_URL/broadcast/segments" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{"name":"Active users","segmentType":"dynamic"}' # Create campaign curl -X POST "$WORKER_URL/broadcast/campaigns" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "name":"Product update", "segmentId":"", "messageTemplate":"Hello {{name}}, check out the new feature!", "channel":"in_app" }' # Send curl -X POST "$WORKER_URL/broadcast/campaigns//send" \ -H "Authorization: Bearer $ADMIN_JWT" ``` Channels: `in_app`, `push`, `email`, `webhook`. Stats [#stats] ```bash curl "$WORKER_URL/api/cdp/stats" -H "Authorization: Bearer $ADMIN_JWT" curl "$WORKER_URL/broadcast/stats/" -H "Authorization: Bearer $ADMIN_JWT" ``` See also [Broadcast campaigns guide](/docs/guides/announcement-channels) for delivery tracking. --- # Decision Rooms (/docs/guides/decision-rooms) Decision Rooms bundle workflows you already have in FluxyChat. No extra tables. You get a group room, starter templates, and links into the console tools below. What's included [#whats-included] | Feature | Console path | Purpose | | ---------------------- | --------------------------- | ------------------------------------------ | | Async quorum decisions | Room chat + `/decisions` UI | Propose, vote by role, close the decision | | Multi-agent debate | `/agents/debate` | Technical, business, and risk perspectives | | Counterfactual replay | `/agents/observability` | Branch agent runs with different inputs | | Truth Market | `/truth-market` | Stake and dispute claims | Create from the dashboard [#create-from-the-dashboard] 1. Open **Rooms** (`/rooms`). 2. Enter a display name (optional; default is "Decision Room"). 3. Click **Create Decision Room** (admin JWT required). The pack creates a `group` room, adds you as owner, seeds three templates, and posts a welcome message with links to the workflows above. API [#api] | Method | Path | Description | | ------ | ----------------------- | ---------------------------------- | | GET | `/packs/decision-rooms` | Preview pack metadata (public) | | POST | `/packs/decision-rooms` | Provision room and templates (JWT) | ```json POST /packs/decision-rooms { "name": "Q3 Planning" } ``` The response includes `room.id`, `templatesCreated`, and `features[]` with deep-link paths. Message templates [#message-templates] Templates use `{{variable}}` placeholders. Fill them from the template picker in chat: * **Decision proposal**: `question`, `options`, `quorum` * **Debate kickoff**: `topic`, `constraints` * **Truth claim**: `claim`, `stake` Related [#related] * [Async decisions](/docs/features/async-decisions) * [Agent debate](/docs/features/agent-debate) * [Truth Market](/docs/features/truth-market) * [Agent tool policy](/docs/reference/agent-tool-policy) --- # Durable AI sessions (/docs/guides/durable-ai-sessions) Use `createResumableAgentStream()` when an AI agent stream must survive tab refreshes, brief network drops, or switching devices. The SDK keeps chunk offsets in a local durable transport; optionally sync chunks to the Worker for cross-device resume. Quick start [#quick-start] ```typescript import { createResumableAgentStream } from "@fluxy-chat/sdk"; const stream = createResumableAgentStream({ deviceId: "mobile-abc", metadata: { roomId: "room_1", agentId: "support-bot" }, }); await stream.appendText("Hello "); await stream.appendText("world"); const { missedChunks, offset } = await stream.reconnect(); for (const chunk of missedChunks) { process.stdout.write(chunk.data); } stream.close(); ``` Resume an existing session [#resume-an-existing-session] Pass `sessionId` and `lastKnownOffset` after reconnecting: ```typescript const stream = createResumableAgentStream({ deviceId: "desktop-xyz", sessionId: savedSessionId, lastKnownOffset: savedOffset, }); ``` Worker-backed continuity [#worker-backed-continuity] When `worker` is set, each `appendText` POSTs to `/ai/streams/:streamId/chunk` and `reconnect()` GETs `/ai/streams/:streamId/resume`: ```typescript const stream = createResumableAgentStream({ deviceId: "web-client", worker: { baseUrl: process.env.FLUXY_WORKER_URL!, token: adminJwt, streamId: runId, // optional — defaults to sessionId }, }); ``` Active streams in a room [#active-streams-in-a-room] ```typescript const res = await fetch( `${workerUrl}/ai/streams/active?roomId=${encodeURIComponent(roomId)}`, { headers: { Authorization: `Bearer ${token}` } }, ); const { streams } = await res.json(); ``` Requires `RATE_LIMIT_KV` or `STREAM_RESUME_KV` on the Worker. Relationship to other APIs [#relationship-to-other-apis] | API | Use when | | ------------------------------ | --------------------------------------------------- | | `createDurableTransport()` | Low-level chunk store and offset math | | `createResumableAgentStream()` | Agent UI with optional Worker sync | | `useChat` + `resumeStream()` | Built-in chat hook stream resumption over WebSocket | See also [Durable AI Transport](/docs/guides/durable-transport) and [Stream Resumption](/docs/guides/stream-resumption). --- # Durable AI Transport (/docs/guides/durable-transport) Durable AI Transport [#durable-ai-transport] Durable sessions survive disconnects and device switches. ```ts import { createDurableTransport } from "@fluxy-chat/sdk"; ``` Session Lifecycle [#session-lifecycle] ```ts const transport = createDurableTransport({ maxChunks: 5000, ttlMs: 1800000 }); // Create session const session = transport.createSession("device-1", { userId: "u1" }); // Append stream chunks transport.appendChunk(session.id, "token1"); transport.appendChunk(session.id, "token2"); // Reconnect with offset recovery const result = transport.reconnect(session.id, "device-2", 1); // result.missedChunks contains chunks after offset 1 // result.liveStream is true if session is still active // Close session when done transport.closeSession(session.id); ``` Cleanup [#cleanup] ```ts // Remove sessions older than ttlMs const removed = transport.cleanup(); ``` --- # Ephemeral Messages (/docs/guides/ephemeral-messages) Ephemeral Messages [#ephemeral-messages] `postEphemeral()` sends a message visible only to a specific user with automatic DM fallback when the platform doesn't support native ephemeral messages. Usage [#usage] ```ts import { postEphemeral } from "@fluxy-chat/sdk"; const result = await postEphemeral(adapter, "thread\:abc", "user:123", "Hello only you can see"); if (result) { console.log(result.usedFallback ? "Sent via DM" : "Sent natively"); } ``` How It Works [#how-it-works] 1. If the adapter provides `postEphemeral()` — sends natively (e.g., Slack `chat.postEphemeral`) 2. If not, and `fallbackToDM` isn't `false` — opens a DM via `adapter.openDM()` and posts there 3. If neither is available — returns `null` Options [#options] ```ts interface PostEphemeralOptions { fallbackToDM?: boolean; // default true } ``` Result [#result] ```ts interface EphemeralMessage { id: string; threadId: string; usedFallback: boolean; // true if sent via DM fallback } ``` Platform Support [#platform-support] | Platform | Native | Fallback | | ----------- | ------ | -------- | | Slack | ✅ | DM | | Google Chat | ✅ | DM | | Discord | ❌ | DM | | Teams | ❌ | DM | Adapter Integration [#adapter-integration] Implement `postEphemeral` and `openDM` on your adapter for platform-native support: ```ts const adapter: ThreadAdapter = { // ...other methods async postEphemeral(threadId, userId, content) { // Platform-specific ephemeral API return { id: result.id, threadId }; }, async openDM(userId) { // Open or create DM conversation return dmThreadId; }, }; ``` --- # External event ingest (/docs/guides/external-event-ingest) External event ingest [#external-event-ingest] Push external signals into a room so agents debate live (Agentroom pattern). Option A: announce server event [#option-a-announce-server-event] ```http POST /rooms/{roomId}/events Authorization: Bearer ``` ```json { "name": "external.incident", "data": { "source": "usgs", "magnitude": 4.2, "region": "CA-North" } } ``` Fans out as `server_event` on the room WebSocket. Option B: automation webhook [#option-b-automation-webhook] Configure a project webhook → automation rule that calls `fanoutRoomInternal` or triggers an ambient agent on `external.incident`. Ambient policy example [#ambient-policy-example] In agent ambient settings, map `external.incident` to invoke debate roles with the event payload in context. Dashboard simulate [#dashboard-simulate] Use **Automations** webhook playground to POST a sample payload and watch the room timeline update. Entity rooms (Linear/GitHub/PagerDuty/… HMAC → linked room): [Integration kit](/docs/guides/integration-kit). --- # External generation into a room (/docs/guides/external-generation-room) External generation into a room [#external-generation-into-a-room] FluxyChat’s Agent Durable Object is one loop. If **your** Inngest / Trigger.dev / Workflows function already generated the answer, do not also `invokeAgent` for that turn. Post the finished string onto chat with a **member JWT** for the bot user (the bot must already be in the room). ```ts import { publishExternalGenerationToRoom } from "@fluxy-chat/sdk"; await publishExternalGenerationToRoom({ workerUrl: process.env.FLUXY_WORKER_URL!, token: process.env.FLUXY_BOT_JWT!, roomId: "lobby", content: textYouAlreadyGenerated, }); ``` This is `POST /messages`. If your job is still yielding strings, `publishExternalGenerationChunksToRoom` creates one row then `PATCH`es it. Room sockets see those edits. The Agent Durable Object stays out of that turn. Keep traces on **feeds**. Hosted is beta — this is not Think resume and not an Inngest product we run. ```ts import { publishExternalGenerationChunksToRoom } from "@fluxy-chat/sdk"; await publishExternalGenerationChunksToRoom({ workerUrl: process.env.FLUXY_WORKER_URL!, token: process.env.FLUXY_BOT_JWT!, roomId: "lobby", chunks: streamOfStringsFromYourJob, }); ``` Hosted is beta. --- # Feature parity checklist (/docs/guides/feature-parity-checklist) Use this when you are mapping from Pusher, Ably, or a custom WebSocket. Core (ship this first) [#core-ship-this-first] * Rooms (public / private) and member JWTs * Realtime messages over WebSocket * REST send + history * Presence and typing (when enabled on the Worker) * Inbox / unread (`useInbox`) * In-room agents (`@assistant`) with Groq/OpenAI on the Worker Hosted vs self-host [#hosted-vs-self-host] | | Hosted | Self-host | | ------ | ------------------------------ | -------------------------------------------- | | Worker | `https://api.fluxychat.com` | Your `workers.dev` or custom domain | | Auth | Clerk in the CLI full template | Your backend mints JWTs (`POST /auth/token`) | | Agents | Same Worker APIs | Same, plus your LLM keys in `.dev.vars` | Not the JS CLI [#not-the-js-cli] Native SDKs (Kotlin, Swift, Flutter, Unity, .NET) live in the repo, not on npm. Vue/Svelte packages are not part of `--full`. Next: [Migrate from Pusher](/docs/guides/migrate-from-pusher), [create-fluxy-chat](/docs/guides/create-fluxy-chat). --- # fluxy.config.ts (/docs/guides/fluxy-config) Use `@fluxy-chat/config` to declare per-room authorization, publish middleware, and client defaults — similar to a `next.config` for your chat deployment. Example [#example] ```typescript import { defineConfig, allow, block, defineMiddleware, allowPublish, blockPublish, } from "@fluxy-chat/config"; const moderate = defineMiddleware("publish", (ctx) => { if (ctx.capabilities.publish === false) { return blockPublish("You do not have permission to post."); } return allowPublish(); }); export default defineConfig({ workerUrl: process.env.FLUXY_WORKER_URL, client: { readOn: "visible", wsCache: "on", historyLimit: 50, }, rooms: { "support-*": { anonymous: false, authz: (ctx) => ctx.anonymous ? block("Sign in to contact support.") : allow({ publish: true }), onPublish: [moderate.handler], }, "room-*": { anonymous: true, authz: () => allow({ publish: true, invokeAgent: true }), onPublish: [moderate.handler], }, }, }); ``` Copy from `packages/config/fluxy.config.example.ts` in the monorepo. `agents` on the same object: `mention`, `tools`, `dailyTokenCap`, `onBehalfOf`. `resolveAgentPolicy(config, agentId)` picks an exact id then `*`. Worker `POST /agents/:id/invoke` returns 403 when `mention: false`. `jurisdiction: "eu"` is for **self-host**. It does not move hosted Cloud. Run `node apps/worker/scripts/apply-do-jurisdiction.mjs --write` to copy that hint onto every `[[durable_objects.bindings]]` as `jurisdiction = "eu"`. D1 stays whatever region you created in the Cloudflare dashboard. Hosted has no project toggle that rewrites Wrangler. Room patterns [#room-patterns] | Pattern | Use case | | ------------- | ----------------------------------- | | `support-*` | Authenticated support rooms | | `room-*` | Public demo rooms with agent invoke | | Exact room id | Override for a single channel | Middleware [#middleware] `defineMiddleware("publish", handler)` runs before messages are accepted. Return `blockPublish(reason)` to reject with a user-visible error, or `allowPublish()` to continue. Worker integration [#worker-integration] The Worker reads `fluxy.config.js` (compiled from TypeScript) on self-host. **Hosted overlay (no forked Worker):** `GET`/`PUT /admin/projects/:id/publish-config` stores deny-substrings, `guestCanPublish`, `iotAutoAgentId`, and **`rooms`** (anonymous, per-room deny, capabilities, extension slots). `pnpm fluxy:deploy` uploads `fluxy.hosted.json`. The publish pipeline runs file `onPublish` first, then these D1 rules. Put an agent handle in `iotAutoAgentId` to `invokeAgent` on each `iot.reading` without an `@mention`. Room extension snapshots: `client.getRoomExtensions(roomId)` / `setRoomExtension(roomId, id, { kind: "kv", data })`. Hosted slots are declared kinds (`kv` | `counter`), not eval. Related [#related] * [Auth JWT](/docs/guides/auth-jwt) * [Self-host one command](/docs/guides/self-host-one-command) * [Room Decisions](/docs/guides/room-decisions) --- # FluxyEdu quickstart (/docs/guides/fluxy-edu-quickstart) FluxyEdu quickstart [#fluxyedu-quickstart] Run a **testable classroom workflow** from the dashboard or SDK. This guide uses deterministic demo seeds — not production persistence. Dashboard [#dashboard] 1. Open **[Education studio](/edu)** from the console sidebar (Industries → Education). 2. Click **Start live class** to begin the journey. 3. Use **Advance demo** to step through: * Create classroom / open session * Record attendance heartbeats * Run a knowledge check (idempotent poll) * Assign breakout groups * Review AI grade suggestion (requires educator approval) The activity panel shows **versioned room events** from `createVerticalWorkflow`, not static copy. SDK [#sdk] ```typescript import { createVerticalWorkflow, runVerticalDemoStep, VERTICAL_DEMO_SEEDS, } from "@fluxy-chat/sdk"; const workflow = createVerticalWorkflow(VERTICAL_DEMO_SEEDS.edu); // Step through the demo journey (0–4) for (let step = 0; step < 5; step += 1) { runVerticalDemoStep(workflow, "edu", step); } console.log(workflow.platform.events()); console.log(workflow.activityFeed()); ``` Polls and attendance [#polls-and-attendance] ```typescript workflow.startSession({ id: "teacher_1", type: "user", role: "teacher" }); workflow.recordAttendance("student_1", "student"); const poll = workflow.createKnowledgeCheck("Ready to start?", [ { id: "yes", label: "Yes" }, { id: "no", label: "Not yet" }, ]); workflow.submitPollVote(poll.id, ["yes"], "student_1"); workflow.platform.closePoll(poll.id); ``` Human-in-the-loop grading [#human-in-the-loop-grading] AI suggestions stay in `draft` until a teacher approves: ```typescript const grade = workflow.suggestGrade({ studentId: "student_1", rubricId: "quiz_1", score: 91, feedback: "Clear steps shown.", suggestedBy: "ai", }); workflow.approveGrade(grade.id, "teacher_1"); ``` Readiness [#readiness] | Capability | Status | | ------------------------ | ---------------------------- | | Room + attendance events | Beta (client demo) | | Idempotent polls | Beta (client demo) | | Yjs whiteboard | Adapter — not wired in demo | | Multiparty media (SFU) | Adapter — configure provider | | AI grading publish | Gated — approval required | Production checklist [#production-checklist] Before FERPA/COPPA-sensitive deployments: * Configure retention and consent policies per workspace * Persist events on Worker/DO (see [Self-hosting](/docs/getting-started/self-hosting)) * Wire Yjs whiteboard through your platform adapter * Connect SFU/TURN for live video Related [#related] * [Self-hosting](/docs/getting-started/self-hosting) * [Decision Rooms](/docs/guides/decision-rooms) --- # Gamification (/docs/guides/gamification) Gamification [#gamification] XP, badges, and leaderboard system for chat engagement. Quick Start [#quick-start] ```ts import { createGamification } from "@fluxy-chat/sdk"; const game = createGamification(); ``` XP System [#xp-system] ```ts // Award XP game.awardXp("user-1", 100, "message sent"); game.awardXp("user-1", 50, "login"); // Query console.log(game.getXp("user-1")); // 150 // History const history = game.getHistory("user-1"); // -> [{ userId: "user-1", amount: 100, reason: "message sent", timestamp: "..." }, ...] ``` Badges [#badges] ```ts game.awardBadge("user-1", { id: "first-msg", name: "First Message", description: "Sent your first message" }); game.awardBadge("user-1", { id: "streak-7", name: "Week Streak" }); const badges = game.getBadges("user-1"); // -> [{ id: "first-msg", name: "First Message", ... }, ...] // Duplicate badges are not awarded game.awardBadge("user-1", { id: "first-msg", name: "First Message" }); console.log(game.getBadges("user-1").length); // 2 (still 2, not 3) ``` Leaderboard [#leaderboard] ```ts game.awardXp("user-1", 300, "threads"); game.awardXp("user-2", 500, "messages"); game.awardXp("user-3", 100, "reactions"); const lb = game.getLeaderboard(3); // -> [ // { userId: "user-2", totalXp: 500, badges: 0, rank: 1 }, // { userId: "user-1", totalXp: 300, badges: 2, rank: 2 }, // { userId: "user-3", totalXp: 100, badges: 0, rank: 3 }, // ] ``` Types [#types] * `XpEvent`: `\{ userId, amount, reason, timestamp \}` * `Badge`: `\{ id, name, description?, iconUrl?, awardedAt? \}` * `LeaderboardEntry`: `\{ userId, username?, avatarUrl?, totalXp, badges, rank \}` * `GamificationApi`: interface with `awardXp`, `getXp`, `getHistory`, `awardBadge`, `getBadges`, `getLeaderboard` --- # Generative UI (/docs/guides/generative-ui) Generative UI [#generative-ui] Tool-name-prefixed parts for rendering AI tool results as UI components. Framework-agnostic core with `ComponentRegistry` for mapping tool names to renderers. AG-UI-shaped stream events map through `createAgUiAdapter` in `@fluxy-chat/sdk` (`packages/sdk/src/ag-ui-adapter.ts`). That is an event bridge, not a CopilotKit / LangGraph host. A LangGraph / CrewAI / Pydantic AI process can **join a room** and read the latest stored run: ```bash curl -X POST "$WORKER/ag-ui/join" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"roomId":"deal-1"}' curl "$WORKER/ag-ui/events?roomId=deal-1&stream=1" \ -H "Authorization: Bearer $JWT" ``` `/ag-ui/events` replays `agent_runs` as `RUN_STARTED` / `TOOL_CALL_*` / `RUN_FINISHED`. Live tokens still come from the room WebSocket or Agent DO. Python: `FluxyChatClient.join_ag_ui` / `ag_ui_events`. Parts [#parts] ```ts import { createTextPart, createToolCallPart, createToolResultPart } from "@fluxy-chat/sdk"; const parts = [ createTextPart("The weather is:"), createToolCallPart("getWeather", "call-1", { location: "SF" }), createToolResultPart("getWeather", "call-1", "output-available", { temp: 72 }), ]; ``` Component Registry [#component-registry] ```ts import { createComponentRegistry, renderParts } from "@fluxy-chat/sdk"; const registry = createComponentRegistry(); registry.register("getWeather", { component: { render: (props) => `Weather: ${props.temp}°` }, loadingComponent: { render: () => "Loading..." }, errorComponent: { render: (props) => `Error: ${props.errorText}` }, }); const result = renderParts(parts, registry); // ["The weather is:", "[getWeather loading...]", "Weather: 72°"] ``` Type Guards [#type-guards] ```ts import { isTextPart, isToolPart, isToolCallPart, isToolResultPart } from "@fluxy-chat/sdk"; if (isToolResultPart(part) && part.state === "output-available") { renderComponent(part.toolName, part.output); } ``` --- # Link a guest to an account (/docs/guides/guest-to-account) Someone joined through a public guest session, then signed up. Linking moves their **room memberships** to the account: they keep every room they were in, and the guest role upgrades to `member`. Each guest can be claimed once. How it works [#how-it-works] `POST /tokens/link-guest` — the caller proves two things: 1. **Who they are** — a `Bearer` JWT of the target account (non-guest). 2. **Ownership of the guest** — the guest's own JWT in `guestToken` (guest-only roles, same project). ```bash curl -X POST "$WORKER_URL/tokens/link-guest" \ -H "Authorization: Bearer $MEMBER_JWT" \ -H "Content-Type: application/json" \ -d '{"guestToken": "'"$GUEST_JWT"'"}' ``` Response: ```json { "ok": true, "guestUserId": "guest_0123456789abcdef012345", "targetUserId": "user_ada", "roomsTransferred": 2, "roomsAlreadyMember": 1 } ``` `roomsAlreadyMember` counts rooms the account was already in — the duplicate guest row is dropped and the account's existing role is kept. SDK: ```ts await client.linkGuestAccount(guestJwt); ``` What moves, what stays [#what-moves-what-stays] | Data | After linking | | ------------------------------------------- | ----------------------------------------------------------------- | | Room membership | Moves to the account (`guest` → `member`); owner/admin roles kept | | Message authorship, reactions, read markers | Stays under the guest user id — history is not rewritten | | The guest identity | Recorded once; a second claim returns `409 guest_already_linked` | Errors [#errors] | Status | Error | Meaning | | ------ | ---------------------- | -------------------------------------------------------------- | | `400` | `guest_token_required` | Missing `guestToken` | | `400` | `invalid_guest_token` | Not a valid guest token for this project | | `400` | `target_is_guest` | The caller is itself a guest — sign in first | | `400` | `same_user` | Guest and target are the same identity | | `409` | `guest_already_linked` | Already claimed (response includes the winning `targetUserId`) | Concurrent claims on the same guest are safe: the first one wins and the rest get the `409`. The successful link is written to the project audit log as `guest.linked`. **Boundary:** linking is about access, not history. Past messages keep the guest author id — if you mirror authorship elsewhere (analytics, attribution), map it yourself at link time. --- # Hackathon cookbooks (/docs/guides/hackathon-cookbooks) Hackathon cookbooks [#hackathon-cookbooks] Copy-paste recipes for weekend builds. Each row links to a focused guide. | ID | Pattern | Guide | | ------ | ------------------------------------- | ----------------------------------------------------------------- | | PH-102 | Presence-aware escalation | [Presence escalation](/docs/guides/presence-escalation) | | PH-103 | Two agents negotiate with human gate | [Cross-org negotiation](/docs/guides/cross-org-negotiation) | | PH-104 | Agent broadcasts to the room | [Agent room broadcast](/docs/guides/agent-room-broadcast) | | PH-110 | N-of-M ack before risky action | [Critical action quorum](/docs/guides/critical-action-quorum) | | PH-111 | External webhook → live room | [External event ingest](/docs/guides/external-event-ingest) | | PH-114 | Multi-agent debate roles | [Multi-agent debate](/docs/guides/multi-agent-debate) | | PH-120 | Interview eval (role-scoped AI notes) | [Interview eval template](/docs/guides/cookbook-interview-eval) | | PH-121 | Knock who is online | [Presence knock template](/docs/guides/cookbook-presence-knock) | | PH-122 | IoT telemetry in one channel | [IoT 20-line starter](/docs/guides/cookbook-iot-telemetry) | | PH-123 | Live audience scorecard | [Audience score template](/docs/guides/cookbook-audience-score) | | PH-124 | Fleet / dispatch demo | [Fleet dispatch template](/docs/guides/cookbook-fleet-dispatch) | | PH-112 | Server-side audience rollup | [Audience score API](/docs/guides/audience-score) | | PH-113 | Asymmetric session profiles | [Asymmetric sessions](/docs/guides/asymmetric-sessions) | | PH-130 | Live knowledge graph (reagraph) | [Live knowledge graph](/docs/guides/live-knowledge-graph) | | PH-131 | Community decision simulation | [Decision simulation](/docs/guides/community-decision-simulation) | See also [Room as MCP server](/docs/guides/room-as-mcp-server) and [Role-scoped visibility](/docs/guides/role-scoped-visibility). --- # HarnessAgent — External Agent Runtime Wrapper (/docs/guides/harness-agent) HarnessAgent — External Agent Runtime Wrapper [#harnessagent--external-agent-runtime-wrapper] `HarnessAgent` wraps external agent runtimes (Claude Code, Codex, custom coding agents) behind a unified interface compatible with AI SDK stream types. When to Use [#when-to-use] * You want to invoke an existing agent runtime (Claude Code, Codex) from your application * You need streaming output from an external coding agent * You want session management (create, detach, resume) for long-running agent interactions Basic Usage [#basic-usage] ```ts import { HarnessAgent, type HarnessAdapter } from '@fluxy-chat/agent'; // Create an adapter for your external runtime const myAdapter: HarnessAdapter = { name: 'my-coding-agent', async createSession(sandbox) { return { id: crypto.randomUUID(), async destroy() { /* cleanup */ }, async detach() { return { sessionId: this.id, state: null, createdAt: Date.now() }; }, }; }, async generate(options) { // Call your external agent return { text: 'Agent response', finishReason: 'stop', usage: { inputTokens: 100, outputTokens: 50 }, steps: [], responseMessages: [], }; }, async stream(options) { // Return streaming result from your agent const result = await this.generate(options); return { stream: new ReadableStream({ ... }), result: Promise.resolve(result), text: Promise.resolve(result.text), }; }, }; const agent = new HarnessAgent(myAdapter); const result = await agent.generate({ prompt: 'Refactor the auth module' }); ``` Session Management [#session-management] Create a session for stateful multi-turn interactions: ```ts const session = await agent.createSession(/* sandbox config */); try { const result = await agent.generate({ session, prompt: 'List all files in the project', }); console.log(result.text); // Resume the session for follow-up const followUp = await agent.generate({ session, prompt: 'Now refactor the main entry point', }); } finally { await session.destroy(); } ``` Streaming [#streaming] `stream()` returns a `HarnessStreamResult` with AI SDK-compatible stream parts: ```ts const sr = agent.stream({ prompt: 'Analyze the codebase' }); // Consume the stream const reader = sr.stream.getReader(); for await (const part of /* async iteration */) { if (part.type === 'text-delta') process.stdout.write(part.delta); } // Or get the final result const result = await sr.result; console.log(result.text, result.usage); ``` Adapter Pattern [#adapter-pattern] The `HarnessAdapter` interface lets you wrap any external runtime: ```ts interface HarnessAdapter { readonly name: string; createSession(sandbox?: unknown): Promise; generate(options: { prompt: string; system?: string; tools?: Record; maxSteps?: number; signal?: AbortSignal; session?: HarnessSession; }): Promise; stream(options: { prompt: string; system?: string; tools?: Record; maxSteps?: number; signal?: AbortSignal; session?: HarnessSession; }): Promise; } ``` Type Reference [#type-reference] ```ts class HarnessAgent { readonly adapter: HarnessAdapter; constructor(adapter: HarnessAdapter); createSession(sandbox?: unknown): Promise; generate(options: HarnessGenerateOptions): Promise; stream(options: HarnessStreamOptions): HarnessStreamResult; } interface HarnessSession { readonly id: string; destroy(): Promise; detach(): Promise; } interface HarnessGenerateResult { text: string; reasoningText?: string; finishReason: AIFinishReason; usage: AIUsage; steps: readonly HarnessStepResult[]; responseMessages: readonly HarnessMessage[]; } interface HarnessStreamResult { stream: ReadableStream; result: Promise; text: Promise; } ``` See Also [#see-also] * [Skill Uploads](/docs/guides/skill-uploads) — uploading custom skills to providers * [Subagents](/docs/guides/subagents) — in-process agent delegation pattern * [LLM Middleware](/docs/guides/llm-middleware) — model-level interceptors --- # HITL approval chain (/docs/guides/hitl-approval-chain) HITL approval chain [#hitl-approval-chain] Configure who must approve sensitive agent tool calls per room. Pending requests **snapshot** the chain at creation time so config changes never affect in-flight approvals. Room config [#room-config] ```http GET /rooms/:roomId/config PATCH /rooms/:roomId/config Authorization: Bearer Content-Type: application/json { "config": { "approvalChain": { "defaultTimeoutSeconds": 180, "steps": [ { "approverId": "user_ana", "timeoutSeconds": 240 }, { "approverId": "user_carlos", "timeoutSeconds": 240 }, { "fallback": "notify_channel" } ] } } } ``` Stored in `room_config` (same pattern as translation settings). Dashboard: **Rooms → HITL approval chain**. Shared-room two-key HITL (guests + private context + outbound tools) is on unless the Worker env or this room’s skip checkbox turns it off. Audit table: **Rooms → Advanced → Room Decisions**. Snapshot on request [#snapshot-on-request] When an agent hits a tool that requires approval, the Worker: 1. Reads the current `approvalChain` from room config 2. Copies it into `hitl_approval_requests.approval_chain_snapshot_json` 3. Sets `current_approver_id` to step 0 4. Writes `approval_requested` to `room_timeline_events` 5. Notifies the current approver: in-app, web-push (if VAPID), email, Slack webhook Email and Slack one-tap [#email-and-slack-one-tap] Approvers can decide from a signed link. No login cookie. The token is HMAC (`ART50_MARK_SECRET` or `JWT_SECRET`), bound to `approvalId`, `userId`, and `approve`/`deny`. `GET /public/hitl/tap?token=…` records the decision only if that user is still the current approver. Set `WORKER_PUBLIC_URL` (preferred) or `PUBLIC_APP_URL` to the **Worker origin** that serves `/public/hitl/tap`. Mail uses the same path as the daily digest (`EMAIL.send` or `RESEND_API_KEY`). Slack is an incoming webhook URL in `HITL_SLACK_WEBHOOK_URL` (`https://hooks.slack.com/…` only). Without `HITL_SLACK_SIGNING_SECRET`, buttons are **link** buttons that open `GET /public/hitl/tap`. With the signing secret, buttons are **interactive**: Slack POSTs to `POST /public/hitl/slack`. Point the Slack app Interactivity Request URL at that Worker path. Save a Slack member id on **Rooms → Advanced → HITL approval chain** (`PUT /api/hitl/slack-user-map`). When that id matches the current approver, the Slack button `value` is the approval UUID only. Email links still use HMAC. Unmapped rooms keep the tap token on the button — anyone who can click that message can use it, same as forwarding the GET link. Digest email opt-out (`email_enabled = 0`) skips HITL mail. Address comes from digest prefs, else `users.email`. Later config edits only affect **new** requests. Timeline audit [#timeline-audit] Every `approvalChain` change emits `approval_chain_updated` on the room timeline: ```http GET /rooms/:roomId/timeline-events?eventType=approval_chain_updated ``` Payload includes `previousChain`, `newChain`, and `changedBy`. Approver inbox (cross-room) [#approver-inbox-cross-room] ```http GET /api/hitl/approvals?approverId=me POST /approvals/:approvalRequestId/decision { "decision": "approve" | "reject" } ``` Dashboard: **Inbox → Approvals inbox**. Each action is bound to a specific `approvalRequestId`. When ≥2 requests are pending, the UI asks for explicit confirmation before submit. Migrations [#migrations] Applied automatically with the rest of the D1 chain (`0208`–`0210`): ```bash cd apps/worker wrangler d1 migrations list fluxychat --remote wrangler d1 migrations apply fluxychat --remote ``` Files: `0208_room_config.sql`, `0209_hitl_approval_requests.sql`, `0210_room_timeline_events.sql`. x402 is an approval card, not a wallet [#x402-is-an-approval-card-not-a-wallet] Cross-org settlement can POST an x402 facilitator URL (`X402_FACILITATOR_URL`) after both sides commit. That is **pay-retry HTTP**, stored as `external_ref` on the settlement row. It is not a room crypto wallet, not a browser extension, and not a spend log for every `http_request`. Operator cost stays on Rooms → Advanced (token budget) plus Stripe **tenant** meter if you enabled it. --- # Huddles — audio, video, and screen share (/docs/guides/huddles-webrtc) **Huddles** combine the SDK `createHuddle()` helper with worker **call sessions**. Default media path is **Cloudflare Realtime SFU** (no rooms on the SFU — the Durable Object is the room). LiveKit JWT mint is a fallback when `LIVEKIT_*` is set. Realtime SFU signaling [#realtime-sfu-signaling] The Worker holds `REALTIME_SFU_APP_ID` and `REALTIME_SFU_APP_SECRET`. Browsers never see the app secret. ```bash curl -X POST "$WORKER_URL/rooms/{roomId}/realtime/sessions" \ -H "Authorization: Bearer $MEMBER_JWT" \ -H "Content-Type: application/json" \ -d '{"sessionDescription":{"type":"offer","sdp":"v=0..."}}' ``` Same sequence as Cloudflare's Echo HTML: create session with the offer, wait for ICE, `POST .../tracks` with local `mid` + `trackName`, then pull peers from `GET /rooms/{roomId}/realtime/tracks`. The app secret never goes to the browser. `GET /admin/calls/token` with no provider returns that signaling map when Realtime SFU is configured, otherwise a LiveKit token or stub. Dashboard: [**Huddles**](/huddles) Bill cap (not Cloudflare's meter) [#bill-cap-not-cloudflares-meter] Realtime includes **1 TB/month** then $0.05/GB. The Worker cannot read Cloudflare's usage, so it keeps its own **high** estimate and **refuses new huddles** when that estimate hits the cap. Defaults (override with Worker env): * `REALTIME_SFU_MONTHLY_GB_CAP=80` (stop at 80 GB estimated, not 1000) * `REALTIME_SFU_MAX_CONCURRENT=2` * `REALTIME_SFU_MAX_SESSION_SECONDS=1200` (20 minutes, then we settle the session) * Video off unless `REALTIME_SFU_ALLOW_VIDEO=true` * Panic: `REALTIME_SFU_DISABLED=true` `GET /rooms/{roomId}/realtime/budget` returns the current estimate. Apply D1 migration `0225_huddle_sfu_budget.sql`. Create and start a call [#create-and-start-a-call] ```bash curl -X POST "$WORKER_URL/admin/calls" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "room_team", "provider": "cloudflare-realtime", "recordingEnabled": true, "maxParticipants": 8 }' curl -X POST "$WORKER_URL/admin/calls/{callId}/start" \ -H "Authorization: Bearer $ADMIN_JWT" curl -X POST "$WORKER_URL/admin/calls/join" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{"callId":"...","displayName":"Alex","role":"host"}' ``` Screen share and recording [#screen-share-and-recording] Update participant state: ```bash curl -X PATCH "$WORKER_URL/admin/calls/participants" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{"callId":"...","screenSharing":true}' ``` Toggle server-side recording: ```bash curl -X POST "$WORKER_URL/admin/calls/{callId}/recording" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{"enabled":true}' ``` SDK — local huddle [#sdk--local-huddle] ```typescript import { createHuddle } from "@fluxy-chat/sdk"; const huddle = createHuddle({ roomId: "room_team", audioEnabled: true, videoEnabled: true, screenShareEnabled: true, captionsEnabled: true, recordingConsent: false, maxParticipants: 8, }); await huddle.join(); await huddle.startScreenShare(); huddle.giveRecordingConsent(); ``` Stats [#stats] ```bash curl "$WORKER_URL/admin/calls/active" -H "Authorization: Bearer $ADMIN_JWT" curl "$WORKER_URL/admin/calls/stats" -H "Authorization: Bearer $ADMIN_JWT" ``` Optional E2E encryption can be layered via room E2E keys — see [Voice huddles core doc](/docs/core/voice-huddles). --- # Import a ChatGPT or Claude export (/docs/guides/import-transcript) Import a ChatGPT or Claude export [#import-a-chatgpt-or-claude-export] You download the file from ChatGPT or Claude, then upload it. We create a group room and insert up to 400 messages. Extra chats in a ChatGPT dump are skipped; first non-empty conversation wins. Console [#console] **Rooms**, then Import ChatGPT/Claude JSON. Member or admin JWT. API [#api] ```http POST /rooms/import-transcript Authorization: Bearer Content-Type: application/json { "export": { }, "roomName": "optional", "inviteUserIds": ["user_optional"] } ``` `export` can be: * ChatGPT `conversations.json` (array of chats with `mapping`) * a Claude chat with `chat_messages` * `{ "title": "…", "messages": [{ "role": "user", "content": "…" }] }` Assistant lines are stored as `user_id=import_assistant`. They are **imported, unverified** (`trust: unverified`). They are not Art. 50-signed as FluxyChat agent output. You are the owner. This does not invite people by email. Pass FluxyChat user ids in `inviteUserIds` if they already exist. Public marketing page for the same importer: [fluxychat.com/migrate-chatgpt](https://fluxychat.com/migrate-chatgpt). OpenAI shutting group chats is their timeline. --- # How-to guides (/docs/guides) Pick a job, not a feature list. Stuck on a 401 or a dead WebSocket? [Troubleshooting](/docs/guides/troubleshooting-integration). --- # Integration kit (entity rooms) (/docs/guides/integration-kit) Integration kit [#integration-kit] FluxyChat is a room behind a Linear issue, GitHub PR, PagerDuty incident, or Zendesk ticket. This Worker path is the shared plumbing: one HMAC URL, one entity-to-room row, write intents. It is not a FluxyChat OAuth app on each vendor, and it is not a Marketplace listing. Entity link [#entity-link] `linear:issue:ENG-123`, `github:pr:org/repo#45`, `pagerduty:incident:Q1XYZ`. One stable row per `(project, provider, type, id)` → `roomId`. Duplicate alerts with the same id reuse the same room if you linked that id. ```http POST /integrations/entity-links Authorization: Bearer { "roomId": "room_…", "entity": "linear:issue:ENG-123" } ``` Inbound webhook [#inbound-webhook] ```http POST /integrations/webhooks/:projectId/:provider ``` HMAC with the signing secret you stored on `PUT /integrations/connections` (encrypted with `WEBHOOK_SECRET_ENCRYPTION_KEY`, same key as outbound webhooks). GitHub uses `X-Hub-Signature-256`. Linear uses `Linear-Signature`. Unknown or unlinked entities are acknowledged and not fanned out. Kill switch: `POST /integrations/connections/:provider/kill`. Failed deliveries come back to you: when a delivery to a webhook URL exhausts its retries, the project receives a metadata-only `webhook.delivery_failed` event (`deliveryId`, `webhookId`, `eventType`, `attempts`, `lastHttpStatus`). The failing webhook is excluded from its own notice, only exhausted retries emit, and a failed failure notice is not re-emitted. Rooms sealed after repeated Durable Object boot crashes skip fan-out (inbound is acknowledged, nothing is delivered) — `POST /rooms/:id/sealed` unseals (owner/admin). Inbound text is `untrusted` and unicode-stripped. Slack / Zendesk / Intercom / HubSpot default `no_train`. Writes [#writes] `POST /integrations/write-intents` then `POST /integrations/write-intents/:id/approve`. GitHub / Linear / Jira execute only if `dryRun` is false **and** a write token exists. Self-host may use Worker env PATs. Hosted needs an encrypted per-project `writeToken` on the connection. Payload hash is stored; if the preview changes, approve returns `payload_changed`. Everyone else stays dry-run. Agents do not get a bypass. Catalog [#catalog] `GET /integrations/catalog` — eleven keys, `oauthApp: false`, `marketplace: false`. Console [#console] **Integrations** → Entity rooms panel. Admin JWT. Not built yet [#not-built-yet] Linear agent-session OAuth, GitHub App required checks, Slack Marketplace, PagerDuty MCP writes, Zendesk Sunshine, Intercom Fin HITL, HubSpot custom channel, Notion External Agents, Jira Forge remote agents. Existing Bridges and HITL Slack stay where they are. Existing `/incidents` CRUD is separate from entity links. Related [#related] * [Room tickets](/docs/guides/room-tickets) * [Shared-room agent defaults](/docs/guides/security/shared-room-agent-defaults) * [External event ingest](/docs/guides/external-event-ingest) --- # Knowledge base connectors (/docs/guides/knowledge-base-connectors) FluxyChat stores connector metadata in KV and indexed documents in D1 (`support_knowledge_base`). Start with a **URL** or **manual paste** connector; Notion, Confluence, Google Drive, Intercom, and Zendesk appear in the dashboard as source types — sync via pasted content or your own OAuth worker until marketplace OAuth ships. Dashboard [#dashboard] Open [**Knowledge base**](/knowledge) in the console: 1. **Add source** — pick type and name (URL sources need a fetchable https link). 2. **Sync** — URL sources fetch and ingest; other types use pasted Markdown/text. 3. **Search** — keyword search over published articles. 4. Attach RAG to agents with `POST /admin/kb/rag` or the [KB + RAG cookbook](/docs/cookbook/kb-rag-agent). Admin API [#admin-api] All routes require an **admin JWT**. | Method | Path | Purpose | | ------ | ---------------------------- | ---------------------------------------------- | | GET | `/admin/kb/sources` | List connectors | | POST | `/admin/kb/sources` | Create connector `{ type, name, config? }` | | DELETE | `/admin/kb/sources/:id` | Remove connector metadata | | POST | `/admin/kb/sources/:id/sync` | URL fetch or `{ content, title? }` ingest | | POST | `/admin/kb/ingest` | Direct ingest `{ sourceId, title, content }` | | GET | `/admin/kb/search?q=` | Search index | | POST | `/admin/kb/rag` | `{ query, maxResults? }` → `synthesizedPrompt` | Example: URL connector [#example-url-connector] ```bash curl -X POST "$WORKER/admin/kb/sources" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"type":"url","name":"Runbooks","config":{"url":"https://docs.example.com/runbooks"}}' curl -X POST "$WORKER/admin/kb/sources/kbs_abc123/sync" \ -H "Authorization: Bearer $JWT" ``` RAG for agent invoke [#rag-for-agent-invoke] ```bash curl -X POST "$WORKER/admin/kb/rag" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"query":"How do I reset MFA?"}' ``` Use `synthesizedPrompt` as extra system context before `POST /agents/:id/invoke`. SDK (client-side dev) [#sdk-client-side-dev] For local prototyping without the Worker: ```typescript import { createKnowledgeBase } from "@fluxy-chat/sdk"; const kb = createKnowledgeBase(); const source = kb.addSource({ type: "notion", name: "Wiki", connectionConfig: { integrationToken: process.env.NOTION_TOKEN! }, enabled: true, syncIntervalMs: 3_600_000, }); ``` Production indexing should go through Worker `/admin/kb/*` so secrets stay server-side. --- # Lifecycle Callbacks (/docs/guides/lifecycle-callbacks) Lifecycle Callbacks [#lifecycle-callbacks] Lifecycle callbacks let you run custom code at key points during `runAgentLoop`. Use them for logging, analytics, monitoring, metrics, or any application-specific hook without modifying the loop internals. Callbacks can be synchronous or asynchronous. If a callback throws, the error is caught internally and the loop continues. Available Callbacks [#available-callbacks] | Callback | When | Event | | ---------------------- | ----------------------------------------------- | ------------------------- | | `onStart` | Once before any steps run | `LoopStartEvent` | | `onStepStart` | Before each step | `StepStartEvent` | | `onToolExecutionStart` | Before each tool's `execute` function | `ToolExecutionStartEvent` | | `onToolExecutionEnd` | After each tool's `execute` completes or errors | `ToolExecutionEndEvent` | | `onStepEnd` | After each step completes | `StepEndEvent` | | `onEnd` | Once when the loop finishes | `LoopEndEvent` | Execution Order [#execution-order] A typical single-step loop with one tool call runs in this order: 1. `onStart` 2. `onStepStart` 3. `onToolExecutionStart` 4. `onToolExecutionEnd` 5. `onStepEnd` 6. `onEnd` A multi-step loop with tool calls in each step repeats steps 2–5: 1. `onStart` 2. `onStepStart` → `onToolExecutionStart` → `onToolExecutionEnd` → `onStepEnd` 3. `onStepStart` → `onToolExecutionStart` → `onToolExecutionEnd` → `onStepEnd` 4. `onEnd` Basic Usage [#basic-usage] ```ts import { runAgentLoop } from '@fluxy-chat/agent'; const result = await runAgentLoop({ model: someModel, tools: { /* ... */ }, onStart({ callId }) { console.log('Loop started', { callId }); }, onStepEnd({ stepNumber, text, toolResults, finishReason }) { console.log(`Step ${stepNumber} finished`, { finishReason, toolCount: toolResults.length, textLength: text.length, }); }, onEnd({ text, usage, steps }) { console.log('Loop finished', { totalTokens: usage.totalTokens, stepCount: steps.length, }); }, }); ``` Request Logging [#request-logging] Use `onStart` and `onEnd` to record one application log for the beginning and end of the loop: ```ts onStart({ callId, tools, maxSteps }) { logger.info('agent.loop.started', { callId, maxSteps, tools: Object.keys(tools ?? {}) }); }, onEnd({ callId, finishReason, usage, steps }) { logger.info('agent.loop.finished', { callId, finishReason, totalTokens: usage.totalTokens, stepCount: steps.length, }); }, ``` Debugging Multi-Step Execution [#debugging-multi-step-execution] Use `onStepStart` and `onStepEnd` to understand how many steps the loop took and which tools were called: ```ts onStepStart({ stepNumber, state }) { console.log(`Step ${stepNumber}: ${state.toolResults.length} tools so far`); }, onStepEnd({ stepNumber, toolCalls, toolResults }) { console.log(`Step ${stepNumber} tools:`, toolCalls.map(t => t.name)); console.log(`Step ${stepNumber} results:`, toolResults.map(r => r.output)); }, ``` Monitoring Tool Execution [#monitoring-tool-execution] Use `onToolExecutionStart` and `onToolExecutionEnd` to track tool usage, latency, and errors: ```ts onToolExecutionStart({ toolCall }) { logger.info('agent.tool.started', { toolName: toolCall.name, input: toolCall.input, }); }, onToolExecutionEnd({ toolCall, toolExecutionMs, output, error }) { logger.info('agent.tool.finished', { toolName: toolCall.name, durationMs: toolExecutionMs, success: !error, }); }, ``` `onToolExecutionEnd` always fires — for successful results, errors denied approvals, and timeouts. Check the `error` field to distinguish success from failure. Event Data Reference [#event-data-reference] LoopStartEvent [#loopstartevent] | Field | Type | Description | | ---------- | -------------------------------------- | ---------------------------------------------- | | `callId` | `string` | Unique ID for this loop execution (`call_...`) | | `tools` | `Record \| undefined` | Available tools | | `maxSteps` | `number` | Maximum steps configured | | `runtime` | `unknown` | Shared runtime context | StepStartEvent [#stepstartevent] | Field | Type | Description | | ------------ | ---------------- | ---------------------------------------------- | | `callId` | `string` | Loop call ID | | `stepNumber` | `number` | Zero-based step index | | `state` | `AgentLoopState` | Current loop state (steps, toolResults, usage) | ToolExecutionStartEvent [#toolexecutionstartevent] | Field | Type | Description | | ------------- | ---------------------- | ------------------------------------------------------ | | `callId` | `string` | Loop call ID | | `stepNumber` | `number` | Current step index | | `toolCall` | `AIToolCall` | The tool call about to execute (`id`, `name`, `input`) | | `toolContext` | `unknown \| undefined` | Tool-specific context from `toolContexts` | ToolExecutionEndEvent [#toolexecutionendevent] | Field | Type | Description | | ----------------- | --------------------------------- | --------------------------------- | | `callId` | `string` | Loop call ID | | `stepNumber` | `number` | Current step index | | `toolCall` | `AIToolCall` | The tool call that executed | | `toolContext` | `unknown \| undefined` | Tool-specific context | | `toolExecutionMs` | `number` | Execution duration in ms | | `output` | `unknown \| undefined` | Tool output (undefined on error) | | `error` | `unknown \| undefined` | Tool error (undefined on success) | | `approval` | `ToolApprovalRecord \| undefined` | Approval result if applicable | StepEndEvent [#stependevent] | Field | Type | Description | | -------------- | ------------------------- | --------------------------- | | `callId` | `string` | Loop call ID | | `stepNumber` | `number` | Zero-based step index | | `text` | `string` | Text generated in this step | | `toolCalls` | `readonly AIToolCall[]` | Tool calls in this step | | `toolResults` | `readonly AIToolResult[]` | Tool results from this step | | `finishReason` | `AIFinishReason` | How the step finished | | `usage` | `AIUsage` | Token usage so far | | `state` | `AgentLoopState` | Current loop state | LoopEndEvent [#loopendevent] | Field | Type | Description | | -------------- | ----------------------------- | --------------------------------- | | `callId` | `string` | Loop call ID | | `text` | `string` | Complete generated text | | `toolCalls` | `readonly AIToolCall[]` | All tool calls across all steps | | `toolResults` | `readonly AIToolResult[]` | All tool results across all steps | | `finishReason` | `AIFinishReason` | Final finish reason | | `usage` | `AIUsage` | Total token usage | | `steps` | `readonly AIGenerationStep[]` | All step results | | `finalState` | `AgentLoopState` | Final loop state | Backward Compatibility [#backward-compatibility] The deprecated `onStepFinish` callback still works. It fires at the same point as `onStepEnd`. Prefer `onStepEnd` for new code. ```ts /** @deprecated Use onStepEnd instead */ onStepFinish?: (state: AgentLoopState, latest: AgentStepResult) => void | Promise; ``` --- # Link Preview (/docs/guides/link-preview) Link Preview [#link-preview] Extract and preview links from message text. ```ts import { createLinkPreview, linkPreviewFromData } from "@fluxy-chat/sdk"; ``` Extracting Links [#extracting-links] ```ts const api = createLinkPreview(); const links = api.extractLinks("Check https://example.com and http://test.com/page"); // -> ["https://example.com", "http://test.com/page"] ``` Fetching Preview Data [#fetching-preview-data] ```ts const preview = await api.fetchMessage("https://example.com"); // -> { url: "https://example.com", title: "example.com" } ``` Results are cached in memory for the lifetime of the API instance. Manual Creation [#manual-creation] ```ts const preview = linkPreviewFromData({ url: "https://example.com", title: "Example", description: "An example site", imageUrl: "https://example.com/og.png", }); ``` Types [#types] * `LinkPreviewData`: `\{ url, title?, description?, imageUrl?, favicon?, siteName? \}` * `LinkPreviewApi`: `\{ fetchMessage(url), extractLinks(text) \}` --- # Live knowledge graph (/docs/guides/live-knowledge-graph) Live knowledge graph [#live-knowledge-graph] While a discussion runs, FluxyChat can extract ideas, tasks, decisions, and contradictions into a queryable graph. The graph is a **semantic index**, not source of truth: every node links to the message that introduced it. Enable [#enable] On the Worker: ```bash KNOWLEDGE_GRAPH_ENABLED=true ``` Configure an LLM provider (same as other AI features). Tenants can opt out via hosted LLM policy. Extract [#extract] ```http POST /rooms/:roomId/kg/extract Authorization: Bearer Content-Type: application/json {} ``` Optional body: `{ "since": "2026-08-13T10:00:00.000Z" }` to limit the transcript window. Response: ```json { "nodesExtracted": 4, "edgesExtracted": 3, "nodesInserted": 2, "edgesInserted": 1 } ``` Extraction is **idempotent**: duplicate nodes/edges are skipped; high-confidence updates supersede older nodes with provenance preserved. Query [#query] ```http GET /rooms/:roomId/kg?limit=80 Authorization: Bearer ``` Returns `nodes`, `edges`, and `stats` (counts by type). Dashboard (reagraph) [#dashboard-reagraph] Open **Rooms → Live knowledge graph**. The console uses [reagraph](https://reagraph.dev) (WebGL) for force-directed layout: * Color by node type (task, decision, concept, user, …) * Click a node to see confidence, source message id, and properties * Drag nodes; curved directed edges with labels Node and edge types [#node-and-edge-types] | Nodes | Edges | | ----------------------------------------------------- | ----------------------------------------------------------------------- | | user, task, decision, concept, external\_entity, file | decided\_by, assigned\_to, references, depends\_on, affects, linked\_to | Related [#related] * [Room memory](/docs/guides/room-memory) (PH-132) * [Community decision simulation](/docs/guides/community-decision-simulation) (PH-131) --- # Language Model Middleware (/docs/guides/llm-middleware) Language Model Middleware [#language-model-middleware] Language model middleware intercepts and modifies LLM calls — enabling guardrails, caching, RAG injection, logging, and parameter transformation in a model-agnostic way. Using Middleware [#using-middleware] `wrapLanguageModel` wraps a model with one or more middleware: ```ts import { wrapLanguageModel } from '@fluxy-chat/agent'; const wrappedModel = wrapLanguageModel({ model: myModel, middleware: myMiddleware, }); // Use like any other model const result = await wrappedModel.generate({ prompt: [...] }); ``` Multiple Middleware [#multiple-middleware] Middleware applies in order (first wraps second): ```ts const wrapped = wrapLanguageModel({ model: myModel, middleware: [loggingMiddleware, cachingMiddleware], }); // loggingMiddleware(cachingMiddleware(myModel)) ``` Built-in Middleware [#built-in-middleware] extractReasoningMiddleware [#extractreasoningmiddleware] Extracts reasoning from `<think>` tags in generated text: ```ts import { wrapLanguageModel, extractReasoningMiddleware } from '@fluxy-chat/agent'; const model = wrapLanguageModel({ model: myModel, middleware: extractReasoningMiddleware({ tagName: 'think' }), }); const result = await model.generate({ prompt: ['Explain AI'] }); console.log(result.text); // Clean text without tags console.log(result.reasoningText); // Extracted reasoning ``` defaultSettingsMiddleware [#defaultsettingsmiddleware] Applies default settings without overriding explicit values: ```ts import { wrapLanguageModel, defaultSettingsMiddleware } from '@fluxy-chat/agent'; const model = wrapLanguageModel({ model: myModel, middleware: defaultSettingsMiddleware({ settings: { temperature: 0.5, maxOutputTokens: 800, providerOptions: { openai: { reasoningEffort: 'low' } }, }, }), }); // Explicit temperature=0.9 overrides the default const result = await model.generate({ prompt: [...], temperature: 0.9 }); ``` extractJsonMiddleware [#extractjsonmiddleware] Strips markdown code fences from JSON responses: ````ts import { wrapLanguageModel, extractJsonMiddleware } from '@fluxy-chat/agent'; const model = wrapLanguageModel({ model: myModel, middleware: extractJsonMiddleware(), }); // If model returns ```json { "key": "value" } ``` // The middleware returns { "key": "value" } ```` simulateStreamingFromGenerate [#simulatestreamingfromgenerate] Creates a streaming interface from a non-streaming model by chunking the response: ```ts import { simulateStreamingFromGenerate } from '@fluxy-chat/agent'; const streamingModel = simulateStreamingFromGenerate(myModel); const stream = await streamingModel.stream({ prompt: [...] }); ``` Custom Middleware [#custom-middleware] Implement the `LanguageModelMiddleware` interface with any of these hooks: ```ts import type { LanguageModelMiddleware } from '@fluxy-chat/agent'; const loggingMiddleware: LanguageModelMiddleware = { transformParams: async ({ params }) => { console.log('Request:', params.prompt.length, 'messages'); return params; }, wrapGenerate: async ({ doGenerate, params }) => { const start = Date.now(); const result = await doGenerate(); console.log('Generated', result.text.length, 'chars in', Date.now() - start, 'ms'); return result; }, wrapStream: async ({ doStream, params }) => { const stream = await doStream(); return stream; // passthrough or pipe through TransformStream }, }; ``` RAG Middleware [#rag-middleware] Inject relevant context from a knowledge base: ```ts const ragMiddleware: LanguageModelMiddleware = { transformParams: async ({ params }) => { const lastUserMsg = params.prompt.findLast(m => m.role === 'user'); if (!lastUserMsg || typeof lastUserMsg.content !== 'string') return params; const context = await searchKnowledgeBase(lastUserMsg.content); return { ...params, prompt: [ ...params.prompt, { role: 'system', content: `Context: ${context}` }, ], }; }, }; ``` Caching Middleware [#caching-middleware] ```ts const cache = new Map(); const cacheMiddleware: LanguageModelMiddleware = { wrapGenerate: async ({ doGenerate, params }) => { const key = JSON.stringify(params); if (cache.has(key)) return cache.get(key); const result = await doGenerate(); cache.set(key, result); return result; }, }; ``` Guardrails Middleware [#guardrails-middleware] ```ts const guardrailMiddleware: LanguageModelMiddleware = { wrapGenerate: async ({ doGenerate }) => { const result = await doGenerate(); return { ...result, text: result.text.replace(/badword/g, ''), }; }, }; ``` Type Reference [#type-reference] ```ts interface LanguageModelMiddleware { transformParams?: (context: MiddlewareParams) => AIModelRequest | Promise; wrapGenerate?: (context: GenerateContext) => Promise; wrapStream?: (context: StreamContext) => Promise>; } interface WrappedModelOptions { model: AILanguageModel; middleware: LanguageModelMiddleware | readonly LanguageModelMiddleware[]; } function wrapLanguageModel(options: WrappedModelOptions): AILanguageModel; ``` See Also [#see-also] * [Provider Options](/docs/guides/provider-options) — provider-specific configuration * [Stream Transforms](/docs/guides/stream-transforms) — stream-level transformations * [Provider Registry](/docs/guides/provider-registry) — combining middleware with provider management --- # Loop control (/docs/guides/loop-control) Cap how long an agent may loop so a bad tool call cannot spin forever. Typical knobs (Worker / agent config): * `maxSteps` — model turns in one run * `maxToolCalls` — tools the model may invoke See [Prune messages](/docs/guides/prune-messages) and [Subagents](/docs/guides/subagents). --- # Matrix bridge (/docs/guides/matrix-bridge) FluxyChat stores Matrix bridge configuration in D1 and exposes admin APIs under `/admin/matrix/*`. Use the dashboard **Bridges → Matrix federation** page or call the REST APIs from your Matrix appservice. Setup (15 minutes) [#setup-15-minutes] 1. Create a Matrix bot user on your homeserver and generate an **access token**. 2. Open [**Matrix federation**](/bridges/matrix) in the dashboard (admin JWT required). 3. **Create bridge** with homeserver URL, token, and `@bot:your.server` user id. 4. **Connect** the bridge (marks status `connected` and logs a sync event). 5. **Add mapping**: FluxyChat `roomId` ↔ Matrix `!roomId:server`. Admin API [#admin-api] ```bash # List bridges curl "$WORKER/admin/matrix/bridges" -H "Authorization: Bearer $ADMIN_JWT" # Create bridge curl -X POST "$WORKER/admin/matrix/bridges" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "homeserverUrl": "https://matrix.example.com", "accessToken": "syt_...", "botUserId": "@fluxy:example.com", "syncMode": "bidirectional" }' # Room mapping curl -X POST "$WORKER/admin/matrix/mappings" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "bridgeId": "mb_abc123", "roomId": "support-eu", "matrixRoomId": "!abcdef:matrix.example.com" }' ``` Sync hooks [#sync-hooks] Three ways to ingest Matrix → FluxyChat messages: Appservice webhook (recommended) [#appservice-webhook-recommended] Point your Matrix appservice transaction URL at: ```text POST {WORKER}/webhooks/matrix/{bridgeId} ``` Body: standard Matrix transaction JSON with an `events` array. Text messages (`m.text`, `m.notice`) are imported into the mapped FluxyChat room via `importAdminMessage`, deduplicated by Matrix `event_id`, and recorded in `matrix_message_map`. Admin sync API [#admin-sync-api] * `POST /admin/matrix/sync/inbound` — single event (admin JWT) * `POST /admin/matrix/sync/outbound` — FluxyChat → Matrix Both require a valid `bridgeId` belonging to the project. Duplicate Matrix events are deduplicated via `matrix_message_map`. Stats [#stats] `GET /admin/matrix/stats` returns bridge counts by status, mapping totals, and synced message counts by direction. Related [#related] * [Slack & Discord bridge](/docs/guides/slack-discord-bridge) * [Cross-channel identity](/docs/guides/cross-channel-identity) --- # MCP Apps marketplace (/docs/guides/mcp-apps-marketplace) The **MCP Apps marketplace** lists pre-built, **curated** MCP servers (GitHub, Slack, Notion, Linear, …) that you can install on any agent in one click. Installs register server identity and tool provenance in the MCP identity registry. Browse from **Marketplace → MCP Apps** in the dashboard or use the APIs below. Catalog (public) [#catalog-public] ```bash curl "$WORKER_URL/marketplace/mcp-apps" ``` Each entry includes `verified`, `auditLevel` (`curated`), `tools`, and `category`. Install on an agent [#install-on-an-agent] Admin JWT required: ```bash curl -X POST "$WORKER_URL/admin/mcp-apps/install" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "appId": "github-mcp", "agentId": "agent_support_1" }' ``` Omit `agentId` for a project-wide install. Tools are registered via `/admin/mcp-identity/*`. List installed apps [#list-installed-apps] ```bash curl "$WORKER_URL/admin/mcp-apps/installed" \ -H "Authorization: Bearer $ADMIN_JWT" ``` Uninstall [#uninstall] ```bash curl -X DELETE "$WORKER_URL/admin/mcp-apps/install?appId=github-mcp&agentId=agent_support_1" \ -H "Authorization: Bearer $ADMIN_JWT" ``` SDK — MCP App UI resources [#sdk--mcp-app-ui-resources] For rendering MCP App HTML resources in the client: ```typescript import { createMCPAppManager, readMCPAppResource } from "@fluxy-chat/sdk"; const manager = createMCPAppManager(); const isApp = manager.isMCPAppTool(toolDefinition); ``` Security [#security] * Curated catalog only for MVP — third-party servers require manual review before listing. * Installed tools appear in [MCP identity & audit](/docs/guides/enterprise/mcp-identity) for every tool call. * Pair with [AI Governance](/docs/guides/enterprise/ai-governance) for risk-tier policies on external tools. --- # MCP Client Integration (/docs/guides/mcp-client) MCP Client Integration [#mcp-client-integration] FluxyChat's MCP (Model Context Protocol) client lets AI agents consume tools and resources from any MCP-compatible server, expanding agent capabilities without writing custom integrations. Overview [#overview] MCP is the de-facto protocol for AI↔app communication, adopted by OpenAI, Google, Microsoft, and Anthropic (\~97M SDK downloads/month). FluxyChat ships an MCP **client** today so agents can call external tools. To expose a **room** to external agents, use the [room as MCP server](/docs/guides/room-as-mcp-server) guide (`POST /mcp/rooms/:roomId`). Supported Transports [#supported-transports] | Transport | Use case | | --------- | ------------------------------- | | **HTTP** | Remote MCP servers (production) | | **SSE** | Server-Sent Events streaming | | **stdio** | Local development, CLI tools | Connecting to an MCP Server [#connecting-to-an-mcp-server] ```ts import { createMcpClient } from "@fluxy-chat/sdk"; const mcp = createMcpClient({ transport: "http", url: "https://mcp.example.com/sse", // or stdio: { command: "npx", args: ["-y", "@modelcontextprotocol/server-git"] } }); // List available tools const tools = await mcp.listTools(); // [{ name: "git_status", description: "...", inputSchema: {...} }, ...] // List resources const resources = await mcp.listResources(); ``` Tool conversion [#tool-conversion] MCP tools are auto-converted to FluxyChat tool definitions, ready for LLM function calling: ```ts import { convertMcpTools } from "@fluxy-chat/sdk"; const mcpTools = await mcp.listTools(); const fluxyTools = convertMcpTools(mcpTools); // Each MCP tool becomes a FluxyChat tool with execute(), description, inputSchema // Use with agent const agent = createAgent({ model: "gpt-4o", tools: [...fluxyTools, ...builtInTools], }); ``` Resources [#resources] MCP resources provide application-driven data that's passed as context to the LLM: ```ts const resources = await mcp.listResources(); // Resources can be: // - File contents (e.g., "file:///repo/README.md") // - Database queries (e.g., "postgres://.../query/users") // - API responses (e.g., "https://api.github.com/repos/...") for (const resource of resources) { const content = await mcp.readResource(resource.uri); // Inject as context in the agent's system prompt } ``` Configuration [#configuration] MCP servers are configured per-project via the admin API: ```bash # Register an MCP server curl -X POST "$WORKER_URL/admin/mcp-servers" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "github", "transport": "http", "url": "https://mcp.github.com/sse", "toolFilter": ["git_status", "git_diff", "create_issue"] }' ``` MCP Apps [#mcp-apps] MCP Apps render sandboxed iframes for tool UIs, letting tools show interactive interfaces inside the chat: * **Model-visible tools:** AI calls them and reads results * **App-only tools:** UI renders for humans, AI doesn't see them * Sandboxed iframe. Pass `allowedOrigins` on `McpAppFrame`. `*` is rejected. srcDoc frames send origin `"null"` — list that string if you want those messages. * Room shared UI state: `PUT /rooms/:id/mcp-apps/state` (KV) plus Y.Map `fluxy_mcp_app_state` on the room doc for Yjs clients. Security [#security] * MCP server URLs are validated against an allowlist * Tool execution respects FluxyChat's approval gates * Resource content is filtered through the DLP pipeline before reaching the LLM * Per-project tool filtering (`toolFilter`) limits which MCP tools are exposed Common MCP Servers [#common-mcp-servers] | Server | Tools | | ------------------------------------------- | ----------------------------- | | `@modelcontextprotocol/server-git` | Git status, diff, log, commit | | `@modelcontextprotocol/server-github` | Issues, PRs, search | | `@modelcontextprotocol/server-filesystem` | File read/write/search | | `@modelcontextprotocol/server-postgres` | SQL queries | | `@modelcontextprotocol/server-brave-search` | Web search | See Also [#see-also] * [AI Tool Presets Guide](/docs/guides/ai-tool-presets): approval gates for MCP tools * [LLM Middleware Guide](/docs/guides/llm-middleware): intercept MCP tool calls --- # MCP registry listing (/docs/guides/mcp-registry) The Worker speaks MCP at `POST /mcp` (project) and `POST /mcp/rooms/:roomId` (one room). Manifest: `apps/worker/server.json`. `mcpName` on `@fluxy-chat/worker` is `io.github.alessandrofare/fluxychat`. That package is **private**; the registry listing is the remote URL, not an npm install. **Not on the official registry.** Do not tell buyers it is. Submit when `https://api.fluxychat.com/mcp` is the production Streamable HTTP endpoint you want indexed. Files [#files] | File | Role | | ------------------------------------- | -------------------------------------------------------------------------------------------- | | `apps/worker/server.json` | `name`, `remotes[0].url`, GitHub repo | | `apps/worker/package.json` `mcpName` | Must match `server.json` `name` | | `packages/sdk/package.json` `mcpName` | Same name on the public npm package. Listing still requires a registry submit after publish. | Submit [#submit] 1. Confirm the remote URL in `server.json` is the host you actually serve (self-host: change it before you file). 2. Follow the current [MCP registry](https://github.com/modelcontextprotocol/registry) publisher docs (server.json schema + GitHub identity). Those steps move; re-read them the day you publish. 3. After it is live, change this page from “not listed” to the registry URL. Until then, clients point at your Worker with a member JWT. CI already runs `mcp-server-manifest.test.js` inside `pnpm run test:worker`. Root gate: `pnpm run check:mcp-server-json`. Not listed on the official MCP registry. --- # Memory System (/docs/guides/memory) Memory System [#memory-system] > A modular memory framework for AI agents. Store, retrieve, and recall information across conversations using pluggable storage backends and agent-integrated tools. Overview [#overview] The memory system gives agents persistent memory. Without it, every conversation starts fresh. With it, agents build context over time, recall user preferences, and adapt their behavior. Three key components: * `AIMemoryStore`: pluggable storage backend (in-memory, filesystem, database) * `createMemoryTools()`: generates agent tools (`remember`, `recall`, `forget`, `listMemories`) * `AUTO_MEMORY_SYSTEM_PROMPT`: ready-to-use instructions for the agent Quick Start [#quick-start] ```typescript import { InMemoryMemoryStore, createMemoryTools } from "@fluxy-chat/agent"; // 1. Pick a store const store = new InMemoryMemoryStore(); // 2. Create memory tools const memoryTools = createMemoryTools({ store }); // 3. Use in an agent loop const result = await runAgentLoop({ runStep: async (state) => { /* your LLM call */ }, tools: memoryTools, maxSteps: 10, }); ``` Memory Stores [#memory-stores] InMemoryMemoryStore [#inmemorymemorystore] Ephemeral storage — perfect for testing and single-session agents. Data lives in a `Map` and is lost when the process exits. ```typescript const store = new InMemoryMemoryStore(); await store.save({ role: "assistant", content: "User likes cats" }); const results = await store.search({ text: "cats" }); ``` FileMemoryStore [#filememorystore] Persists to a JSON file on disk. Useful for local development. Falls back silently in non-Node environments (browser, edge). ```typescript const store = new FileMemoryStore({ filePath: "./memory.json", autoSave: true }); await store.save({ role: "assistant", content: "Persistent fact" }); ``` Custom Store [#custom-store] Implement `AIMemoryStore` to back memory with any database: ```typescript class MyDatabaseStore implements AIMemoryStore { async save(entry) { /* INSERT into db */ } async search(query) { /* SELECT with WHERE + scoring */ } async get(id) { /* SELECT by id */ } async list(opts) { /* SELECT with filters */ } async delete(id) { /* DELETE */ } async clear(userId?) { /* DELETE with optional scope */ } } ``` Agent Tools [#agent-tools] `createMemoryTools()` returns four tools that an agent can call during its loop: | Tool | Description | Input | | -------------- | ------------------------------------ | ------------------------------------ | | `remember` | Save a fact for future conversations | `content: string`, `tags?: string[]` | | `recall` | Search past memories by keyword | `query: string`, `limit?: number` | | `forget` | Delete a specific memory by ID | `id: string` | | `listMemories` | List or filter recent memories | `tag?: string`, `limit?: number` | User-scoped memory [#user-scoped-memory] Pass `userId` through tool context to scope memories per user: ```typescript import { InMemoryMemoryStore, createMemoryTools, runAgentLoop } from "@fluxy-chat/agent"; const store = new InMemoryMemoryStore(); const tools = createMemoryTools({ store }); // Per-request: scope memory to the current user const result = await runAgentLoop({ runStep: async () => { /* ... */ }, tools, toolContexts: { remember: { userId: "user-123" }, recall: { userId: "user-123" }, listMemories: { userId: "user-123" }, }, }); ``` Or set a default user with `CreateMemoryToolsOptions`: ```typescript const tools = createMemoryTools({ store, defaultUserId: "user-123" }); ``` System Prompt [#system-prompt] Inject `AUTO_MEMORY_SYSTEM_PROMPT` into the agent's system prompt so it knows how to use memory tools: ```typescript import { AUTO_MEMORY_SYSTEM_PROMPT } from "@fluxy-chat/agent"; const result = await generate({ model, prompt: "Remember my name is Alice", system: AUTO_MEMORY_SYSTEM_PROMPT + "\n\nYou are a helpful assistant.", }); ``` API Reference [#api-reference] `AIMemoryEntry` [#aimemoryentry] ```typescript interface AIMemoryEntry { id: string; userId?: string; sessionId?: string; role: "user" | "assistant" | "system"; content: string; tags?: string[]; metadata?: Record; embedding?: number[]; createdAt: string; updatedAt: string; } ``` `AIMemoryStore` [#aimemorystore] ```typescript interface AIMemoryStore { save(entry: Omit): Promise; search(query: AIMemoryQuery): Promise; get(id: string): Promise; list(options?: { userId?, sessionId?, tags?, limit? }): Promise; delete(id: string): Promise; clear(userId?: string): Promise; close?(): Promise; } ``` `AIMemoryQuery` [#aimemoryquery] ```typescript interface AIMemoryQuery { text: string; userId?: string; sessionId?: string; tags?: string[]; limit?: number; minScore?: number; } ``` `CreateMemoryToolsOptions` [#creatememorytoolsoptions] ```typescript interface CreateMemoryToolsOptions { store: AIMemoryStore; embeddingModel?: AIEmbeddingModel; // for semantic search (future) defaultUserId?: string; defaultSessionId?: string; } ``` --- # Message Subject (/docs/guides/message-subject) Message Subject [#message-subject] Associate a message with a parent resource (GitHub issue, Linear ticket, etc.). ```ts import { createSubject, subjectToString, subjectToUrl } from "@fluxy-chat/sdk"; ``` Creating a Subject [#creating-a-subject] ```ts const subject = createSubject("github-issue", "42", { title: "Fix login bug", status: "open", url: "https://github.com/org/repo/issues/42", }); ``` Supported resource types: * `github-issue` * `github-pr` * `linear-issue` * `jira-ticket` * `url` Formatting [#formatting] ```ts subjectToString(createSubject("github-issue", "42", { title: "Bug" })); // -> "#42: Bug" subjectToString(createSubject("github-pr", "100")); // -> "!100" subjectToString(createSubject("linear-issue", "ABC-123", { title: "Feature" })); // -> "LIN-ABC-123: Feature" ``` URL Generation [#url-generation] ```ts subjectToUrl(createSubject("github-issue", "42")); // -> "https://github.com/issues/42" subjectToUrl(createSubject("url", "1", { url: "https://example.com/1" })); // -> "https://example.com/1" ``` Types [#types] * `SubjectResourceType`: `"github-issue" | "github-pr" | "linear-issue" | "jira-ticket" | "url"` * `MessageSubject`: `\{ type, id, title?, url?, status?, metadata? \}` --- # Message-to-LLM Converter (/docs/guides/messages-to-ai) Message-to-LLM Converter [#message-to-llm-converter] `toAiMessages()` converts FluxyChat messages into the message format expected by AI SDKs (OpenAI, Anthropic, Vercel AI SDK, etc.). When to Use [#when-to-use] * Feeding chat history to an AI agent * Converting a conversation thread into context for `generateText` or `streamText` * Building AI-powered chat features on top of FluxyChat Usage [#usage] ```ts import { toAiMessages } from "@fluxy-chat/sdk"; const messages = await client.getMessages("room-1", { limit: 50 }); const history = await toAiMessages(messages, { botUserId: "agent-bot-123", }); // Use with any AI SDK const response = await openai.chat.completions.create({ model: "gpt-4", messages: history, }); ``` Options [#options] `botUserId` [#botuserid] Identifies which user is the bot/agent. Messages from this user are mapped to `role: "assistant"`, all others to `role: "user"`. ```ts toAiMessages(messages, { botUserId: "my-bot-id" }); ``` `includeNames` [#includenames] When `true`, prefixes user messages with `[userId]:` for multi-user context: ```ts toAiMessages(messages, { includeNames: true }); // User message → "[alice]: hello there" ``` `transformMessage` [#transformmessage] Hook to modify or skip individual messages: ```ts toAiMessages(messages, { transformMessage: (aiMessage, sourceMsg) => { // Add prefix to all messages return { ...aiMessage, content: `[${sourceMsg.roomId}] ${aiMessage.content}` }; // Or return null to skip }, }); ``` `onUnsupportedAttachment` [#onunsupportedattachment] Callback for attachment types that can't be converted (audio, video): ```ts toAiMessages(messages, { onUnsupportedAttachment: (att, msg) => { console.warn(`Can't include ${att.kind} from message ${msg.id}`); }, }); ``` How It Works [#how-it-works] 1. Messages are sorted chronologically by `createdAt` 2. Empty/whitespace-only content is filtered out 3. Bot messages become `assistant`, user messages become `user` 4. Link previews are appended as text 5. Image and text files are converted to `FilePart` using their URL 6. Unsupported attachments trigger the callback Output Format [#output-format] ```ts type AiMessage = | { role: "user"; content: string | AiMessagePart[] } | { role: "assistant"; content: string }; ``` This format is compatible with the Vercel AI SDK's `ModelMessage` type and most LLM provider APIs. See Also [#see-also] * [Provider Registry Guide](/docs/guides/provider-registry) — Managing AI providers * [LLM Middleware Guide](/docs/guides/llm-middleware) — Transforming AI SDK calls --- # Migrate from Pusher / Ably / Sendbird (/docs/guides/migrate-from-pusher) Use this guide when replacing a third-party chat/realtime vendor with FluxyChat. For Pusher-specific parity details see [Pusher Channels parity](/docs/reference/pusher-channels-parity). Quick mapping [#quick-mapping] | Pusher / Ably | Sendbird | FluxyChat | | ---------------------- | ----------------- | ------------------------------------------------ | | Channel | Group channel | Room (`rooms.id`) | | Private channel | — | Room `type: "group"` + membership | | Presence channel | Member list | WS `presence` / `member_joined` events | | `socket_id` | Session id | `socketId` on subscribe | | `POST /events` trigger | Admin message API | `POST /events` or `FluxyChatClient.sendMessage` | | Channel auth endpoint | Token | `POST /auth/channel` + JWT | | User auth | Access token | `POST /auth/signin` + user channel WS | | Webhooks | Platform webhooks | Signed outbound webhooks + `/webhooks` dashboard | Ably uses channels + capabilities; map each Ably channel name one-to-one to a Fluxy room id and issue JWTs with the same `userId` you used in Ably `clientId`. Sendbird maps cleanly: group channel → room, open channel → public room, user → `userId` in JWT. Auth migration [#auth-migration] **Pusher:** server signs subscription to `private-*` channels. **FluxyChat:** mint a member JWT on your backend: ```ts // Your auth server const token = await signFluxyMemberJwt({ projectId, userId: pusherUserId, roles: ["member"], exp: "1h", }); ``` Pass `token` to `FluxyChatClient` or `?token=` on the WebSocket URL. No separate per-channel auth call unless you use the optional `POST /auth/channel` helper for Pusher-compatible clients. Client SDK swap [#client-sdk-swap] ```ts // Before (Pusher) const pusher = new Pusher(key, { cluster: "eu", authEndpoint: "/pusher/auth" }); const channel = pusher.subscribe("private-room-42"); channel.bind("new-message", handler); // After (FluxyChat) import { useChat } from "@fluxy-chat/react"; const { messages, sendMessage } = useChat("room-42"); // messages updates include history + live WS ``` REST history: `GET /rooms/{roomId}/messages` replaces polling or Pusher cache channels. Map an export with fluxy-migrate [#map-an-export-with-fluxy-migrate] You download JSON from the old vendor. We do not scrape their API. ```bash pnpm --filter @fluxy-chat/sdk build npx fluxy-migrate ./pusher-or-ably-export.json --out rows.json FLUXY_WORKER_URL=… FLUXY_ADMIN_JWT=… pnpm import-chat-history ./rows.json ``` Cap 400 rows. `private-` / `presence-` prefixes are stripped from channel names. This is not a live proxy of Pusher Channels. Import message history [#import-message-history] FluxyChat has no vendor lock-in import API — push history via REST: ```bash # Batch import (server-side, admin JWT) curl -X POST "$WORKER/rooms/support-1/messages" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "content": "Legacy message body", "userId": "legacy-user-id", "createdAt": "2024-06-01T12:00:00.000Z" }' ``` Recommended import script (repo root): ```bash # messages.json → [{ "roomId", "content", "userId?", "createdAt?", "clientMessageId?" }] FLUXY_WORKER_URL=https://your-worker FLUXY_ADMIN_JWT=eyJ... pnpm import-chat-history ./export/messages.json ``` Uses `POST /admin/messages/import` with optional **backdated `createdAt`** and **legacy `userId`**. `clientMessageId` keeps re-runs idempotent. Batch mode: up to 100 rows per request via `/admin/messages/import/batch`. Single message example: ```bash curl -X POST "$WORKER/admin/messages/import" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "support-1", "userId": "legacy-user-42", "content": "Imported body", "createdAt": "2024-06-01T12:00:00.000Z", "clientMessageId": "pusher-991" }' ``` Legacy SDK skeleton (without admin backfill): ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; async function importHistory( client: FluxyChatClient, rows: Array<{ roomId: string; userId: string; content: string; createdAt: string }>, ) { for (const row of rows) { await client.createMessage(row.roomId, row.content, null, undefined, undefined, { createdAt: row.createdAt, userId: row.userId, }); await new Promise((r) => setTimeout(r, 50)); } } ``` Verify `createMessage` options against OpenAPI for your Worker version — use admin/service JWT for backdated `createdAt`. Webhooks [#webhooks] | Pusher event | Fluxy webhook | | ----------------- | -------------------------------------------------- | | `channel_vacated` | `room.vacated` | | `member_added` | `room.member_joined` | | Client events | `client_event` | | — | `message.created`, `message.updated`, inbox events | Re-point your backend URL in dashboard **Webhooks** and verify HMAC signature with the project secret. Feature parity checklist [#feature-parity-checklist] * [ ] Private/presence → room types + WS presence * [ ] Client events → `client-*` WS events (rate-limited) * [ ] Encrypted channels → room E2E (`e2eEnabled` + `/e2e-key`) * [ ] User notifications → user channel + `useInbox` * [ ] Push → Web push (VAPID) or mobile SDK Rollout strategy [#rollout-strategy] 1. Dual-write new messages to Fluxy while reading legacy for history 2. Backfill history with import script 3. Cut over WebSocket URL in client config flag 4. Drain legacy vendor after 7-day read-only window See also [#see-also] * [Pusher Channels parity](/docs/reference/pusher-channels-parity) * [Auth & JWT](/docs/guides/auth-jwt) * [Testing integrations](/docs/guides/testing-integration) --- # After Twilio Conversations / Flex Chat (/docs/guides/migrate-from-twilio) After Twilio Conversations [#after-twilio-conversations] Twilio Flex Programmable Chat shut down on **1 June 2026**. FluxyChat is not a drop-in Conversations proxy and we are not building a billed Twilio channel this quarter. What to do now [#what-to-do-now] 1. Export history from Twilio while you still can (their tools, not ours). 2. Shape JSON like the [transcript import](/docs/guides/import-transcript) `{ title, messages: [{ role, content }] }` form, or wait for a dedicated Twilio mapper **after** the room wedge is paying for itself. 3. Put new live chat on FluxyChat rooms (`pk_` public or member JWT), not on a compatibility shim. SMS/voice **inbound** into a room is a separate telco handoff (`TELCO_INBOUND_*`), not Conversations. Related [#related] * [Import a transcript](/docs/guides/import-transcript) * [Migrate from Pusher](/docs/guides/migrate-from-pusher) --- # Multi-agent debate (/docs/guides/multi-agent-debate) Multi-agent debate packaging [#multi-agent-debate-packaging] Ship AI War Room / Agentroom-style debates using existing debate agent presets. Roles [#roles] Seed three room members (humans or agents): | Role | Job | | ----------- | -------------------------------------- | | `pro` | Argues for the motion | | `con` | Argues against | | `moderator` | Synthesizes and calls the next speaker | Assign via `room_members.role` or agent profile metadata. Flow [#flow] 1. Post the motion as a normal room message. 2. Trigger debate agents from **Agents → Debate** or ambient policy on `debate.start`. 3. Each agent posts with `visibility: "room"` so the audience sees one stream. 4. Moderator agent posts a summary message tagging `@pro` and `@con` conclusions. StackBlitz [#stackblitz] Open the dashboard **Templates → Code** snippet for multi-agent debate, or link from **Agents → Rehearsal**. Cross-link [#cross-link] Pair with [External event ingest](/docs/guides/external-event-ingest) when the motion comes from a live feed. --- # PostableObject Interface (/docs/guides/postable-objects) PostableObject Interface [#postableobject-interface] FluxyChat's `PostableObject` interface defines a contract for objects that can be passed to `thread.post()` and rendered by adapters. This enables third-party extensions to create custom postable types. Overview [#overview] A `PostableObject` is any object that implements the `$$typeof`, `kind`, `isSupported()`, `getPostData()`, `getFallbackText()`, and `onPosted()` interface. When posted, the adapter checks if it supports the object natively; if not, it falls back to the text representation. **Source:** `apps/worker/src/lib/postable-object.js` Interface [#interface] ```ts interface PostableObject { $$typeof: symbol; // Must equal POSTABLE_OBJECT kind: string; // Object kind (e.g. "card", "plan", "poll") isSupported(adapter): boolean; // Can this adapter render it natively? getPostData(): object; // Data to send to adapter.postObject() getFallbackText(): string; // Text for unsupported adapters onPosted(context): void; // Callback after posting (e.g. store messageId) } ``` Built-in Postable Objects [#built-in-postable-objects] FluxyChat's `Card` builder produces objects that implement the `PostableObject` interface: * **Card** — Rich interactive messages with buttons, tables, sections * **Plan** — Streaming plan objects with task/step updates Creating a Custom PostableObject [#creating-a-custom-postableobject] Using a class [#using-a-class] ```js import { POSTABLE_OBJECT, isPostableObject } from "@fluxy-chat/sdk"; class Poll { constructor(question, options) { this.question = question; this.options = options; } get $$typeof() { return POSTABLE_OBJECT; } get kind() { return "poll"; } isSupported(adapter) { // Only supported on web and Slack return ["web", "slack"].includes(adapter.slug); } getFallbackText() { return `${this.question}\n${this.options.map((o, i) => `${i + 1}. ${o}`).join("\n")}`; } getPostData() { return { question: this.question, options: this.options, }; } onPosted(context) { this.messageId = context.messageId; this.threadId = context.threadId; } } ``` Using the mixin helper [#using-the-mixin-helper] ```js import { withPostable } from "@fluxy-chat/sdk"; class MyObject extends withPostable(BaseClass) { kind = "my-object"; getFallbackText() { return "Custom object (not supported here)"; } getPostData() { return { /* ... */ }; } // isSupported() defaults to true, onPosted() defaults to no-op } ``` Posting [#posting] The `postPostableObject` helper handles the adapter negotiation: ```js import { postPostableObject } from "@fluxy-chat/sdk"; const poll = new Poll("Lunch?", ["Pizza", "Sushi", "Tacos"]); await postPostableObject( poll, // The PostableObject adapter, // Target adapter (or null for web) threadId, // Thread ID postFn, // Fallback: (threadId, message) => Promise<{id}> logger // Optional logger ); ``` Flow: 1. Check `poll.isSupported(adapter)` → if true and adapter has `postObject()`, use native rendering. 2. Otherwise, call `postFn(threadId, poll.getFallbackText())` for text fallback. 3. Call `poll.onPosted(context)` with the result. Type Guard [#type-guard] ```js import { isPostableObject } from "@fluxy-chat/sdk"; function handleContent(content) { if (isPostableObject(content)) { console.log(`PostableObject of kind: ${content.kind}`); // Use postPostableObject() } else if (typeof content === "string") { // Regular text message } } ``` Context [#context] The `onPosted` callback receives a context object: ```ts interface PostableObjectContext { adapter: Adapter; // Adapter instance that posted messageId: string; // ID of the sent message threadId: string; // Thread ID where it was posted logger?: Logger; // Optional logger } ``` See Also [#see-also] * [Card Builder](/docs/guides/card-builder) — Built-in PostableObject for rich messages * [Unified Chat API](/docs/guides/unified-chat-api) — Thread posting methods * [Adapter Pattern](/docs/guides/adapter-pattern) — How adapters handle PostableObjects --- # PrepareStep — Dynamic Step Configuration (/docs/guides/prepare-step) PrepareStep — Dynamic Step Configuration [#preparestep--dynamic-step-configuration] `prepareStep` lets you dynamically modify the runtime, tool access, tool contexts, tool approval rules, and provider options **each step** of `runAgentLoop`. Use it to implement adaptive agent behavior: restrict tools after a certain step, inject context based on conversation state, or change provider options mid-loop. How It Works [#how-it-works] The `prepareStep` function is called at the start of each step, **before** the model generates a response. It receives the current loop state and can return overrides for the step's configuration. ```ts import { runAgentLoop } from '@fluxy-chat/agent'; const result = await runAgentLoop({ runStep: myRunStep, tools: { search, read, write }, prepareStep({ stepNumber, steps, toolResults, state, runtime, providerOptions }) { if (stepNumber === 0) { // First step: allow read-only tools return { allowTools: ['read'] }; } // Subsequent steps: allow all tools return { allowTools: ['read', 'search', 'write'] }; }, }); ``` Return Values [#return-values] All fields on `PrepareStepResult` are optional. Only return what needs to change. | Field | Type | Description | | ----------------- | ----------------------------------- | -------------------------------------------------- | | `allowTools` | `readonly string[]` | Restrict available tools to this list for the step | | `runtime` | `unknown` | Override shared runtime context | | `toolContexts` | `Readonly>` | Override per-tool contexts | | `toolApproval` | `ToolApprovalConfig` | Override tool approval rules | | `providerOptions` | `Record` | Override provider-specific options | Adaptive Tool Access [#adaptive-tool-access] Restrict tools in the first step, then gradually expand access: ```ts prepareStep({ stepNumber }) { if (stepNumber < 2) { return { allowTools: ['search', 'read'] }; } // After step 2, allow modification tools return { allowTools: ['search', 'read', 'write', 'delete'] }; } ``` Runtime Context Injection [#runtime-context-injection] Use `prepareStep` to pass dynamic state to tool implementations: ```ts prepareStep({ toolResults, runtime }) { const userId = (runtime as any)?.userId; const previousErrors = toolResults.filter(r => r.error); return { runtime: { userId, errorCount: previousErrors.length, }, }; } ``` Provider Options Adaptation [#provider-options-adaptation] Change provider options mid-loop, e.g., enable reasoning only on complex steps: ```ts prepareStep({ stepNumber }) { if (stepNumber > 2) { return { providerOptions: { openai: { reasoningEffort: 'high' }, }, }; } return { providerOptions: { openai: { reasoningEffort: 'low' }, }, }; } ``` Multi-Override Example [#multi-override-example] Every field can be combined in a single return: ```ts prepareStep({ stepNumber, steps }) { return { allowTools: stepNumber < 1 ? ['search'] : undefined, runtime: { conversationLength: steps.length }, toolContexts: { search: { maxResults: 10 } }, toolApproval: stepNumber < 1 ? 'auto' : { search: 'never' }, providerOptions: { openai: { reasoningEffort: 'low' } }, }; } ``` Type Reference [#type-reference] ```ts interface PrepareStepContext { stepNumber: number; steps: readonly AIGenerationStep[]; toolResults: readonly AIToolResult[]; state: AgentLoopState; runtime: unknown | undefined; providerOptions?: Record; } interface PrepareStepResult { allowTools?: readonly string[]; runtime?: unknown; toolContexts?: Readonly>; toolApproval?: ToolApprovalConfig; providerOptions?: Record; } type PrepareStepFunction = ( context: PrepareStepContext, ) => PrepareStepResult | Promise | void | Promise; ``` See Also [#see-also] * [Lifecycle Callbacks](/docs/guides/lifecycle-callbacks) — events at each phase of the loop * [Tool Approvals](/docs/guides/tool-approvals) — per-tool approval configuration * [Provider Options](/docs/guides/provider-options) — provider-specific settings --- # Presence-aware escalation (/docs/guides/presence-escalation) Presence-aware escalation [#presence-aware-escalation] When an agent needs a human and the primary contact does not answer, FluxyChat walks an **escalation chain** and nudges the next **online** member in the room. Start a watch [#start-a-watch] ```http POST /rooms/{roomId}/presence-escalation Authorization: Bearer ``` ```json { "escalationChain": ["tier1_user", "tier2_user", "manager_user"], "awaitingUserId": "tier1_user", "nudgeIntervalSeconds": 300 } ``` Cron tick [#cron-tick] Every five minutes (webhook flush cron), the Worker runs `tickPresenceEscalations`. Online users are read from room presence (`fetchAggregatedRoomLive`). Each nudge emits: * WebSocket `server_event` named `presence_escalation.nudge` * Audit event `presence_escalation.nudged` Manual tick (admin): ```http POST /presence-escalation/tick ``` Human responds [#human-responds] Any message in the room from a chain participant auto-resolves the watch (REST `POST /messages` path). Or call: ```http POST /rooms/{roomId}/presence-escalation/resolve ``` Dashboard [#dashboard] Configure chains from **Agent queue** and room settings. Pair with [Presence knock template](/docs/guides/cookbook-presence-knock). --- # Run a process (/docs/guides/processes) Self-host needs the ops D1 migrations under `apps/worker/db` (`0242`–`0244`, then `0252` guest redemption, `0256` MCP registry and `0257` per-user OAuth connections). Hosted already applies Worker migrations on deploy. Console [#console] Sign in so the dashboard has a project JWT (`NEXT_PUBLIC_FLUXYCHAT_WORKER_URL` is the same Worker you already use). Open **Processes**. 1. Describe the work. Example chips are prompts, not a product SKU. 2. If lint passes, request publish. The builder cannot publish itself. 3. A reviewer approves in Inbox or on the draft. Then start a run. 4. Complete human steps on **Runs**. Stop a run with the kill switch. Tools and policy: enable connectors there. Guests need an allowed email domain. Named views list columns you may filter. Free SQL is not a feature. Approvals reach people outside the room [#approvals-reach-people-outside-the-room] A write step stops the run and freezes the exact payload (hash-bound). The people who can act are told three ways, so an approval is never stuck because nobody re-opened the room: * **Inbox**: `GET /ops/inbox` returns tasks addressed to you (`assignee`) and tasks addressed to a role you hold. * **Off-room**: the run room's admins (or every member when the room has none) get an in-app notification, a web push, and an email with the run link. The operator Slack webhook `HITL_SLACK_WEBHOOK_URL`, when set, gets one summary line. Fan-out is capped at 20 recipients per approval. * **One-tap email**: room admins also get **Approve** and **Deny** links, single use and bound to the frozen payload hash. The link opens a confirmation page first (GET never decides; email scanners and Slack unfurls stop there); the button posts the token. Tokens expire with the approval (24h max) and need `ART50_MARK_SECRET` in production; links point at the Worker origin (`WORKER_PUBLIC_URL`, else `PUBLIC_APP_URL`). Members without the room admin role only get the console link. * **Runs page**: **Approvals waiting** on `/ops/runs` lists pending run approvals with Approve/Deny. Deciding needs an admin token; a decision on a changed payload is void. ```bash curl -X POST "$WORKER_URL/ops/approvals/$APPROVAL_ID/decide" \ -H "Authorization: Bearer $ADMIN_JWT" -H "Content-Type: application/json" \ -d '{"decision":"approve","payloadHash":"'"$PAYLOAD_HASH"'"}' ``` Publisher approvals (`stepId: "publish"`) stay on the builder page: approving the hash there still requires the matching publish call. Audit trail [#audit-trail] `GET /ops/runs/:id/audit` returns the evidence pack for one run: the step flow, every event, and the human decisions — who approved or denied, when, against which frozen payload hash. The payload itself is not copied; the hash is the proof of what was approved. * `?format=pdf` renders a one-page summary for a meeting. * `?format=jsonl` returns one JSON object per line (`record: run | step | event | approval`) for a SIEM or an auditor's system of record. `GET /ops/tool-calls` is the invocation log: one row per gateway call, whether it ran (`ops.tool.called`), is waiting on a frozen payload (`ops.tool.approval_required`), was denied before execution (`ops.tool.denied` with the reason: `tool_not_enabled`, `budget_exceeded`, `kill_switch`, …), or failed in the tool itself (`ops.tool.failed`). Filter with `?runId=`. The console shows the same list under **Tool activity** on `/ops/runs`, and each run row shows `tool calls used / budget`. `GET /ops/audit/export` (admin) is the project-wide version for a period — `?from=&to=&format=jsonl` returns run envelopes, every event, and the approvals with their decisions: the rows behind the SOC 2 evidence pack counts. Keep at least six months if you are a deployer of a high-risk AI system under the EU AI Act (Art. 26(6)). Search and files [#search-and-files] `files.search` talks to Cloudflare AI Search when you bind it. Response shape is `chunks` plus `citations` (`sourceId`, `title`, `score`). Legacy AutoRAG `{ data }` still maps. If AI Search is missing, search falls back to Vectorize room memory, then a D1 text scan. File bytes go to `OPS_R2` if you add that bucket, otherwise the existing `ATTACHMENTS` binding. OCR uses stored text first. Empty files can go through Workers AI `toMarkdown` when `env.AI.toMarkdown` exists. Incident workflows [#incident-workflows] A signature-verified incident event (PagerDuty, incident.io, Sentry) can start a published workflow in the room linked to the incident. Which workflow runs is per phase: `policy.incidentWorkflowSlugs` = `{ created, acknowledged, resolved }`; the legacy `policy.incidentWorkflowSlug` still covers `created`. Set it on the **Incident workflows** section of the policy page (`/ops/settings`) or with `PUT /ops/policy`. The run context carries `incident` (`id`, `title`, `severity`, `phase`) and the provider body stays untrusted text. Resolving an incident also writes an incident report into `files.search`. Phase slugs are provider-agnostic: do not also declare `trigger.match` on those workflows. The read tool `incidents.read` returns the tracked incident plus its recent timeline; with no `incidentId` it follows the incident carried by the run, so the built-in **Incident response** template and builder drafts for incident requests can read their own context. Enable it under **Process tools** like any other built-in. MCP servers [#mcp-servers] `mcp.call` calls a real MCP server registered for the project (Streamable HTTP). Admins manage the registry on **Process tools** (`/ops/settings`, section "MCP servers") or with `POST /ops/mcp-servers`; `GET /ops/mcp-servers` lists it redacted. A registration is a name, a URL, an optional bearer secret and the tool names the project may call. When the builder drafts an `mcp.call` step it pre-fills `server` and `tool` from the registry (keyword match, single-candidate fallback); if nothing fits it asks instead and the draft carries a `tool_input_missing` warning. Tool arguments come from the run context, not from the registry. Secrets are AES-GCM encrypted with `WEBHOOK_SECRET_ENCRYPTION_KEY` and never come back over HTTP. Tool names are opt-in: registration runs discovery and returns the names the server exposes; calls stay denied (`tool_not_allowed`) until you allow them. The server host must be in `ALLOWED_SSRF_HOSTS`, same as tenant webhooks. `mcp.call` is high risk and keeps its approval step. `POST /ops/mcp-servers/:id/refresh` re-discovers tools after the server changes. Per-user OAuth [#per-user-oauth] A server can authenticate **as each user** instead of with a shared secret: register it with `auth: "oauth"` (select "Per-user OAuth" on **Process tools**) and every `mcp.call` presents the access token of the user who triggered the run, so the provider enforces that user's permissions. * **Connect:** each member opens **Connected accounts** (`/ops/settings`) and clicks Connect (`POST /ops/mcp-servers/:id/connect`). The Worker discovers the authorization server from the MCP URL (RFC 9728 protected-resource metadata, then RFC 8414 / OIDC metadata) or from the registry overrides `oauthAuthorizeUrl` + `oauthTokenUrl`, and sends the browser to the provider with PKCE S256, a `resource` indicator and a single-use state. The state is stored only as a SHA-256 hash, expires in 10 minutes and is bound to one user and server. * **Callback:** `GET /public/ops/mcp/oauth/callback` exchanges the code (the verifier is encrypted at rest), stores the encrypted access and refresh tokens per user, and renders a plain HTML page. Tokens are never returned over HTTP, logged or shown in the console. * **Client:** set `oauthClientId` / `oauthClientSecret`, or leave them empty when the authorization server supports dynamic client registration (RFC 7591); the registration is stored on the server row and reused. * **Calls:** tokens refresh automatically shortly before expiry with the refresh token (rotated tokens are kept). With no connection the call fails as `mcp_connection_required`; when the refresh is refused the connection turns `expired` and calls fail as `mcp_connection_expired` until the user reconnects. `GET /ops/mcp-connections` lists your connections redacted; `DELETE /ops/mcp-connections/:id` disconnects (admins can disconnect any connection in the project). Deleting the server deletes its connections. * **Catalog:** `tools/list` needs a token, so the discoverable tools are filled when the first user connects; pick the allowed names afterwards as usual. * **Runs without a user actor** (incident-triggered or system runs) cannot use per-user servers: give those servers a bearer secret, or keep them out of system workflows. The authorization server host (often different from the MCP host) must also be in `ALLOWED_SSRF_HOSTS`. No new environment variables are needed: tokens and the PKCE verifier use the existing `WEBHOOK_SECRET_ENCRYPTION_KEY`, and the callback origin comes from `WORKER_PUBLIC_URL`; without it the Worker uses the origin of the connect request itself. Enterprise SSO (ID-JAG) [#enterprise-sso-id-jag] For servers in an enterprise deployment the provider may not want to trust an OAuth app at all: it trusts its own identity provider for SSO. Register those servers with `auth: "enterprise"` (cross-app access, the EMA/ID-JAG profile) and the same **Connect** button signs the user in **at the IdP**, not at the resource server: * **Config on the server:** `oauthAuthorizeUrl` = IdP authorize endpoint, `oauthClientId` / `oauthClientSecret` = the client registered at the IdP, `enterpriseIdpTokenUrl` = IdP token endpoint, `enterpriseIssuer` = the IdP `iss` value, `enterpriseAudience` = the **issuer identifier of the Resource Authorization Server**, `enterpriseJwksUrl` = IdP JWKS, `oauthTokenUrl` = the Resource AS token endpoint, `enterpriseResourceClientId` (+ optional `enterpriseResourceClientSecret`) = the client registered at the AS, `oauthScopes` = scopes for the resource. Registration is refused (`enterprise_config_incomplete`, with the missing field names) until the config is complete; there is no dynamic registration for enterprise servers. * **Flow:** the browser signs in at the IdP (authorization code + PKCE, scope `openid offline_access`). The Worker exchanges the OIDC ID token — or the IdP refresh token, on renewal — for an **ID-JAG** (RFC 8693 token exchange, `requested_token_type=urn:ietf:params:oauth:token-type:id-jag`), validates it (`typ`, signature against the IdP JWKS, `iss`, `aud`, `client_id`, `jti`, `exp`/`iat`, `resource` = this server), then redeems it at the AS with the RFC 7523 `jwt-bearer` grant. The AS access token is stored like a per-user OAuth token; the IdP refresh token is what renews it (rotation is kept). * **Fail closed:** an ID-JAG that does not validate is never presented to the AS, and no connection is stored. If the server switches auth mode between Connect and the callback, the attempt is refused before any network call. * **Hosts:** the IdP authorize/token/JWKS hosts **and** the AS token host must be in `ALLOWED_SSRF_HOSTS`. Like per-user OAuth, enterprise servers need a user actor, and an admin must allow the tools after the first connection. Optional Wrangler [#optional-wrangler] Keep `[ai]` for speech. For Processes search, create an AI Search instance in the Cloudflare dashboard, then uncomment in `wrangler.toml`: ```toml # [[ai_search]] # binding = "OPS_AI_SEARCH" # instance = "fluxychat-ops-default" # [[ai_search_namespaces]] # binding = "AI_SEARCH" # namespace = "default" ``` Namespace `get(projectId)` / `create({ id })` is used when the binding supports it. Vectorize stays the optional ranking index you already had commented. No extra `NEXT_PUBLIC_*` keys on the dashboard. Guests need `JWT_SECRET` on the Worker (you already use it for JWTs). HTTP sketch [#http-sketch] ```ts import { startBuilderSession, fetchOpsInbox } from "@fluxy-chat/sdk"; const session = await startBuilderSession(client, "When someone asks for time off, their manager approves, then notify HR."); const inbox = await fetchOpsInbox(client); ``` Inbox summaries may include `opsTasks`. That is the same queue as `/ops/inbox`. Guest invites: `POST /ops/guests/invite` with `comment` and/or `upload_file`. Redeem at `/ops/guest` without a member JWT. What we are not doing [#what-we-are-not-doing] Nango is ELv2. Do not embed it. New SaaS connectors wait for a real partner. Do not re-export Cloudflare `useAgent`. --- # Provider Options (/docs/guides/provider-options) Provider Options [#provider-options] Provider options let you pass provider-specific configuration beyond standard settings. They are namespaced by provider name so you can include options for multiple providers in the same call. Passing Provider Options [#passing-provider-options] Provider options flow through `AgentLoopOptions.providerOptions` and are accessible via `AgentLoopState.providerOptions` in `runStep`: ```ts import { runAgentLoop } from '@fluxy-chat/agent'; const result = await runAgentLoop({ runStep: async (state) => { const openaiOpts = state.providerOptions?.openai; // Use provider options when building the model request const response = await model.generate({ prompt: buildPrompt(state), providerOptions: state.providerOptions, }); return { text: response.text, finishReason: response.finishReason }; }, providerOptions: { openai: { reasoningEffort: 'high', }, }, }); ``` PrepareStep Integration [#preparestep-integration] Provider options can be changed mid-loop via `prepareStep`: ```ts const result = await runAgentLoop({ runStep: myRunStep, providerOptions: { openai: { reasoningEffort: 'low' } }, prepareStep({ stepNumber }) { if (stepNumber > 2) { return { providerOptions: { openai: { reasoningEffort: 'high' } }, }; } }, }); ``` Common Options Pattern [#common-options-pattern] Provider options are `Record` — each provider uses its own key: ```ts providerOptions: { openai: { reasoningEffort: 'high', reasoningSummary: 'detailed' }, anthropic: { thinking: { type: 'enabled', budgetTokens: 12000 }, effort: 'medium' }, } ``` Only the options matching the active provider are used by the model. Type Reference [#type-reference] ```ts interface AgentLoopOptions { providerOptions?: Record; // ... } interface AgentLoopState { providerOptions?: Record; // ... } // In prepareStep: interface PrepareStepResult { providerOptions?: Record; // ... } ``` See Also [#see-also] * [Prepare Step](/docs/guides/prepare-step) — dynamic step configuration * [LLM Middleware](/docs/guides/llm-middleware) — applying default settings via middleware * [Provider Registry](/docs/guides/provider-registry) — typed provider management --- # Provider & Model Management (/docs/guides/provider-registry) Provider & Model Management [#provider--model-management] The provider registry lets you manage multiple providers and models centrally, access models through simple string IDs, and pre-configure model settings. AIProviderRegistry [#aiproviderregistry] The base registry for registering and resolving models: ```ts import { AIProviderRegistry, DeterministicLanguageModel } from '@fluxy-chat/agent'; const registry = new AIProviderRegistry(); registry.register(new DeterministicLanguageModel('hello', undefined, 'my-model')); const model = registry.resolve('fluxy-test:my-model'); ``` createCustomProvider [#createcustomprovider] Creates a provider with preset models and optional fallback: ```ts import { createCustomProvider } from '@fluxy-chat/agent'; const myProvider = createCustomProvider({ languageModels: { fast: someFastModel, reasoning: someReasoningModel, }, fallbackProvider: baseRegistry, }); ``` ProviderRegistry [#providerregistry] Manages multiple providers and resolves with `providerId:modelId` notation: ```ts import { ProviderRegistry, AIProviderRegistry } from '@fluxy-chat/agent'; const registry = new ProviderRegistry({ openai: openaiRegistry, anthropic: anthropicRegistry, }); const model = registry.languageModel('openai:gpt-4'); // Or with custom separator: // registry.languageModel('anthropic > claude-3') ``` Custom Separator [#custom-separator] ```ts const registry = new ProviderRegistry( { openai: openaiRegistry, anthropic: anthropicRegistry, }, { separator: ' > ' }, ); const model = registry.languageModel('openai > gpt-4'); ``` Aliases with Preconfigured Settings [#aliases-with-preconfigured-settings] Combined with middleware for default settings: ```ts import { createCustomProvider, wrapLanguageModel, defaultSettingsMiddleware } from '@fluxy-chat/agent'; const myProvider = createCustomProvider({ languageModels: { 'fast': wrapLanguageModel({ model: baseModel, middleware: defaultSettingsMiddleware({ settings: { temperature: 0.3 }, }), }), 'reasoning': wrapLanguageModel({ model: baseModel, middleware: defaultSettingsMiddleware({ settings: { providerOptions: { openai: { reasoningEffort: 'high' } }, }, }), }), }, }); ``` createProviderRegistry [#createproviderregistry] Factory function for creating a `ProviderRegistry`: ```ts import { createProviderRegistry } from '@fluxy-chat/agent'; const registry = createProviderRegistry({ openai: openaiRegistry, anthropic: anthropicRegistry, }); registry.hasProvider('openai'); // true registry.listProviders(); // ['anthropic', 'openai'] ``` Type Reference [#type-reference] ```ts interface CustomProviderConfig { languageModels?: Record; embeddingModels?: Record; rerankModels?: Record; fallbackProvider?: AIProviderRegistry | AILanguageModel | (() => AILanguageModel); } interface ProviderRegistryConfig { [providerId: string]: AIProviderRegistry | CustomProviderConfig | AILanguageModel | (() => AILanguageModel); } function createCustomProvider(config: CustomProviderConfig): AIProviderRegistry; function createProviderRegistry(config: ProviderRegistryConfig, options?: ProviderRegistryOptions): ProviderRegistry; ``` See Also [#see-also] * [Provider Options](/docs/guides/provider-options) — per-provider settings * [LLM Middleware](/docs/guides/llm-middleware) — middleware combined with providers * [Available Providers](/docs/guides/provider-registry) — provider implementations --- # Prune Messages — Context Compaction (/docs/guides/prune-messages) Prune Messages — Context Compaction [#prune-messages--context-compaction] `pruneMessages` compacts a message array to stay within token or count limits while preserving essential context. Use it to prevent agent loops from growing beyond the model's context window. Basic Usage [#basic-usage] ```ts import { pruneMessages } from '@fluxy-chat/agent'; const messages = [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Tell me about AI.' }, { role: 'assistant', content: 'AI stands for Artificial Intelligence...' }, { role: 'user', content: 'Tell me more.' }, ]; const pruned = pruneMessages(messages, { maxMessages: 2 }); // Keeps system message + the most recent message // Result: [{ role: 'system', ... }, { role: 'user', content: 'Tell me more.' }] ``` Options [#options] | Option | Type | Default | Description | | -------------- | -------------------------- | ------- | ------------------------------------------------------------ | | `maxMessages` | `number` | — | Maximum number of messages to keep (system always preserved) | | `maxChars` | `number` | — | Maximum total characters across all messages | | `removeRoles` | `readonly AIMessageRole[]` | — | Filter out specific roles (e.g., `['tool']`) | | `removeEmpty` | `boolean` | `false` | Remove messages with empty/no content | | `preserveLast` | `boolean` | `true` | Always keep the last non-system message | Max Messages [#max-messages] Truncates the history to the N most recent messages, always preserving the system message: ```ts const pruned = pruneMessages(messages, { maxMessages: 5 }); // Keeps system + 4 most recent messages ``` Max Characters [#max-characters] Truncates character count, removing oldest messages first: ```ts const pruned = pruneMessages(messages, { maxChars: 4000 }); // Drops oldest messages until total is <= 4000 chars ``` Remove by Role [#remove-by-role] Strip tool-role messages to reduce noise: ```ts const pruned = pruneMessages(messages, { removeRoles: ['tool'] }); // All tool-role messages are removed ``` Multi-Constraint [#multi-constraint] Multiple options compose. The system message is always preserved: ```ts const pruned = pruneMessages(messages, { maxMessages: 20, maxChars: 8000, removeRoles: ['tool'], removeEmpty: true, }); ``` Type Reference [#type-reference] ```ts interface PruneMessagesOptions { maxMessages?: number; maxChars?: number; removeRoles?: readonly AIMessageRole[]; removeEmpty?: boolean; preserveLast?: boolean; } function pruneMessages( messages: readonly AIMessage[], options: PruneMessagesOptions, ): AIMessage[]; ``` See Also [#see-also] * [Loop Control](/docs/guides/loop-control) — `maxSteps`, `maxToolCalls` limits * [Subagents](/docs/guides/subagents) — context isolation pattern --- # Public share link (/docs/guides/public-share) Public share link [#public-share-link] Hosted console: **Rooms** → pick a **public** room → **Copy public share link**. That URL is `/share/:token` on the dashboard origin. The token is random, not the room id. Optional `?pk=pk_…` if your Worker requires a publishable key for guest join. Never put `fc_` on this URL. The page is a spectator: no composer. Whispers, tool arguments, and `visibleTo` are stripped. Group and DM rooms return 404. Revoke with `POST /rooms/:id/share/revoke` (mints a new token). The HTML is `noindex`. API [#api] ```http GET /public/share/:token ``` No JWT. Rate-limited by IP. Response has `name`, `path`, `guestEnabled`, `guestReadOnly`. No API keys. Members can also: ```http GET /rooms/:id/share Authorization: Bearer ``` Same metadata after `canAccessRoom`. Still no keys. Embed [#embed] `FluxyChatWidget` and `ChatWindow` accept `readOnly`. Guest embeds still show **Powered by FluxyChat** unless `poweredBy={false}`. Worker flag `PUBLIC_GUEST_READ_ONLY` blocks guest writes on the API. The share page hides the composer even if that flag is off. Hosted is beta. --- # Publishable keys (/docs/guides/publishable-keys) `fc_` keys mint member JWTs (`POST /auth/token`, `signIn`). Never put them in a SPA. `pk_` keys are **publishable**. Safe in the bundle. They identify the project for: * `FluxyRealtimeProvider` `publishableKey` (anonymous guest JWT, public rooms) * `POST /tokens/anonymous` * `POST /public/rooms/:id/guest-session` (optional header `X-Fluxy-Api-Key`) Hosted weekend path: `GET /public/demo-credentials` returns `{ publishableKey, roomId }` when the Worker has `PUBLIC_DEMO_PUBLISHABLE_KEY`. `pnpm setup:hosted` writes that into `.env`. Without that env, copy a `pk_` from the console. They **cannot** mint a member JWT. The Worker returns `403 publishable_key_not_allowed`. ```tsx import { FluxyRealtimeProvider, useChat } from "@fluxy-chat/react"; function Room() { const { messages, sendMessage } = useChat({ roomId: "general" }); } ``` Anonymous JWTs have `roles: ["guest"]` and no `roomId` claim. They can join **public** rooms in that project. Private rooms still need a member JWT. Widget / guest-session (stable `guestKey` in localStorage, scoped to one room): ```tsx import { FluxyChatClient } from "@fluxy-chat/sdk"; import { FluxyChatWidget } from "@fluxy-chat/ui-kit"; const guest = await FluxyChatClient.joinPublicRoomAsGuest(workerUrl, "general", { publishableKey: "pk_...", }); ``` New projects return both `apiKey` (`fc_`) and `publishableKey` (`pk_`). Rotate secret keys with the existing rotate route (does not revoke `pk_`). Mint or rotate `pk_` with `POST /admin/projects/:id/publishable-key`. When a guest later signs up, [link the guest identity to the account](/docs/guides/guest-to-account) — room memberships move over, nothing is lost. --- # Regex Message Matching (/docs/guides/regex-message-matching) Regex Message Matching [#regex-message-matching] `createMessagePatternMatcher()` provides pattern-based message routing using regular expressions, enabling keyword-triggered handlers without @-mentions. Usage [#usage] ```ts import { createMessagePatternMatcher } from "@fluxy-chat/sdk"; const matcher = createMessagePatternMatcher(); matcher.onNewMessage(/^!help/, async (msg, match) => { console.log(`Help requested by ${msg.userId} in ${msg.roomId}`); }); // Wire into event stream connection.onAnyEvent((event) => { matcher.match(event); }); ``` API [#api] * `onNewMessage(pattern, handler, options?)`: Register a pattern handler * `removeHandler(pattern, handler)`: Remove a specific handler * `match(event)`: Test event against all patterns; returns match count * `getPatterns()`: List registered patterns * `clear()`: Remove all patterns Multiple Patterns [#multiple-patterns] Multiple patterns can match the same message; all matching handlers are called: ```ts matcher.onNewMessage(/^!ping/, handlePing); matcher.onNewMessage(/^!pong/, handlePong); ``` Labels [#labels] Optional labels and descriptions help identify patterns for debugging: ```ts matcher.onNewMessage(/^!status/, handler, { label: "status", description: "Matches !status commands", }); ``` --- # Resumable useChat without Redis (/docs/guides/resumable-usechat-cloudflare) Vercel AI SDK `useChat` resume often assumes Redis. FluxyChat does not. The session is the **room**. What you get [#what-you-get] `FluxyRoomChatTransport` maps `sendMessages` to `invokeAgentRest` and `reconnectToStream` to `GET /ai/streams/active` then `GET /ai/streams/:id/resume`. Those routes read `RATE_LIMIT_KV` or `STREAM_RESUME_KV`. No Redis. Live token paint still uses the room WebSocket. The HTTP body is the full reply encoded as `text-delta` chunks. If the **room** Durable Object hibernates mid-call, that LLM request does not resume like Cloudflare Think `chatRecovery`. Generation for `POST /agents/:id/invoke` runs on the Worker isolate, and when `AGENT` is bound it runs on `AgentDurableObject` id `room-run:{project}:{room}` so two invokes serialize. Kill the room object; the run object can keep going. Kill the run object and you lose the in-flight model call. Clone [#clone] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-room --example shared-ai-room ``` ```ts import { FluxyChatClient, FluxyRoomChatTransport } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: "https://your-worker.example.workers.dev", userId: "alice", token: jwt, }); const transport = new FluxyRoomChatTransport({ client, roomId: "general", agentId: "assistant-id", }); ``` Pass `transport` to AI SDK `useChat({ transport })`. Do not import `ai` from `@fluxy-chat/sdk`. Mid-turn inject: `POST /rooms/:roomId/agent-steer` with `{ content }`. Stop from another tab: `POST /rooms/:roomId/agent-stop`. Room `stopAgentStream` still aborts the Worker fetch. Dev.to / Show HN posting is on you. This page is the tutorial. --- # Role-scoped message visibility (/docs/guides/role-scoped-visibility) Role-scoped message visibility [#role-scoped-message-visibility] This is a **room kernel primitive** (D1 `visibility` / `visible_to_json`, WebSocket fan-out filter), not only a cookbook. Whisper messages target **specific user ids**. Role-scoped messages target **everyone with a room role** (for example all evaluators in an interview room). Candidates and guests in the same session do not see them on the timeline or over WebSocket. The gallery app [`deal-room`](/docs/getting-started/gallery) does the two-tab check: buyer vs `?seat=counsel`. Counsel sends a whisper `visibleTo` itself. Use a public guest room so each seat is a different user. A shared member JWT is one identity, so both tabs would see the note. Send from the SDK [#send-from-the-sdk] Assign roles with `room_members.role` when you add members (REST or provisioning). Then send with a `role:` prefix: ```ts await client.createMessage(roomId, "Candidate used O(n²) sort; suggest follow-up.", { visibility: "role:evaluator", }); ``` Whisper still works for named users: ```ts await client.createMessage(roomId, "Private nudge", { visibility: "whisper", visibleTo: [teacherUserId], }); ``` WebSocket sends use the same fields on the `message` frame. MCP agents [#mcp-agents] Room MCP `send_message` accepts optional `visibility` and `visibleTo`: ```json { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "send_message", "arguments": { "content": "AI note for evaluators only", "visibility": "role:evaluator" } }, "id": 1 } ``` `read_timeline` applies the same rules for the JWT holder. Enforcement [#enforcement] * **WebSocket fan-out** delivers scoped messages only to authorized sockets (author always receives their own message). * **History** (connect snapshot, REST, search, export, MCP) filters in D1 using the viewer's membership role. * Role names are lowercase alphanumeric with underscores (1–64 chars), matched case-insensitively against `room_members.role`. Interview eval pattern [#interview-eval-pattern] 1. Create a room and add the candidate as `member` (or `guest`). 2. Add human evaluators and your AI agent with `role: evaluator` (or `evaluator` in `room_members.role`). 3. Agent posts analysis with `visibility: "role:evaluator"`. 4. Candidate UI shows the public thread only; evaluator dashboard shows public plus role-scoped notes. See [Room as MCP server](/docs/guides/room-as-mcp-server) to connect an external evaluator agent. --- # Room as MCP server (/docs/guides/room-as-mcp-server) Room as MCP server [#room-as-mcp-server] External agents can join a **single room** like a human member: read the timeline, send messages, list who is online, and subscribe to live events. They use **your** member JWT and their own LLM. FluxyChat does not proxy their model calls. Endpoint [#endpoint] ``` POST https:///mcp/rooms/ Authorization: Bearer Content-Type: application/json ``` JSON-RPC 2.0 body, same as other MCP HTTP transports: ```json { "jsonrpc": "2.0", "method": "initialize", "params": {}, "id": 1 } { "jsonrpc": "2.0", "method": "tools/list", "params": {}, "id": 2 } { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "send_message", "arguments": { "content": "Hello from Claude" } }, "id": 3 } ``` Tools (room-scoped) [#tools-room-scoped] | Tool | What it does | | ------------------- | ------------------------------------------------------------ | | `send_message` | Post text to this room (D1 + WebSocket fan-out) | | `read_timeline` | Recent messages, newest first; whisper and role scopes apply | | `list_participants` | Room members + online presence | | `subscribe_events` | Returns SSE and WebSocket URLs for live events | There is no `roomId` argument on these tools. The room comes from the URL path. Live events [#live-events] `subscribe_events` returns: * `sseUrl`: `GET /rooms/:roomId/stream` with `Accept: text/event-stream` * `websocketPath`: `/ws/room/:roomId?token=` * `mcpEventsUrl`: alias at `GET /mcp/rooms/:roomId/events` (same SSE stream) Use the same JWT you used for MCP. Claude Desktop [#claude-desktop] In **Settings → Developer → Edit config**, add a server block (replace worker URL, room id, and JWT): ```json { "mcpServers": { "fluxychat-support": { "url": "https://YOUR_WORKER/mcp/rooms/support", "headers": { "Authorization": "Bearer YOUR_MEMBER_JWT" } } } } ``` Mint JWTs server-side in production. Do not ship long-lived tokens in client apps. Project-wide MCP [#project-wide-mcp] `POST /mcp` still exposes project-level tools (`list_rooms`, `search_chat`, etc.). Use room MCP when the external agent should stay in one channel. Security and limits [#security-and-limits] * JWT must be a **member** of the room (same rules as REST and WebSocket). * Guest tokens scoped to one public room cannot call MCP for a different room id. * Rate limits: `RATE_LIMIT_MCP_MESSAGES_PER_MINUTE` (default 30) and `RATE_LIMIT_MCP_TOOLS_PER_MINUTE` (default 120). * Tool calls are logged in the MCP identity audit log (Settings → MCP). Dashboard [#dashboard] Open **Rooms**, select a room, and use **Connect external agent (MCP)** for copy-ready curl and Claude Desktop JSON. See also [#see-also] * [MCP client integration](/docs/guides/mcp-client): FluxyChat agents calling *external* tools * [MCP registry listing](/docs/guides/mcp-registry): `server.json` — not published on the official registry yet * [Agent events on the same WebSocket](/docs/learn/agent-events-same-websocket-stream) --- # Room Decisions (/docs/guides/room-decisions) Room Decisions [#room-decisions] Jev (TypeSafe, Workers AI `typesafe/jev`) and CLM-8B (Apache-2.0, self-hosted GPU) **do not generate messages**. They return a typed choice or a noul score. Groq (or your room LLM) still writes text. Thresholds, HITL, and two-key stay in application code. Author numbers (DeepSWE, Terminal-Bench, BFCL, WikiRacing, “13×”) are **theirs**. We do not claim them. CLM needs vLLM-class GPUs; that is not on the hosted free plan. What is on [#what-is-on] | Kind | Default | What it does | | -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Floor (`shouldRespond`) | `keyword` | Legacy ambient keyword policies. Opt-in: `invoke_only`, `calibrated`, `silent`. | | Tool HITL (`approveTool`) | `shadow` | Log System One; extra alignment HITL only in `enforce`. Two-key remains last word. Auto-handoff stays off unless `SYSTEM_ONE_AUTO_HANDOFF`. | | Cost router (`routeModel`) | `shadow` | Logs skip / small / large. **`enforce`** may skip LLM (`OK.`) or cap tokens / `ROOM_LLM_SMALL_MODEL`. No published €/room-hour. | | Notify (`notifyTriage`) | `shadow` | Reuses existing priority scores. **`enforce`** skips push on low, non-mention. Mentions still push. | | Auto-summon | `shadow` | Fixed bot roster (max 12) + silence. **`enforce`** writes a feed suggestion. Does not add members. Not a 1k-candidate directory. | | NL policy | `shadow` | Room `nlPolicy` or `ROOM_NL_POLICY`. System One noul → ok / warn / block. **`enforce`** rewrites agent text only. Not a medical-device or legal filter. | | Labels | opt-in | D1 `room_system_one_decisions`: kind, options, probabilities, model, human outcome (approved / denied / escalated). Hosted needs `ROOM_DECISIONS_LABELS=true` or `decisions.labelsOptIn`. Skip rooms linked to `no_train` connections. | `GET /rooms/:id/system-one-decisions` (member JWT). Console: Rooms → Advanced → **Room Decisions**. Model counts on that page are not a significance test. `fluxy.config` [#fluxyconfig] ```ts decisions: { shouldRespond: { mode: "keyword" }, approveTool: { mode: "shadow" }, routeModel: { mode: "shadow" }, notifyTriage: { mode: "shadow" }, autoSummon: { mode: "shadow" }, nlPolicy: { mode: "shadow" }, } ``` Env: `ROOM_FLOOR_MODE`, `ROOM_TOOL_DECISION_MODE`, `ROOM_ROUTE_MODE`, `ROOM_NOTIFY_MODE`, `ROOM_SUMMON_MODE`, `SYSTEM_ONE_CASCADE=clm_then_jev`. `ROOM_DECISION_MARGIN_MIN` is per-decision-type, not copied from a Jev noul threshold. Floor modes [#floor-modes] * **keyword** — today’s ambient `message_keyword` policies (no behavior change). * **invoke\_only** — ambient only if the line contains `@handle` (CHI-style: don’t jump into small talk). * **calibrated** — System One `silence` vs `speak` on a **fixed** two-option menu. Low margin → silence. * **silent** — no ambient dispatch. @mentions still invoke agents on the mention path. That is not ambient. Tool gate [#tool-gate] Deterministic two-key + tool policy first. System One noul can add HITL. Alignment noul (LlamaFirewall-style “does this serve the user’s goal?”) runs only in `enforce`. We do **not** abort the run: extra HITL or a tool error, not a silent kill. Shadow/warn only write the audit row. Not in this slice [#not-in-this-slice] Mid-stream abort. Best-of-N draft pick (Jev lost as a selector on two public benches; don’t sell it). A published cost-per-room-hour. Certified medical/legal compliance. Related [#related] * [HITL](/docs/guides/hitl-approval-chain) * [Shared-room defaults](/docs/guides/security/shared-room-agent-defaults) * [fluxy.config](/docs/guides/fluxy-config) --- # Room memory for operators (/docs/guides/room-memory) Room memory for operators [#room-memory-for-operators] Room memory stores durable facts from the conversation: decisions, tasks, FAQs, user context, and key facts. Each entry links to source messages for audit. Query [#query] ```http GET /rooms/:roomId/memory?limit=12 Authorization: Bearer ``` Optional filter: `?kind=decision` Keyword search: `?q=pricing` (D1 `LIKE`). If you bind Vectorize + Workers AI (`VECTORIZE`, `AI`), extract also upserts embeddings and `q` re-ranks hits that already matched D1. Unbound Vectorize is a no-op. Not Cloudflare AI Search. Not Notion/Drive connectors. Extract on demand [#extract-on-demand] ```http POST /rooms/:roomId/memory/extract Authorization: Bearer ``` Requires a configured LLM provider on the Worker. Returns extracted entries and insert/update counts. Dashboard [#dashboard] **Rooms → Advanced → Room memory**. Search box calls `?q=`. Extract still needs an LLM on the Worker. Memory kinds [#memory-kinds] | Kind | Use | | -------------- | --------------------------------------- | | `decision` | Choices made in the room | | `task` | Action items and TODOs | | `faq` | Repeated questions and answers | | `user_context` | Preferences or facts about participants | | `key_fact` | Durable technical or business facts | | `sentiment` | Tone signals (use sparingly) | Pair with [Live knowledge graph](/docs/guides/live-knowledge-graph) for relational context. --- # Room OS positioning (/docs/guides/room-os-positioning) Room OS for humans and agents [#room-os-for-humans-and-agents] FluxyChat is not a chat widget SKU. It is a **room operating system**: * Humans and agents are peers on one timeline * Visibility scopes (room, whisper, role) control who sees what * External agents join via MCP with their own LLM keys * Cross-org negotiation, quorum acks, and presence escalation are primitives Compare page and marketing copy should lead with these patterns, not feature parity tables alone. See [Hackathon cookbooks](/docs/guides/hackathon-cookbooks) for proof from 35 weekend builds. --- # Room tickets (GitHub, Linear, Jira) (/docs/guides/room-tickets) Room tickets [#room-tickets] Turn a room outcome into an issue in a tracker you already pay for. You put the tokens on the Worker. There is no FluxyChat OAuth app for Linear or Jira. Route [#route] ```http POST /rooms/:roomId/tickets Authorization: Bearer Content-Type: application/json { "provider": "github", "title": "Follow up from room", "body": "optional markdown", "repo": "owner/name" } ``` `provider` is `github`, `linear`, or `jira`. | Provider | Extra fields | Worker env | | -------- | --------------------- | ----------------------------------------------- | | GitHub | `repo` (`owner/name`) | `GITHUB_TOKEN` | | Linear | `teamId` | `LINEAR_API_KEY` | | Jira | `projectKey` | `JIRA_BASE_URL`, `JIRA_EMAIL`, `JIRA_API_TOKEN` | The Worker appends the room id to the body. GitHub and Linear call only `api.github.com` and `api.linear.app`. Jira `JIRA_BASE_URL` must be `https://*.atlassian.net`. Hosted multi-tenant refuses Worker-env PATs; put a per-project encrypted `writeToken` on `PUT /integrations/connections`. Self-host may still use env PATs. Not this product [#not-this-product] * Slack HITL taps stay on `/public/hitl/*`. This route does not post to Slack channels. * Agent-drafted bodies are still plaintext to the LLM that wrote them. * GitHub issues also exist as an **AI Action** (`github_issue`) with a token in the action config. Room tickets use the Worker env token so operators do not paste a PAT into every action row. Related [#related] * [Import a transcript](/docs/guides/import-transcript) * [Shared-room agent defaults](/docs/guides/security/shared-room-agent-defaults) --- # Self-host one command (/docs/guides/self-host-one-command) Self-host in one command [#self-host-in-one-command] `pnpm run self-host` copies env templates, then asks for a Groq key if the terminal is interactive. It also writes `API_KEY_HASH_SALT` if missing. Agent model on Groq: `openai/gpt-oss-20b`. ```bash pnpm run self-host ``` Then start services: ```bash # Terminal 1 — Worker API + WebSocket pnpm --filter @fluxy-chat/worker dev # Terminal 2 — Dashboard console (optional) pnpm --filter dashboard dev ``` Verify with: ```bash pnpm run first-message ``` What the script does [#what-the-script-does] 1. `pnpm install` (if needed) 2. `pnpm run dev:setup` — creates `apps/worker/.dev.vars` and `apps/dashboard/.env.local` from templates 3. `wrangler d1 migrations apply fluxychat --local` — schema + seed data (including `builtin_agent_templates`) Production deploy [#production-deploy] For remote Cloudflare deploy, see [Local development](/docs/getting-started/local-development) and [Production setup](/docs/operations/production-setup): ```bash cd apps/worker pnpm exec wrangler d1 migrations apply fluxychat --remote pnpm run deploy ``` Set secrets via `wrangler secret put` (JWT signing keys, LLM provider keys, webhook HMAC secrets). Related [#related] * [Client setup](/docs/getting-started/client-setup) — SDK integration * [Auth JWT](/docs/guides/auth-jwt) — mint member tokens --- # SentMessage (Chainable Message Result) (/docs/guides/sent-message) SentMessage (Chainable Message Result) [#sentmessage-chainable-message-result] `createSentMessage()` wraps a sent message with chainable `.edit()`, `.delete()`, `.addReaction()`, `.removeReaction()` methods. Usage [#usage] ```ts import { createSentMessage } from "@fluxy-chat/sdk"; const msg = createSentMessage(adapter, "thread\:abc", "msg:123", "Hello world"); // Chainable operations await msg.addReaction("+1"); await msg.edit("Updated content"); await msg.removeReaction("+1"); await msg.delete(); ``` API [#api] ```ts interface SentMessage { id: string; threadId: string; content: string; edit(newContent: string): Promise; delete(): Promise; addReaction(emoji: string): Promise; removeReaction(emoji: string): Promise; } ``` Chaining [#chaining] `edit()` returns a new `SentMessage` so calls can be chained: ```ts const edited = await msg.edit("v1").edit("v2"); ``` Integration [#integration] Combine with `postMessage` on a `ThreadAdapter`: ```ts const raw = await adapter.postMessage(threadId, "Hello"); const sent = createSentMessage(adapter, threadId, raw.id, "Hello"); await sent.addReaction("rocket"); ``` --- # shadcn registry (/docs/guides/shadcn-registry) shadcn registry [#shadcn-registry] This is **our** registry, not a listing on ui.shadcn.com. `npx shadcn add` fetches JSON from the hosted dashboard origin. ```bash npx shadcn@latest add https://fluxychat.com/r/fluxy-chat-widget.json ``` Index: `GET /r/registry.json`. Other items: `fluxy-chat-window.json`. The files dropped in your repo import `@fluxy-chat/ui-kit` / `@fluxy-chat/ui`. Pin those packages. This is not a fork of the component source. Self-host: point the URL at your dashboard origin that serves `/r/:name`. --- # Shared AI room in 10 minutes (/docs/guides/shared-ai-room-10-minutes) Shared AI room in 10 minutes [#shared-ai-room-in-10-minutes] This is the gallery app for “people and agents in the same room.” It is not a Notion clone. Chat, a Yjs document, and `invokeAgent` share one Cloudflare Durable Object. You already have the template; this page is the 10-minute path. 1\. Scaffold [#1-scaffold] ```bash npx @fluxy-chat/create-fluxy-chat@latest my-room --example shared-ai-room cd my-room cp .env.example .env ``` Pin `@fluxy-chat/sdk@0.6.16` (the template already does). Hosted beta: set `VITE_FLUXYCHAT_WORKER_URL` to `https://api.fluxychat.com` and a `pk_` from the console. Self-host: deploy `apps/worker` from this repo, then point the Vite app at that origin. 2\. Run two tabs [#2-run-two-tabs] ```bash pnpm install pnpm dev ``` Open the URL twice. Guest `pk_` rooms do not mint a member JWT. Send a message in one tab; it should appear in the other. If you wired an agent, `@assistant` (or your handle) writes `tool_call` / `tool_result` on the same timeline. 3\. What you are not building [#3-what-you-are-not-building] * Not MQTT, not an SFU, not a 14-channel helpdesk. * Bridges exist: you create the Slack/Discord/Telegram/WhatsApp/Teams app and paste the token. We do not sell a WhatsApp channel. * Hosted is open beta, no SLA. Next: [Gallery](/docs/getting-started/gallery), [Choose your path](/docs/getting-started/choose-your-path), [Reconnect + jitter](/docs/learn/reconnect-durable-objects-hibernation). --- # Skill Uploads (/docs/guides/skill-uploads) Skill Uploads [#skill-uploads] Skill uploads let you upload custom skill bundles to AI providers. A skill is a set of files (e.g., a `SKILL.md` describing behavior) that providers load into sandboxed environments. Basic Usage [#basic-usage] ```ts import { uploadSkill, generateText } from '@fluxy-chat/agent'; const { providerReference } = await uploadSkill({ api: mySkillProvider, files: [ { path: 'my-skill/SKILL.md', content: readFileSync('./SKILL.md') }, ], displayTitle: 'My Custom Skill', }); // Use the providerReference in subsequent model calls ``` Skill Files [#skill-files] Each file has a relative `path` and `content` (string or Uint8Array): ```ts const { providerReference } = await uploadSkill({ api: provider, files: [ { path: 'skill/SKILL.md', content: '# My Skill\nHelps with data analysis.' }, { path: 'skill/helper.py', content: 'def analyze(data): ...' }, ], }); ``` Upload Result [#upload-result] `uploadSkill` returns an `UploadSkillResult`: | Field | Type | Description | | ------------------- | ------------------- | ------------------------------------ | | `providerReference` | `ProviderReference` | Maps provider names to skill IDs | | `displayTitle` | `string?` | Human-readable title | | `name` | `string?` | Name inferred by the provider | | `description` | `string?` | Description inferred by the provider | | `latestVersion` | `string?` | Latest version identifier | | `providerMetadata` | `object?` | Provider-specific metadata | | `warnings` | `Warning[]` | Warnings for unsupported options | ProviderReference [#providerreference] A `ProviderReference` maps provider names to provider-specific skill IDs: ```ts type ProviderReference = Record; // Example: { anthropic: 'skill_abc123', openai: 'sk_...' } ``` Multi-Provider Usage [#multi-provider-usage] Upload a skill to multiple providers and merge references: ```ts const [openaiUpload, anthropicUpload] = await Promise.all([ uploadSkill({ api: openaiProvider, files }), uploadSkill({ api: anthropicProvider, files, displayTitle: 'My Skill' }), ]); const mergedRef = { ...openaiUpload.providerReference, ...anthropicUpload.providerReference, }; ``` Implementing a SkillProvider [#implementing-a-skillprovider] ```ts import type { SkillProvider, UploadSkillResult, SkillFile } from '@fluxy-chat/agent'; class MySkillProvider implements SkillProvider { async upload(files: readonly SkillFile[], options?: { displayTitle?: string }): Promise { // Upload files to the provider's API return { providerReference: { myprovider: 'sk_abc' }, displayTitle: options?.displayTitle, }; } } ``` Type Reference [#type-reference] ```ts type ProviderReference = Record; interface SkillFile { path: string; content: string | Uint8Array; } interface SkillProvider { upload(files: readonly SkillFile[], options?: { displayTitle?: string }): Promise; } interface UploadSkillOptions { api: SkillProvider; files: readonly SkillFile[]; displayTitle?: string; } interface UploadSkillResult { providerReference: ProviderReference; displayTitle?: string; name?: string; description?: string; latestVersion?: string; providerMetadata?: Record; warnings?: Array<{ code?: string; message: string }>; } function uploadSkill(options: UploadSkillOptions): Promise; ``` See Also [#see-also] * [Provider Registry](/docs/guides/provider-registry) — combining providers * [HarnessAgent](/docs/guides/harness-agent) — external agent runtime wrapper --- # Slack and Discord bridge (/docs/guides/slack-discord-bridge) Bridge external chat platforms into FluxyChat rooms with **two-way channel mappings**: room messages are delivered out to the platform, and **signed webhooks** sync replies back. Manage bridges from the dashboard [**Bridges**](/bridges) page or the admin REST API. Create a bridge [#create-a-bridge] ```bash curl -X POST "$WORKER_URL/admin/bridges" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "platform": "slack", "name": "Support Slack", "token": "xoxb-...", "signingSecret": "a1b2c3..." }' ``` Supported platforms: `slack`, `discord`. * `token` (optional) is the bot token used for outbound delivery. * `signingSecret` (optional, but inbound returns `503` without it) is the Slack signing secret or the Discord application public key. * Both secrets are encrypted at rest when the worker has `WEBHOOK_SECRET_ENCRYPTION_KEY` configured. Rotate or add secrets later without recreating the bridge (recreating deletes its mappings and message map): ```bash curl -X PATCH "$WORKER_URL/admin/bridges/br_abc123" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "signingSecret": "rotated-secret" }' ``` Inbound webhook URLs [#inbound-webhook-urls] Point your Slack Event Subscriptions or Discord interactions endpoint at: | Platform | URL | | -------- | ------------------------------------------------------ | | Slack | `POST {WORKER_URL}/webhooks/bridge/slack/{bridgeId}` | | Discord | `POST {WORKER_URL}/webhooks/bridge/discord/{bridgeId}` | Inbound requests are verified before parsing: * Slack: `x-slack-signature` (v0 scheme); `x-slack-request-timestamp` must be within 5 minutes. * Discord: `x-signature-ed25519` over `{timestamp}{body}`. Failures are fail-closed: `401` for a bad or stale signature, `503 signature_not_configured` when the bridge has no secret. Slack URL verification (`url_verification` challenge) is answered after the signature check. Channel mappings [#channel-mappings] Map an external channel ID to a FluxyChat room: ```bash curl -X POST "$WORKER_URL/admin/bridges/mappings" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "bridgeId": "br_abc123", "roomId": "room_support", "externalChannelId": "C01234567", "externalChannelName": "#support", "syncDirection": "both" }' ``` `syncDirection` accepts `both` (default), `inbound`, or `outbound`. Outbound delivery [#outbound-delivery] Messages sent in a mapped room of a `connected` bridge are queued in `bridge_deliveries` and delivered with the bridge credentials: * Slack: `chat.postMessage` with the bot token, or the configured `webhookUrl` (incoming webhook) when no token is set. * Discord: `POST /channels/{channel_id}/messages` with the bot token, or the configured webhook URL. Failures retry with backoff (60s, 5m, 30m, 1h) on the webhook-flush cron until `BRIDGE_MAX_ATTEMPTS` (default 5), then land as `failed` with the provider error surfaced on the bridge. Inspect the last 20 deliveries: ```bash curl "$WORKER_URL/admin/bridges/br_abc123/deliveries" \ -H "Authorization: Bearer $ADMIN_JWT" ``` Messages imported from a platform are never echoed back to that same platform. Connect and monitor [#connect-and-monitor] ```bash # List bridges curl "$WORKER_URL/admin/bridges" -H "Authorization: Bearer $ADMIN_JWT" # Connect / disconnect curl -X POST "$WORKER_URL/admin/bridges/br_abc123/connect" \ -H "Authorization: Bearer $ADMIN_JWT" # Stats curl "$WORKER_URL/admin/bridges/stats" -H "Authorization: Bearer $ADMIN_JWT" ``` Troubleshooting [#troubleshooting] * **503 on webhook** — no signing secret configured. Add one from the dashboard (Secrets) or with PATCH. * **401 on webhook** — signature mismatch or a Slack timestamp older than 5 minutes. * **404 on webhook** — verify `bridgeId` and platform match (`slack` bridge only accepts the `/slack/` path). * **Messages not appearing inbound** — confirm a mapping exists for the external `channel_id` and the bridge status is `connected`. * **Outbound stuck pending or failed** — check `GET /deliveries` for `lastError`; delivery needs a bot token or a webhook URL. * **Slack duplicates** — ignore bot subtypes; the parser skips `message` events with `subtype`. See also [Webhooks catalog](/docs/webhooks/catalog) for delivery signing and replay tooling, and [Matrix bridge](/docs/guides/matrix-bridge) for federation. --- # Slash Commands (/docs/guides/slash-commands) Slash Commands [#slash-commands] `createSlashCommandRegistry()` provides command parsing, registration, and execution for chat messages starting with `/`. Usage [#usage] ```ts import { createSlashCommandRegistry } from "@fluxy-chat/sdk"; const registry = createSlashCommandRegistry(); registry.register({ name: "ping", description: "Check latency", execute: async (args, ctx) => { await ctx.reply("pong"); return { success: true }; }, }); ``` Parsing [#parsing] ```ts const result = registry.parse("/kick user123 --reason spam"); // { command: "kick", args: { positional: ["user123"], named: { reason: "spam" }, flags: Set() } } ``` Built-in Commands [#built-in-commands] * `/help` — Show available commands * `/clear` — Clear the conversation --- # StackBlitz examples (/docs/guides/stackblitz-snippets) StackBlitz examples [#stackblitz-examples] Open a pre-configured project in [StackBlitz](https://stackblitz.com) and chat in seconds. Templates call `GET /demo/session` on the hosted Worker for a guest JWT. No API key goes in the browser. Where to open them [#where-to-open-them] | Place | Templates | | ------------------------------- | ---------------------------------------------------------------------- | | [fluxychat.com/docs](/docs) | All three templates in the Interactive examples section | | [fluxychat.com/guides](/guides) | Open in StackBlitz on selected guides (Workers, Next.js, agent events) | | Console → Code Templates | Gallery and custom snippet editor | Templates [#templates] | Template | What you get | | ---------------- | -------------------------------------------------- | | Basic connection | Vanilla JS: connect, join demo room, send messages | | React chat UI | React + `useChat`: room list and composer | | AI agent chat | Same demo room with an AI agent that replies | Requirements [#requirements] The hosted Worker must have `DEMO_ENABLED=true` and a configured demo room. If demo is off, replace `BASE_URL` in the StackBlitz project and mint a JWT from your backend with `POST /auth/token`. Try the full product UI without signup: [Public demo](/demo). Related [#related] * [SDK quickstart](/docs/getting-started/quickstart) * [Embed widget](/docs/reference/embed-widget) * [Public demo hardening](/docs/cookbook/public-demo-hardening) --- # Stream resumption (/docs/guides/stream-resumption) `GET /ai/streams/active` and `GET /ai/streams/:id/resume` read a KV snapshot (`RATE_LIMIT_KV` or `STREAM_RESUME_KV`). `POST /ai/streams/:id/chunk` appends text. If those bindings are missing, active lists are empty and resume returns 503. This is **not** Cloudflare Think `chatRecovery`. If the room Durable Object hibernates mid-generation, the in-flight LLM call does not come back. Chat already written to D1 still loads on reconnect. ```ts const streams = await client.getActiveStreams(roomId); const hit = streams.find((s) => s.active !== false) ?? streams[0]; if (hit?.streamId) { const snapshot = await client.resumeStream(hit.streamId); // snapshot.content is what KV stored. Live token paint still uses the room WebSocket. } ``` `getActiveStreams` / `resumeStream` are aliases of `listActiveAiStreams` / `resumeAiStream`. `FluxyRoomChatTransport.reconnectToStream` calls the same HTTP. Room `useChat` from `@fluxy-chat/react` does not auto-call these endpoints. --- # Stream Transformations (/docs/guides/stream-transforms) Stream Transformations [#stream-transformations] Stream transforms modify AI stream parts in real-time — adding delays, filtering, or transforming content as it flows from the model to the consumer. smoothStream [#smoothstream] Adds configurable delay between text chunks for a smooth streaming UX: ```ts import { smoothStream } from '@fluxy-chat/agent'; const stream = await model.stream({ prompt: [...] }); const smoothed = stream.pipeThrough(smoothStream({ delayInMs: 30, // 30ms between chunks chunkSize: 1, // 1 character per chunk })); // Consume the smoothed stream const reader = smoothed.getReader(); ``` Options [#options] | Option | Type | Default | Description | | ----------- | --------- | ------- | ------------------------------------ | | `delayInMs` | `number` | `50` | Milliseconds delay between chunks | | `chunkSize` | `number` | `1` | Characters per chunk | | `wordDelay` | `boolean` | `false` | Chunk by words instead of characters | Word-Level Delay [#word-level-delay] ```ts const stream = modelStream.pipeThrough(smoothStream({ wordDelay: true, delayInMs: 100, // 100ms between words })); ``` experimental_transform [#experimental_transform] Custom part-by-part transformation function: ```ts import { experimental_transform } from '@fluxy-chat/agent'; const stream = modelStream.pipeThrough(experimental_transform({ transform: (part) => { if (part.type === 'text-delta') { // Uppercase all text return { ...part, delta: part.delta.toUpperCase() }; } if (part.type === 'reasoning-delta') { // Skip reasoning parts return null; } return part; }, })); ``` Multiple Outputs [#multiple-outputs] Return an array to split one part into multiple: ```ts experimental_transform({ transform: (part) => { if (part.type === 'text-delta') { return [ { type: 'text-delta', id: part.id, delta: part.delta[0] ?? '' }, { type: 'text-delta', id: part.id, delta: part.delta.slice(1) }, ]; } return part; }, }); ``` Returning null [#returning-null] Return `null` to drop a part entirely. Chaining Transforms [#chaining-transforms] Transforms compose with `.pipeThrough()`: ```ts const stream = modelStream .pipeThrough(experimental_transform({ transform: filterToolParts })) .pipeThrough(smoothStream({ delayInMs: 20 })); ``` Type Reference [#type-reference] ```ts interface SmoothStreamOptions { delayInMs?: number; chunkSize?: number; wordDelay?: boolean; } function smoothStream(options?: SmoothStreamOptions): TransformStream; type StreamTransformFunction = ( part: AIStreamPart, ) => AIStreamPart | AIStreamPart[] | null | Promise; function experimental_transform( options: ExperimentalTransformOptions, ): TransformStream; ``` See Also [#see-also] * [LLM Middleware](/docs/guides/llm-middleware) — model-level transforms (before/after streaming) * [Generating Text](/docs/guides/llm-middleware) — `generate()` and `stream()` functions * [Stream Utils](/docs/guides/stream-transforms) — `collectStreamParts`, `toTextStream` --- # Streaming Enhancements (/docs/guides/streaming-enhancements) Streaming Enhancements [#streaming-enhancements] Stream chunk types, markdown healing, and table buffering utilities. Stream Chunks [#stream-chunks] Stream chunks represent pieces of a streaming response. ```ts import { createStreamChunk, parseStreamChunks, serializeStreamChunks, isTextChunk, isToolCallChunk, isToolResultChunk, healMarkdown, bufferTableCells, } from "@fluxy-chat/sdk"; ``` Creating Chunks [#creating-chunks] ```ts const text = createStreamChunk("text", { content: "Hello " }); const toolCall = createStreamChunk("tool-call", { toolName: "get_weather", toolArgs: '{"city":"London"}' }); const toolResult = createStreamChunk("tool-result", { toolResult: '{"temp":20}' }); const done = createStreamChunk("done"); ``` Parsing & Serializing [#parsing--serializing] Uses Vercel AI SDK wire format prefixes (`0:` for text, `8:` for tool calls, `9:` for tool results, `3:` for errors): ```ts const raw = '0:Hello\n8:{"toolName":"get_weather","args":{"city":"London"}}\n9:{"temp":20}'; const chunks = parseStreamChunks(raw); // -> [{ type: "text", content: "Hello" }, { type: "tool-call", toolName: "get_weather" }, { type: "tool-result", ... }] const serialized = serializeStreamChunks(chunks); // -> same as raw ``` Type Guards [#type-guards] ```ts if (isTextChunk(chunk)) console.log(chunk.content); if (isToolCallChunk(chunk)) console.log(chunk.toolName); if (isToolResultChunk(chunk)) console.log(chunk.toolResult); ``` Markdown Healing [#markdown-healing] Closes unclosed code fences that may result from streaming interruption: ````ts healMarkdown("```js\nconsole.log('hi')"); // -> "```js\nconsole.log('hi')\n```" healMarkdown("hello **world**"); // unchanged (valid) ```` Table Buffering [#table-buffering] Adds a separator row to pipe tables: ```ts bufferTableCells("| Name | Age |\n| Alice | 30 |"); // -> "| Name | Age |\n| --- | --- |\n| Alice | 30 |" ``` Types [#types] * `StreamChunkType`: `"text" | "tool-call" | "tool-result" | "error" | "done"` * `StreamChunk`: `\{ type, content?, toolName?, toolArgs?, toolResult?, error? \}` --- # Streaming Markdown Renderer (/docs/guides/streaming-markdown) Streaming Markdown Renderer [#streaming-markdown-renderer] FluxyChat's `StreamingMarkdownRenderer` buffers incoming text chunks and produces clean, incrementally rendered HTML, even when the markdown is incomplete mid-stream. Why It Matters [#why-it-matters] When an AI agent streams a response token-by-token, the partial markdown is often broken: * Open code fences (` ``` `) without a closing fence * Table headers (`| Name | Age |`) without a separator row yet * Unclosed inline markers (`**bold` without closing `**`) * Partial link syntax (`[link text` without `]`) Naive rendering shows raw markdown text. The `StreamingMarkdownRenderer` fixes all of these. Features [#features] Table Buffering [#table-buffering] Trailing pipe-delimited lines are held back until a separator row (`|---|---|`) confirms it's a table. This prevents `| Name | Age |` from flashing as raw text during streaming. Code Fence Tracking [#code-fence-tracking] A counter increments on every ` ``` ` or `~~~` encounter. Odd count = inside a code fence. This O(1) check prevents markdown inside code blocks from being rendered. Inline Marker Healing [#inline-marker-healing] Uses the `remend` library to scan backward from the end of the buffer for unclosed `*`, `~`, `` ` ``, and `[` markers. Returns the longest clean prefix, so partial bold/italic/code/link syntax doesn't break rendering. Monotonic Output [#monotonic-output] Wrapped tables are left open during streaming and closed only on `finish()`. This keeps output monotonic — downstream consumers can safely append deltas without worrying about mid-stream table closure. Usage [#usage] ```ts import { StreamingMarkdownRenderer } from "@fluxy-chat/sdk"; const renderer = new StreamingMarkdownRenderer(); // Feed chunks as they arrive for await (const chunk of aiStream) { renderer.push(chunk); document.getElementById("output").innerHTML = renderer.getHtml(); } // Finalize — closes any open tables, fences, markers renderer.finish(); const finalHtml = renderer.getHtml(); ``` How It Works [#how-it-works] ``` Input stream: "Here's a table:\n\n| Name | Age |\n|---" ↑ held back until separator confirmed Buffer state: "Here's a table:\n\n" Output: "

Here's a table:

\n" After "|---|---|\n| Alice | 30 |": Buffer: "Here's a table:\n\n| Name | Age |\n|---|---|\n| Alice | 30 |" Output: "...
Alice30
" ``` Integration [#integration] The renderer is used inside `adapter-web.js` when streaming AI agent responses. The worker imports it to transform streamed token deltas before broadcasting to WebSocket clients. See Also [#see-also] * [Adapter Pattern Guide](/docs/guides/adapter-pattern) — Platform adapters and format conversion * [Card Builder Guide](/docs/guides/card-builder) — Rich interactive message elements --- # Subagents — Delegation Pattern (/docs/guides/subagents) Subagents — Delegation Pattern [#subagents--delegation-pattern] A subagent is an agent that a parent agent invokes via a tool. The parent delegates work, the subagent executes autonomously, and returns a result. This keeps the parent's context clean and coherent. When to Use Subagents [#when-to-use-subagents] **Use subagents when:** * Tasks require exploring large amounts of tokens (reading files, searching codebases) * You need to parallelize independent research * Context would grow beyond model limits **Avoid subagents when:** * Tasks are simple and focused * Sequential processing suffices * Context stays manageable Creating a Subagent Tool [#creating-a-subagent-tool] Use `createSubagentTool` to create an AITool that runs a subagent internally: ```ts import { createSubagentTool } from '@fluxy-chat/agent'; const researchTool = createSubagentTool({ description: 'Research a topic in depth and return findings.', inputSchema: { type: 'object', properties: { task: { type: 'string', description: 'The research task' }, }, }, subagent: { runStep: async (state) => { const task = (state.runtime as any)?.subagentTask?.task ?? ''; const response = await someModel.generate({ prompt: [{ role: 'user', content: task }], }); return { text: response.text, finishReason: response.finishReason }; }, tools: { search, read }, maxSteps: 5, }, }); ``` Controlling What the Model Sees [#controlling-what-the-model-sees] Use `toModelOutput` to transform the subagent's full output into a compact summary for the parent model: ```ts const researchTool = createSubagentTool({ description: 'Research a topic.', inputSchema: { /* ... */ }, subagent: { runStep: myRunStep, tools: { read, search } }, toModelOutput: (result) => ({ summary: result.text, toolCount: result.toolResults.length, }), }); ``` Direct Subagent Invocation [#direct-subagent-invocation] Use `runSubagent` to run a subagent without wrapping it in a tool: ```ts import { runSubagent } from '@fluxy-chat/agent'; const result = await runSubagent( { runStep: myRunStep, tools: { search, read }, maxSteps: 3, }, 'Analyze the project structure', { system: 'You are a code analyst.' }, ); console.log(result.text); console.log('Usage:', result.usage); ``` Context Isolation [#context-isolation] Each subagent invocation starts with a fresh context window. The parent's runtime is merged into the subagent's runtime under `subagentTask`: ```ts // Parent runtime: { userId: 'abc' } // Subagent runtime: { subagentTask: { task: '...' }, ...parentRuntime } // ^-- merged from parent ``` Limitations [#limitations] * Subagent tools cannot use approval flows (`toolApproval`, `needsApproval`) * Each subagent gets an isolated context — does not inherit parent's conversation history * Pass `messages` manually if the subagent needs context from the parent * Streaming progress to the UI requires generator-based tools (not currently supported in AITool.execute) Type Reference [#type-reference] ```ts interface SubagentConfig { runStep: AgentLoopOptions['runStep']; tools?: Record; maxSteps?: number; maxToolCalls?: number; toolTimeoutMs?: number; allowTools?: readonly string[]; stopWhen?: AgentStopCondition | readonly AgentStopCondition[]; toolApproval?: ToolApprovalConfig; // ... lifecycle callbacks } interface SubagentToolOptions { description: string; inputSchema: Record; subagent: SubagentConfig; toModelOutput?: (result: AgentLoopResult) => TOutput | Promise; } function createSubagentTool( options: SubagentToolOptions, ): AITool; function runSubagent( config: SubagentConfig, prompt: string, options?: { signal?: AbortSignal; runtime?: unknown; system?: string }, ): Promise; ``` See Also [#see-also] * [Agent Loop Control](/docs/guides/loop-control) — step limits, stop conditions * [Prune Messages](/docs/guides/prune-messages) — context compaction for parent * [Memory](/docs/guides/memory) — persistent agent memory --- # Svelte quickstart (/docs/guides/svelte-quickstart) Install the Svelte package and the core SDK: ```bash npm install @fluxy-chat/svelte @fluxy-chat/sdk ``` Minimal example: ```svelte {#if $chat}

Messages: {$chat.messages.length}

{/if} ``` `useChat` returns a Svelte readable store with the full room snapshot (messages, connection state, send helpers). --- # Telephony to agent handoff (/docs/guides/telephony-handoff) When someone texts or calls your number, you can drop them into a support room, flag a human handoff, and optionally start a Voice AI session on the same room. Turn it on [#turn-it-on] Set these Worker environment variables: ```bash TELCO_INBOUND_ENABLED=true TELEPHONY_AGENT_HANDOFF=true # or TELCO_AGENT_HANDOFF=true TELCO_INBOUND_DEFAULT_ROOM_ID= ``` After a successful inbound telco message, FluxyChat can call `maybeTelephonyHandoffOnInbound` automatically. Call the API yourself [#call-the-api-yourself] ```http POST /integrations/telephony/handoff Authorization: Bearer Content-Type: application/json { "roomId": "room-uuid", "fromE164": "+15551234567", "channel": "voice", "providerId": "openai-realtime", "requestVoiceSession": true, "reason": "Caller asked for an agent" } ``` The response includes: * `handoff`: active human handoff state * `voiceSession`: Voice AI session (`sessionId`, `wsUrl`) when you asked for one * `suggestedAgentUserId`: best support agent match from presence and skill tags What happens end to end [#what-happens-end-to-end] 1. Telco webhook hits `handleTelcoInboundMessage` (SMS or WhatsApp body becomes a room message). 2. The agent queue enqueues the room if you use support routing. 3. Handoff runs `requestHumanHandoff`, optionally `createVoiceAiSession`, and picks a support routing candidate. Dashboard [#dashboard] Open **Settings → Telephony handoff** (`/settings/telephony`) to review env vars and fire a test handoff. After a voice escalation, check **Voice AI** (`/voice-ai`) for the session and **Agent queue** to claim the room. Related [#related] * [Voice AI pipeline](/docs/guides/voice-ai-pipeline) * [US SMS compliance](/docs/operations/us-sms-compliance-playbook) * [Agent tool policy](/docs/reference/agent-tool-policy) --- # Testing integrations (/docs/guides/testing-integration) Use `@fluxy-chat/sdk/testing` in Vitest or Jest suites. Two spy adapters in one test is the cheap CI stand-in for two humans in a room. There is no separate `@fluxy-chat/testing` package. Install dev deps [#install-dev-deps] ```bash pnpm add -D vitest @testing-library/react ``` Spy adapter + matchers [#spy-adapter--matchers] ```ts import { describe, expect, it } from "vitest"; import { createSpyAdapter, registerFluxyChatMatchers } from "@fluxy-chat/sdk/testing"; registerFluxyChatMatchers(expect); describe("bot posts to thread", () => { it("records postMessage", async () => { const adapter = createSpyAdapter(); await adapter.postMessage("thread-1", "hello"); expect(adapter).toHavePosted("thread-1", "hello"); }); }); ``` | Matcher | Asserts | | --------------------------------------------- | ------------------------ | | `toHavePosted(threadId, content?)` | `postMessage` was called | | `toHaveEdited(threadId, messageId, content?)` | `editMessage` was called | Mock FluxyChatClient [#mock-fluxychatclient] ```ts import { createFluxyChatMockClient } from "@fluxy-chat/sdk/testing"; import { renderHook, waitFor } from "@testing-library/react"; import { useInbox } from "@fluxy-chat/react"; const client = createFluxyChatMockClient({ inbox: { mentions: [], unreadRooms: [{ roomId: "r1", roomName: "General", unreadCount: 2, lastReadMessageId: 1, firstUnreadMessageId: 2, }], snoozedRooms: [], followUps: [], counts: { mentions: 0, unreadRooms: 1, snoozedRooms: 0, followUps: 0 }, }, }); const { result } = renderHook(() => useInbox({ client, enabled: true, pollIntervalMs: 0 }), ); await waitFor(() => expect(result.current.items.length).toBe(1)); ``` onItem callback test [#onitem-callback-test] See `apps/dashboard/app/inbox/use-inbox-on-item.test.tsx` for a full `useInbox` + user-channel push example. Related [#related] * [SDK API playground](/playground) * [Troubleshooting integration](/docs/guides/troubleshooting-integration) --- # Per-Thread Typed State (/docs/guides/thread-state) Per-Thread Typed State [#per-thread-typed-state] `createThreadState()` provides a typed state accessor per thread with merge/replace semantics and TTL — designed for multi-turn agent context. Usage [#usage] ```ts import { createThreadState, createThreadStateStore } from "@fluxy-chat/sdk"; interface AgentState { mode: "chat" | "agent"; count: number; } const store = createThreadStateStore(); const ts = createThreadState("thread\:abc", store); // Set state (merge by default) await ts.setState({ mode: "agent" }); await ts.setState({ count: 1 }); // Read state const state = await ts.state; // { mode: "agent", count: 1 } // Replace entire state await ts.setState({ mode: "chat" }, { replace: true }); ``` TypedThreadState API [#typedthreadstate-api] | Member | Type | Description | | ----------------------------- | --------------------- | ------------------------- | | `state` | `Promise` | Read current state | | `setState(partial, options?)` | `Promise<void>` | Set state (merge/replace) | | `threadId` | `string` | Thread identifier | Store [#store] ```ts const store = createThreadStateStore(); // In-memory const store = createThreadStateStore(kv); // Cloudflare KV ``` TTL [#ttl] Default 30 days (`THREAD_STATE_TTL_MS`). Override per accessor: ```ts const ts = createThreadState("thread:1", store, 60_000); // 1 min ``` --- # OAuth Token Encryption (/docs/guides/token-encryption) OAuth Token Encryption [#oauth-token-encryption] FluxyChat token encryption provides AES-256-GCM encryption for securely storing OAuth tokens used by platform adapters (Slack, Linear, and others). Overview [#overview] OAuth tokens stored in D1 or external systems should never be plaintext. The `TokenCrypto` class wraps the Web Crypto API's AES-256-GCM implementation with a simple encrypt/decrypt interface. Each encryption uses a random 12-byte IV, ensuring the same plaintext produces different ciphertext every time. **Source:** `apps/worker/src/lib/token-crypto.js` Quick Start [#quick-start] ```js import { TokenCrypto } from "@fluxy-chat/sdk"; // Initialize with your master encryption key (store in Worker secrets) const crypto = new TokenCrypto(process.env.OAUTH_ENCRYPTION_KEY); // Encrypt an OAuth token before storing it const encrypted = await crypto.encrypt("xoxb-slack-bot-token-..."); // { ciphertext: "base64...", iv: "base64...", tag: "base64..." } // Store `encrypted` in D1 await db.prepare( "INSERT INTO oauth_tokens (adapter, user_id, ciphertext, iv, tag) VALUES (?, ?, ?, ?, ?)" ).bind("slack", "U123", encrypted.ciphertext, encrypted.iv, encrypted.tag); // Decrypt when you need to use the token const row = await db.prepare("SELECT * FROM oauth_tokens WHERE user_id = ?").bind("U123").first(); const plaintext = await crypto.decrypt({ ciphertext: row.ciphertext, iv: row.iv, tag: row.tag, }); // "xoxb-slack-bot-token-..." ``` How It Works [#how-it-works] 1. **Key derivation:** The master key string is SHA-256 hashed to produce a 256-bit AES-GCM `CryptoKey`. 2. **Encryption:** A random 12-byte (96-bit) IV is generated per encryption. The plaintext is encrypted using AES-GCM with a 128-bit authentication tag. 3. **Output:** Three base64-encoded values: `ciphertext`, `iv`, and `tag`. 4. **Decryption:** The IV and tag are combined with the ciphertext to decrypt back to plaintext. The Web Crypto API (`crypto.subtle`) is used throughout, so this works on Cloudflare Workers, browsers, and Node.js >= 19. Lower-Level API [#lower-level-api] For cases where you already have a `CryptoKey` (e.g., shared across multiple operations): ```js import { deriveKey, encryptToken, decryptToken } from "@fluxy-chat/sdk"; const key = await deriveKey(process.env.OAUTH_ENCRYPTION_KEY); const encrypted = await encryptToken("my-secret-token", key); // { ciphertext, iv, tag } const plaintext = await decryptToken(encrypted, key); // "my-secret-token" ``` Type Guard [#type-guard] ```js import { isEncryptedTokenData } from "@fluxy-chat/sdk"; const value = JSON.parse(row.data); if (isEncryptedTokenData(value)) { const token = await crypto.decrypt(value); } ``` Adapter Integration [#adapter-integration] Adapters that handle OAuth flows (Slack, Linear, etc.) use `TokenCrypto` internally: ```js class SlackAdapter extends BaseAdapter { constructor(env) { this.tokenCrypto = new TokenCrypto(env.OAUTH_ENCRYPTION_KEY); } async storeUserToken(userId, token) { const encrypted = await this.tokenCrypto.encrypt(token); await this.db.prepare( "INSERT INTO slack_oauth (user_id, ciphertext, iv, tag) VALUES (?, ?, ?, ?)" ).bind(userId, encrypted.ciphertext, encrypted.iv, encrypted.tag).run(); } async getUserToken(userId) { const row = await this.db.prepare( "SELECT ciphertext, iv, tag FROM slack_oauth WHERE user_id = ?" ).bind(userId).first(); if (!row) return null; return this.tokenCrypto.decrypt({ ciphertext: row.ciphertext, iv: row.iv, tag: row.tag, }); } } ``` Security Notes [#security-notes] * **Master key:** Store `OAUTH_ENCRYPTION_KEY` in Cloudflare Worker secrets (`wrangler secret put`). Never commit it to source. * **Key rotation:** To rotate, decrypt all tokens with the old key and re-encrypt with the new key. There's no built-in migration tool — handle this in a maintenance script. * **IV uniqueness:** Each encryption call generates a cryptographically random IV. Never reuse an IV with the same key. * **Authentication tag:** The GCM tag ensures ciphertext integrity. If the encrypted data is tampered with, decryption will throw. See Also [#see-also] * [Adapter Errors](/docs/guides/adapter-errors) — `AuthenticationError` for invalid/expired tokens * [Adapter Pattern](/docs/guides/adapter-pattern) — How adapters are structured --- # Tool Approvals (/docs/guides/tool-approvals) Tool Approvals [#tool-approvals] By default, tools with an `execute` function run automatically when the model calls them. Use `toolApproval` on `runAgentLoop` to review, approve, or deny selected tool calls before they execute. Tool approvals are useful for tools that can modify data, spend money, execute code, send messages, access private data, or perform any other sensitive action. Statuses [#statuses] Every approval rule returns one of these statuses, either as a string or as an object with a `type` field: | Status | Effect | | ------------------ | ------------------------------------------------------------- | | `'not-applicable'` | Execute the tool normally without approval metadata (default) | | `'approved'` | Record automatic approval, then execute the tool | | `'denied'` | Record automatic denial and return a denied tool output | | `'user-approval'` | Emit an approval request and wait for an explicit response | For automatic approvals and denials, use the object form to include a reason: ```ts toolApproval: { deleteFile: { type: 'denied', reason: 'Deleting files is disabled in this workspace', }, } ``` Require Approval for a Tool [#require-approval-for-a-tool] Use a per-tool map when each tool has a simple policy: ```ts import { runAgentLoop } from '@fluxy-chat/agent'; const result = await runAgentLoop({ model: someModel, tools: { runCommand: { inputSchema: { type: 'object', properties: { command: { type: 'string' } } }, execute: async ({ command }) => runShellCommand(command), }, }, toolApproval: { runCommand: 'user-approval', }, }); ``` When `runCommand` is called, the agent returns approval requests instead of executing the tool. Decide Based on Tool Input [#decide-based-on-tool-input] Use a per-tool approval function when the decision depends on the parsed tool input: ```ts toolApproval: { processPayment: async (input, { toolCallId, messages, runtime }) => { const amount = (input as { amount?: number }).amount ?? 0; if (amount > 1000) { return { type: 'user-approval' }; } if ((runtime as { role?: string }).role !== 'admin') { return { type: 'denied', reason: 'Only admins can send payments' }; } return undefined; // not-applicable = execute normally }, }, ``` One Policy for All Tools [#one-policy-for-all-tools] Pass a function directly as `toolApproval` when approval depends on the full tool call or shared state: ```ts toolApproval: ({ toolCall, messages, runtime }) => { if (toolCall.name === 'deleteFile') { return { type: 'denied', reason: 'Manual deletion disabled' }; } if ((runtime as { env?: string }).env === 'production') { return 'user-approval'; } return undefined; // not-applicable }, ``` The generic function receives: * `toolCall`: the full tool call (`id`, `name`, `input`) * `messages`: messages sent to the model for the step that produced the call * `runtime`: shared runtime context Manual Approval Flow [#manual-approval-flow] Manual approval requires two calls when using `runAgentLoop`: 1. Configure `toolApproval` + `onApprovalRequired` callback 2. The callback receives an `ApprovalRequest` — return `true` to approve or `false` to deny ```ts const result = await runAgentLoop({ model: someModel, tools: { deleteFile: { inputSchema: {}, execute: async () => 'deleted' } }, toolApproval: { deleteFile: 'user-approval' }, onApprovalRequired: async (request: ApprovalRequest) => { const approved = await askUser(`Allow ${request.toolName}?`); return approved; }, maxSteps: 5, }); ``` If approved, the tool executes. If denied, the model receives a denial result and can respond without the tool output. HMAC-Signed Approvals [#hmac-signed-approvals] For sensitive tools that modify data, spend money, or access private resources, use `toolApprovalSecret` to cryptographically bind approvals to the server that issued them. When a secret is provided, the server HMAC-signs each approval request and verifies the signature when the approval is replayed. A forged or tampered approval is rejected before the tool executes. ```ts const result = await runAgentLoop({ model: someModel, tools: { deleteFile: { inputSchema: { type: 'object', properties: { path: { type: 'string' } } }, execute: async ({ path }) => deleteFile(path), }, }, toolApproval: { deleteFile: 'user-approval' }, toolApprovalSecret: process.env.TOOL_APPROVAL_SECRET, onApprovalRequired: async (request) => { // request.signature is the HMAC binding this approval to its input return askUser(`Delete ${request.input}?`); }, maxSteps: 5, }); ``` **Setup:** 1. Generate a high-entropy random string (at least 32 bytes): ```bash openssl rand -base64 32 ``` 2. Store it as an environment variable accessible to all server instances: ``` TOOL_APPROVAL_SECRET=your-generated-secret-here ``` 3. Pass it via `toolApprovalSecret`. **Behavior when configured:** * Approval requests without a valid signature are rejected (fail-closed) * No secret configured: approvals work as before (backward compatible) * The secret is never sent to the client or included in the stream The signature binds the approval to the exact tool name, tool call ID, and input arguments. Changing any of these after signing invalidates the approval. Priority Resolution [#priority-resolution] `resolveToolApproval` follows this order: 1. **Generic function** (if `toolApproval` is a function) — evaluated first 2. **Per-tool function** (if `toolApproval[toolName]` is a function) — evaluated with typed input 3. **Per-tool status** (string or object status) — direct match 4. **needsApproval legacy** (`tool.needsApproval`) — fallback for backward compatibility User-defined settings always take precedence over tool-defined settings. API Reference [#api-reference] ToolApprovalStatus [#toolapprovalstatus] ```ts type ToolApprovalStatus = | undefined | 'not-applicable' | 'approved' | 'denied' | 'user-approval' | ToolApprovalDecision; ``` ToolApprovalDecision [#toolapprovaldecision] ```ts interface ToolApprovalDecision { type: 'not-applicable' | 'approved' | 'denied' | 'user-approval'; reason?: string; } ``` ApprovalRequest [#approvalrequest] ```ts interface ApprovalRequest { type: 'tool-approval-request'; approvalId: string; toolCallId: string; toolName: string; input: unknown; isAutomatic?: boolean; signature?: string; } ``` ApprovalResponse [#approvalresponse] ```ts interface ApprovalResponse { type: 'tool-approval-response'; approvalId: string; approved: boolean; reason?: string; providerExecuted?: boolean; } ``` ToolApprovalRecord [#toolapprovalrecord] ```ts interface ToolApprovalRecord { status: 'not-applicable' | 'approved' | 'denied' | 'user-approval'; reason?: string; signed?: ApprovalRequest; } ``` ToolApprovalConfig [#toolapprovalconfig] ```ts type ToolApprovalConfig = | Record | GenericToolApprovalFunction; ``` AgentLoopOptions [#agentloopoptions] ```ts interface AgentLoopOptions { // ... toolApproval?: ToolApprovalConfig; toolApprovalSecret?: string | Uint8Array; onApprovalRequired?: (request: ApprovalRequest) => Promise; // ... } ``` Stream Parts [#stream-parts] ```ts type AIStreamPart = // ... | { type: 'approval-request'; approvalId: string; toolCallId: string; toolName: string; input: unknown; isAutomatic?: boolean; signature?: string } | { type: 'approval-response'; approvalId: string; toolCallId: string; toolName: string; approved: boolean; reason?: string; providerExecuted?: boolean }; ``` Legacy Support [#legacy-support] For backward compatibility, tools can define `needsApproval`: ```ts const tool: AITool = { inputSchema: {}, needsApproval: (input) => (input as { dangerous?: boolean }).dangerous ?? false, execute: async (input) => { /* ... */ }, }; ``` When no `toolApproval` config is provided, `needsApproval` on the tool definition is used. When both are present, `toolApproval` takes precedence. --- # Transcripts API (/docs/guides/transcripts) Transcripts API [#transcripts-api] `createTranscriptsApi()` provides per-user message persistence keyed by a stable cross-platform identifier and capped per user. Two stores: * **In-memory (default)** — nothing is persisted; entries are gone on reload. Fine for tests and demos. * **Worker (D1)** — pass `worker: { baseUrl, token }`; entries persist in `user_transcripts` and show up in the console at `/transcripts`. Usage [#usage] ```ts import { createTranscriptsApi } from "@fluxy-chat/sdk"; const api = createTranscriptsApi({ retention: "30d", maxPerUser: 200, worker: { baseUrl: "https://fluxychat-worker.example.workers.dev", token: adminJwt, // admin JWT for /admin/transcripts }, }); // Append user message await api.append("thread:1", "slack", { content: "hello", id: "msg-1" }, { userKey: "user@example.com" }); // Append bot reply await api.append("thread:1", "slack", { text: "Hi there!", role: "assistant" }, { userKey: "user@example.com" }); // List recent entries const recent = await api.list({ userKey: "user@example.com", limit: 20 }); // Count entries const total = await api.count({ userKey: "user@example.com" }); // Delete all entries const result = await api.delete({ userKey: "user@example.com" }); ``` Drop `worker` for the in-memory store. Configuration [#configuration] * `retention`: TTL for entries (ms or duration string like `"30d"`, `"6h"`, `"45s"`). Applied at append time; expired entries are hidden from lists and counts. Refreshed on append. * `maxPerUser`: Hard cap per user. Older entries evicted on append (default: 200). * `worker`: `{ baseUrl, token }` — route the API through the Worker. Records are scoped by the JWT's project, so one project never reads another's transcripts. Filtering [#filtering] ```ts await api.list({ userKey: "u1", platforms: ["slack"] }); await api.list({ userKey: "u1", threadId: "slack\:C123:1234" }); await api.list({ userKey: "u1", roles: ["user"] }); await api.list({ userKey: "u1", limit: 50 }); ``` HTTP routes [#http-routes] The Worker store uses these admin routes (all project-scoped by the JWT): | Route | Purpose | | ---------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `POST /admin/transcripts` | Append `{ userKey, role, text, platform, threadId?, platformMessageId?, maxPerUser?, retentionMs? }` | | `GET /admin/transcripts?userKey=…` | List entries (filters: `platforms`, `roles`, `threadId`, `limit`) | | `GET /admin/transcripts/count?userKey=…` | Count live entries | | `DELETE /admin/transcripts?userKey=…` | Delete all entries for the user | --- # Troubleshooting integration (/docs/guides/troubleshooting-integration) Symptoms mapped to fixes you can paste into your app or curl. 401 Unauthorized / invalid API key [#401-unauthorized--invalid-api-key] **Symptom:** REST returns 401; `FluxyAuthError` on connect. **Checks:** 1. API key belongs to the project you expect (`Projects` console or `POST /dev/provision` in local dev). 2. Header is `X-Fluxy-Api-Key: fc_...` (server-side only). 3. Worker URL matches the project (`NEXT_PUBLIC_FLUXYCHAT_WORKER_URL`). ```bash curl -sS -X POST "$FLUXY_BASE_URL/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{"userId":"test","roles":["member"],"ttlSeconds":300}' ``` Token expired [#token-expired] **Symptom:** `FluxyTokenExpiredError`, WS close reason `token_expired`. **Fix:** Mint a fresh JWT and call `client.setToken(token)` (alias `updateToken`). Or pass a function to `authTokenProvider` so the provider remints before `exp`. ```ts const res = await fetch("/api/fluxy/token", { method: "POST" }); const { token } = await res.json(); client.setToken(token); ``` Use `ttlSeconds` with buffer; refresh before `exp` (dashboard uses \~5 min buffer). Not a room member [#not-a-room-member] **Symptom:** `FluxyNotMemberError`, WS 1008 Forbidden. **Fix:** Add the user to the room or join with a JWT whose `sub` is a member: ```bash curl -sS -X POST "$FLUXY_BASE_URL/rooms/$ROOM_ID/members" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{"userId":"alice","role":"member"}' ``` Connection degraded / reconnect loop [#connection-degraded--reconnect-loop] **Symptom:** `connectionStatus` is `degraded`, `degraded-http`, or `reconnecting`. **Checks:** 1. Worker reachable: `curl $FLUXY_BASE_URL/health` 2. CORS / mixed content (HTTPS page → HTTP worker blocked in prod) 3. Rate limits: `RateLimitError` with `retryAfterMs` Use `getConnectionStatusLabel()` from `@fluxy-chat/sdk` for user-facing copy. Messages not appearing [#messages-not-appearing] 1. Confirm JWT `sub` matches sender you expect. 2. Check `roomId` spelling (project-scoped ids like `{projectId}-general`). 3. For history: call `loadHistory()` / wait for `historyLoaded` in `useChat`. Local dev checklist [#local-dev-checklist] ```bash pnpm run first-message # provisions dev-local, sends first message pnpm run smoke:create-fluxy-chat ``` Worker needs `ALLOW_DEV_PROVISION=true` in `apps/worker/.dev.vars` for local provision. Named errors [#named-errors] Branch on classes from `@fluxy-chat/sdk`, not Cloudflare stack traces: | Class | When | | ------------------------------- | ----------------------- | | `FluxyNotMemberError` | WS 1008, not a member | | `FluxyTokenExpiredError` | expired / invalid JWT | | `FluxyAnonymousNotAllowedError` | room `anonymous: false` | | `FluxyAuthError` | other 1008 refusals | `describeConnectionError(err)` returns `{ code, message, isTerminal }` for UI copy. Related [#related] * [Authentication (JWT)](/docs/guides/auth-jwt) * [Testing integrations](/docs/guides/testing-integration) * [Connection state](/docs/core/connection-state) --- # Unified Chat API (/docs/guides/unified-chat-api) Unified Chat API [#unified-chat-api] FluxyChat's unified Chat API provides top-level methods that auto-infer the correct adapter from thread IDs and user IDs, so you can perform cross-platform operations without manual adapter lookup. Overview [#overview] Thread IDs in FluxyChat follow the format `adapter:channelId:messageId`. The unified API parses the prefix to resolve the adapter, returns lightweight `ThreadRef` objects, and delegates posting to the appropriate platform. **Source:** `apps/worker/src/lib/chat-api.js` `chat.thread(threadId)` [#chatthreadthreadid] Returns a `ThreadRef` for the given thread ID. The adapter is inferred from the ID prefix. ```js import { chat } from "@fluxy-chat/sdk"; // Slack thread const thread = chat.thread("slack\:C123ABC:1234567890.123456"); console.log(thread.adapterSlug); // "slack" console.log(thread.channelId); // "C123ABC" // Web thread const webThread = chat.thread("web:room-123\:msg-456"); console.log(webThread.adapterSlug); // "web" ``` ThreadRef [#threadref] `ThreadRef` is a lightweight thread reference. It holds the ID, adapter slug, and channel ID, and supports JSON serialization for D1 round-trips. ```js const thread = chat.thread("slack\:C123:1234567890.123456"); // Serialize const json = thread.toJSON(); // { _type: "fluxy\:Thread", id: "slack\:C123:1234567890.123456", adapterSlug: "slack", channelId: "C123" } // Deserialize const restored = ThreadRef.fromJSON(json); ``` `chat.openDM(userId)` [#chatopendmuserid] Opens a DM by user ID, auto-inferring the adapter from the ID format. ```js const dm = await chat.openDM("U123ABC"); // Slack console.log(dm.adapterSlug); // "slack" console.log(dm.id); // "slack:dm\:U123ABC" const discordDM = await chat.openDM("123456789012345678"); // Discord console.log(discordDM.adapterSlug); // "discord" ``` User ID inference rules [#user-id-inference-rules] | Pattern | Adapter | Example | | ---------------------------------------- | ----------- | -------------------- | | `U...` / `W...` (uppercase alphanumeric) | Slack | `U123ABC` | | `29:...` | Teams | `29:1abc...` | | 17–19 digit snowflake | Discord | `123456789012345678` | | `users/...` | Google Chat | `users/123` | | 1–13 digit numeric | Telegram | `123456789` | | UUID | Web | `a1b2c3d4-...` | `chat.getUser(userId)` [#chatgetuseruserid] Looks up user info (email, avatar, full name) by user ID, auto-inferring the adapter. ```js const user = await chat.getUser("alice-uuid"); // { userId: "alice-uuid", email: "alice@example.com", fullName: "Alice", avatarUrl: "...", adapter: "web" } // For external adapters without D1 lookup, returns minimal info const slackUser = await chat.getUser("U123ABC"); // { userId: "U123ABC", adapter: "slack" } ``` Context-bound API [#context-bound-api] For worker routes that need D1/KV access, create a context-bound instance: ```js import { createChatApi } from "@fluxy-chat/sdk"; const api = createChatApi({ env, db, roomStub }); // thread() works the same const thread = api.thread("web:room-123\:msg-456"); // openDM() and getUser() can use D1 const user = await api.getUser("alice-uuid"); // looks up from D1 ``` `thread.mentionUser(userId)` [#threadmentionuseruserid] Format platform-specific mentions. Each adapter handles this differently: ```js // Slack: <@U123ABC> // Discord: <@123456789012345678> // Teams: John Doe // Web: @alice ``` `thread.getParticipants()` [#threadgetparticipants] Scans messages in a thread and returns deduplicated non-bot authors. Useful for subscribe/unsubscribe logic and analytics. ```js const participants = await thread.getParticipants(); // [{ userId: "alice", adapter: "web" }, { userId: "bob", adapter: "web" }] ``` `chat.shutdown()` [#chatshutdown] Gracefully disconnects all registered adapters, calling each adapter's `disconnect()` method. Useful for worker lifecycle management. ```js const result = await chat.shutdown(); // { disconnected: ["web", "slack"], errors: [] } ``` See Also [#see-also] * [Adapter Errors](/docs/guides/adapter-errors) — Standardized error hierarchy for adapter operations * [Chat Singleton](/docs/guides/chat-singleton) — Global singleton for thread deserialization * [Adapter Pattern](/docs/guides/adapter-pattern) — Multi-platform adapter interface --- # Unified Reasoning (/docs/guides/unified-reasoning) Unified Reasoning [#unified-reasoning] > Cross-provider reasoning control for AI generation. Configure how much "thinking" a model does before answering, with a portable API that works across OpenAI, Anthropic, Google, and more. Overview [#overview] FluxyChat provides a unified `reasoning` parameter that abstracts away provider-specific reasoning APIs. Instead of learning OpenAI's `reasoning_effort`, Anthropic's `thinking.budget_tokens`, or Google's `thinkingConfig`, you use one config object that maps to each provider automatically. Quick Start [#quick-start] ```typescript import { generate, stream } from "@fluxy-chat/agent"; // Generate with high reasoning effort const result = await generate({ model: myModel, prompt: "What is the square root of 144?", reasoning: { effort: "high", summary: "detailed" }, }); console.log(result.text); // "12" console.log(result.reasoningText); // "To find the square root of 144, I need..." console.log(result.usage.reasoningTokens); // 832 ``` Configuration [#configuration] The `AIReasoningConfig` interface: ```typescript interface AIReasoningConfig { effort?: "low" | "medium" | "high"; // How hard the model thinks summary?: "auto" | "concise" | "detailed" | "none"; // Reasoning summary style budgetTokens?: number; // Max tokens for reasoning } ``` Effort Levels [#effort-levels] | Level | OpenAI | Anthropic | Google | | -------- | ---------------------------- | ---------------------- | ----------------------- | | `low` | `reasoning_effort: "low"` | `budget_tokens: 2000` | `thinkingBudget: 1024` | | `medium` | `reasoning_effort: "medium"` | `budget_tokens: 8000` | `thinkingBudget: 8192` | | `high` | `reasoning_effort: "high"` | `budget_tokens: 32000` | `thinkingBudget: 24576` | Boolean Shorthand [#boolean-shorthand] Pass `true` as a shorthand for `\{ effort: "medium", summary: "auto" \}`: ```typescript await generate({ model, prompt: "Explain quantum entanglement", reasoning: true, // equivalent to { effort: "medium", summary: "auto" } }); ``` Streaming with Reasoning [#streaming-with-reasoning] Reasoning parts are emitted as stream events before the text response: ```typescript import { stream } from "@fluxy-chat/agent"; const result = stream({ model: myModel, prompt: "Design a REST API for a todo app", reasoning: { effort: "high" }, }); for await (const part of result.stream) { switch (part.type) { case "reasoning-start": console.log("Model is thinking..."); break; case "reasoning-delta": process.stdout.write(part.delta); break; case "reasoning-end": console.log("\n--- Reasoning complete ---"); break; case "text-delta": process.stdout.write(part.delta); break; case "finish": console.log("\nUsage:", part.usage); break; } } const resolved = await result.result; console.log("Reasoning:", resolved.reasoningText); ``` Provider Mapping [#provider-mapping] Use `reasoningToProviderOptions` to convert the unified config to provider-specific options: ```typescript import { reasoningToProviderOptions } from "@fluxy-chat/agent"; // For OpenAI reasoningToProviderOptions({ effort: "high" }, "openai"); // → { reasoning_effort: "high" } // For Anthropic reasoningToProviderOptions({ effort: "high" }, "anthropic"); // → { thinking: { type: "enabled", budget_tokens: 32000 } } // For Google reasoningToProviderOptions({ effort: "low" }, "google"); // → { thinkingConfig: { thinkingBudget: 1024 } } ``` Extracting Reasoning [#extracting-reasoning] ```typescript import { extractReasoningText } from "@fluxy-chat/agent"; const reasoning = extractReasoningText(streamParts); // → "Let me think about this..." ``` Usage Tracking [#usage-tracking] Reasoning tokens are included in the `AIUsage` object: ```typescript const result = await generate({ model, prompt: "Complex question", reasoning: { effort: "high" }, }); console.log(result.usage); // { // inputTokens: 12, // outputTokens: 45, // reasoningTokens: 832, // ← reasoning token count // totalTokens: 889 // } ``` Testing with Reasoning [#testing-with-reasoning] Use `DeterministicLanguageModel` with a reasoning response for tests: ```typescript import { DeterministicLanguageModel } from "@fluxy-chat/agent"; const model = new DeterministicLanguageModel( "The answer is 42.", // text response "I considered multiple approaches...", // reasoning response "test-model", ); const result = await generate({ model, prompt: "What is the answer?", reasoning: { effort: "high" }, }); expect(result.reasoningText).toBe("I considered multiple approaches..."); expect(result.usage.reasoningTokens).toBe(31); ``` API Reference [#api-reference] | Export | Type | Description | | -------------------------------- | --------- | ---------------------------------------------- | | `AIReasoningConfig` | interface | Configuration object for reasoning | | `AIReasoningEffort` | type | `"low" \| "medium" \| "high"` | | `AIReasoningSummary` | type | `"auto" \| "concise" \| "detailed" \| "none"` | | `AIReasoningResult` | interface | Extracted reasoning result | | `normalizeReasoningConfig` | function | Normalizes config (handles `true` shorthand) | | `isReasoningConfig` | function | Type guard for `AIReasoningConfig` | | `reasoningToProviderOptions` | function | Maps config to provider-specific options | | `reasoningToOpenAIOptions` | function | Maps to OpenAI format | | `reasoningToAnthropicOptions` | function | Maps to Anthropic format | | `reasoningToGoogleOptions` | function | Maps to Google format | | `extractReasoningText` | function | Extracts reasoning text from stream parts | | `mergeReasoningProviderMetadata` | function | Merges reasoning config into provider metadata | --- # User Lookup API (/docs/guides/user-lookup) User Lookup API [#user-lookup-api] The user lookup API provides a registry for user profiles and a lookup service to query users by ID. Quick Start [#quick-start] ```ts import { createUserLookup, registerUser } from "@fluxy-chat/sdk"; const lookup = createUserLookup(); // Register users registerUser({ userId: "user-1", fullName: "Alice", email: "alice@example.com", avatarUrl: "https://..." }); registerUser({ userId: "user-2", username: "bob", bot: true }); // Single lookup const user = await lookup.getUser("user-1"); console.log(user?.fullName); // "Alice" // Batch lookup const users = await lookup.getUsers(["user-1", "user-2", "unknown"]); console.log(users.size); // 2 ``` API [#api] `registerUser(profile)` [#registeruserprofile] Register a user profile in the global registry. `createUserLookup(): UserLookupApi` [#createuserlookup-userlookupapi] Create a new lookup API instance. Returns: * `getUser(userId)` — returns `UserProfile | null` * `getUsers(userIds)` — returns `Map` Types [#types] * `UserProfile`: `\{ userId, username?, fullName?, email?, avatarUrl?, bot? \}` * `UserLookupApi`: interface for the lookup service --- # Vercel AI SDK ChatTransport (/docs/guides/vercel-ai-sdk-chat-transport) `FluxyRoomChatTransport` lives in `@fluxy-chat/sdk` and `@fluxy-chat/sdk/ai-sdk`. Pass it to AI SDK `useChat({ transport })`. It does not import the `ai` package. ```ts import { FluxyChatClient, FluxyRoomChatTransport } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: "https://api.example.com", userId: "alice", token: jwt, }); const transport = new FluxyRoomChatTransport({ client, roomId: "deal", agentId: "assistant-id", }); ``` | AI SDK | FluxyChat | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sendMessages` | Last user text → `invokeAgentRest`. `abortSignal` aborts that fetch. The HTTP response body is encoded as `text-delta` chunks. Live token paint on the chat row still uses the room WebSocket. | | `reconnectToStream` | `GET /ai/streams/active?roomId=` then `GET /ai/streams/:id/resume`. Returns `null` if nothing is stored. | `chatId` is ignored. The session is the **room**. If the room Durable Object hibernates mid-call, in-flight generation does not resume. Do not confuse this with SDK `FluxyChatTransport` (`websocket` | `sse` | `polling`). Non-goals [#non-goals] * Think-style fiber resume after Durable Object eviction. * Copilot `AiChat` writing the room timeline. * Replacing Groq / the room LLM. Gallery `deal-room` uses `@fluxy-chat/react` `useChat` on the room socket, not this transport. Use `FluxyRoomChatTransport` when the UI is Vercel AI SDK `useChat`. AI SDK 7 tool approval [#ai-sdk-7-tool-approval] `addToolApprovalResponse` lands as a `tool-approval-response` part. `sendMessages` POSTs `decideHitl` first (optional `signature` / `vercelSignature` HMAC), then `invokeAgent`, then lists pending HITL and may emit `tool-approval-request`. The HMAC matches `experimental_toolApprovalSecret`: `approvalId`, `toolCallId`, `toolName`, base64url SHA-256 of canonical JSON input. The room still applies quorum / approval chain. A valid SDK signature is not a skip for other approvers. `FluxyChatClient.requireApproval()` POSTs `/approvals/require` and opens an ephemeral group room. Use that when the agent never adopted chat UI. OpenAI Agents / LangGraph adapters: `openaiAgentsRequireApproval(client)`. `GET /api/hitl/metrics` returns pending count, decisions in the last 24h, and distinct current approvers. Counts, not a score. `GET /api/hitl/approvals/:id/evidence` returns a v=1 evidence pack (tool, chain, decision). Room membership required. `agentPolicy.opaUrl` (HTTPS only) is posted `buildAgentPolicyOpaInput` v=1. Localhost and RFC1918 hosts are rejected. Workspace package `@fluxy-chat/ai-sdk-workflow` is `createRoomReviewer`. It does not vendor Vercel `WorkflowAgent`. --- # Voice AI pipeline (/docs/guides/voice-ai-pipeline) End-to-end voice AI with **OpenAI Realtime API** as the standard adapter and **Gemini Live** in OpenAI-compatible WS mode. Dashboard: [**Voice AI**](/voice-ai) · SDK: `useVoice()` hook. Providers [#providers] ```bash curl "$WORKER_URL/voice-ai/providers" ``` Returns `openai-realtime` (300ms target) and `gemini-live` with feature flags: `vad`, `barge_in`, `noise_suppression`, `aec`. Create session [#create-session] ```bash curl -X POST "$WORKER_URL/admin/voice-ai/sessions" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "providerId": "openai-realtime", "roomId": "room_support", "settings": { "vad": true, "semanticTurnDetection": true, "bargeIn": true, "noiseSuppression": true, "echoCancellation": true } }' ``` Quality metrics [#quality-metrics] Report pipeline latency from the client: ```bash curl -X POST "$WORKER_URL/admin/voice-ai/metrics" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "sessionId": "vas_abc123", "providerId": "openai-realtime", "totalLatencyMs": 245, "stages": [{"stage":"asr","durationMs":80},{"stage":"llm","durationMs":120},{"stage":"tts","durationMs":45}] }' curl "$WORKER_URL/admin/voice-ai/stats" -H "Authorization: Bearer $ADMIN_JWT" ``` SDK — useVoice hook [#sdk--usevoice-hook] ```typescript import { useVoice } from "@fluxy-chat/react"; const voice = useVoice({ noiseSuppression: true, echoCancellation: true, onMetrics: ({ totalLatencyMs }) => console.log(totalLatencyMs), }); await voice.start(); await voice.processText("What's the weather?"); ``` Production keys (OpenAI/Gemini) are required for live STT/TTS — the dashboard runs pipeline simulation and metrics without billing. Latency SLO & fallback [#latency-slo--fallback] | Path | Target P95 | When | | ----------- | ---------- | ----------------------------------------------- | | `realtime` | 300ms | OpenAI Realtime WS (default when mic available) | | `chunked` | \~500ms | REST STT/TTS segments when WS unavailable | | `text_only` | N/A | Dashboard demo / no mic — LLM+TTS text path | The SDK auto-falls back: `realtime → chunked → text_only`. Set `autoFallback: false` to surface errors instead. ```typescript const voice = useVoice({ preferredTransport: "realtime", autoFallback: true, onMetrics: ({ totalLatencyMs }) => { if (totalLatencyMs > 300) console.warn("above SLO"); }, }); await voice.start(); await voice.processText("Hello"); console.log(voice.activeTransport); // text_only | realtime | chunked ``` See [Voice platform doc](/docs/platform/voice) for production checklist. --- # Vue quickstart (/docs/guides/vue-quickstart) Install the Vue package and the core SDK: ```bash npm install @fluxy-chat/vue @fluxy-chat/sdk ``` Minimal example: ```vue ``` The composable mirrors [`@fluxy-chat/react`](/docs/packages/react): same room state, reconnect behavior, and send helpers. --- # WorkflowAgent — Durable Execution (/docs/guides/workflow-agent) WorkflowAgent — Durable Execution [#workflowagent--durable-execution] FluxyChat's `WorkflowAgent` runs long-lived AI agents that survive deploys, restarts, and interruptions. State is persisted to D1/KV, so agents resume exactly where they left off. Overview [#overview] Standard agent invocations are ephemeral — if the Worker restarts mid-run, the agent's state is lost. `WorkflowAgent` wraps agent execution in a durable layer: * **State persistence:** Every step, tool call, and intermediate result is saved to D1 * **Automatic resume:** On restart, the agent picks up from the last completed step * **Typed context:** Shared typed context across steps, tools, and calls * **Step boundaries:** Each step is atomic — either completes fully or doesn't start When to Use [#when-to-use] | Scenario | Use WorkflowAgent? | | --------------------------- | ---------------------------- | | Quick Q\&A (\< 5s) | No — standard invoke is fine | | Multi-step research (30s+) | Yes — survives timeouts | | Code review with tool calls | Yes — durable tool execution | | File processing pipeline | Yes — atomic steps | | Scheduled recurring agent | Yes — durable scheduling | Basic Usage [#basic-usage] ```ts import { WorkflowAgent } from "@fluxy-chat/sdk"; const workflow = new WorkflowAgent({ agentId: "research-agent", roomId: "research-room", model: "gpt-4o", tools: messengerPreset, }); // Define steps workflow.step("gather", async (ctx) => { const messages = await ctx.searchRoom("pricing discussion"); ctx.set("findings", messages); }); workflow.step("analyze", async (ctx) => { const findings = ctx.get("findings"); const analysis = await ctx.llm({ prompt: `Analyze these messages: ${JSON.stringify(findings)}`, }); ctx.set("analysis", analysis); }); workflow.step("report", async (ctx) => { const analysis = ctx.get("analysis"); await ctx.postMessage(`## Analysis\n\n${analysis}`); }); // Run — survives restarts const run = await workflow.run({ maxSteps: 10 }); ``` Typed runtime context [#typed-runtime-context] Define a typed context schema for type-safe data sharing across steps: ```ts import { WorkflowAgent, defineContext } from "@fluxy-chat/sdk"; const ResearchContext = defineContext({ findings: { type: "array", required: true }, analysis: { type: "string", required: false }, confidence: { type: "number", default: 0 }, }); const workflow = new WorkflowAgent({ context: ResearchContext, // ... }); workflow.step("analyze", async (ctx) => { const findings = ctx.get("findings"); // typed as array ctx.set("confidence", 0.85); // type-checked // ctx.set("typo", "value"); // TypeScript error! }); ``` Durable Execution [#durable-execution] State is persisted after each step completion: ``` Step 1: gather → ✅ persisted Step 2: analyze → ✅ persisted Step 3: report → 💥 Worker restart → 🔄 Resume from Step 3 (state from Step 2 is loaded) Step 3: report → ✅ completed ``` Multi-step loop control [#multi-step-loop-control] Configure stop conditions for agent loops: ```ts const workflow = new WorkflowAgent({ maxSteps: 20, stopWhen: (ctx) => ctx.get("confidence") > 0.9, // or: stopWhen: hasToolCall("final_answer") // or: stopWhen: isStepCount(10) // or: stopWhen: isLoopFinished() }); ``` Tool Execution [#tool-execution] Tools called within a workflow are also durable. If a tool call is interrupted: 1. The tool call is logged in D1 with `status: "pending"` 2. On resume, the workflow checks for pending tool calls 3. If the tool is idempotent, it re-executes 4. If not, it waits for manual resolution Monitoring [#monitoring] Track workflow progress via the DevTools UI or API: ```ts const status = await client.getWorkflowStatus(runId); // { // step: "analyze", // completedSteps: ["gather"], // pendingSteps: ["analyze", "report"], // startedAt: "2026-07-01T12:00:00Z", // lastCheckpoint: "2026-07-01T12:01:30Z", // context: { findings: [...] } // } ``` Integration with Cloudflare Workflows [#integration-with-cloudflare-workflows] `WorkflowAgent` integrates with Cloudflare Workflows binding for native durable execution: ```ts export class FluxyScheduledWorkflow extends Workflow { async run(event, step) { const agent = new WorkflowAgent({ /* ... */ }); await agent.runWithWorkflow(step); } } ``` See Also [#see-also] * [Stream Resumption Guide](/docs/guides/stream-resumption) — Reconnecting to active AI streams * [AI Tool Presets Guide](/docs/guides/ai-tool-presets) — Tool governance for workflow agents --- # Activepieces integration (CRM / automation) (/docs/integrations/activepieces) Activepieces integration (CRM / automation) [#activepieces-integration-crm--automation] Use **Activepieces** (MIT, self-hostable) to run no-code automations when FluxyChat events fire — sync to CRM, notify Slack, update Notion. Important: embed vs external dashboard [#important-embed-vs-external-dashboard] | Approach | Cost | FluxyChat status | | ----------------------------------------------- | --------------------------- | ------------------------ | | **Self-host + use Activepieces UI directly** | Free (MIT) | ✅ Recommended | | **Custom FluxyChat piece (webhooks + actions)** | Free | ✅ Supported | | **Iframe embed inside FluxyChat console** | Enterprise / custom license | ❌ Not used (zero-budget) | Activepieces [embedding](https://www.activepieces.com/docs/embedding/overview) is an **enterprise feature** for white-label / multi-tenant embed. Self-hosting the OSS core is free for **your own** automations, but embedding Activepieces inside the FluxyChat dashboard requires a separate embed license. **Our approach:** Console → **Settings → Automation integrations** opens your Activepieces instance in a **new tab** (`automation.yourdomain.com`), not an iframe. *** Architecture [#architecture] ``` FluxyChat Worker webhooks → Activepieces Webhook trigger Activepieces action → FluxyChat REST / admin API Operator → Activepieces web UI (separate tab) ``` Activepieces runs **outside** Cloudflare Workers. *** Self-host setup (free) [#self-host-setup-free] Prerequisites [#prerequisites] * VPS with Docker * Subdomain DNS A record, e.g. `automation.fluxychat.com` → VPS IP * HTTPS reverse proxy (Caddy recommended — automatic Let's Encrypt) Install [#install] ```bash mkdir -p /opt/activepieces && cd /opt/activepieces git clone https://github.com/activepieces/activepieces . # Generate secrets openssl rand -hex 16 # → AP_ENCRYPTION_KEY openssl rand -hex 32 # → AP_JWT_SECRET openssl rand -hex 16 # → AP_POSTGRES_PASSWORD ``` Create `.env` (names match official docker-compose): ```text AP_FRONTEND_URL=https://automation.fluxychat.com AP_POSTGRES_DATABASE=activepieces AP_POSTGRES_USERNAME=ap_user AP_POSTGRES_PASSWORD= AP_POSTGRES_HOST=postgres AP_POSTGRES_PORT=5432 AP_REDIS_HOST=redis AP_REDIS_PORT=6379 AP_ENCRYPTION_KEY= AP_JWT_SECRET= AP_SIGN_UP_ENABLED=false ``` ```bash docker compose up -d ``` HTTPS with Caddy (example) [#https-with-caddy-example] ```text automation.fluxychat.com { reverse_proxy localhost:8080 } ``` Point Activepieces container port 80/8080 per their compose file. Dashboard link (not embed) [#dashboard-link-not-embed] Set in Vercel / dashboard env: ```text NEXT_PUBLIC_ACTIVEPIECES_URL=https://automation.fluxychat.com ``` Users click **Open automation studio** in **Settings → Automation integrations** — opens Activepieces in a new tab. **Do not set** `NEXT_PUBLIC_ACTIVEPIECES_EMBED_URL` unless you have an enterprise embed license. *** FluxyChat custom piece [#fluxychat-custom-piece] Code: `examples/integrations/activepieces/src/` | Trigger | FluxyChat event | | ------------- | ------------------- | | New message | `message.created` | | Agent handoff | `handoff.requested` | | Action | API | | ------------ | -------------------------- | | Send message | `POST /rooms/:id/messages` | | Create room | Admin rooms API | Install piece in Activepieces [#install-piece-in-activepieces] 1. **Settings → Pieces → Add custom piece** → path to `examples/integrations/activepieces/src/` 2. Or build and upload per Activepieces custom piece docs Webhooks [#webhooks] 1. FluxyChat **Console → Webhooks** → register outbound URL from Activepieces flow 2. Verify `X-Fluxy-Signature` with shared secret in Activepieces connection API key (automations) [#api-key-automations] Activepieces **Platform Admin → Security → API Keys** — use for server-side calls from FluxyChat piece actions (not for dashboard embed). *** CRM adapters today [#crm-adapters-today] KV stubs: `apps/worker/src/lib/crm-adapters.js`. Activepieces replaces bespoke CRM glue with user-configurable flows. *** References [#references] * [Activepieces docs](https://www.activepieces.com/docs/overview/welcome) * [Embedding (enterprise)](https://www.activepieces.com/docs/embedding/overview) * [PRODUCTION-SETUP.md](/docs/operations/production-setup) * Piece README: `examples/integrations/activepieces/README.md` --- # Kotlin Multiplatform mobile SDK (/docs/integrations/kotlin-multiplatform) Kotlin Multiplatform mobile SDK [#kotlin-multiplatform-mobile-sdk] Shared WebSocket client for Android and iOS — same protocol as `@fluxy-chat/sdk`. Current state [#current-state] | Package | Status | | ---------------------- | ----------------------------------------- | | `packages/sdk-kmp/` | **Active** — Ktor WS, Android / iOS / JVM | | `packages/kotlin-sdk/` | Legacy Android starter | | `packages/swift-sdk/` | Legacy iOS starter | Layout [#layout] ``` packages/sdk-kmp/ shared/src/commonMain/kotlin/ FluxyChatClient, FluxyRoomWebSocket shared/src/androidMain/ OkHttp engine shared/src/iosMain/ Darwin engine shared/src/jvmMain/ CIO engine (tests) ``` Build locally [#build-locally] Requires JDK 17+. ```bash cd packages/sdk-kmp gradle :shared:jvmTest gradle :shared:compileDebugKotlinAndroid ``` CI uses `gradle/actions/setup-gradle@v4` (no local wrapper required). Usage [#usage] ```kotlin val config = FluxyChatConfig( apiUrl = "https://api.example.com", wsUrl = FluxyChatConfig.wsUrlFromApi("https://api.example.com"), projectId = "your-project-uuid", token = memberJwt, ) val client = FluxyChatClient(config) client.connectRoom("general") client.sendMessage("general", "Hello from KMP") ``` Publish to Maven Central [#publish-to-maven-central] Tag `sdk-v*` triggers `.github/workflows/publish-sdk-kmp.yml`. **Full setup (Sonatype, GPG, GitHub secrets):** [maven-central-publish.md](/docs/integrations/maven-central-publish) Coordinates: `com.fluxychat:shared` iOS [#ios] XCFramework zip attached to GitHub Release on each `sdk-v*` tag. Embed in Xcode per [Kotlin Apple framework docs](https://kotlinlang.org/docs/apple-framework.html). References [#references] * [maven-central-publish.md](/docs/integrations/maven-central-publish) * `packages/sdk-kmp/README.md` * TS SDK: `packages/sdk/src/` --- # LiveKit integration (voice / video) (/docs/integrations/livekit) LiveKit integration (voice / video) [#livekit-integration-voice--video] FluxyChat voice features use **LiveKit** as the WebRTC SFU. The Cloudflare Worker issues short-lived JWT access tokens; media runs on your LiveKit server, not on Workers. Architecture [#architecture] ``` Browser (livekit-client) ←WebRTC→ LiveKit SFU ↑ JWT token FluxyChat Worker (POST /voice/token or dashboard voice-ai routes) ``` * **Worker**: member token mint `POST /rooms/:id/voice/token` (identity is the JWT user). Admin `POST /admin/calls/token` remains. Media never runs on the Worker. * **Dashboard**: `/voice-ai` for agent voice configuration. * **Client**: add `livekit-client` in React apps; connect with token from Worker. If no `LIVEKIT_*` secrets are set on the Worker, both token routes answer `503 { "error": "livekit_not_configured" }`. There is no stub token to connect with — configure the keys, or treat voice as unavailable in your UI. Self-hosted LiveKit [#self-hosted-livekit] 1. Deploy [LiveKit server](https://docs.livekit.io/home/self-hosting/deployment/) (Docker/K8s). 2. Set Worker secrets: * `LIVEKIT_API_KEY` * `LIVEKIT_API_SECRET` * `LIVEKIT_URL` (wss\://your-livekit.example.com) 3. Token mint: `POST /admin/calls/token` uses `mintLiveKitAccessToken` in `apps/worker/src/lib/livekit-token.js`. 4. Extend client apps with `livekit-client` when connecting to the SFU. React quick start [#react-quick-start] ```tsx import { Room, RoomEvent } from "livekit-client"; import { useLiveKitToken } from "@fluxy-chat/react"; function VoiceRoom({ roomId, adminJwt }: { roomId: string; adminJwt: string }) { const { token, fetchToken } = useLiveKitToken({ workerUrl: process.env.NEXT_PUBLIC_FLUXYCHAT_WORKER_URL!, adminJwt, roomId, displayName: "Alice", }); async function join() { const creds = await fetchToken(); if (!creds?.token || !creds.url) return; const room = new Room(); await room.connect(creds.url, creds.token); } return ; } ``` LiveKit Agents (optional) [#livekit-agents-optional] For AI voice agents, use [LiveKit Agents](https://docs.livekit.io/agents/) as a separate process. FluxyChat agent runtime can hand off to an agent worker via webhook when a voice session starts. References [#references] * [LiveKit overview](https://docs.livekit.io/intro/overview/) * [Access tokens](https://docs.livekit.io/home/get-started/authentication/) * Worker stubs: `apps/worker/src/lib/video-voice.js`, `apps/dashboard/app/voice-ai/` --- # Publish KMP SDK to Maven Central (Sonatype) (/docs/integrations/maven-central-publish) Publish KMP SDK to Maven Central (Sonatype) [#publish-kmp-sdk-to-maven-central-sonatype] This guide covers **Fase 5** from [PRODUCTION-SETUP.md](/docs/operations/production-setup): getting `OSSRH_USER`, `OSSRH_PASS`, `GPG_KEY`, and `GPG_PASS` into GitHub Actions so `sdk-v*` tags publish `com.fluxychat` artifacts. > **Not SonarQube.** The portal at [my.sonatype.com](https://my.sonatype.com) is **Sonatype** (Maven Central / OSSRH). SonarQube is unrelated code quality tooling. *** What you are setting up [#what-you-are-setting-up] | GitHub secret | What it is | | ------------- | -------------------------------------------------------------- | | `OSSRH_USER` | Sonatype Central Portal username (or token username) | | `OSSRH_PASS` | Sonatype Central Portal password (or user token) | | `GPG_KEY` | ASCII-armored **private** GPG key used to sign Maven artifacts | | `GPG_PASS` | Passphrase for that GPG key | CI workflow: `.github/workflows/publish-sdk-kmp.yml` — triggered by tags `sdk-v*` (e.g. `sdk-v1.0.0`). Gradle coordinates: `com.fluxychat:shared` from `packages/sdk-kmp/shared/build.gradle.kts`. *** Step 1 — Register on Sonatype Central Portal [#step-1--register-on-sonatype-central-portal] 1. Go to [central.sonatype.com](https://central.sonatype.com/) (new portal) or sign in via [my.sonatype.com](https://my.sonatype.com). 2. Create / verify your account (same login as the dashboard you saw). 3. **Publish namespace** → **Register namespace** → enter: ``` com.fluxychat ``` 4. Prove ownership of the GitHub repo (recommended path): * Add a temporary empty commit or file Sonatype asks for, **or** * Add a DNS TXT record if you prefer domain verification for `fluxychat.com`. 5. Wait for **Approved** status on namespace `com.fluxychat`.\ **First-time approval often takes 1–2 business days** — start this early; it is the slowest step. *** Step 2 — Generate a user token (OSSRH credentials) [#step-2--generate-a-user-token-ossrh-credentials] In Central Portal: 1. **Account** (profile icon) → **Generate User Token** (or **Access Tokens**). 2. Copy the generated **username** and **password** pair immediately (password shown once). Map to GitHub: ``` OSSRH_USER = OSSRH_PASS = ``` These replace legacy OSSRH “JIRA username + password” for the new Central Portal API. *** Step 3 — Create a GPG signing key [#step-3--create-a-gpg-signing-key] Maven Central requires signed artifacts. On your machine (Git Bash on Windows is fine): ```bash gpg --full-generate-key # RSA and RSA, 4096 bits, expiry 0 (no expiry) or 2y # Real name: FluxyChat Release # Email: your-email@domain.com ``` List keys: ```bash gpg --list-secret-keys --keyid-format=long ``` Export **private** key (for CI — store only in GitHub Secrets): ```bash gpg --armor --export-secret-keys YOUR_KEY_ID > gpg-private.asc ``` Copy the entire file contents (including `-----BEGIN PGP PRIVATE KEY BLOCK-----`) into GitHub secret `GPG_KEY`. Set `GPG_PASS` to the passphrase you chose when creating the key. Upload public key to keyserver (required once) [#upload-public-key-to-keyserver-required-once] ```bash gpg --keyserver keyserver.ubuntu.com --send-keys YOUR_KEY_ID ``` Sonatype verifies signatures against public keys on keyservers. *** Step 4 — Add GitHub repository secrets [#step-4--add-github-repository-secrets] **GitHub → your repo → Settings → Secrets and variables → Actions → New repository secret** | Name | Value | | ------------ | ------------------------------------ | | `OSSRH_USER` | Token username from Step 2 | | `OSSRH_PASS` | Token password from Step 2 | | `GPG_KEY` | Full armored private key from Step 3 | | `GPG_PASS` | GPG passphrase | No Worker or Vercel env vars needed for Maven publish — this is CI-only. *** Step 5 — Tag and publish [#step-5--tag-and-publish] After namespace `com.fluxychat` is **Approved** and secrets are set: ```bash git tag sdk-v1.0.0 git push origin sdk-v1.0.0 ``` Workflow jobs: 1. **test** — `gradle :shared:jvmTest` 2. **publish-android** — Maven Central (skipped if `OSSRH_USER` empty) 3. **publish-ios** — XCFramework zip attached to GitHub Release Monitor: **GitHub → Actions → Publish SDK KMP**. First release manual step [#first-release-manual-step] After Gradle uploads artifacts, CI runs `scripts/sonatype-upload-staging.sh`, which: 1. Calls `GET /manual/search/repositories` for **open** staging repos (Android + JVM often create two). 2. POSTs each to `/manual/upload/repository/\{key\}?publishing_type=user_managed` (same runner IP as Gradle — required by Sonatype). Set `SONATYPE_PUBLISHING_TYPE=automatic` in the workflow env to attempt auto-release after validation. If upload fails with **400**, check [Central Portal → Deployments](https://central.sonatype.com/publishing) — Gradle may already have uploaded; release manually with **Publish**. Gradle staging URL (replaces legacy `s01.oss.sonatype.org`, which returns **402** after OSSRH sunset): ``` https://ossrh-staging-api.central.sonatype.com/service/local/staging/deploy/maven2/ ``` Then open [central.sonatype.com](https://central.sonatype.com/) → **Deployments** → **Release** the staging deployment (first time only). Subsequent releases can use `publishing_type=automatic` once namespace auto-publish is enabled. *** Step 6 — Consume from Android [#step-6--consume-from-android] ```kotlin // settings.gradle.kts or build.gradle.kts repositories { mavenCentral() } dependencies { implementation("com.fluxychat\:shared:1.0.0") } ``` iOS: download `FluxyChatSDK.xcframework.zip` from the GitHub Release attached to the same tag. *** Troubleshooting [#troubleshooting] | Problem | Fix | | --------------------------------- | --------------------------------------------------------------------------------------------- | | Namespace pending | Wait for Sonatype approval; cannot publish until approved | | `401 Unauthorized` on publish | Regenerate user token; update `OSSRH_USER` / `OSSRH_PASS` | | `402 Payment Required` on publish | Repo still points at legacy `s01.oss.sonatype.org` — use Central Portal staging API URL above | | Signature verification failed | Re-upload public key to keyserver; check `GPG_KEY` is private key armored | | CI skips Maven publish | Log says `OSSRH_USER not set` — add secrets or expect build-only | | `./gradlew` not found locally | CI uses `gradle/actions/setup-gradle@v4`; local dev optional | *** Quick checklist [#quick-checklist] * [ ] Namespace `com.fluxychat` registered and **Approved** * [ ] User token → `OSSRH_USER` / `OSSRH_PASS` * [ ] GPG key created, public key on keyserver * [ ] `GPG_KEY` / `GPG_PASS` in GitHub Secrets * [ ] Tag `sdk-v1.0.0` pushed * [ ] Release staging deployment on Central Portal (first time only) * [ ] Update docs / feature parity: “Mobile native SDK — live on Maven Central” See also: [kotlin-multiplatform.md](/docs/integrations/kotlin-multiplatform), `packages/sdk-kmp/README.md`. --- # Labs (/docs/labs) The product is a **room**: chat, presence, Yjs, `invokeAgent`, HITL. Stream overlays, IoT, fleet, game ticks, audience scores, and community simulations live here so they stay off the main nav. Healthcare is **not for sale**. There is no BAA and no SOC 2 Type II. A later hybrid (data in the customer Cloudflare account) is the only HIPAA-shaped path we would discuss, and we do not promise it. Cookbooks that used to sit at the top of docs: [Cookbook](/docs/cookbook). Voice: we do not run an SFU. `POST /rooms/:id/voice-bridge` takes transcripts, tool calls, and approval requests from LiveKit Agents, Pipecat, or OpenAI Realtime. Media stays in those products. Legal: `--example negotiation-room` is two counterparties in one room with auto / ask / deny. Ask is HITL. We do not sell a CLM. Finance: maker-checker on HITL (`rooms.*.makerChecker`), `toolAutonomy` on the agent, SHA-256 evidence pack on decide. Not a core banking rail. Native push: register with `expo` / `fcm-v1` / `apns`. Notification copy has no tool args. Approve/deny is POST with a one-time token. Browser handoff: `POST /rooms/:id/browser-handoff` publishes a Live View card as a whisper. Recording pauses on login/MFA. Screenshots do not go on the transcript. Browser Run traffic is bot-identified. A2UI: agents declare ui-kit catalog components (`POST /rooms/:id/a2ui`). Buttons are person-attributed and can require quorum. Agent Inbox: `GET /inbox/agent` lists pending HITL for you. Ambient `cron` policies need a `roomId` and a 5-field (or minute-step) pattern. Worker `*/5` ticks them. DSA: public `/report` posts to `POST /public/dsa-report`. Share tokens are disabled in place. Not a VLOP process and not legal advice. --- # After Cloudflare's real-time chat tutorial (/docs/learn/after-cloudflare-chat-tutorial) After Cloudflare's real-time chat tutorial [#after-cloudflares-real-time-chat-tutorial] You finished the official Workers + Durable Objects walkthrough. Here is what production SaaS chat still needs, and how FluxyChat packages it. What the tutorial proves [#what-the-tutorial-proves] Cloudflare's real-time chat application tutorial validates the core pattern: WebSocket upgrade on a Worker, shared state in a Durable Object, fan-out to clients in a room. That is the right mental model. It is not yet multi-tenant auth, billing, operator tooling, or client reconnect semantics. What teams add next (the long tail) [#what-teams-add-next-the-long-tail] * Project-scoped JWT and room membership, not open rooms. * D1 (or equivalent) for history, search, and export, not memory-only fan-out. * Reconnect, loadMore, and delivery status on the client. * Quotas, webhooks, GDPR flows, and an operator console. * Agent tool\_call / tool\_result on the same timeline as user messages. FluxyChat as the production layer [#fluxychat-as-the-production-layer] * One RoomDurableObject per room: same architecture as the tutorial, maintained in MIT source. * Self-host on your Cloudflare account or try hosted beta. No second socket vendor. * @fluxy-chat/sdk for React/Next.js; vanilla store for other stacks. * Dashboard for projects, rooms, agents, and billing hooks. Astro, Nuxt, or Vercel front [#astro-nuxt-or-vercel-front] Keep your UI on Pages, Astro, or Vercel. Point the SDK at your Worker URL. You get edge chat without rebuilding the tutorial boilerplate on every feature. --- # Agent events on the same WebSocket as chat (/docs/learn/agent-events-same-websocket-stream) Agent events on the same WebSocket as chat [#agent-events-on-the-same-websocket-as-chat] When humans and copilots share a room, debugging and handoffs are easier if tool\_call, tool\_result, and user messages share one ordered stream, not a side channel. Pain from AI-at-work threads [#pain-from-ai-at-work-threads] * Operators ask: what did the agent do, in which order, relative to the user? * Split transports (chat in one pipe, tools in another) make replay and support harder. * Observability improves when the room timeline is the source of truth. What FluxyChat streams on the room socket [#what-fluxychat-streams-on-the-room-socket] * User messages with deliveryStatus and clientMessageId. * tool\_call, tool\_result, tool\_error, and agentRun events on the same timeline. * Optional webhooks for downstream automation, still keyed to room + project. * Console + D1 for history export when you need audit, not only live fan-out. Demo narrative [#demo-narrative] In the operator console, open a room with an agent configured: mention the agent, watch tool events appear beside human messages, then inspect runs from the agents page. That is the workflow product teams describe when they want copilots inside SaaS, not a separate debug UI. React hook [#react-hook] ``` const { messages, invokeAgent, agentTyping } = useChat({ roomId, client, agentId: "agt_…", }); // messages includes user posts and agent/tool events for your UI to render ``` --- # API key management: rotate, scope, and revoke (/docs/learn/api-key-management) API key management: rotate, scope, and revoke [#api-key-management-rotate-scope-and-revoke] Best practices for managing FluxyChat API keys: project-scoped keys, rotation, and emergency revocation. How API keys work [#how-api-keys-work] FluxyChat issues project-scoped API keys (prefixed with fc\_) that authenticate REST and WebSocket access. Each key is tied to a specific project and inherits the project's permissions. Keys are stored hashed in D1 using API\_KEY\_HASH\_SALT. The raw key is only visible at creation time. Rotating API keys [#rotating-api-keys] * Generate a new key via POST /projects/api-keys before removing the old one * Update your application to use the new key * Verify all services work with the new key * Delete the old key via DELETE /projects/api-keys/:id * Never have zero active keys. Overlap during rotation. Key scoping [#key-scoping] Each project has its own set of API keys. In multi-tenant deployments (HOSTED\_MULTI\_TENANT=true), tenant projects cannot use worker-level keys. They must use their own project-scoped credentials. Use ALLOW\_WORKER\_LLM\_FALLBACK=true to let all projects use the worker's shared AI credentials as a fallback. Emergency revocation [#emergency-revocation] To immediately revoke access, delete the API key from the dashboard or via DELETE /projects/api-keys/:id. All active sessions using that key will be disconnected on the next WebSocket heartbeat. For project-wide revocation, rotate the project's jwt\_secret. All existing JWTs become invalid immediately. --- # Build realtime chat with Next.js and FluxyChat (/docs/learn/build-chat-nextjs-fluxychat) Build realtime chat with Next.js and FluxyChat [#build-realtime-chat-with-nextjs-and-fluxychat] Nuxt/Vue-style CF tutorials, but for Next.js App Router: Route Handler JWT, client useChat, reconnect, and history pagination on Cloudflare Workers + Durable Objects. Prerequisites [#prerequisites] * Next.js 14+ App Router on Vercel (or elsewhere). * FluxyChat hosted beta or self-hosted Worker + D1. * pnpm add @fluxy-chat/sdk 1\. Mint JWT server-side [#1-mint-jwt-server-side] ``` // app/api/chat/token/route.ts export async function POST(req: Request) { const { userId } = await req.json(); const res = await fetch(`${process.env.FLUXY_WORKER_URL}/auth/token`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fluxy-Api-Key": process.env.FLUXY_API_KEY!, }, body: JSON.stringify({ userId, roles: ["member"], ttlSeconds: 3600 }), }); return Response.json(await res.json()); } ``` 2\. Client room component [#2-client-room-component] ``` "use client"; import { FluxyChatClient } from "@fluxy-chat/sdk"; import { useChat } from "@fluxy-chat/react"; const client = new FluxyChatClient({ baseUrl: process.env.NEXT_PUBLIC_FLUXYCHAT_CLOUD_URL!, userId, token: memberJwt, }); export function RoomChat({ roomId }: { roomId: string }) { const { messages, sendMessage, connectionState, loadMore, hasMore } = useChat({ roomId, client, replay: "connect" }); return (/* render messages + connectionState + loadMore button */); } ``` 3\. Reconnect and history [#3-reconnect-and-history] * Show connectionState.status and nextRetryAt in the UI. * Call loadMore() after refresh or reconnect. * Use clientMessageId for idempotent retries on failed sends. 4\. Deploy split [#4-deploy-split] Keep Next on Vercel; Worker on Cloudflare. Same pattern as the Nuxt-on-Pages tutorials: different import, same split. If you landed here from a Next.js realtime chat tutorial and do not want Socket.IO on a VPS, this is the packaged version of that split. --- # How to build instant messaging on Cloudflare Workers (/docs/learn/cloudflare-workers-chat) How to build instant messaging on Cloudflare Workers [#how-to-build-instant-messaging-on-cloudflare-workers] cloudflare workers websocket + durable objects chat: shared state coordination per room, D1 history, realtime without a VPS. For Cloudflare Pages, Vercel, or Netlify fronts. Start with Cloudflare’s chat demo (mental model) [#start-with-cloudflares-chat-demo-mental-model] The official Workers WebSocket chat example shows: Worker upgrade → one Durable Object per room → fan-out to connected clients. Treat it as hello-world, not multi-tenant production. Use Cloudflare’s vocabulary [#use-cloudflares-vocabulary] Buyers researching DOs see the same phrases in official docs: coordination, shared state, chat rooms, WebSocket hibernation, transactional consistency. FluxyChat is the production chat layer built on those primitives. Understand what production adds [#understand-what-production-adds] * JWT auth per tenant and room membership checks in D1. * History pagination and reconnect/backoff on the client. * Quotas, webhooks, GDPR export, operator console. * Human + agent events on the same room WebSocket. Pick your deploy split [#pick-your-deploy-split] Next.js or Nuxt on Vercel/Netlify for HTTP + UI; FluxyChat Worker on Cloudflare for chat. Avoid Vercel WebSocket limits and a second Pusher/Ably vendor. Go deeper with a walkthrough [#go-deeper-with-a-walkthrough] Worker routing at `/ws/room/:roomId`, RoomDurableObject, SDK useChat, and self-host commands: in the long-form Dev.to article. --- # Discord-style realtime chat on Cloudflare (no VPS) (/docs/learn/discord-style-chat-cloudflare) Discord-style realtime chat on Cloudflare (no VPS) [#discord-style-realtime-chat-on-cloudflare-no-vps] Workers + Durable Objects + D1 (+ R2 for attachments): the same "no container socket fleet" story as serverless Discord clones, packaged as a chat layer for your product. Why builders search for this [#why-builders-search-for-this] Show HN posts and CF tutorials keep winning with one message: realtime rooms without running your own WebSocket VM. Discord-style here means many clients in a room, ordered messages, presence. Not cloning Discord's entire product. FluxyChat targets teams who want that architecture for in-app SaaS chat, not a gaming social network. The Cloudflare stack (Accord-style) [#the-cloudflare-stack-accord-style] * Workers: HTTP API, JWT mint, WebSocket upgrade routing. * One Durable Object per room: fan-out, typing, live connections. * D1: message history, search, tenant metadata. * R2 (optional): attachments; your Worker signs uploads. * No Socket.io cluster on a VPS; no second realtime vendor if you self-host on CF. Replacing Socket.io or a VPS fleet [#replacing-socketio-or-a-vps-fleet] * Socket.io on Node: you operate processes, regions, and sticky sessions. * Room-per-DO: Cloudflare routes clients to the object that owns that room's state. * Client: @fluxy-chat/sdk (reconnect, loadMore) instead of hand-rolled socket.io client glue. * Tradeoff: you learn CF billing and DO patterns, not a managed Pusher dashboard. Where FluxyChat fits [#where-fluxychat-fits] MIT monorepo with RoomDurableObject, operator console, agents on the same room WebSocket, hosted beta or deploy to your account. Use the demo to feel the UX, then self-host when you need control. --- # Single-threaded Durable Objects and chat: honest tradeoffs (/docs/learn/durable-objects-chat-tradeoffs) Single-threaded Durable Objects and chat: honest tradeoffs [#single-threaded-durable-objects-and-chat-honest-tradeoffs] When the Room DO is the source of truth, when D1 is, and what throughput to expect per room (without pretending one object scales infinite hot rooms). "DOs are single-threaded": what it means for chat [#dos-are-single-threaded-what-it-means-for-chat] Each Durable Object processes requests sequentially. For one chat room, that is often a feature: ordering is straightforward and you avoid distributed locks inside the room. A single ultra-hot room (thousands of messages per second in one channel) may need sharding or fan-out patterns beyond one object. Most SaaS tenant rooms are far below that. DO vs D1: division of labor [#do-vs-d1-division-of-labor] * DO: who is connected now, fan-out, ephemeral signals (typing). * D1: durable messages, membership, audit-friendly history. * Worker: auth, REST pagination, webhooks, GDPR export. * Do not treat DO storage as your message database for unbounded history. Workers only (no DO)? [#workers-only-no-do] Stateless Workers cannot hold open WebSocket fan-out for a room across clients. You need sticky coordination. That is the DO (or an external broker). "Just Workers" fits HTTP, not multi-client room state. FluxyChat's scope [#fluxychats-scope] We optimize for many rooms with moderate throughput each, not one global firehose. If you outgrow one room object, you shard by roomId (multiple products) or redesign that hot channel. We do not hide that limit. --- # Durable Objects for chat rooms (/docs/learn/durable-objects-for-chat-rooms) Durable Objects for chat rooms [#durable-objects-for-chat-rooms] Shared state coordination, transactional consistency, and WebSocket hibernation: the Cloudflare primitives behind edge-native chat without a socket fleet. Why Durable Objects fit chat [#why-durable-objects-fit-chat] Cloudflare documents Durable Objects for coordination problems: chat rooms, multiplayer games, collaborative documents, and any workload that needs strongly consistent shared state on the edge. A chat room is exactly that pattern: one coordination point per room, many WebSocket clients, ordered fan-out, and optional persistence to D1. Vocabulary buyers search for [#vocabulary-buyers-search-for] * Shared state coordination: one Room DO holds live connections and ephemeral signals (typing, presence). * Transactional consistency: membership and message writes go through D1 with clear project scoping. * WebSocket hibernation: the DO can sleep while clients reconnect; your app still needs client-side replay semantics. * cloudflare workers websocket: HTTP + upgrade on the Worker, sticky room state on the DO. * durable objects chat: one object name per roomId, not one global socket server. How FluxyChat maps the primitives [#how-fluxychat-maps-the-primitives] * RoomDurableObject: one DO per room for fan-out, ordering, and connection lifecycle. * D1: queryable history, templates, webhooks metadata; not every keystroke as a hot write. * Worker: JWT mint, REST writes, GDPR export, and `/ws/room/:roomId` upgrade routing. * SDK: connectionState, loadMore (history replay), clientMessageId idempotency on reconnect. PartyKit vs chat-layer DOs [#partykit-vs-chat-layer-dos] PartyKit and DO demos excel at collab "party" state and tutorials. FluxyChat targets SaaS in-app messaging: multi-tenant JWT, operator console, billing hooks, and production reconnect, not a generic party runtime. Shared human + agent workspace [#shared-human--agent-workspace] Agentic products need the same durable room state for people and bots: tool\_call, tool\_result, and agentRun events on the same WebSocket timeline as user messages. FluxyChat ships that on the room stream so you do not fork transport for AI features. From official demo to production [#from-official-demo-to-production] Start with Cloudflare's Workers chat example, then add auth, history pagination, quotas, and operator tooling, or adopt FluxyChat as the maintained layer. --- # Chat room costs: Durable Objects, hibernation, and idle WebSockets (/docs/learn/durable-objects-hibernation-cost) Chat room costs: Durable Objects, hibernation, and idle WebSockets [#chat-room-costs-durable-objects-hibernation-and-idle-websockets] Why idle WebSockets used to pin DOs in memory, and how room-per-DO chat plus D1 persistence keeps Cloudflare realtime costs understandable. The cost fear (and what changed) [#the-cost-fear-and-what-changed] Teams evaluating CF realtime often hear: "WebSockets keep Durable Objects awake and you pay duration forever." Hibernation APIs exist so idle connections can sleep; you still need a clear persistence and reconnect story. Cost surprises usually come from unbounded writes or one hot object, not from "using WebSockets" alone. Mental model for chat billing [#mental-model-for-chat-billing] * Room DO: live fan-out, presence, typing; wake on message or connection. * D1: durable messages. Room DO chat frames go through a **write-behind WAL in `state.storage`**, then `D1.batch()` (default on; `MESSAGE_D1_WRITE_BEHIND=false` restores one INSERT per message). That cuts D1 round-trips. It is **not** a measured Cloudflare invoice. Broadcast waits for the batch so message ids stay D1 `last_row_id`. History REST and GDPR export flush the WAL first. * One DO per room: blast radius stays room-scoped (not one global coordinator). * Avoid logging every keystroke into DO storage; rate-limit abusive clients. Hibernation + client replay [#hibernation--client-replay] When a DO hibernates, clients disconnect. Production apps use REST history + SDK `loadMore()` and `connectionState`. See the reconnect guide. Idle-socket **duration on the Cloudflare invoice** is not published here. To get a number: staging room, many idle connections, one hour, read Durable Object duration in the Cloudflare dashboard. If duration stays near zero, that is the figure for a cost page. Until then, treat this page as the mental model, not a measurement. What FluxyChat does [#what-fluxychat-does] * RoomDurableObject per roomId: same pattern as CF demos, with quotas in the Worker. * Console + budget alarms still on you. Set CF notifications. * Self-host: you see raw CF invoices; hosted beta: plan limits on messages/agents. Cost hygiene checklist [#cost-hygiene-checklist] * Staging load test before prod traffic. * Archive or delete dead rooms if you create thousands of idle DOs. * Monitor DO requests/storage; don't retry-loop on WebSocket close 1008. * Read Cloudflare pricing pages for DO and D1. FluxyChat does not flatten this into opaque "per connection" pricing. --- # Moved (/docs/learn/for-analysts) This page is now [Status and limits](/docs/learn/status-and-limits). --- # GDPR compliance and data retention (/docs/learn/gdpr-compliance) GDPR compliance and data retention [#gdpr-compliance-and-data-retention] Export, anonymize, and delete user data to comply with GDPR and privacy regulations. GDPR in FluxyChat [#gdpr-in-fluxychat] FluxyChat stores user data in Cloudflare D1 (messages, reactions, room memberships) and R2 (attachments, voice messages, AI-generated images). To comply with GDPR, you must be able to export, anonymize, and delete user data on request. Data export [#data-export] * GET /users/:userId/export returns all user data as JSON * Includes messages, reactions, room memberships, and file metadata * Attachments can be downloaded via their R2 URLs * Export is rate-limited to once per 24 hours per user ```bash curl -sS -H "Authorization: Bearer $MEMBER_JWT" \ "$FLUXY_BASE_URL/gdpr/export" ``` Starter hosted plans include export. Erasure: ```bash curl -sS -X DELETE -H "Authorization: Bearer $OWNER_JWT" \ "$FLUXY_BASE_URL/gdpr/delete" ``` Also `GET /users/:userId/export` with a member JWT for a JSON dump of that user's messages and memberships. Right to be forgotten [#right-to-be-forgotten] DELETE /users/:userId permanently deletes all user data. This operation is irreversible: * Soft-deletes all messages (content replaced, deleted\_at set) * Hard-deletes all reactions and read receipts * Removes user from all room memberships * Deletes user's attachments from R2 * Anonymizes the user record (name, avatar, metadata cleared) * Preserves audit trail (user\_id retained for compliance, but no PII) Data retention policies [#data-retention-policies] Configure retention via the dashboard or API: * Set message\_expires\_at on individual messages for ephemeral chats * Use AUTO\_ROOM\_SUMMARY\_ENABLED to summarize old messages (reduces storage) * Run scheduled cleanup via cron: DELETE FROM messages WHERE deleted\_at IS NOT NULL AND deleted\_at \< datetime('now', '-30 days') * R2 objects can be configured with lifecycle rules for auto-expiration Audit trail [#audit-trail] FluxyChat logs all admin actions (user deletion, key rotation, config changes) with timestamps and actor IDs. Access audit logs via GET /admin/audit-log. --- # In-app chat vs support desk (/docs/learn/in-app-chat-vs-support-desk) In-app chat vs support desk [#in-app-chat-vs-support-desk] Intercom-style roundups are written for support teams. FluxyChat is the room layer you embed in your SaaS: SDK, history, webhooks, agent timeline. Not a helpdesk replacement. Two different products [#two-different-products] * Support desk: shared inbox, tickets, CSAT, macros, help-center widget. * In-app chat infra: tenant rooms, JWT members, WebSocket transport, D1 history, your UI. * FluxyChat is the second. You can still build support on top. See docs/use-cases/support-chat.md. Same benefits, different buyer [#same-benefits-different-buyer] Articles about live chat often talk about onboarding and retention inside the product. That applies to embedded chat too. The buyer is just different: your engineering team shipping messaging in the app, not a CS lead shopping for a helpdesk. FluxyChat is for builders who want a chat layer on Cloudflare they can self-host. Not a full support suite. Humans, agents, and CRM hooks [#humans-agents-and-crm-hooks] * Users describe what they want in chat; your agent calls tools or external APIs. * tool\_call and tool\_result ride the same WebSocket as user messages. One timeline to replay. * Pair with whatever integration runner you use (MCP, CLI skills, webhooks) for Salesforce, HubSpot, etc. When you actually need a helpdesk [#when-you-actually-need-a-helpdesk] If you need ticketing, SLA queues, and a standalone support portal on day one, look at Intercom-style or Libredesk-style products. FluxyChat replaces the socket layer when chat lives inside your product UI, not the whole support operation. Search intent (for your own landing copy) [#search-intent-for-your-own-landing-copy] * Good fit: embedded chat for SaaS, in-app chat platform, Pusher alternative, realtime chat in Next.js. * Usually wrong fit: best live chat software, Zendesk alternatives, unless you want support-team traffic. * More detail on /compare and /why#product-chat. --- # JWT Authentication for self-hosted FluxyChat (/docs/learn/jwt-auth) JWT Authentication for self-hosted FluxyChat [#jwt-authentication-for-self-hosted-fluxychat] Configure JWT-based auth for your FluxyChat worker without external identity providers: issue, refresh, and verify tokens. How JWT auth works in FluxyChat [#how-jwt-auth-works-in-fluxychat] FluxyChat uses HMAC-signed JWTs to authenticate WebSocket connections and REST API calls. Each project has its own jwt\_secret stored in the project\_secrets table. Tokens are issued on login and verified on every request. The worker's verifyJwtAndGetContext middleware extracts the project ID, user ID, and roles from the token, then enforces per-project isolation. Issuing JWT tokens [#issuing-jwt-tokens] Tokens are issued via the POST /auth/session endpoint. The worker signs them with the project's jwt\_secret and returns a short-lived access token plus a refresh token. ``` POST /auth/session { "projectId": "your-project-id", "userId": "user_123", "roles": ["member"] } Response: { "accessToken": "eyJ...", "refreshToken": "eyJ...", "expiresIn": 3600 } ``` Token verification [#token-verification] * Every REST request must include Authorization: Bearer \ * WebSocket connections pass the token as a query parameter: /ws?roomId=...\&token=... * The worker verifies the signature, checks expiry, and extracts projectId/userId * Expired tokens return 401. The client should refresh automatically. Secret rotation [#secret-rotation] To rotate the jwt\_secret without invalidating all active sessions, set JWT\_SECRET\_PREVIOUS in your worker env. The worker accepts tokens signed with either the current or previous secret. Set JWT\_SECRET\_PREVIOUS\_EXPIRES\_AT to a future ISO timestamp after which the old secret is rejected. --- # LLM memory vs room state in chat apps (/docs/learn/llm-memory-vs-room-state) LLM memory vs room state in chat apps [#llm-memory-vs-room-state-in-chat-apps] The model forgetting context is a different problem from your app losing messages. Own replay, history, and tool visibility in your infrastructure. Two different problems [#two-different-problems] * LLM memory: what the model keeps in context or RAG; vendor-specific, prompt-sized. * Room state: messages, tool\_call, tool\_result, who is connected; your product's job. What to store in your stack [#what-to-store-in-your-stack] * D1 (or your DB) for durable timeline per room. * Durable Object for live fan-out and presence. * SDK reconnect + loadMore so refresh does not wipe the UI. Why operators still get burned [#why-operators-still-get-burned] Teams bolt a copilot UI on one pipe and chat on another, then cannot answer what the agent did at 2pm. One WebSocket timeline for humans and tools fixes most support tickets. FluxyChat's slice [#fluxychats-slice] We do not fix model amnesia. We fix app state: room DO, D1 history, agent events on the same stream, console for runs. --- # Realtime chat in Next.js on Vercel (/docs/learn/nextjs-vercel-realtime-chat) Realtime chat in Next.js on Vercel [#realtime-chat-in-nextjs-on-vercel] Ship the App Router on Vercel; run WebSocket rooms on Cloudflare Workers + Durable Objects. Ably and Pusher are not the only path. The buyer question Ably owns [#the-buyer-question-ably-owns] Tutorials for "live app on Vercel" often assume Ably or Pusher because serverless functions are not a socket fleet. That is correct. The fix is not forcing WebSockets into Vercel alone; it is a dedicated realtime layer. FluxyChat integration shape [#fluxychat-integration-shape] * Route Handler or API route mints a member JWT with your fc\_... key (server-only). * Client component uses useChat(\{ roomId, client }) with baseUrl = your Worker. * Map Ably channels or Pusher channels → FluxyChat roomIds. * Use loadMore() after reconnect; connectionState drives UI copy. Why not a second vendor [#why-not-a-second-vendor] * Room-per-DO on your Cloudflare account: cost and data stay readable. * MIT self-host when hosted beta is not enough. * Same WebSocket stream for human messages and agent tool events. Code placement in Next.js [#code-placement-in-nextjs] ``` // app/api/fluxy/token/route.ts: mint JWT server-side // app/room/[id]/room-chat.tsx: "use client" + useChat import { FluxyChatClient } from "@fluxy-chat/sdk"; import { useChat } from "@fluxy-chat/react"; const client = new FluxyChatClient({ baseUrl: process.env.NEXT_PUBLIC_FLUXYCHAT_CLOUD_URL!, userId, token: memberJwtFromRouteHandler, }); ``` --- # OAuth token encryption at rest (/docs/learn/oauth-encryption) OAuth token encryption at rest [#oauth-token-encryption-at-rest] Encrypt stored OAuth tokens with AES-256-GCM using the FluxyChat TokenCrypto utility. Why encrypt OAuth tokens? [#why-encrypt-oauth-tokens] When your FluxyChat adapters store OAuth tokens (e.g., Slack, Discord, Telegram bot tokens), they need to be encrypted at rest. Storing plaintext tokens in D1 means a database leak exposes all connected accounts. FluxyChat provides AES-256-GCM token encryption via the TokenCrypto class in the SDK, using Web Crypto API (works on Workers, browsers, and Node.js 19+). Using TokenCrypto [#using-tokencrypto] Create a TokenCrypto instance with a master key, then encrypt tokens before storing them and decrypt when needed. ``` import { TokenCrypto } from "@fluxy-chat/sdk"; const crypto = new TokenCrypto(process.env.OAUTH_ENCRYPTION_KEY); // Encrypt before storing const encrypted = await crypto.encrypt("xoxb-slack-token-here"); // Store encrypted.ciphertext, encrypted.iv, encrypted.tag in D1 // Decrypt when needed const plaintext = await crypto.decrypt(encrypted); ``` Key derivation [#key-derivation] TokenCrypto derives the AES key by SHA-256 hashing the master key string. For stronger derivation, pre-hash with PBKDF2 before passing to TokenCrypto. Generate a strong master key: use 32+ random bytes, base64-encode. Store it as a worker secret (never in wrangler.toml). ``` // Generate a key const key = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))); console.log(key); // base64-encoded 32 bytes ``` Rotating the encryption key [#rotating-the-encryption-key] * Decrypt all tokens with the old key * Re-encrypt with the new key * Store the new key as a worker secret * Keep the old key until all tokens are migrated * Use the SDK's isEncryptedTokenData() to detect already-encrypted tokens --- # In-app chat + SMS when users are offline (/docs/learn/offline-notify-in-app-plus-sms) In-app chat + SMS when users are offline [#in-app-chat--sms-when-users-are-offline] Keep FluxyChat for realtime rooms and webhooks; fan out transactional SMS or WhatsApp with Sent.dm when your app decides the user is not active. Split transport by context [#split-transport-by-context] FluxyChat is room-based in-app transport: WebSocket history, mentions, agents on the same stream. Telco APIs (Sent.dm, Twilio, etc.) are for offline reach (password resets, mention alerts, DM summaries), not for replacing your message list UI. * Online: FluxyChat WS + optional in-app notification inbox * Offline: webhook consumer → Sent.dm template send * Never expose telco API keys to the browser Webhook-driven fan-out [#webhook-driven-fan-out] Subscribe to message.created on your project. Verify X-Fluxy-Signature, resolve the recipient’s phone from your user profile, and skip send when your own presence or read-receipt logic says they are active. ``` // See docs/cookbook/offline-notify-sent-dm.md for full Worker example await fetch("https://api.sent.dm/v3/messages", { method: "POST", headers: { Authorization: `Bearer ${env.SENT_DM_API_KEY}`, "x-profile-id": env.SENT_PROFILE_ID, }, body: JSON.stringify({ channel: ["sms"], to: [user.e164], template: { name: "chat_mention", parameters: { sender, preview } }, }), }); ``` Workspace apps vs chat wedge [#workspace-apps-vs-chat-wedge] Full GPL workspaces bundle email invites and org-wide AI. FluxyChat stays MIT and room-scoped: use Clerk or Resend for invite email, Sent.dm for SMS, and our in-app notification rows for mentions inside the product. Harden public demos [#harden-public-demos] If you expose a guest demo room, combine Turnstile, origin allowlist, and per-IP rate limits so bots cannot mint JWTs indefinitely. --- # Pusher Channels alternative for SaaS chat (/docs/learn/pusher-alternative-saas) Pusher Channels alternative for SaaS chat [#pusher-channels-alternative-for-saas-chat] Pusher's free tier works until it doesn't. If connection pricing is climbing faster than your app, room chat on Cloudflare with optional self-host is worth a look. Why people leave Pusher [#why-people-leave-pusher] * Demo runs on the free tier; production traffic hits connection and message line items. * Start on hosted beta; self-host on your Cloudflare account when you want cost control. * You read Cloudflare DO/D1 pricing instead of guessing at a channels SKU. Three paths [#three-paths] * Roll your own Socket.IO on a VM: full control, full ops. * Pusher / Ably / Stream: fast start, vendor bill, less schema ownership. * FluxyChat: room-per-DO on Workers + D1, MIT self-host or hosted beta, SDK with loadMore. What Pusher threads complain about [#what-pusher-threads-complain-about] * History and replay take extra work on Channels. * Pricing at scale (connections, messages). * Second vendor when the app already runs on Cloudflare. Migration sketch [#migration-sketch] * Map channel names to roomIds. * Mint JWTs server-side; client uses useChat. * Keep Next on Vercel; Worker handles WS. When to stay on Pusher [#when-to-stay-on-pusher] Generic pub/sub, telco-scale fan-out, or you need their dashboard tomorrow. FluxyChat is for tenant in-app chat where you want D1 history and the option to self-host. --- # Reconnect, replay, and Durable Object hibernation (/docs/learn/reconnect-durable-objects-hibernation) Reconnect, replay, and Durable Object hibernation [#reconnect-replay-and-durable-object-hibernation] When a Room DO hibernates, WebSockets drop and wake again. FluxyChat’s SDK handles the client experience: backoff, connectionState, and history replay via loadMore. What happens on the server [#what-happens-on-the-server] Durable Objects can hibernate idle WebSocket connections to save resources. When clients reconnect, the DO accepts a new upgrade and resumes fan-out. Messages sent while a client was offline are not magically replayed over the socket alone. That is why production chat pairs live WebSocket events with persisted history in D1. Crash loops and sealed rooms [#crash-loops-and-sealed-rooms] A room Durable Object can wake into a state it cannot hydrate (in practice: a boot that runs out of memory). The DO guards itself: every boot leaves a marker, and a boot that never completes is counted as a crash. After **two consecutive crash boots** the room **seals itself and purges its storage**, so it cannot die on the same state forever. A sealed room: * closes WebSocket connections with code `1011`, reason `room_sealed` (SDK `onDisconnect` reports `reason: "server_error"`, `reasonText: "room_sealed"`); * refuses stream operations (`503 { error: "room_sealed" }`) and skips announcements and alarms (no agent schedules); * keeps serving reads, D1 history, and REST writes — messages still persist, nobody receives them live. ```bash # Status — any room member curl "$WORKER_URL/rooms/$ROOM_ID/sealed" -H "Authorization: Bearer $JWT" # Recover — owner/admin. Clears the seal; purged DO storage is NOT restored # (use PITR snapshots at /rooms/{id}/pitr if you need the pre-crash state). curl -X POST "$WORKER_URL/rooms/$ROOM_ID/sealed" -H "Authorization: Bearer $ADMIN_JWT" ``` Reconnect storms (backoff + jitter) [#reconnect-storms-backoff--jitter] `computeReconnectBackoffMs` is on by default in `@fluxy-chat/sdk` (`FluxyChatRoomConnection.scheduleReconnect`). Exponential cap is 20s from a 500ms base. **Equal jitter** (`delay * (0.5 + random()/2)`) spreads retries so a Worker or DO blip does not slam one room with every client at 500ms, 1s, 2s. `GET /client/feature-flags` can advertise `reconnectBackoff: { baseBackoffMs, maxBackoffMs }`. Optional PartySocket transport already uses `reconnectionDelayGrowFactor: 1.5` (1s–30s). Auth close **1008** does not retry. What the SDK does for you [#what-the-sdk-does-for-you] * connectionState.status: connected, connecting, reconnecting, disconnected. * connectionState.nextRetryAt: show "Reconnecting in 3s…" in your UI. * connectionState.transport: websocket, sse, or polling when WS is blocked. * loadMore(): paginate older messages after refresh or reconnect. * clientMessageId: idempotent retries for sends that failed mid-flight. * deliveryStatus per message: pending, sent, failed with retryMessage(). Typed disconnect reasons [#typed-disconnect-reasons] `onDisconnect` fires on every socket close with a typed reason; the last one stays on `connection.disconnectReason`: ```ts const conn = client.connectRoom(roomId, { onDisconnect: ({ reason, reasonText, willReconnect, code, error }) => { // reason: FluxyDisconnectReason · reasonText: raw server text (e.g. terminated_by_moderator) if (!willReconnect) showToast(`Disconnected: ${reason}`, error); }, }); ``` | reason | meaning | reconnects? | | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | ----------- | | `client_initiated` | your code called `close()` | no | | `network` | dropped connection (1005/1006) | yes | | `server_error` | DO/Worker restart or setup failure (1001, 1011–1014) | yes | | `heartbeat_timeout` | no pong within `heartbeatTimeoutMs` (close 4000) | yes | | `removed` | a moderator/admin terminated this socket (close 4001; `reasonText` keeps the raw value) | yes | | `token_expired`, `not_member`, `anonymous_not_allowed`, `channel_at_capacity`, `banned` | terminal refusals (close 1008) | no | | `protocol_unsupported` | client protocol newer than the server | no | | `auth_failed` | other 1008 refusals (`Unauthorized`, policy) | no | | `reconnect_failed` | attempts exhausted (pairs with `onReconnectFailed`) | no | | `unknown` | unrecognized code — inspect `code` / `reasonText` | — | `onDisconnect` can fire more than once per connection (once per dropped socket); a `willReconnect: false` entry is terminal. Raw mapping is exported too: `mapWebSocketCloseToDisconnectReason(code, reasonText)`. JWT refresh before expiry (partysocket-style) [#jwt-refresh-before-expiry-partysocket-style] Long-lived sessions need the JWT refreshed before `exp` to avoid a 1008 close mid-session. The SDK passes the token on the WS URL. Re-connecting with a fresh JWT keeps the user online without an explicit reconnect trigger. * Use `decodeFluxyJwtPayload(token)` and `jwtRefreshDelayMs(payload)` (from `@fluxy-chat/sdk`) to schedule a refresh \~60s before `exp`. * On `onAuthError` (close 1008), mint a new JWT server-side and call `client.connectRoom(roomId, …)` again with the new token. The previous `FluxyChatRoomConnection` instance is already in the disconnected state, so the new connect is a clean re-handshake. * The room DO does not store the JWT. Every connect re-validates the token + room membership, so token rotation is safe. React example (useChat) [#react-example-usechat] ``` import { FluxyChatClient } from "@fluxy-chat/sdk"; import { useChat } from "@fluxy-chat/react"; const client = new FluxyChatClient({ baseUrl, userId, token }); function Room({ roomId }: { roomId: string }) { const { messages, sendMessage, connectionState, loadMore, hasMore, retryMessage } = useChat({ roomId, client }); return (

{connectionState.status} {connectionState.nextRetryAt ? ` · retry ${connectionState.nextRetryAt}` : null}

{hasMore ? ( ) : null} {messages.map((m) => (
{m.content} {m.deliveryStatus === "failed" ? ( ) : null}
))}
); } ``` Vanilla / Vue / Solid (createFluxyRoomSession) [#vanilla--vue--solid-createfluxyroomsession] ``` import { FluxyChatClient, createFluxyRoomSession } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl, userId, token }); const { store, stop } = createFluxyRoomSession({ roomId: "support-1", client }); store.subscribe((state) => { console.log(state.connectionState, state.messages.length); }); // After reconnect: store.getState().loadMore() // Cleanup: stop(); ``` --- # Session security: storage, refresh, and token lifecycle (/docs/learn/session-security) Session security: storage, refresh, and token lifecycle [#session-security-storage-refresh-and-token-lifecycle] Best practices for managing FluxyChat sessions: secure token storage, refresh strategies, and preventing session fixation. Session lifecycle [#session-lifecycle] FluxyChat sessions consist of a short-lived access token (1 hour) and a longer-lived refresh token (30 days). The access token is used for API calls and WebSocket connections; the refresh token obtains new access tokens without re-authentication. Token storage strategies [#token-storage-strategies] * Browser: store tokens in httpOnly, secure, SameSite=Strict cookies * Avoid localStorage/sessionStorage for access tokens (XSS exposure) * Mobile apps: use the platform secure storage (Keychain/Keystore) * Never store tokens in URLs or query parameters * Refresh tokens should be stored server-side when possible Token refresh flow [#token-refresh-flow] When the access token expires, the SDK automatically calls POST /auth/refresh with the refresh token. If the refresh token is also expired, the user must re-authenticate. The SDK's FluxyRealtimeProvider handles refresh transparently. Configure refreshTokenBufferMs to refresh before expiry. ``` // SDK auto-refresh configuration { const res = await fetch("/api/auth/token"); return res.json(); }} refreshBufferMs={60_000} // refresh 60s before expiry > ``` Preventing session fixation [#preventing-session-fixation] FluxyChat rotates the refresh token on every use (refresh token rotation). If a stolen refresh token is used, the legitimate user's next refresh will fail, forcing re-authentication. Set REQUIRE\_ADMIN\_AUTH=true in production to prevent unauthenticated admin access. --- # Status and limits (/docs/learn/status-and-limits) FluxyChat is a **room** on Cloudflare: one Durable Object plus D1. Humans and `invokeAgent` share the chat timeline. Hosted is beta. Self-host is MIT. Claim strings in this page are checked against `capabilities.json` in CI. Game, IoT, fleet, spatial, and voice **media** are optional modules on the same bus. They are not the product promise. The kernel is rooms, presence, Yjs, agents on that timeline, feeds (not chat), `visibility` / `visibleTo`, and `pk_` vs `fc_`. Shipped [#shipped] | Area | Where | Limit | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Room sockets | Hibernation API (`acceptWebSocket`). [Cost notes](/docs/learn/durable-objects-hibernation-cost) | Code path exists. Idle-duration numbers from a Cloudflare invoice are **not** published yet. | | Agent mid-hibernate | [Agents](/docs/core/agents) | Room DO sleep is not Think `chatRecovery`. `POST /agents/:id/invoke` can run on `AgentDurableObject` `room-run:{project}:{room}` when `AGENT` is bound. | | Large rooms | Supergroup DO (`docs/supergroup-room-sharding.md` in the repo) | Sharding is in tree, not “roadmap only.” | | Search | [Search](/docs/core/search) | FTS and optional hybrid. | | Yjs / cursors | [Storage](/docs/core/storage), gallery boards | Second binary WebSocket, same room route. | | HITL / quorum / tool policy | [Tool presets](/docs/guides/ai-tool-presets), [quorum](/docs/guides/critical-action-quorum) | Email/Slack tap: GET shows confirm, POST decides (one-time token + payload hash). Maker-checker: requester and agent cannot approve. | | Voice → room | `POST /rooms/:id/voice-bridge` · [Labs](/docs/labs) | Transcripts, tool calls, coaching whispers, handoff. LiveKit Agents / Pipecat / OpenAI Realtime. **Not an SFU.** | | Maker-checker / evidence | HITL `decide` + `sealHitlEvidencePack` | Requester and agent cannot approve. Pack is SHA-256 over v2 JSON. Autonomy (`toolAutonomy`) still honors HITL. | | Native push | `POST /api/device/register` · SDK `createPushProvider` | Backends: expo, fcm-v1, apns. Expo Go (SDK 53+) does not receive remote push. | | GenAI traces | [OTel](/docs/reference/observability-otel) | `invoke_agent` / `execute_tool`, room as `gen_ai.conversation.id`. Spec: semantic-conventions-genai @ 1.42.0 Development. `fluxy.approval.wait` is ours. | | Browser handoff | `POST /rooms/:id/browser-handoff` | Cloudflare Browser Run / Browserbase Live View as a whisper card. Invoker only (plus named approvers). No screenshots on the transcript. | | A2UI | `POST /rooms/:id/a2ui` · SDK catalog | v0.9 data UI mapped to ui-kit. Buttons are attributed actions; quorum optional. Not an iframe. | | Public share | `/share/:token` · [guide](/docs/guides/public-share) | Unguessable token, `noindex`, no whispers/tool args. `type=public` only. | | Transcript import | `POST /rooms/import-transcript` · [guide](/docs/guides/import-transcript) | File you already have. Cap 400. Marked imported, unverified. | | Room tickets | `POST /rooms/:id/tickets` · [guide](/docs/guides/room-tickets) | Self-host env PAT. Hosted: per-project encrypted token. GitHub/Linear/Jira host allowlist. Not OAuth apps. | | Integration kit | HMAC webhooks + entity links · [guide](/docs/guides/integration-kit) | Maps 11 vendors. Writes need intent. No Marketplace. | | AG-UI events | `createAgUiAdapter` · `POST /ag-ui/join` · [Generative UI](/docs/guides/generative-ui) | Join + last-run replay. Not a CopilotKit host. Live tokens stay on the room socket. | | Connection fallback | SDK `FluxyChatTransport`: websocket / SSE / polling | Room socket fallback. | | AI SDK ChatTransport | `FluxyRoomChatTransport` in `@fluxy-chat/sdk` / `@fluxy-chat/sdk/ai-sdk` | [Guide](/docs/guides/vercel-ai-sdk-chat-transport). Full token stream still wants the room WebSocket. | | MCP official registry | [guide](/docs/guides/mcp-registry) | Manifest in-repo. Not listed on the official MCP registry. | | npm | `@fluxy-chat/sdk` (pin **0.6.16**), `react`, `ui`, `ui-kit`, `vue`, `svelte`, `agent`, `protocol`, `config`, `create-fluxy-chat` | `@fluxy-chat/auth` is in-repo with `publishConfig` but may not be on npm yet. `@fluxy-chat/ai-sdk-workflow` is **private**. `chat-adapter-fluxychat` is unpublished. Swift/Kotlin/Flutter/.NET are **source** under `packages/`. Python HTTP + WS stub: `packages/python` — **not published to PyPI**. Go WS: `packages/sdk-go`. Generated REST: OpenAPI Generator, Apache-2.0, see `scripts/generate-rest-sdks.md`. Confirm with `npm view @fluxy-chat/sdk version`. | | Clone | `github.com/AlessandroFare/fluxychat` | | | E2EE | [Compare](https://fluxychat.com/compare) | Not claimed. | | HIPAA / SOC 2 | README | Checklists are not attestations. **No BAA. We do not sell healthcare.** | | Bridges | Console | You create the vendor app. Not a 14-channel desk. | | System One | `SYSTEM_ONE_PROVIDER` | Gate next to the room LLM (e.g. Groq). Not a replacement chat model. See [Room Decisions](/docs/guides/room-decisions). | | Voice | `joinVoiceStage` + voice-bridge | Signaling only for media. Transcripts on the room bus. Media is yours (LiveKit/Pipecat). | | Hosted SAML login | Off unless `SAML_SSO_ENABLED=true` | Self-host SAML is unchanged. | | Shared-room agent defaults | Two-key HITL · [guide](/docs/guides/security/shared-room-agent-defaults) | On unless you opt out. Tests use synthetic markers. | | Room Decisions | [guide](/docs/guides/room-decisions) | Labels + floor. Default shadow. Hosted labels opt-in. | | Art. 50 marks | [checklist](/docs/features/art-50-checklist) | HMAC integrity, key rotation. Not a legal guarantee. | | Agent Inbox | `GET /inbox/agent` · SDK `fetchAgentInbox` | Pending HITL for the current approver. Accept / ignore map to HITL decide. LangGraph `{ ns, value }` and `askHuman` land on the same queue. Ambient `cron` needs `roomId`. | | DSA notice | `POST /public/dsa-report` · [hosted /report](https://fluxychat.com/report) | Unauthenticated, rate-limited. Share tokens are revoked, not reminted. Not legal advice. | | RoomDojo | `apps/worker/src/lib/room-dojo.test.js` | Synthetic two-key ON vs OFF. No exploit recipes. | Not shipped yet (priority) [#not-shipped-yet-priority] 1. A 60-second **hosted** clip: two humans, one agent, refresh mid-stream, a second seat approves a tool. Gallery `deal-room` is the closest app. Guest-first UI: `--example shared-ai-room`. 2. Measured load and Durable Object duration from staging (idle sockets vs invoice). Do not treat qualitative hibernation docs as that number. June 2026 audit files in git history are snapshots. Closed work lives in `docs/audit/REMEDIATION.md`. Open security work is not listed in this repository. --- # Realtime chat on Vercel without Pusher or Ably (/docs/learn/vercel-realtime-without-pusher) Realtime chat on Vercel without Pusher or Ably [#realtime-chat-on-vercel-without-pusher-or-ably] Vercel excels at HTTP and SSR. Long-lived WebSocket rooms belong on Cloudflare Workers + Durable Objects. Keep your Next.js app on Vercel; run chat edge-native. Why "just add Pusher on Vercel" is the default [#why-just-add-pusher-on-vercel-is-the-default] Vercel's own guides and third-party tutorials often route teams to Pusher Channels or Ably when they need live features. That works, but you add a second realtime vendor, another bill, and another region to reason about. Builders also hit WebSocket limits and pricing friction when they try to keep everything on serverless functions alone. Recommended architecture split [#recommended-architecture-split] * Vercel: Next.js App Router, auth UI, billing pages, marketing. * Cloudflare Worker + Room DO: WebSocket upgrade, room fan-out, presence. * D1: message history and tenant metadata on your CF account. * Browser: @fluxy-chat/sdk pointed at your Worker URL; mint JWTs from a Vercel Route Handler or API route. FluxyChat vs Pusher on Vercel [#fluxychat-vs-pusher-on-vercel] * No Channels app or Pusher keys in the frontend. Member JWT from your backend only. * Room-per-DO isolation instead of a global channel namespace you wire yourself. * Reconnect, loadMore history, and delivery status in the SDK, not only pub/sub events. * Optional MIT self-host on your Cloudflare account when hosted beta is not enough. Migration sketch (Pusher → FluxyChat) [#migration-sketch-pusher--fluxychat] * Deploy FluxyChat Worker (hosted beta or self-host) and create a project + API key. * Replace Pusher client subscribe with FluxyChatClient + useChat(\{ roomId, client }). * Map channel names to roomIds; persist history via REST/D1 instead of Pusher-only caches. * Mint per-user JWTs server-side on Vercel; never expose fc\_... keys to the browser. Build vs buy on the same stack [#build-vs-buy-on-the-same-stack] You can still DIY a Durable Objects chat repo on GitHub. FluxyChat is for teams that want multi-tenant JWT, RoomDurableObject, D1 history, and operator console without stitching a second vendor. See the DIY comparison on /compare. --- # Webhook signing and verification (/docs/learn/webhook-signing) Webhook signing and verification [#webhook-signing-and-verification] Verify that webhook payloads came from FluxyChat using HMAC-SHA256 signatures. Why sign webhooks? [#why-sign-webhooks] Webhooks allow FluxyChat to notify your backend about events like new messages, agent runs, or reactions. Without signature verification, an attacker could send fake webhook payloads to your endpoint. FluxyChat signs every webhook with HMAC-SHA256 using a shared secret. Your backend must verify the signature before processing the payload. Setting up webhook signing [#setting-up-webhook-signing] * Generate a strong secret (32+ random bytes, base64-encoded) * Set WEBHOOK\_SECRET\_ENCRYPTION\_KEY in your worker env for at-rest encryption * Each webhook subscription stores its own signing secret (encrypted in D1) * The signature is sent in the X-FluxyChat-Signature header Verifying signatures [#verifying-signatures] The signature header contains the HMAC-SHA256 of the raw request body, hex-encoded. Compare it using a constant-time comparison to prevent timing attacks. ``` import crypto from "crypto"; function verifyWebhook(rawBody: Buffer, signature: string, secret: string): boolean { const expected = crypto .createHmac("sha256", secret) .update(rawBody) .digest("hex"); return crypto.timingSafeEqual( Buffer.from(expected), Buffer.from(signature), ); } ``` Replay protection [#replay-protection] Each webhook includes a timestamp in the X-FluxyChat-Timestamp header. Reject webhooks older than 5 minutes to prevent replay attacks. The timestamp is included in the signed payload. --- # Accessibility (WCAG 2.2 / VPAT) (/docs/operations/accessibility-conformance) Accessibility (WCAG 2.2 / VPAT) [#accessibility-wcag-22--vpat] This is an **internal status note**, not a completed Voluntary Product Accessibility Template you can attach to an RFP, and not an EN 301 549 / EAA certificate. What we test [#what-we-test] | Surface | Check | Result we claim | | ----------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Dashboard public pages (`/`, `/why`, `/compare`, `/get-started`, `/docs`, `/enter`) | Playwright + axe-core (`apps/dashboard/e2e/a11y.axe.spec.ts`) | Fail the job on Critical / Serious / Moderate. Marketing contrast gaps on other routes are documented in that file, not hidden. | | Landing “build gallery” | Same `/` page (`#build-gallery`) | Covered only as part of landing, not as live Vite `--example` apps. | | Chat widget | Live region, skip link, Escape to stop, labeled stop/ask | First pass. Not WCAG 2.2 AA certified. | | Docs gallery MDX | Fumadocs | Not in the dashboard axe suite. | WCAG 2.2 AA — not claimed [#wcag-22-aa--not-claimed] We target **AA** for the widget composer and dashboard console where we have labels and contrast fixes (composer border `#5c5c5c`). We do **not** claim full 2.2 AA on marketing, Clerk iframes, or third-party embeds. How to fill a real VPAT later [#how-to-fill-a-real-vpat-later] Hire an auditor against a frozen build. Use [ITI VPAT](https://www.itic.org/policy/accessibility/vpat) 2.5 WCAG. Until then, do not put “VPAT available” on a sales page. --- # D1 schema consolidation (internal) (/docs/operations/d1-schema-consolidation) This document describes how we plan to consolidate D1 migrations for faster fresh installs. It is maintained for the core team in the repository (`docs/` and `apps/worker/db/`). If you are self-hosting FluxyChat, follow [Production setup](/docs/operations/production-setup) and apply migrations with: ```bash cd apps/worker pnpm exec wrangler d1 migrations apply fluxychat --remote ``` Do not wait for a consolidated baseline unless the project publishes one in release notes. --- # Environment setup -- local, staging, production (/docs/operations/environment-setup) Environment setup -- local, staging, production [#environment-setup----local-staging-production] Step-by-step configuration before first deploy. Run code checks first (`pnpm run check:env`). Quick start (local only, ~10 min) [#quick-start-local-only-10-min] ```bash pnpm install pnpm run dev:setup # copies .dev.vars + .env.local from examples (won't overwrite) pnpm dev # worker :8787 + dashboard :3000 ``` Open `http://localhost:3000/onboarding` → paste admin JWT (from Worker `POST /auth/token` with a project API key) → create room → message. **Worker:** edit `apps/worker/.dev.vars` (from example). Minimum: | Var | Value | | --------------------------------- | ---------------------------------------------------------------------------- | | `ALLOWED_ORIGINS` | `http://localhost:3000,http://127.0.0.1:3000` | | `REQUIRE_ADMIN_AUTH` | `true` | | `ALLOW_PLAINTEXT_WEBHOOK_SECRETS` | `true` (local only) | | `SHARED_ROOM_TWO_KEY` | omit or `true` (default). `false` only for a locked private-room experiment | | `AGENT_MARKDOWN_HOST_ALLOWLIST` | optional HTTPS hosts for agent markdown images/links after untrusted context | **Dashboard:** edit `apps/dashboard/.env.local`: | Var | Value | | ---------------------------------- | ----------------------- | | `NEXT_PUBLIC_FLUXYCHAT_WORKER_URL` | `http://127.0.0.1:8787` | Leave Clerk keys empty for manual JWT onboarding. *** Architecture (what talks to what) [#architecture-what-talks-to-what] ```text Browser → Dashboard (Vercel) → Worker API (Cloudflare) ↓ ↓ Clerk (optional) D1 + DO + KV + R2 ``` | Host (example) | App | Env file / config | | ---------------------- | ------------------- | --------------------------------------- | | `app.fluxychat.com` | Dashboard | Vercel env vars | | `api.fluxychat.com` | Worker | `wrangler.toml` + secrets | | `status.fluxychat.com` | Dashboard `/status` | Same Vercel project, optional subdomain | *** Phase 1 -- Cloudflare Worker (staging or production) [#phase-1----cloudflare-worker-staging-or-production] 1.1 Create resources (staging -- separate from prod) [#11-create-resources-staging----separate-from-prod] Run from `apps/worker`: ```bash # D1 pnpm exec wrangler d1 create fluxychat-staging # → paste database_id into wrangler.staging.toml # KV (rate limits) pnpm exec wrangler kv namespace create RATE_LIMIT_KV pnpm exec wrangler kv namespace create RATE_LIMIT_KV --preview # → paste id + preview_id into wrangler.staging.toml # R2 pnpm exec wrangler r2 bucket create fluxychat-attachments-staging ``` Production uses names in `wrangler.toml` (`fluxychat`, `fluxychat-attachments`) -- create if not already done. 1.2 Migrations [#12-migrations] ```bash cd apps/worker # Staging pnpm exec wrangler d1 migrations apply fluxychat-staging --remote --config wrangler.staging.toml # Production pnpm exec wrangler d1 migrations apply fluxychat --remote ``` 1.3 Worker vars (`wrangler.toml` / `wrangler.staging.toml` `[vars]`) [#13-worker-vars-wranglertoml--wranglerstagingtoml-vars] | Var | Staging | Production | | ---------------------------- | ------------------------------------------------------- | ------------------------------------------------- | | `WORKFLOW_SCHEDULES_ENABLED` | `false` | `false` (unless using Workflows) | | `BROWSER_ENABLED` | `false` | `false` until you need SPA OG previews | | `ALLOWED_ORIGINS` | `https://staging-app.example.com,http://localhost:3000` | `https://app.fluxychat.com,https://fluxychat.com` | 1.4 Worker secrets (`wrangler secret put NAME`) [#14-worker-secrets-wrangler-secret-put-name] **Required for hosted multi-tenant:** | Secret | How to get | | ------------------------------- | ---------------------------------------------------- | | `PLATFORM_BOOTSTRAP_SECRET` | `openssl rand -base64 32` -- one-time bootstrap only | | `WEBHOOK_SECRET_ENCRYPTION_KEY` | `openssl rand -base64 32` -- 32 bytes base64 | **After bootstrap** (see Phase 2): | Secret | Notes | | ------ | ------------------------------------------------------------------------------------------- | | -- | Per-project `jwt_secret` lives in D1 `project_secrets` (bootstrap creates platform project) | **Optional by feature:** | Secret | Feature | | --------------------------------- | ----------------------- | | `STRIPE_SECRET_KEY` | Billing checkout | | `STRIPE_WEBHOOK_SECRET` | Stripe webhooks | | `AI_GATEWAY_TOKEN` + gateway vars | AI agents | | `AI_API_KEY` | Legacy AI fallback | | `TURNSTILE_SECRET_KEY` | Public `/demo` | | `CLERK_WEBHOOK` N/A on worker | Clerk is dashboard-side | Set hosted mode on Worker: ```bash pnpm exec wrangler secret put HOSTED_MULTI_TENANT # enter: true pnpm exec wrangler secret put FLUXY_PLATFORM_PROJECT_ID # enter: ``` Or use `[vars]` for non-secret flags and secrets for keys. 1.5 Deploy [#15-deploy] ```bash # Staging pnpm exec wrangler deploy src/worker.js --config wrangler.staging.toml # Production pnpm --filter @fluxy-chat/worker deploy ``` 1.6 Custom domain (API) [#16-custom-domain-api] Cloudflare dashboard → Worker → Custom domains → add `api.fluxychat.com` (or staging subdomain).\ `wrangler.toml` already has `[[routes]]` for production pattern. *** Phase 2 -- Platform bootstrap (hosted tenants) [#phase-2----platform-bootstrap-hosted-tenants] One-time per Worker deployment: 1. Set on Worker: `ALLOW_PLATFORM_BOOTSTRAP=true`, `PLATFORM_BOOTSTRAP_SECRET=<random>`. 2. From repo root: ```bash PLATFORM_BOOTSTRAP_SECRET= \ FLUXY_WORKER_URL=https://api.fluxychat.com \ pnpm provision:bootstrap ``` 3. Read `scripts/.provision-secrets.env` (gitignored) -- contains `FLUXY_CONSOLE_API_KEY` and project UUID. 4. Copy to **dashboard** `.env.local` / Vercel: ```bash FLUXY_CONSOLE_API_KEY=fc_... FLUXY_CONSOLE_PROJECT_ID= FLUXY_PLATFORM_PROJECT_ID= NEXT_PUBLIC_FLUXYCHAT_CLOUD_URL=https://api.fluxychat.com ``` 5. Copy to **Worker** secret: `FLUXY_PLATFORM_PROJECT_ID=<uuid>`, set `HOSTED_MULTI_TENANT=true`. 6. Disable bootstrap: remove `ALLOW_PLATFORM_BOOTSTRAP` or set false. *** Phase 3 -- Dashboard (Vercel or self-host) [#phase-3----dashboard-vercel-or-self-host] 3.1 Environment variables [#31-environment-variables] See `apps/dashboard/.env.example`, `.env.staging.example`, `.env.production.example`. | Var | Required | Purpose | | ----------------------------------- | -------- | ---------------------------------------- | | `NEXT_PUBLIC_FLUXYCHAT_CLOUD_URL` | Hosted | Worker API URL (wins over WORKER\_URL) | | `NEXT_PUBLIC_SITE_URL` | Prod | Canonical / OG (`https://fluxychat.com`) | | `FLUXY_CONSOLE_API_KEY` | Hosted | Server-only; provisions tenants | | `FLUXY_PLATFORM_PROJECT_ID` | Hosted | Must match Worker | | `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` | Optional | Hosted sign-in | | `CLERK_SECRET_KEY` | Optional | Clerk server | | `CLERK_WEBHOOK_SIGNING_SECRET` | Optional | Auto-provision on sign-up | | `DASHBOARD_PUBLIC_URL` | Optional | Clerk webhook URL base | **Do not** expose `FLUXY_CONSOLE_API_KEY` to the browser -- only server routes use it. 3.2 Vercel project [#32-vercel-project] 1. Import repo → root `apps/dashboard` or monorepo with filter. 2. Build: `pnpm --filter @fluxy-chat/dashboard build` (or Turbo from root). 3. Env vars: paste from `.env.production.example` checklist. 4. Domains: `app.fluxychat.com`, optional `status.fluxychat.com` → same project (`/status` route exists). 3.3 Clerk (optional) [#33-clerk-optional] Clerk Dashboard → Application → API Keys → paste into Vercel.\ Paths: Sign-in `/sign-in`, Sign-up `/sign-up`, after sign-up redirect `/onboarding`. *** Phase 4 -- Stripe (optional, billing) [#phase-4----stripe-optional-billing] 1. Stripe Dashboard → Developers → API keys → `STRIPE_SECRET_KEY` on Worker. 2. Webhook endpoint: `https://api.fluxychat.com/webhooks/stripe` → `STRIPE_WEBHOOK_SECRET`. 3. Without Stripe: `/health` shows `paymentsEnabled: false`; users stay on Free tier. *** Phase 5 -- GitHub Actions (CI deploy) [#phase-5----github-actions-ci-deploy] Repository → Settings → Secrets and variables → Actions: | Secret | Purpose | | ----------------------- | ------------------------------ | | `CLOUDFLARE_API_TOKEN` | Wrangler deploy (Workers + D1) | | `CLOUDFLARE_ACCOUNT_ID` | Account ID | | `E2E_ADMIN_JWT` | Optional integrated Playwright | Create environments `staging` and `production` in GitHub → wire approval on `production`. Manual deploy: Actions → **Deploy** → choose environment. *** Phase 6 -- Smoke verification [#phase-6----smoke-verification] ```bash # Worker pnpm --filter @fluxy-chat/worker smoke:remote -- \ --base-url https://api.fluxychat.com \ --admin-jwt "" # Dashboard CI smoke (no worker) cd apps/dashboard && CI=true pnpm test:e2e:smoke # Full integrated (local worker + dashboard) E2E_ADMIN_JWT= pnpm --filter @fluxy-chat/dashboard test:e2e:integrated ``` Browser checks: * `https://<dashboard>/status` -- public health * `https://<dashboard>/onboarding` -- wizard * `https://<dashboard>/billing` -- load plan *** Configuration matrix (minimum vs full) [#configuration-matrix-minimum-vs-full] | Capability | Local dev | Staging | Production | | ------------- | ------------------------------ | --------------------------------- | ------------------- | | Chat / rooms | Worker + `.dev.vars` | Worker staging + D1 | Worker prod | | Dashboard | `.env.local` localhost | Vercel preview env | Vercel prod | | Multi-tenant | Optional bootstrap | Bootstrap + `HOSTED_MULTI_TENANT` | Same | | Clerk sign-in | Skip (manual JWT) | Test Clerk app | Live Clerk | | Stripe | Off | Test mode keys | Live keys | | AI agents | `AI_API_KEY` optional | Gateway or API key | Gateway recommended | | Browser OG | `BROWSER_ENABLED=true` locally | Off | Off until needed | | Status page | `/status` | `/status` | + DNS `status.*` | *** Troubleshooting [#troubleshooting] | Symptom | Check | | --------------------- | --------------------------------------------------- | | CORS errors | `ALLOWED_ORIGINS` includes dashboard origin | | Connect forbidden | `FLUXY_PLATFORM_PROJECT_ID` matches API key project | | 401 on hosted routes | `HOSTED_MULTI_TENANT=true` + valid API key/JWT | | Billing 501 | `STRIPE_SECRET_KEY` not set (expected in beta) | | `/status` unreachable | `NEXT_PUBLIC_FLUXYCHAT_CLOUD_URL` or `WORKER_URL` | | Staging deploy fails | Replace `REPLACE_WITH_*` in `wrangler.staging.toml` | See also [Production setup](/docs/operations/production-setup). --- # Hosted multi-tenant (/docs/operations/hosted-multi-tenant) Hosted multi-tenant [#hosted-multi-tenant] When `HOSTED_MULTI_TENANT=true`, the Worker treats missing tenant context as **unauthorized** instead of falling back to a shared `default` project. Required vars (Worker) [#required-vars-worker] ```bash HOSTED_MULTI_TENANT=true FLUXY_PLATFORM_PROJECT_ID= ALLOWED_ORIGINS=https://app.fluxychat.com,https://your-dashboard.vercel.app REQUIRE_ADMIN_AUTH=true ``` Bootstrap once: ```bash pnpm provision:bootstrap # Copy fc_... API key + project UUID to dashboard .env.local AND worker .dev.vars ``` Client behaviour [#client-behaviour] * Dashboard sends `X-Fluxy-Api-Key` or JWT with `tid` (project id). * `resolveProjectId` in `apps/worker/src/lib/resolve-project-id.js` returns `null` without a key in hosted mode → routes respond **401**, not cross-tenant data. Local dev [#local-dev] Simplest path: leave `HOSTED_MULTI_TENANT` unset/false and use a single project + manual JWT in onboarding. For hosted parity locally, align **both** dashboard `.env.local` and worker `.dev.vars` after `pnpm provision:bootstrap`. Smoke [#smoke] ```bash # Without API key on hosted worker → expect 401 on tenant-scoped routes curl -i https://api.example.com/projects ``` See also [staging and status](/docs/operations/staging-and-status). --- # Hybrid data plane (/docs/operations/hybrid-control-plane) Hybrid data plane [#hybrid-data-plane] Self-host is the data plane: your Cloudflare account, your D1, your room Durable Objects, MIT Worker in this repo. Hosted console and keys on fluxychat.com are a **separate** control plane and stay beta. There is no product SKU today that means “we operate your Worker while you keep the account.” What exists as ops, not as a sold hybrid: * Deploy the Worker with Wrangler / the in-repo Terraform sketches. * Mint `fc_` on **your** Worker. The hosted dashboard talks to **its** Worker URL. If you want that split later, the contract is: customer account = rooms + messages; we would only ship console + updates. Do not advertise that until it is a path you can buy. See [Self-host](/docs/guides/self-host-one-command). --- # Observability & scheduled jobs (/docs/operations/observability) Observability & scheduled jobs [#observability--scheduled-jobs] Default alert rules [#default-alert-rules] New projects receive seeded operational alert rules via `insertNewProject` → `seedDefaultAlertRules`. Console: **Analytics** → alerts list; open alerts also surface in the red **System status** banner (owner/admin JWT). Cron / workflows default [#cron--workflows-default] | Mode | `WORKFLOW_SCHEDULES_ENABLED` | What runs | | ----------------------------- | ---------------------------- | ---------------------------------------------------------------- | | **Production default (repo)** | `false` | Worker `[triggers] crons` in `wrangler.toml` | | Workflows (optional) | `true` | `FluxyScheduledWorkflow` bindings; Worker `scheduled` is a no-op | Crons when enabled (either path): | Schedule | Job | | -------------- | ------------------------------ | | `0 8 * * *` | Daily AI digest | | `*/15 * * * *` | Quiet-hours notification batch | | `0 3 * * *` | Data retention purge | | `*/5 * * * *` | Pending webhook delivery flush | Local dev [#local-dev] In `apps/worker/.dev.vars`: ```bash WORKFLOW_SCHEDULES_ENABLED=false ``` Uses Worker cron from `wrangler.toml` `[triggers]` during `wrangler dev`. Manual trigger (owner/admin JWT): ```http POST /admin/scheduled/run Content-Type: application/json { "cron": "0 8 * * *" } ``` Allowed values: `0 8 * * *`, `*/15 * * * *`, `0 3 * * *`, `*/5 * * * *`. See [Scheduled workflows](/docs/reference/scheduled-workflows) for the Workflows setup. Health & smoke [#health--smoke] * Public: dashboard `/status` → Worker `/health` * Operator: `pnpm --filter @fluxy-chat/worker smoke:remote -- --base-url --admin-jwt ` --- # Open beta deploy (internal) (/docs/operations/open-beta-deploy-guide) This runbook is for FluxyChat operators deploying the hosted stack from the monorepo. It is not required reading for integrators. Public alternatives [#public-alternatives] * [Production setup](/docs/operations/production-setup) * [Post-launch checklist](/docs/operations/post-launch-checklist) * [Staging and status](/docs/operations/staging-and-status) Quick deploy (contributors) [#quick-deploy-contributors] From repo root: ```bash pnpm install pnpm test cd apps/worker && pnpm exec wrangler d1 migrations apply fluxychat --remote pnpm exec wrangler deploy ``` Rollback and secrets detail live in the repository contributor runbook (not required for integrators). See [Production setup](/docs/operations/production-setup) for the public deploy path. --- # Post-launch checklist (Phase 6) (/docs/operations/post-launch-checklist) Post-launch checklist (Phase 6) [#post-launch-checklist-phase-6] Execution tasks after Worker deploy, npm publish, and GitHub secrets are in place. No new architecture — run, record, publish. *** 1\. Voice load test — real numbers [#1-voice-load-test--real-numbers] **Goal:** Fill [VOICE-LOAD-TEST-REPORT.md](/docs/operations/voice-load-test-report) with verifiable P90/P95, not estimates. **Prereqs:** LiveKit configured (Cloud or `examples/livekit/` Docker). ```bash # Install LiveKit CLI: https://docs.livekit.io/home/cli/cli-setup/ cp examples/livekit/.env.example examples/livekit/.env docker compose -f examples/livekit/docker-compose.yml up -d export FLUXY_WORKER_URL=https://your-worker export FLUXY_MEMBER_JWT=your-member-jwt # Run 3 times at increasing load PUBLISHERS=10 SUBSCRIBERS=50 DURATION=5m ./scripts/voice-load-test.sh PUBLISHERS=25 SUBSCRIBERS=100 DURATION=5m ./scripts/voice-load-test.sh PUBLISHERS=50 SUBSCRIBERS=200 DURATION=5m ./scripts/voice-load-test.sh ``` Or direct `lk load-test`: ```bash lk load-test --url wss://your-livekit --api-key $KEY --api-secret $SECRET \ --room fluxy-loadtest-v1 --publishers 10 --subscribers 50 --duration 5m ``` Copy raw CLI output + dashboard screenshots into the report. Transparency matters more than perfect scores. *** 2\. MCP audit — populate marketplace badges [#2-mcp-audit--populate-marketplace-badges] **Goal:** Audit grades visible on **Marketplace → MCP Apps**. 1. Confirm GitHub secrets: `WORKER_AUDIT_WEBHOOK_URL`, `WORKER_AUDIT_HMAC_SECRET` 2. **Actions → MCP marketplace audit → Run workflow** (or push to `examples/mcp/**`) 3. Regenerate verified page: ```bash node scripts/generate-mcp-verified-page.mjs ``` 4. Commit updated `apps/docs/.../mcp-verified-servers.mdx` and `apps/dashboard/public/mcp-verified.json` if changed **Retroactive:** Re-run workflow after adding more servers under `examples/mcp/`. For third-party MCP servers, outreach to maintainers — ask permission to list as verified in your catalog. See: [MCP audit runbook in docs site](/docs/operations/production-setup) (apps/docs). *** 3\. Inbox demo GIF / video [#3-inbox-demo-gif--video] **Goal:** 15–20s demo for README and `/get-started` — unread badge, realtime message, mark-read. **With ui-kit:** ```tsx import { FluxyInboxPanel, FluxyChatWidget } from "@fluxy-chat/ui-kit"; ``` **Recording (free tools):** * macOS: QuickTime → export → `ffmpeg -i demo.mov -vf "fps=10,scale=800:-1" docs/assets/inbox-demo.gif` * Or ScreenStudio / OBS **Place assets:** | Location | File | | ------------------------------ | --------------------------------------------------- | | `packages/react/README.md` | Link or embed GIF | | `apps/dashboard/public/demos/` | `inbox-demo.gif` (optional, alongside existing SVG) | | Docs | [ui-kit quickstart](/docs/packages/ui-kit) | *** 4\. npm + docs prominence [#4-npm--docs-prominence] After publish: * [ ] `@fluxy-chat/ui-kit@0.1.3` on npm * [ ] `@fluxy-chat/protocol@0.1.5`, `@fluxy-chat/sdk@0.6.5`, `create-fluxy-chat@0.5.14` * [ ] Docs homepage card → [UI kit quickstart](/docs/packages/ui-kit) * [ ] `/get-started` mentions `npx @fluxy-chat/create-fluxy-chat@latest my-chat --minimal` *** 5\. KMP Maven Central (Sonatype) [#5-kmp-maven-central-sonatype] Not blocking console deploy. When ready: 1. Follow [maven-central-publish.md](/docs/integrations/maven-central-publish) 2. `git tag sdk-v1.0.0 && git push origin sdk-v1.0.0` 3. Approve first staging release on central.sonatype.com 4. Update [feature parity checklist](/docs/guides/migrate-from-pusher): Mobile SDK → live *** 6\. Activepieces (optional, zero-budget) [#6-activepieces-optional-zero-budget] Skip iframe embed. Self-host + external link only: 1. [activepieces.md](/docs/integrations/activepieces) 2. Set `NEXT_PUBLIC_ACTIVEPIECES_URL=https://automation.yourdomain.com` 3. Import piece from `examples/integrations/activepieces/src/` *** 7\. Smoke test matrix [#7-smoke-test-matrix] | URL | Pass criteria | | ------------------------ | ---------------------------------------- | | `/compare` | CLI + ui-kit rows visible | | `/marketplace` | MCP tab, audit badges after CI | | `/voice-ai` | Voice UI (LiveKit or stub) | | `/settings/integrations` | Opens Activepieces in new tab if URL set | | `/get-started` | `--minimal` + ui-kit | | Landing mobile | Hash links close menu | *** What we explicitly skip (by design) [#what-we-explicitly-skip-by-design] | Item | Reason | | ---------------------------- | ------------------------------------------------- | | Hosted zero-ops SaaS | Positioning: MIT self-host first | | Activepieces iframe embed | Enterprise license | | Native Zendesk/SF connectors | Activepieces POC sufficient until customer demand | See [Platform modules](/docs/features/platform-status) for adapters, IoT, game, and federation as they ship. --- # Production: demo hardening & inbound SMS (/docs/operations/production-demo-and-sms) Production: demo hardening & inbound SMS [#production-demo-hardening--inbound-sms] Public demo (`/demo`) [#public-demo-demo] * Configure Turnstile / rate limits per [public demo hardening](/docs/cookbook/public-demo-hardening). * Worker: `TELCO_INBOUND_ENABLED`, guest session limits in `.dev.vars.example`. Inbound SMS / WhatsApp (optional) [#inbound-sms--whatsapp-optional] See `apps/worker/.dev.vars.example` (`TELCO_INBOUND_*`) and [Twilio parity inspiration](/docs/operations/us-sms-compliance-playbook). For US 10DLC and STOP handling, see [US SMS compliance playbook](/docs/operations/us-sms-compliance-playbook). --- # Production setup guide (free-tier friendly) (/docs/operations/production-setup) Production setup guide (free-tier friendly) [#production-setup-guide-free-tier-friendly] Checklist before `wrangler deploy`, dashboard deploy, and GitHub Actions secrets. *** 1\. Cloudflare (required — you already have this) [#1-cloudflare-required--you-already-have-this] | Item | Cost | Action | | ------------------ | ---------------------------------- | ------------------------------------------------------------------------ | | Cloudflare account | Free | Workers + D1 + DO on your account | | Worker deploy | Pay-as-you-go (generous free tier) | `pnpm --filter worker deploy` | | D1 migrations | Included | Apply all `apps/worker/db/*.sql` including `0163_marketplace_audits.sql` | | Dashboard (Vercel) | Free hobby tier | Set env vars below | **Worker secrets** (Wrangler / CF dashboard → Settings → Variables): ```bash # Core (from onboarding / provision) JWT secrets, API keys, ALLOWED_ORIGINS=https://app.fluxychat.com,... # PG-ZB-7 MCP audit webhook (CI → Worker) MARKETPLACE_AUDIT_HMAC_SECRET= # PG-ZB-10 LiveKit (see section 3) LIVEKIT_API_KEY= LIVEKIT_API_SECRET= LIVEKIT_URL=wss://... ``` **GitHub repository secrets** (for MCP audit CI): | Secret | Value | | -------------------------- | --------------------------------------------------------------- | | `WORKER_AUDIT_WEBHOOK_URL` | `https://<your-worker>/internal/marketplace/audit-result` | | `WORKER_AUDIT_HMAC_SECRET` | Same string as `MARKETPLACE_AUDIT_HMAC_SECRET` | No third-party account needed for mcp-audit — it runs in GitHub Actions via `adudley78/setup-mcp-audit@v1` (OSS). *** 2\. MCP marketplace audit (free — no signup) [#2-mcp-marketplace-audit-free--no-signup] **What it does:** CI scans `examples/mcp/*` with [mcp-audit](https://github.com/adudley78/mcp-audit), posts grade to D1, shows badge in console. **Accounts needed:** None. Only GitHub + your Worker. **Steps:** 1. Apply D1 migration `0163_marketplace_audits.sql` 2. Set `MARKETPLACE_AUDIT_HMAC_SECRET` on Worker 3. Set GitHub secrets `WORKER_AUDIT_WEBHOOK_URL` + `WORKER_AUDIT_HMAC_SECRET` 4. Push to `main` or run workflow **MCP marketplace audit** manually **Verify:** Marketplace → MCP Apps → apps show **Audit A–F** badge after CI runs. *** 3\. LiveKit voice (free options) [#3-livekit-voice-free-options] WebRTC SFU runs **outside** Workers. Pick one: Option A — LiveKit Cloud free tier (easiest) [#option-a--livekit-cloud-free-tier-easiest] 1. Sign up at [cloud.livekit.io](https://cloud.livekit.io) (free tier: limited participant minutes) 2. Create a project → copy **API Key**, **API Secret**, **WebSocket URL** (`wss://…livekit.cloud`) 3. Set Worker secrets: ``` LIVEKIT_API_KEY=APIxxxxx LIVEKIT_API_SECRET=xxxxxxxx LIVEKIT_URL=wss://your-project.livekit.cloud ``` 4. Token mint: `POST /admin/calls/token` with member JWT (already wired via `livekit-token.js`) 5. Client: `useLiveKitToken` from `@fluxy-chat/react` + `livekit-client` npm package **No VPS.** Good for beta / demos. Option B — Self-hosted LiveKit (free software, ~€5 VPS optional) [#option-b--self-hosted-livekit-free-software-5-vps-optional] 1. On any Linux host (Hetzner CX11, Fly.io, local Docker): ```bash cd examples/livekit cp .env.example .env # set LIVEKIT keys (generate with livekit-server generate-keys) docker compose up -d ``` 2. Point `LIVEKIT_URL=wss://livekit.yourdomain.com` (TLS via Caddy/nginx or Cloudflare Tunnel) 3. Same Worker secrets as Option A **Accounts:** None for OSS; optional VPS provider. Option C — Skip voice SFU for now [#option-c--skip-voice-sfu-for-now] Worker answers `503 livekit_not_configured` when `LIVEKIT_*` is unset — it never returns a fake token. Text pipeline (`useVoice` simulation) still works on `/voice-ai`. *** 4\. Activepieces automation (free — self-host, external link) [#4-activepieces-automation-free--self-host-external-link] **What it does:** No-code CRM/helpdesk flows; FluxyChat webhooks as triggers. **Embed iframe:** Activepieces [embedding](https://www.activepieces.com/docs/embedding/overview) is an **enterprise feature**. FluxyChat opens the self-hosted studio in a **new tab** (zero-budget). See [docs/integrations/activepieces.md](/docs/integrations/activepieces). Self-host (MIT, free) [#self-host-mit-free] 1. VPS + subdomain (e.g. `automation.fluxychat.com`) 2. Clone [activepieces/activepieces](https://github.com/activepieces/activepieces), configure `.env` (`AP_FRONTEND_URL`, `AP_ENCRYPTION_KEY`, `AP_JWT_SECRET`, Postgres/Redis) 3. `docker compose up -d` + HTTPS reverse proxy (Caddy) 4. Dashboard env: ``` NEXT_PUBLIC_ACTIVEPIECES_URL=https://automation.yourdomain.com ``` 5. **Settings → Automation integrations** → **Open automation studio** 6. Import FluxyChat piece from `examples/integrations/activepieces/src/` **API key:** Activepieces **Platform Admin → Security → API Keys** (for piece actions, not dashboard embed). **FluxyChat webhooks:** Console → Webhooks → Activepieces webhook trigger URL; verify `X-Fluxy-Signature`. *** 5\. Dashboard env (Vercel / local) [#5-dashboard-env-vercel--local] ```text NEXT_PUBLIC_FLUXYCHAT_WORKER_URL=https://api.yourdomain.com NEXT_PUBLIC_DOCS_URL=https://docs.fluxychat.com NEXT_PUBLIC_ACTIVEPIECES_URL=https://automation.yourdomain.com # optional, section 4 — opens in new tab # Clerk, Stripe, etc. — existing onboarding vars ``` *** 6\. Kotlin Multiplatform mobile (Maven Central) [#6-kotlin-multiplatform-mobile-maven-central] **Package:** `packages/sdk-kmp/` — shared WebSocket client for Android / iOS. **Publish to Maven Central:** requires Sonatype account + GPG signing. Full guide: [docs/integrations/maven-central-publish.md](/docs/integrations/maven-central-publish). **GitHub secrets** (for tag `sdk-v*`): | Secret | Source | | ------------ | -------------------------------------- | | `OSSRH_USER` | Sonatype Central Portal user token | | `OSSRH_PASS` | Sonatype Central Portal token password | | `GPG_KEY` | Armored private GPG key | | `GPG_PASS` | GPG passphrase | ```bash git tag sdk-v1.0.0 git push origin sdk-v1.0.0 ``` Local build (optional): ```bash cd packages/sdk-kmp gradle :shared:jvmTest ``` *** 7\. Deploy order [#7-deploy-order] 1. D1 migrations (all pending SQL) 2. `wrangler secret put MARKETPLACE_AUDIT_HMAC_SECRET` 3. LiveKit secrets (if using voice) 4. `wrangler deploy` 5. GitHub secrets for MCP audit CI 6. Dashboard deploy with env vars 7. Smoke: `/compare`, `/marketplace` MCP tab, `/voice-ai`, `/settings/integrations` 8. Phase 6 execution: [docs/operations/post-launch-checklist.md](/docs/operations/post-launch-checklist) *** 8\. What you do **not** need for Phase 2 [#8-what-you-do-not-need-for-phase-2] | Service | Needed? | | ------------------------------ | ---------------------------------------- | | Portal / third-party chat SaaS | No | | Paid mcp-audit | No (Apache 2.0, full features) | | LiveKit paid plan | No for dev (Cloud free or Docker) | | Activepieces paid embed | No — use external link + self-host MIT | | Separate MongoDB/Redis | No (D1 + DO + KV) | | Apple Developer ($99/yr) | Only when shipping iOS app to App Store | | Google Play ($25) | Only when shipping Android to Play Store | *** Shared-room agent defaults [#shared-room-agent-defaults] Leave `SHARED_ROOM_TWO_KEY` unset (on). Optional `AGENT_MARKDOWN_HOST_ALLOWLIST`. See [shared-room agent defaults](/docs/guides/security/shared-room-agent-defaults). Not a pen test. Quick reference — secret parity [#quick-reference--secret-parity] ``` Worker MARKETPLACE_AUDIT_HMAC_SECRET ═══ GitHub WORKER_AUDIT_HMAC_SECRET GitHub WORKER_AUDIT_WEBHOOK_URL ───► POST /internal/marketplace/audit-result LiveKit Cloud project keys ───► LIVEKIT_API_KEY / SECRET / URL on Worker ``` --- # Staging deploy and public status (/docs/operations/staging-and-status) Staging deploy and public status [#staging-deploy-and-public-status] Staging Worker [#staging-worker] Template: `apps/worker/wrangler.staging.toml` 1. Create staging D1, KV, R2 with unique names. 2. Replace `REPLACE_WITH_*` IDs in the staging toml. 3. Deploy: ```bash cd apps/worker pnpm exec wrangler deploy src/worker.js --config wrangler.staging.toml ``` 4. Point dashboard staging env at the staging Worker: ```bash NEXT_PUBLIC_FLUXYCHAT_WORKER_URL=https:// ``` GitHub Actions: workflow **Deploy** → environment `staging` (requires `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`). Public status page [#public-status-page] Dashboard route: `/status` (server-rendered, polls `GET /health` on the configured Worker). Optional custom domain: 1. Add `status.fluxychat.com` (or your domain) in Vercel/hosting DNS → dashboard project. 2. Link from marketing footer and console (already wired to `/status`). Health payload fields: `ok`, `degraded`, `checks`, `platformBindings`, `paymentsEnabled`, `payments.stripeCheckout`, `bindings.agent`, `routes` (share, importTranscript, tickets, hitl, voiceBridge, deviceRegister, browserHandoff, a2ui, agentInbox, dsaReport). `paymentsEnabled: false` means Stripe checkout is off, not that hosted plans are free forever. Console operational alerts (RD-6) [#console-operational-alerts-rd-6] Signed-in admins with an active project see a banner when `GET /stats/alerts` reports `openAlerts > 0`. Link goes to **Analytics**. CI gate before deploy [#ci-gate-before-deploy] `.github/workflows/deploy.yml` runs pricing/tenant/openapi/DO checks, worker typecheck, and `pnpm test` before `wrangler deploy`. --- # US SMS compliance (10DLC, STOP) (/docs/operations/us-sms-compliance-playbook) US SMS compliance (10DLC, STOP) [#us-sms-compliance-10dlc-stop] Placeholder for carrier registration and opt-out flows when using Sent.dm / Twilio-style inbound SMS with Fluxychat. Minimum checklist [#minimum-checklist] * Register 10DLC brand/campaign before production US SMS. * Honor `STOP` / `UNSUBSCRIBE` on inbound webhooks; persist opt-out per E.164 in your tenant DB. * Include opt-in language wherever you collect phone numbers. * Log consent timestamp and source (form, checkout, etc.). Worker inbound routing: `TELCO_INBOUND_*` vars and telco HTTP routes. See `docs/twilio-parity-inspiration.md`. --- # Vercel Marketplace (/docs/operations/vercel-marketplace) Vercel Marketplace [#vercel-marketplace] There is **no live listing**. Native integrations go through Vercel’s partner process (manifest, OAuth or API keys, review). In-repo draft: `docs/marketplace/vercel-integration.draft.json`. What you can ship today without Marketplace: * Self-host the Worker on the customer Cloudflare account ([hybrid data plane](/docs/operations/hybrid-control-plane)). * Mint `fc_` from a Next.js route on Vercel with [`@fluxy-chat/auth`](/docs/guides/auth-jwt). * Point the dashboard at **your** Worker URL. `vercel integration add` only works for integrations Vercel already lists. We are not listed, so that command is not a supported install path. A Community badge on a future chat-sdk catalog is also not Marketplace. Do not write “available on Vercel Marketplace” in public copy until the listing exists. --- # Voice load report (/docs/operations/voice-load-test-report) The numbers below are product SLO targets, not a load test against a distributed fleet. Regenerate them with `pnpm --filter @fluxy-chat/sdk exec vitest run src/voice-load-bench.test.ts` (unit bench in this repo). Do not quote them as measured P95 in production. Live operator stats (when you collect them) are `POST /admin/voice-ai/metrics` then `GET /admin/voice-ai/stats`. Product SLO [#product-slo] | Path | Target | | --------------- | --------------- | | OpenAI Realtime | P95 ≤ 300ms e2e | | Chunked REST | P95 ≤ 500ms | | Barge-in | ≤ 500ms | Production source of truth: `POST /admin/voice-ai/metrics` → `GET /admin/voice-ai/stats`. See [Voice AI pipeline](/docs/guides/voice-ai-pipeline) and [Platform voice](/docs/platform/voice). --- # @fluxy-chat/agent (/docs/packages/agent) @fluxy-chat/agent [#fluxy-chatagent] Server-side agent SDK for [FluxyChat](https://github.com/AlessandroFare/fluxychat): WebSocket bots, message streaming, `waitFor`, and optional AI provider helpers. Use this package in **Node.js**, **Cloudflare Workers**, or any server runtime. For browser/React apps, use [`@fluxy-chat/sdk`](https://www.npmjs.com/package/@fluxy-chat/sdk) and [`@fluxy-chat/react`](https://www.npmjs.com/package/@fluxy-chat/react). Install [#install] ```bash pnpm add @fluxy-chat/agent @fluxy-chat/sdk ``` Quick start [#quick-start] ```ts import { createFluxyAgent } from "@fluxy-chat/agent"; const agent = await createFluxyAgent({ baseUrl: process.env.FLUXY_WORKER_URL!, id: "support-bot", apiKey: process.env.FLUXY_API_KEY!, }); const room = await agent.join("support-general"); room.on("message", async (msg) => { if (msg.userId === agent.id) return; await room.reply(`You said: ${msg.content}`); }); ``` Features [#features] | Area | API | | ----------------- | --------------------------------------------------- | | Bot lifecycle | `createFluxyAgent`, `FluxyAgent`, `FluxyRoom` | | Token minting | `mintWorkerToken` | | Streaming replies | `FluxyMessageStream`, `waitFor` | | AI providers | `AIProviderRegistry`, `retryAI`, middleware helpers | | Tool / HITL flows | Re-exports from SDK where shared | Configuration [#configuration] | Variable | Purpose | | --------- | --------------------------------------------------------------- | | `baseUrl` | Your FluxyChat Worker URL | | `id` | Stable bot user id | | `apiKey` | Project API key (`fc_…`) for JWT minting — **server-side only** | Mint member JWTs with `POST /auth/token` and the `X-Fluxy-Api-Key` header, or use `mintWorkerToken` from this package. Related packages [#related-packages] * [`@fluxy-chat/sdk`](https://www.npmjs.com/package/@fluxy-chat/sdk) — core client, REST, room sessions * [`@fluxy-chat/react`](https://www.npmjs.com/package/@fluxy-chat/react) — React hooks (`useChat`, `useInbox`) * [`@fluxy-chat/config`](https://www.npmjs.com/package/@fluxy-chat/config) — `fluxy.config.ts` room authz and middleware License [#license] MIT --- # @fluxy-chat/auth (/docs/packages/auth) @fluxy-chat/auth [#fluxy-chatauth] Wraps `createFluxyTokenRoute`. Not a Clerk/Auth.js substitute. `pk_` cannot mint. See [Authentication (JWT)](/docs/guides/auth-jwt). --- # @fluxy-chat/config (/docs/packages/config) @fluxy-chat/config [#fluxy-chatconfig] Type-safe `fluxy.config.ts` authoring for FluxyChat: room authz, middleware, and client defaults. Install [#install] ```bash pnpm add -D @fluxy-chat/config ``` Quick start [#quick-start] Create `fluxy.config.ts` at your worker project root: ```ts import { defineConfig, allow, block, defineMiddleware, allowPublish } from "@fluxy-chat/config"; const moderate = defineMiddleware("publish", (ctx) => { if (!ctx.capabilities.publish) { return { action: "block", reason: "You cannot post here." }; } return allowPublish(); }); export default defineConfig({ client: { readOn: "visible", wsCache: "on", historyLimit: 50, }, rooms: { "support-*": { anonymous: false, authz: (ctx) => (ctx.anonymous ? block("Sign in first.") : allow({ publish: true })), onPublish: [moderate.handler], }, "room-*": { anonymous: true, onPublish: [moderate.handler] }, }, }); ``` Wire it in the Worker (this repo: `apps/worker/fluxy.config.js` → bundled by Wrangler). What you can configure [#what-you-can-configure] | Area | Typical hosted SDK | Fluxy field | | ----------------------- | ------------------ | ----------------------------------- | | Room templates `room-*` | Channel patterns | `rooms` | | Anonymous access | Guest connect | `rooms.*.anonymous` | | Connect authz | Join rules | `rooms.*.authz` | | Message middleware | Pre-send hooks | `rooms.*.onPublish` | | Disconnect hooks | Cleanup | `rooms.*.disconnect` | | SDK defaults | — | `client` (via `GET /config/client`) | Client defaults [#client-defaults] The worker exposes merged defaults: ``` GET /config/client → { client: { readOn, wsCache, historyLimit, ... }, source: "fluxy.config" } ``` Use in your app to align `useChat` options with server policy. Hosted overlay (`pnpm fluxy:deploy`) [#hosted-overlay-pnpm-fluxydeploy] One file on hosted: `fluxy.hosted.json` (or `hostedPublish` + serializable `rooms` on `defineConfig`). Push with `PUT /admin/projects/:id/publish-config` or `pnpm fluxy:deploy`. Fields: `denySubstrings`, `guestCanPublish`, `iotAutoAgentId`, and `rooms` templates (`anonymous`, per-room deny, `guestCanPublish`, `capabilities`, `extensions` kv/counter slots). This is not Worker-bundled `onPublish` / `authz` callbacks. Those run only on a Worker you deploy. Room snapshots: `GET/PUT /rooms/:id/extensions/:extId` (max 5, 16 KiB). Hosted ids must be declared on the overlay. Self-hosted execution [#self-hosted-execution] Fluxy runs your config callbacks **inside your Worker** — you own execution and secrets (Wrangler vars / secrets). --- # create-fluxy-chat (/docs/packages/create-fluxy-chat) Always: ```bash npx @fluxy-chat/create-fluxy-chat@latest ``` Full flags, hosted vs self-host, and adapters: [create-fluxy-chat guide](/docs/guides/create-fluxy-chat). Path comparison: [Choose your path](/docs/getting-started/choose-your-path). --- # fluxychat_sdk (/docs/packages/flutter-sdk) fluxychat_sdk [#fluxychat_sdk] Flutter SDK for [FluxyChat](https://fluxychat.com) — realtime chat infrastructure for SaaS. Add in-app chat, AI agents, and multi-platform messaging with real-time WebSocket rooms, REST API, and full state management. Installation [#installation] Add to your `pubspec.yaml` from this repo (the package is not on pub.dev yet): ```yaml dependencies: fluxychat_sdk: git: url: https://github.com/AlessandroFare/fluxychat.git path: packages/flutter-sdk ``` Quick Start [#quick-start] ```dart import 'package:fluxychat_sdk/fluxychat_sdk.dart'; final client = FluxyChatClient( config: FluxyChatConfig( apiUrl: 'https://your-worker.workers.dev', wsUrl: 'wss://your-worker.workers.dev', projectId: 'your-project-id', token: 'your-jwt-token', ), ); // Connect to a room await client.connect('room_123'); // Listen for messages client.on('message', (event) { final message = event.data as Message; print('New message: ${message.content}'); }); // Send a message await client.sendMessage( 'room_123', content: 'Hello from Flutter!', ); // Load message history final messages = await client.loadMessages('room_123'); // Invoke an AI agent final response = await client.invokeAgent( 'room_123', agentId: 'support-bot', message: 'What are your hours?', ); ``` Features [#features] * **REST API** — Rooms, messages, members, reactions, search * **WebSocket** — Real-time messaging with auto-reconnect (exponential backoff) * **Typing indicators** — Broadcast and receive typing status * **Presence** — Online/offline tracking per room * **Read receipts** — Track message delivery and read status * **Message reactions** — Emoji reactions on messages * **AI agents** — Invoke agents with streaming responses * **Message search** — Full-text search across rooms * **Optimistic delivery** — Instant UI updates with server confirmation * **E2E encryption** — Client-side encryption support (TLS + Double Ratchet roadmap) * **Polls** — Create and vote in polls * **File uploads** — Multipart file upload support * **Push notifications** — Web push and mobile device registration * **Custom domains** — Domain management API * **Webhook management** — Register and manage webhooks * **Scheduled messages** — Schedule messages for future delivery * **Message templates** — Template rendering with variable substitution * **Voice messages** — Voice message sending support API [#api] FluxyChatClient [#fluxychatclient] ```dart final client = FluxyChatClient( config: FluxyChatConfig( apiUrl: 'https://api.example.com', wsUrl: 'wss://api.example.com', projectId: 'proj_123', token: 'jwt_token', debug: false, ), ); ``` Connection [#connection] * `connect(roomId)` — Connect to a room via WebSocket * `disconnect()` — Disconnect from current room * `connectionStatus` — Stream of connection state changes * `connectUser()` — Connect to user channel for personal events Rooms [#rooms] * `listRooms()` — List all accessible rooms * `getRoom(roomId)` — Get room details * `createRoom(name, \{type\})` — Create a new room * `updateRoom(roomId, data)` — Update room metadata * `deleteRoom(roomId)` — Delete a room Messages [#messages] * `sendMessage(roomId, content, \{kind, metadata, parentId\})` — Send a message * `sendOptimisticMessage(roomId, content)` — Send with optimistic UI update * `loadMessages(roomId, \{limit, before\})` — Load message history * `editMessage(roomId, messageId, content)` — Edit a message * `deleteMessage(roomId, messageId)` — Delete a message * `sendTyping(roomId, isTyping)` — Send typing indicator * `addReaction(roomId, messageId, emoji)` — Add emoji reaction * `removeReaction(roomId, messageId, emoji)` — Remove reaction * `sendReadReceipt(roomId, messageId)` — Mark message as read AI Agents [#ai-agents] * `invokeAgent(roomId, agentId, message)` — Invoke an AI agent * `listAgents()` — List available agents * `getAgent(agentId)` — Get agent details Events [#events] * `on(event, handler)` — Subscribe to events * `off(event, handler)` — Unsubscribe from events * `onStatusChange(handler)` — Connection status changes **Available events:** `message`, `message_edit`, `message_delete`, `typing`, `presence`, `reaction`, `read`, `member_joined`, `member_left`, `agentTyping`, `agentRun`, `stream`, `error` Protocol [#protocol] The SDK implements the FluxyChat wire protocol (v1.0.0) with 30 inbound and 11 outbound event types. Protocol parity is validated against `packages/protocol/protocol-events.json`. Testing [#testing] ```bash flutter test ``` Requirements [#requirements] * Dart SDK >=3.2.0 * Flutter >=3.16.0 License [#license] MIT — see LICENSE for details. --- # @fluxy-chat/protocol (/docs/packages/protocol) @fluxy-chat/protocol [#fluxy-chatprotocol] Shared wire protocol for FluxyChat clients and the worker. What it covers [#what-it-covers] * Canonical **inbound** WebSocket event types (server → client) * Canonical **outbound** client event types (client → room) * Lightweight runtime guards (`isFluxyInboundEvent`, `isFluxyOutboundEvent`) Install [#install] ```bash pnpm add @fluxy-chat/protocol ``` Usually consumed as a dependency of `@fluxy-chat/sdk` — you rarely install it directly. Usage [#usage] ```ts import { isFluxyInboundEvent, FLUXY_INBOUND_EVENT_TYPES } from "@fluxy-chat/protocol"; socket.onmessage = (raw) => { const data = JSON.parse(raw.data); if (!isFluxyInboundEvent(data)) return; // dispatch by data.type }; ``` Contract tests [#contract-tests] SDK packages should keep their event unions aligned with `FLUXY_INBOUND_EVENT_TYPES`. When adding a new WS event in the worker: 1. Add to `@fluxy-chat/protocol` inbound/outbound lists 2. Update Room DO handler 3. Extend SDK `FluxyChatEvent` union 4. Run `pnpm --filter @fluxy-chat/protocol test` License [#license] MIT --- # @fluxy-chat/react-native-sdk (/docs/packages/react-native-sdk) @fluxy-chat/react-native-sdk [#fluxy-chatreact-native-sdk] React Native SDK for FluxyChat - realtime chat infrastructure for SaaS. Installation [#installation] ```bash npm install @fluxy-chat/react-native-sdk # or yarn add @fluxy-chat/react-native-sdk ``` Quick Start [#quick-start] ```tsx import { FluxyChatClient, useChat, useRooms } from '@fluxy-chat/react-native-sdk'; const client = new FluxyChatClient({ apiUrl: 'https://your-worker.workers.dev', wsUrl: 'wss://your-worker.workers.dev', projectId: 'your-project-id', token: 'your-jwt-token', }); function ChatScreen({ roomId }) { const { messages, sendMessage, connectionStatus } = useChat(client, { roomId }); return ( Status: {connectionStatus} {item.content}} /> {subscriptions.map((s) => (
{s.endpointHost} (failures: {s.failureCount})
))} {error &&
{error}
} ); } ``` 3\. (Manual) Without the SDK [#3-manual-without-the-sdk] ```ts const { publicKey } = await fetch(`${WORKER_URL}/push/web/vapid-public-key`) .then((r) => r.json()); const rawKey = (b64) => { const pad = "=".repeat((4 - (b64.length % 4)) % 4); return Uint8Array.from( atob(b64.replace(/-/g, "+").replace(/_/g, "/") + pad), (c) => c.charCodeAt(0), ); }; const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: rawKey(publicKey), }); await fetch(`${WORKER_URL}/push/web/subscribe`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${jwt}`, "X-Fluxy-Project-Id": "proj_1", }, body: JSON.stringify({ endpoint: sub.endpoint, keys: { p256dh: sub.toJSON().keys.p256dh, auth: sub.toJSON().keys.auth, }, userAgent: navigator.userAgent, }), }); ``` Server-side hookup [#server-side-hookup] The push loop is **already wired** into the post-message automations: when a message is sent to a room, every member with a registered web push subscription gets a notification (subject to failure-count gating). The VAPID key pair is auto-generated on first use — no manual seeding required. To inspect/manage subscriptions: ```bash # List all subscriptions for the authenticated user curl -H "Authorization: Bearer $JWT" $WORKER/push/web/subscriptions # Remove one (by id or endpoint URL) curl -X DELETE -H "Authorization: Bearer $JWT" $WORKER/push/web/subscribe/ ``` Triage behavior [#triage-behavior] | Push service response | FluxyChat action | | --------------------- | ------------------------------------------------------------ | | 201 / 202 | Delivered → reset `failure_count` to 0 | | 404 / 410 | Subscription gone → DELETE row | | 429 | Rate-limited → bump `failure_count`, keep row | | 400 / 401 / 403 | Config error → bump `failure_count`, log `push.config_error` | | 5xx (other) | Transient → bump `failure_count`, retry next message | Subscriptions with `failure_count >= 10` are skipped until a manual unsubscribe/resubscribe cycle. Environment variables [#environment-variables] | Variable | Default | Purpose | | ---------------- | ------------------------------ | ------------------------------------------------------ | | `VAPID_SUBJECT` | `mailto:admin@fluxychat.local` | RFC 8292 `sub` claim (must be `mailto:` or `https://`) | | `WEB_PUSH_ICON` | `/icon-192.png` | Default icon for `showNotification` (client-side) | | `WEB_PUSH_BADGE` | `/badge-72.png` | Default badge (client-side) | | `PUBLIC_APP_URL` | `https://fluxy.chat` | Origin for `url` field in payload | Migrations [#migrations] * `0047_web_push_vapid.sql` — adds `project_vapid_keys` and `web_push_subscriptions` tables. Apply via: ```bash cd apps/worker wrangler d1 migrations apply fluxychat-db --remote ``` Cross-browser support [#cross-browser-support] | Browser | Status | Notes | | --------------------- | ---------- | -------------------------------------------------------------------- | | Chrome / Edge / Opera | ✅ | Full support | | Firefox | ✅ | Full support, no quota difference | | Safari 16+ macOS | ✅ | macOS only — Web Push is **not** supported in iOS Safari before 16.4 | | iOS Safari 16.4+ | ✅ PWA only | User must install to home screen | For iOS Safari \< 16.4, fall back to FCM (`POST /push/devices` with `platform: "fcm"`). Security notes [#security-notes] * The VAPID public key endpoint is **unauthenticated** by design — the public key is not secret; the JWT it signs is authenticated by the browser's push service. * Subscription endpoints are bound to the JWT user — one user cannot see another user's subscriptions via the API. * The subject (`mailto:` or `https://`) is **required** by RFC 8292; push services may refuse requests with a missing or invalid subject. * VAPID JWT TTL defaults to 12 hours (per RFC 8292 recommendation) and is regenerated on every push. --- # Webhook Secret Encryption Migration (/docs/reference/webhook-secret-migration) Background [#background] When `WEBHOOK_SECRET_ENCRYPTION_KEY` is **absent**, new webhooks created via `POST /webhooks/register` store their secret in plaintext (the `secret` column, with `secret_ciphertext`/`secret_iv` left NULL). This is a deployment safety net — the worker continues to function without the key, but secrets are stored in the clear. Once the key is provisioned, existing plaintext rows should be encrypted to eliminate the plaintext surface. Prerequisites [#prerequisites] 1. `WEBHOOK_SECRET_ENCRYPTION_KEY` is set in your Cloudflare Workers environment (or `.dev.vars` for local/dev). 2. The key is a **32-byte hex string** (64 hex chars) or a **raw 32-byte base64 string** (43 base64 chars). Generate with: ```bash node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" ``` 3. Backup your D1 database before running any migration SQL. Migration: Encrypt existing plaintext secrets [#migration-encrypt-existing-plaintext-secrets] Step 1 — Identify plaintext rows [#step-1--identify-plaintext-rows] ```sql -- Preview: list all webhooks that have plaintext secrets SELECT id, project_id, url, secret, created_at FROM webhooks WHERE secret IS NOT NULL AND (secret_ciphertext IS NULL OR secret_iv IS NULL); ``` Count the rows. If the count is 0, no migration is needed. Step 2 — Encrypt and update [#step-2--encrypt-and-update] For each row from Step 1, encrypt the secret using the worker logic and update the row: ```sql UPDATE webhooks SET secret = NULL, secret_ciphertext = '', secret_iv = '' WHERE id = ''; ``` To encrypt, use the worker itself. Run a wrangler dev session: ```js // Encrypt a secret using the same logic the worker uses const key = await crypto.subtle.importKey( "raw", new TextEncoder().encode(process.env.WEBHOOK_SECRET_ENCRYPTION_KEY), { name: "AES-GCM" }, false, ["encrypt"] ); const iv = crypto.getRandomValues(new Uint8Array(12)); const ct = await crypto.subtle.encrypt( { name: "AES-GCM", iv }, key, new TextEncoder().encode(secret) ); const ciphertext = btoa(String.fromCharCode(...new Uint8Array(ct))); const ivB64 = btoa(String.fromCharCode(...iv)); // Then UPDATE webhooks SET secret = NULL, secret_ciphertext = '', secret_iv = '' WHERE id = ''; ``` Or add a dedicated admin route in the worker: ```js // POST /admin/encrypt-webhook-secrets (requires admin auth) const rows = await env.DB.prepare( "SELECT id, secret FROM webhooks WHERE secret IS NOT NULL AND secret_ciphertext IS NULL" ).all(); for (const row of rows.results || []) { const enc = await encryptWebhookSecret(env, row.secret); if (enc) { await env.DB.prepare( "UPDATE webhooks SET secret = NULL, secret_ciphertext = ?, secret_iv = ? WHERE id = ?" ).bind(enc.secretCiphertext, enc.secretIv, row.id).run(); } } ``` Verification [#verification] After migration, verify no plaintext secrets remain: ```sql SELECT COUNT(*) AS plaintext_count FROM webhooks WHERE secret IS NOT NULL AND (secret_ciphertext IS NULL OR secret_iv IS NULL); ``` Expected result: `0`. Also verify webhook deliveries are still signed by checking for the `X-Fluxy-Signature` header on a test delivery. Rollback (if needed) [#rollback-if-needed] If a row was updated incorrectly, restore the plaintext: ```sql UPDATE webhooks SET secret = '', secret_ciphertext = NULL, secret_iv = NULL WHERE id = ''; ``` Security notes [#security-notes] * After migration, the `secret` column is NULL for all rows — the delivery path no longer falls back to plaintext. * If `WEBHOOK_SECRET_ENCRYPTION_KEY` is rotated, a new migration must re-encrypt all rows. Old keys cannot decrypt rows encrypted with a rotated key. --- # Authentication (/docs/rooms/auth) The socket and REST both take a token. What you mint depends on the room. | Token | Where | Use | | --------------------- | ---------------------------------------- | ------------------------------------------------------- | | Member JWT | Browser, after your sign-in | Private rooms, roles, production | | `pk_` publishable key | `FluxyRealtimeProvider` | Public rooms via `POST /tokens/anonymous` | | Guest session | `joinPublicRoomAsGuest` / widget `guest` | Same public path, stable `guestKey` in localStorage | | `fc_…` project key | Server only | `POST /auth/token`. 403 if you send it from the browser | ```ts // Server const res = await fetch(`${workerUrl}/auth/token`, { method: "POST", headers: { authorization: `Bearer ${process.env.FLUXY_API_KEY}`, "content-type": "application/json", }, body: JSON.stringify({ userId: "ada", roomId: "lobby" }), }); const { token } = await res.json(); ``` Pass that JWT to `FluxyChatClient` or `authTokenProvider`. Recipe: [JWT auth](/docs/cookbook/auth-jwt). Expired tokens close the socket with 1008 and `token_expired` (40100). Mint again, then `client.setToken(next)` / `attach()`. Catalog: [error codes](/docs/errors). Hosted is beta. Self-host SAML is separate from hosted login. Hosted SAML stays off unless you set `SAML_SSO_ENABLED`. --- # Live cursors (/docs/rooms/cursors) ```ts await room.attach(); room.cursors.subscribe("update", (cursor) => { draw(cursor.userId, cursor.x, cursor.y); }); window.addEventListener("mousemove", (event) => { room.cursors.set({ x: event.clientX, y: event.clientY }); }); const all = room.cursors.getAll(); const me = await room.cursors.getSelf(); const others = await room.cursors.getOthers(); const page = await room.cursors.history({ limit: 50 }); ``` Outbound points batch (\~100ms). Inbound replay uses `offset` so the remote pointer travels instead of teleporting. The Room DO skips fan-out when you are the only socket. On connect, the DO sends the last cursor per user (`snapshot: true`). `await history()` pages the in-session ring plus the Room DO trail from `GET /rooms/:id/live` (`cursorHistory`, cap 200). Hibernated DOs start empty — this is not a durable channel.history of every past point. `useCursors()` is the React hook on `FluxyRoomProvider`. `useLiveCursors({ roomId })` is the store path. UI: `Cursors` / `Cursor` in `@fluxy-chat/ui`. Presence layers (`presenceKey`) [#presence-layers-presencekey] Every frame above rides the default cursor layer. Pass `presenceKey` to publish a named layer instead — an agent pointer next to the human one, never on top of it: ```ts sendCursor({ x, y, presenceKey: "agent", label: "assistant" }); ``` Layers are keyed `userId` (default) or `userId#presenceKey` in `liveCursors` and `room.cursors.getAll()`. `getSelf()`, `get(userId)` and `useOthers()` read the default layer only, so a layer can never clobber the human pointer. `useLiveCursors({ roomId }).cursors` returns every layer. A bot user publishes its own layer by connecting with its token and sending the same `cursor` frames with `presenceKey: "agent"` — no extra API. Server-side agent cursors (from the Worker's own agent runtime) ride the internal `announce` path with the same frame shape and default `presenceKey: "agent"`; they are ephemeral (no snapshot, no history). --- # Message history (/docs/rooms/history) ```ts const page = await room.messages.history({ limit: 50 }); for (const message of page.items) { console.log(message.id, message.text, message.serial); } if (page.hasNext()) { const older = await page.next(); } ``` | Param | What it does | | --------------- | ---------------------------------------- | | `limit` | Page size | | `orderBy` | `newestFirst` (default) or `oldestFirst` | | `before` | ISO timestamp, exclusive | | `fromSerial` | Numeric id, `id > n` | | `beforeSerial` | Numeric id, `id < n` | | `start` / `end` | Time window on `createdAt` | REST: `GET /messages` with the same bounds. The Worker does not speak MessagePack. Versions of one line: `room.messages.getVersions(id)` reads `room_message_events` (REST PATCH also records an update). If the socket resumes with a hole it cannot fill, you get `onDiscontinuity` (code 10200). Reload history from there. Cookbook: [message history](/docs/cookbook/message-history). --- # Rooms (/docs/rooms) A room is one Durable Object plus D1. Chat, presence, occupancy, typing, locks, and cursors share the JSON WebSocket. Yjs uses a second binary connection on the same `/ws/room/:id` route. Hosted is beta. Pin `@fluxy-chat/sdk` (see [status and limits](/docs/learn/status-and-limits)). Get a room [#get-a-room] ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: workerUrl, token: memberJwt, userId: "ada", }); const room = await client.rooms.get("lobby"); await room.attach(); ``` `client.room("lobby")` is the same object, without waiting. `await room.attach()` resolves when the socket is attached, or rejects on `suspended` / `failed`. `rooms.get` rejects if you request the same id with different options (`unable to get room; options differ`). `rooms.release("lobby")` detaches and drops the cache. `client.close()` / `rooms.dispose()` tears down every tracked room. `useChat({ roomId })` still connects as a side effect. For attach-on-purpose, use `useChat({ roomId, autoConnect: false })` and call `attach()`, or wrap with `FluxyRoomProvider`. What is on the bag [#what-is-on-the-bag] | Field | Job | | ------------------------------------ | ------------------------------------------------------ | | [`messages`](/docs/rooms/messages) | Send, history, edit, delete, message reactions | | [`presence`](/docs/rooms/presence) | Enter, leave, update. Leave does not close the socket | | [`occupancy`](/docs/rooms/occupancy) | Socket count vs unique members | | [`typing`](/docs/rooms/typing) | Ephemeral `keystroke` / `stop` | | [`reactions`](/docs/rooms/reactions) | Room-level bursts (`room_reaction`), not message emoji | | [`cursors`](/docs/rooms/cursors) | Batched pointer + last-position map | | [`locks`](/docs/rooms/locks) | Exclusive lock on the Room DO | | [`locations`](/docs/rooms/locations) | UI locus (`uiLocation`), not GPS | | [`members`](/docs/rooms/members) | Roster + leaver TTL | | `objects` | Shared JSON bag (`derived` / `derived_set`) | | [`status`](/docs/rooms/status) | Attach lifecycle | | `onDiscontinuity` | Resume hole you could not fill | React hooks with the same names live on `FluxyRoomProvider`: `useMessages`, `usePresence`, `useOccupancy`, `useTyping`, `useLocks`, `useCursors`, `useMembers`, `useRoomStatus`. Dedicated pages: [Message history](/docs/rooms/history), [Message replies](/docs/rooms/replies), [Share media](/docs/rooms/media), [UI kit](/docs/rooms/ui-kit). Options [#options] ```ts const room = await client.rooms.get("lobby", { occupancy: { enableEvents: true }, messages: { rawMessageReactions: false }, }); ``` Occupancy events default on (same socket, not a second channel). Set `enableEvents: false` if you only want `occupancy.get()`. Raw message reactions default off. Related [#related] * [Auth](/docs/rooms/auth) * [Cookbook](/docs/cookbook) * [Connection state](/docs/core/connection-state) * [Wire protocol](/docs/core/wire-protocol) * [Error codes](/docs/errors) --- # Locations (/docs/rooms/locations) A location here is "which slide / which node", not lat/lng. ```ts await room.attach(); await room.presence.enter(); room.locations.subscribe((event) => { console.log(event.member.userId, event.currentLocation, event.previousLocation); }); await room.locations.set({ surface: "slide", id: "3" }); const self = await room.locations.getSelf(); const others = await room.locations.getOthers(); ``` Wire: `uiLocation` on `presence_patch`. Aliases on the event: `member`, `currentLocation`, `previousLocation` (plus `userId` / `current` / `previous`). Fleet GPS stays `location_update`. Do not put 60 Hz pointers on `client_event`. Use [cursors](/docs/rooms/cursors). `useLocations()` is the React hook. --- # Locks (/docs/rooms/locks) Locks are not Yjs. They are a table on the room: `pending`, `locked`, `unlocked`. ```ts await room.attach(); room.locks.subscribe((event) => { console.log(event.lockId, event.held, event.acquired, event.owner); }); room.locks.acquire("slide-1", { ttlMs: 30_000, attributes: { section: "intro" } }); const mine = await room.locks.getSelf(); const others = await room.locks.getOthers(); const all = await room.locks.getAll(); room.locks.release("slide-1"); ``` `getAll` / `getSelf` / `getOthers` skip pending. `get(id)` is sync and still returns a pending row. React: `useLock("slide-1")`, `useLocks()`. Recipe: [Locks](/docs/cookbook/locks). --- # Share media (/docs/rooms/media) Files go through the Worker (`uploadFile` / composer `uploadComposerFile`). The object lives in the `ATTACHMENTS` R2 bucket. The chat line stores metadata, not the bytes. ```ts const client = new FluxyChatClient({ baseUrl: workerUrl, token: memberJwt, userId: "ada" }); const attachment = await client.uploadFile(file, "image"); await room.messages.send("see this"); // useChat sendMessage(content, replyTo, [attachment]) ``` In the UI kit, `ChatWindow` takes `uploadComposerFile`. The composer shows chips for pending files, then sends them with the next message. Limits: Worker enforces size and type. Do not put secrets in filenames. Treat the stored name as untrusted when you render it. Public guest rooms can be write-locked with `PUBLIC_GUEST_READ_ONLY=true`. Hosted is beta; check your plan quota in the dashboard, not this page. --- # Members (/docs/rooms/members) `room.members` is the Spaces-style roster. Presence is who entered. Members also keep people who just left, until `members.offlineTimeoutMs`. ```ts await room.attach(); await room.presence.enter({ name: "Ada" }); room.members.subscribe((event) => { console.log(event.type, event.member.userId); }); const all = await room.members.getAll(); room.members.updateProfile({ name: "Ada L." }); ``` React: `useMembers()` on `FluxyRoomProvider`. Split helpers: `useSelf`, `useOthers`, `useLeavers`, `usePresenceAvatars`. UI: `AvatarStack` with `selfId`. Recipe: [Presence avatars](/docs/cookbook/presence-avatars). Enter/leave on the occupancy set is still `attach()` / `detach()`. --- # Messages (/docs/rooms/messages) Chat lines are D1 rows on the room. The live socket emits `message` / `edit` / `delete`. The room bag maps those to `message.created`, `message.updated`, `message.deleted`. ```ts const room = client.room("lobby"); await room.attach(); const sub = room.messages.subscribe((event) => { console.log(event.type, event.message.id, event.message.text); }); await room.messages.send("hello"); await room.messages.send({ text: "hello with extras", metadata: { ticket: "42" }, headers: { "x-source": "cli" }, replyTo: 12, quotedMessageId: 8, }); const one = await room.messages.get(1); await room.messages.update(1, { text: "hello (edit)" }); await room.messages.delete(1); sub.unsubscribe(); ``` `message.serial` is a string form of the numeric id. `fromSerial` / `beforeSerial` use that id, not an Ably-style lex serial. `messages.with(message, event)` applies a later event if the version serial is newer. Older or same serial is skipped. `messages.copy(message, params)` is a local clone. Subscribe before attach if you want `historyBeforeSubscribe` on the subscription (newest-first page, then live events). ```ts const sub = room.messages.subscribe((event) => { /* live */ }); const page = await sub.historyBeforeSubscribe({ limit: 50 }); ``` Message reactions: `room.messages.reactions.send(id, emoji)` / `delete`. Summaries fold unique / distinct / multiple. Raw create/delete events need `messages: { rawMessageReactions: true }`. Operator CLI (Worker JWT, not Control): `fluxy-room get|update|delete|react|unreact|reactions|versions --id `. Room-level bursts (👏 in the footer) are [room reactions](/docs/rooms/reactions), not this API. Nested replies: `parentId` / `useThread`. Stream-style quotes use `quotedMessageId` (citation, not a thread). Comment pins are a different primitive (`useThreads`). See [nested threads](/docs/core/nested-threads). Slow mode: `client.enableSlowMode(roomId, seconds)`. --- # Occupancy (/docs/rooms/occupancy) A viewer can be connected without being present. Watching is `connections − presenceMembers` on the occupancy frame, `/live`, `GET /rooms/:id/info`, and the kit (“2 in chat · 2 watching” when there are 4 sockets and 2 members). ```ts const room = await client.rooms.get("lobby", { occupancy: { enableEvents: true }, }); room.occupancy.subscribe((event) => { const { connections, presenceMembers, watching } = event.occupancy; console.log(event.type); // occupancy.updated console.log(connections, presenceMembers, watching); }); await room.attach(); const live = await room.occupancy.get(); const cached = room.occupancy.current(); console.log(room.occupancy.current.connections, room.occupancy.current.watching); ``` `get()` is REST (`GET /rooms/:id/live`). It works while detached. `current()` is the last realtime frame. It is `null` until the first event. With `occupancy.enableEvents: false`, `subscribe` and `current()` throw `feature_not_enabled` (40040). `get()` still works. Events ride the room socket. There is no extra occupancy channel. React: `useOccupancy(store)` on `useChat`, or `useOccupancy()` inside `FluxyRoomProvider`. Recipe: [Live occupancy](/docs/cookbook/occupancy). --- # Presence (/docs/rooms/presence) Occupancy join is `attach()`. Presence is a separate roster: who opted in with `enter`. ```ts await room.attach(); await room.presence.enter({ name: "Ada" }); await room.presence.update({ status: "away" }); room.presence.subscribe((event) => { console.log(event.type, event.member.userId); }); room.presence.subscribe("enter", (event) => { console.log("in", event.member.userId); }); const members = await room.presence.get(); const here = room.presence.isUserPresent("ada"); await room.presence.leave({ name: "Ada" }); ``` `leave(data?)` hides you from `presenceMembers`. The WebSocket stays open. REST `GET /rooms/:id/live` uses the same filter. Event types: `enter`, `leave`, `update`, `present`. `subscribe(type, listener)` filters. `onAnyEvent` still sees the wire names (`presence_patch`, `presence_leave`). `getSelf` / `getOthers` / `getAll` are on `room.presence` and `room.members`. Members keep leavers until `members.offlineTimeoutMs`. Avatars: [presence avatars](/docs/cookbook/presence-avatars). GPS is `location_update`, not this API. UI locus is [locations](/docs/rooms/locations). --- # Reactions (/docs/rooms/reactions) Two APIs. Do not mix them. Message reactions [#message-reactions] Tied to a message id. Persist. Summaries fold unique, distinct, and multiple. ```ts await room.messages.reactions.send(messageId, "👍"); await room.messages.reactions.delete(messageId, "👍"); room.messages.reactions.subscribe((event) => { console.log(event.type, event.summary); }); ``` Raw create/delete frames need `messages: { rawMessageReactions: true }` on `rooms.get`. Default is off (`feature_not_enabled` on `subscribeRaw`). Operator CLI: `fluxy-room react|unreact|reactions --id --emoji 👍`. Room reactions [#room-reactions] Ephemeral. Everyone in the room sees a burst. Nothing is stored on a chat line. ```ts await room.reactions.send("👏"); await room.reactions.send({ name: "👏", metadata: { source: "header" } }); room.reactions.subscribe((event) => { console.log(event.type, event.reaction.name, event.reaction.userId); }); ``` Wire name: `room_reaction`. Recipe: [Room reactions](/docs/cookbook/room-reactions). `ChatWindow` can show bursts in the footer if you pass them in. --- # Message replies (/docs/rooms/replies) A reply is another chat row with `parentId` set to the parent message id. Same room, same socket. `room.messages.send({ text, replyTo })` sets REST `replyTo` / `parentId` / `threadParentId` (same field). `useChat().sendMessage(content, replyTo)` is the store path. ```ts await room.messages.send({ text: "reply", replyTo: 42 }); ``` `useThread({ roomId, threadParentId: 42 }).sendMessage("reply")` is the same parent id. Max thread depth is 8. Deeper replies return `thread_depth_exceeded`. A Stream-style **quote** (`quotedMessageId`) cites a message without setting `parentId`. Use Quote in `ChatWindow`, not Reply. Thread typing: `room.typing.keystroke(parentId)` / `useThread().setTyping` — does not light the main transcript. Canvas pins (`useThreads`, `/comment-threads`) are a different table. Do not mix them with chat replies. Full page: [Chat reply threads](/docs/core/nested-threads). --- # Room status (/docs/rooms/status) `room.status()` (and `room.status.current()`) is the attach label. `onStatusChange` / `status.subscribe` emit `{ current, previous, retryIn, error }`. | Label | Means | | ------------- | ------------------------------------------------------------------- | | `initialized` | Object exists. Socket idle | | `attaching` | Handshake in progress | | `attached` | Live on WebSocket | | `suspended` | Long outage. Client still retries (`retryIn`) | | `failed` | Auth or max attempts. Call `attach()` again after you fix the token | | `detached` | You called `detach()`, or the socket is down without a retry | ```ts const room = client.room("lobby"); if (room.status() === "attached") { await room.messages.send("hello"); } room.onStatusChange((change) => { console.log(change.previous, "->", change.current, change.retryIn); }); await room.attach(); // waits until attached; rejects on suspended or failed ``` `String(room.status)` is the same label. Strict `room.status === "attached"` is false because `status` is also the subscribe handle. Use `room.status()`. Client-wide socket state is `client.connection` (`ping()`, `whenState`). Per-room attach status and client connection are not the same object. See [Connection state](/docs/core/connection-state). `room.error` is the last attach error, or `null`. React: `useRoomStatus()` inside `FluxyRoomProvider`. --- # Typing (/docs/rooms/typing) ```ts await room.attach(); room.typing.subscribe((event) => { const names = [...event.currentlyTyping]; console.log(names.length, names); }); input.addEventListener("input", () => room.typing.keystroke()); input.addEventListener("blur", () => room.typing.stop()); ``` `keystroke()` / `start()` send `typing` started. The SDK throttles outbound starts (default 10s heartbeat). After 10s of silence it sends stop. `stop()` sends idle now. `typing.current()` is a `Set` of user ids. `currentlyTyping` on the event is a snapshot Set. Do not persist it. `useChat().setTyping` is the same wire event. `useTyping()` reads the bound room. Caption helper in `@fluxy-chat/ui`: `formatTypingCaption`. Recipe: [Typing](/docs/cookbook/typing). --- # UI kit (/docs/rooms/ui-kit) `@fluxy-chat/ui` is layout. `@fluxy-chat/react` / `@fluxy-chat/sdk` own the socket. ```tsx import { ChatWindow } from "@fluxy-chat/ui"; import { useChat } from "@fluxy-chat/react"; function Room({ roomId }: { roomId: string }) { const { messages, sendMessage, online, typingUsers } = useChat({ roomId }); return ( sendMessage(text)} /> ); } ``` `ChatWindow` props (not children): transcript, composer, optional `ChannelList`, `RoomInfo` header when `roomName` is set, typing footer, send-error alert, connection chrome, discontinuity banner, room-reaction bursts. | Piece | What it does | | --------------------- | ---------------------------------------------------------------------------- | | `ChatWindow` | Cap latest N (`windowSize`), load-older at the top, header/footer slots | | `RoomInfo` | `{name} · N in chat · M watching` (`M = connections − presenceMembers`) | | `ChannelList` | Occupancy per room, collapse, empty "Select a room…", add/leave | | `MessageInput` | Enter sends, textarea grows to 150px, emoji at caret, `onSendError` | | `MessageList` | Preserve scroll on prepend, `loadMoreThreshold` 150, empty “No messages yet” | | `AvatarStack` | `selfId` first, overflow `+N` | | `ParticipantList` | roster, self first, extra watchers | | `formatTypingCaption` | 1 / 2 / N people | | `formatSenderTooltip` | name, client id, time | Drop-in widget (guest + `pk_`): [`@fluxy-chat/ui-kit`](/docs/packages/ui-kit) `FluxyChatWidget`. It wires those `ChatWindow` props from `useChat`. `FluxyChatSettingsProvider` gates edit / delete / react on `ChatWindow`. Wrap the tree to change defaults. Delete asks `Delete this message?`. Pass `discontinuity` and `roomReactions` / `onSendRoomReaction` for the Ably hole banner and footer bursts. Pass `connectionStatus` for reconnect chrome. --- # Agent runtime: tool_execute_url and data exfiltration (/docs/security/agent-tool-exfiltration) Agent runtime: tool_execute_url and data exfiltration [#agent-runtime-tool_execute_url-and-data-exfiltration] Fluxychat agents can call tenant-configured HTTP endpoints during a run: * `context_fetch_url` — read-only context for the model * `tool_execute_url` — executes tool calls the model selects Both URLs are chosen by the **project admin** who owns the agent. SSRF to private networks is blocked (`assertSafeOutboundUrl` in `apps/worker/src/lib/url-ssrf.ts` and `agent-tools.js`). Insider threat (by design) [#insider-threat-by-design] A tenant admin can: 1. Set `tool_execute_url` to a server they control. 2. Craft a `system_prompt` that instructs the model to send room content, user metadata, or tool arguments to that server. This is intentional: agents integrate with the tenant's own systems. Fluxychat does not inspect or censor admin-authored prompts across tenants. What we do mitigate [#what-we-do-mitigate] | Risk | Mitigation | | ------------------------------------------ | --------------------------------------------------------- | | SSRF to `127.0.0.1`, RFC1918, metadata IPs | Blocked before `fetch` | | Runaway cost | Per-agent `rate_limit_rpm`, project `agent_invokes` quota | | Cross-tenant access | JWT + project scope on agent CRUD and invoke paths | Operator guidance [#operator-guidance] * Document in your security FAQ that **tenant admins are trusted** for agent configuration. * For enterprise deals, offer review of agent configs or restrict agent admin roles. * Optional future: prompt lint endpoint or allow-list domains per project (not implemented today). Related code [#related-code] * `apps/worker/src/lib/agent-runtime.js` — mention invoke, tool dispatch * `apps/worker/src/lib/agent-tools.js` — POST to `tool_execute_url` * `apps/worker/src/lib/url-ssrf.ts` — outbound URL policy --- # SAML SSO (/docs/security/saml-signature-verification) FluxyChat can verify SAML responses from your IdP on the Worker. The dashboard page is **Settings → Identity**. The Worker module is `sso-saml.js`. This is not a click-through IdP wizard. You still configure the IdP (Okta, Azure AD, Google) and paste ACS URL, entity ID, and certificate into the Worker secrets / identity settings. What the Worker checks: * XML signature on the assertion * Audience and recipient match your tenant ACS * Assertion is not expired * NameID (or configured attribute) maps to a FluxyChat user Turn it on only after JWT auth works. SSO sits on top of the same rooms and member tokens. Related: [Auth JWT](/docs/guides/auth-jwt), [Production setup](/docs/operations/production-setup), [Agent tool exfiltration](/docs/security/agent-tool-exfiltration). --- # Snippet: Next.js end-to-end (App Router) (/docs/snippets/nextjs-end-to-end) Snippet: Next.js end-to-end (App Router) [#snippet-nextjs-end-to-end-app-router] Goal: a copy-paste integration that: * mints a **JWT** from the Next.js backend (server-side API key) * renders a client page that connects to a room and sends messages (SDK) 1\) `.env.local` (Next.js) [#1-envlocal-nextjs] ```bash NEXT_PUBLIC_FLUXYCHAT_WORKER_URL="http://127.0.0.1\:8787" FLUXY_BASE_URL="http://127.0.0.1\:8787" FLUXY_API_KEY="fc_..." ``` Notes: * `NEXT_PUBLIC_*` is readable in the browser (OK for base URL). * **Do not** expose `FLUXY_API_KEY` to the client — server-side only. 2\) Route handler to mint JWT [#2-route-handler-to-mint-jwt] Create `app/api/fluxy/token/route.ts`: ```ts import { NextResponse } from "next/server"; export async function POST(request: Request) { const body = await request.json().catch(() => null); const userId = body?.userId; if (!userId) return NextResponse.json({ error: "userId required" }, { status: 400 }); const roles = Array.isArray(body?.roles) && body.roles.length ? body.roles : ["member"]; const res = await fetch(`${process.env.FLUXY_BASE_URL}/auth/token`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fluxy-Api-Key": process.env.FLUXY_API_KEY!, }, body: JSON.stringify({ userId, roles, ttlSeconds: 3600 }), }); const json = await res.json().catch(() => ({})); return NextResponse.json(json, { status: res.status }); } ``` 3\) Chat page (client) with SDK [#3-chat-page-client-with-sdk] Create `app/fluxy-demo/page.tsx`: ```tsx "use client"; import { useEffect, useMemo, useState } from "react"; import { FluxyChatClient, useChat } from "@fluxy-chat/sdk"; export default function FluxyDemoPage() { const baseUrl = process.env.NEXT_PUBLIC_FLUXYCHAT_WORKER_URL!; const [userId, setUserId] = useState("alice"); const [roomId, setRoomId] = useState("public-demo-room"); const [token, setToken] = useState(null); const [input, setInput] = useState(""); useEffect(() => { let cancelled = false; async function loadToken() { const res = await fetch("/api/fluxy/token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId, roles: ["member"] }), }); const json = await res.json(); if (!cancelled) setToken(json?.token ?? null); } loadToken().catch(() => {}); return () => { cancelled = true; }; }, [userId]); const client = useMemo(() => { if (!token) return null; return new FluxyChatClient({ baseUrl, userId, token }); }, [baseUrl, token, userId]); const { messages, sendMessage, connectionStatus } = useChat({ roomId, client: client ?? undefined, }); return (

Fluxychat demo

status: {connectionStatus}

{messages.map((m) => (
{m.userId}: {m.content}
))}
{ e.preventDefault(); const text = input.trim(); if (!text) return; sendMessage(text); setInput(""); }} style={{ display: "flex", gap: 8 }} > setInput(e.target.value)} placeholder="Type a message…" style={{ flex: 1 }} />
); } ``` 4\) Important notes [#4-important-notes] * The room must exist and the user must be a member, otherwise WS may fail with `403`. * In production, your backend should decide roles (not the client). --- # Use case: Assistant room (AI agent) (/docs/use-cases/assistant-room) Use case: Assistant room (AI agent) [#use-case-assistant-room-ai-agent] Goal: a room where an AI agent can be invoked (manually or via mentions), with run history and cost visibility. The gallery app [`deal-room`](/docs/getting-started/gallery) is the two-tab check: `@assistant` or `invokeAgent`, token stream on the chat row, `agentStatus` on presence, traces in a feed. If the room Durable Object hibernates mid-call, that LLM run does not resume. Console (open beta UX) [#console-open-beta-ux] * Default room id: `assistant:general` (created from Quickstart or **Agents → Chat in room**). * Built-in agents (`@assistant`, `@onboarding`, etc.) are seeded when a project is created on the Worker. * **Agents** page: unified **agent profile** (identity, model from Worker registry, instructions, hooks) + **LLM keys** overview per provider. * Select an agent → **Chat in room** for live WebSocket chat (requires member JWT). Run banner shows `runId`, latency, tokens; **tool\_call / tool\_result / tool\_error** cards appear **in the message thread** when `toolExecuteUrl` is configured (WebSocket + run poll). * **Agent profile** → starter **templates** (assistant, support, onboarding, summarizer, moderator) prefill system prompt and handle. * **Reply-to**: hover a message → **Reply**; sends with `parent_id` (mention invoke and REST invoke both pass `replyTo`). * **Fallback model**: optional second provider/model in agent profile (`config.llm.fallbackProvider`) when the primary fails on the first attempt. * **Rooms** page: **Assistant room** panel opens `assistant:general` with embedded chat. * Agents with a **handle** (e.g. `@assistant`): send `@assistant your question` — the Worker invokes in the background and **streams** token edits over WebSocket (`streaming: true` on message rows). * Agents without a handle: REST invoke after send (same stream on the Worker when the provider supports it). 1\) Create an agent (admin JWT) [#1-create-an-agent-admin-jwt] ```bash export FLUXY_BASE_URL="http://127.0.0.1\:8787" export ADMIN_JWT="" curl -sS -X POST "$FLUXY_BASE_URL/agents" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "Assistant", "handle": "assistant", "provider": "openai", "model": "gpt-4o-mini", "capabilities": ["chat"] }' ``` 2\) Create a dedicated room [#2-create-a-dedicated-room] ```bash export FLUXY_API_KEY="fc_..." curl -sS -X POST "$FLUXY_BASE_URL/rooms" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "type": "group", "name": "assistant\:general", "members": [ { "userId": "alice", "role": "member" } ] }' ``` 3\) Invoke the agent (REST) [#3-invoke-the-agent-rest] ```bash export AGENT_ID="" export ROOM_ID="" curl -sS -X POST "$FLUXY_BASE_URL/agents/$AGENT_ID/invoke" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "'"$ROOM_ID"'", "content": "Write a 3-bullet summary of this thread" }' ``` 4\) Run history and cost insight [#4-run-history-and-cost-insight] ```bash curl -sS "$FLUXY_BASE_URL/agents/$AGENT_ID/runs?limit=20" \ -H "Authorization: Bearer $ADMIN_JWT" curl -sS "$FLUXY_BASE_URL/stats/ai?minutes=60" \ -H "Authorization: Bearer $ADMIN_JWT" ``` --- # Use case: Support chat (/docs/use-cases/support-chat) Use case: Support chat [#use-case-support-chat] Goal: a support chat between end users and your support team, with moderation and export. Recommended flow [#recommended-flow] * Your app backend mints a JWT for the end user (`member` role) * The dashboard / support tool uses an `admin` or `moderator` JWT * The support room is a `group` (or `dm` for 1:1) 1\) Mint JWT for the user (server-side) [#1-mint-jwt-for-the-user-server-side] ```bash export FLUXY_BASE_URL="http://127.0.0.1\:8787" export FLUXY_API_KEY="fc_..." curl -sS -X POST "$FLUXY_BASE_URL/auth/token" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "userId": "customer_123", "roles": ["member"], "ttlSeconds": 3600 }' ``` 2\) Create a support room (server-side) [#2-create-a-support-room-server-side] ```bash curl -sS -X POST "$FLUXY_BASE_URL/rooms" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "type": "group", "name": "support\:customer_123", "members": [ { "userId": "customer_123", "role": "member" }, { "userId": "support_1", "role": "admin" } ] }' ``` 3\) Send messages (client/SDK or REST) [#3-send-messages-clientsdk-or-rest] REST (requires JWT): ```bash export FLUXY_JWT="" export ROOM_ID="" curl -sS -X POST "$FLUXY_BASE_URL/messages" \ -H "Authorization: Bearer $FLUXY_JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "'"$ROOM_ID"'", "content": "Hi, I need help" }' ``` 4\) Basic moderation (admin/moderator) [#4-basic-moderation-adminmoderator] ```bash export ADMIN_JWT="" curl -sS -X POST "$FLUXY_BASE_URL/admin/mute" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "roomId": "'"$ROOM_ID"'", "userId": "customer_123", "reason": "spam", "durationSeconds": 600 }' ``` Audit trail: ```bash curl -sS "$FLUXY_BASE_URL/admin/audit/events?limit=50&action=admin.mute" \ -H "Authorization: Bearer $ADMIN_JWT" ``` 5\) Export for audit/compliance [#5-export-for-auditcompliance] ```bash curl -sS "$FLUXY_BASE_URL/export/messages.json?roomId=$ROOM_ID" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" > messages.json ``` --- # Use case: Team chat (/docs/use-cases/team-chat) Use case: Team chat [#use-case-team-chat] Goal: internal team workspace chat with multiple rooms, unread counts, and webhooks for integrations. 1\) Rooms and membership [#1-rooms-and-membership] Create a room with members: ```bash export FLUXY_BASE_URL="http://127.0.0.1\:8787" export FLUXY_API_KEY="fc_..." curl -sS -X POST "$FLUXY_BASE_URL/rooms" \ -H "Content-Type: application/json" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" \ -d '{ "type": "group", "name": "team\:engineering", "members": [ { "userId": "alice", "role": "member" }, { "userId": "bob", "role": "member" } ] }' ``` List rooms: ```bash curl -sS "$FLUXY_BASE_URL/rooms" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" ``` Unread count per room: ```bash export ROOM_ID="" curl -sS "$FLUXY_BASE_URL/rooms/$ROOM_ID/unread?userId=alice" \ -H "X-Fluxy-Api-Key: $FLUXY_API_KEY" ``` 2\) WebSocket connect (client-side) [#2-websocket-connect-client-side] The WebSocket is room-scoped and requires a token: * URL: `/ws/room/:roomId?token=<JWT>` * Membership is enforced in the Worker / Durable Object Conceptual example: ```js const ws = new WebSocket(`${baseUrl.replace("http", "ws")}/ws/room/${roomId}?token=${encodeURIComponent(jwt)}`); ws.onmessage = (ev) => console.log(JSON.parse(ev.data)); ``` 3\) Webhooks for integrations (server-side) [#3-webhooks-for-integrations-server-side] Register a webhook (admin JWT): ```bash export ADMIN_JWT="" curl -sS -X POST "$FLUXY_BASE_URL/webhooks" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/fluxy/webhook", "secret": "whsec_...", "eventTypes": ["message.created","report.created"] }' ``` Notes: * Deliveries are stored in `webhook_deliveries` with retry/backoff. * Admin inspection: `GET /admin/webhooks/deliveries` --- # Webhook event catalog (/docs/webhooks/catalog) FluxyChat delivers project events to HTTPS endpoints you register in the dashboard **Admin** tab or via `POST /webhooks/register`. Discover types [#discover-types] ```bash curl "$WORKER_URL/webhooks/event-types" ``` Returns the canonical `events[]` list (same as this page). Event types [#event-types] | Event | When it fires | Payload highlights | | ------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- | | `message.created` | New message persisted | `roomId`, `messageId`, `userId`, `content` | | `mention` | User @mentioned | `roomId`, `messageId`, `mentionedUserId` | | `report.created` | Moderation report filed | `roomId`, `messageId`, `reporterId` | | `moderation.auto_flag` | Automation flagged content | `roomId`, `messageId`, `reason` | | `room.occupied` | First subscriber connects | `roomId`, `at` | | `room.vacated` | Last subscriber disconnects | `roomId`, `at` | | `member_joined` | Presence join | `roomId`, `userId`, `subscriptionCount` | | `member_left` | Presence leave | `roomId`, `userId`, `subscriptionCount` | | `subscription_count` | Connection count changed | `roomId`, `subscriptionCount` | | `client_event` | Client-sent `client-*` WS event | `roomId`, `event`, `data` | | `cache_miss` | Cache channel empty on subscribe | `roomId`, `at` | | `user.event` | User channel push | `userId`, `event` | | `webhook.delivery_failed` | A delivery exhausted its retries (error workflow; see below) | `deliveryId`, `webhookId`, `webhookUrl`, `eventType`, `attempts`, `lastHttpStatus`, `lastError` | Subscribe only to events you handle — unknown types are rejected at registration time. Envelope [#envelope] Each delivery POST body: ```json { "type": "message.created", "projectId": "proj_abc", "payload": { "roomId": "support", "messageId": 42 }, "createdAt": "2026-07-28T12:00:00.000Z" } ``` Headers: | Header | Value | | --------------------- | --------------------------------- | | `Content-Type` | `application/json` | | `X-Fluxy-Signature` | HMAC-SHA256 hex of raw body | | `X-Fluxy-Event` | Event type | | `X-Fluxy-Project-Id` | Project id | | `X-Fluxy-Delivery-Id` | Delivery row id (for idempotency) | Verify signatures with your webhook secret (shown once at registration). Use the dashboard **Webhooks** playground to test HMAC locally. Retry policy [#retry-policy] Deliveries succeed when your endpoint returns **2xx** (typically `200`). | Attempt | Backoff (default) | | ------- | ----------------- | | 1 | immediate | | 2 | 60s | | 3 | 5m | | 4 | 30m | | 5 | 60m | Max attempts: `WEBHOOK_MAX_ATTEMPTS` (default `5`). Failed deliveries appear under **Activities** in the console. Error workflow (n8n-style) [#error-workflow-n8n-style] Register a **second** webhook subscribed to `webhook.delivery_failed` and it becomes your error workflow: every time a delivery exhausts its retries, that endpoint receives a notice with the failed delivery's metadata (`deliveryId`, `webhookId`, `eventType`, `attempts`, `lastHttpStatus`, `lastError`). ```bash curl -X POST "$WORKER_URL/webhooks/register" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "url": "https://api.example.com/fluxy/errors", "eventTypes": ["webhook.delivery_failed"], "secret": "whsec_your_other_secret" }' ``` Rules, so the chain cannot loop: * The failing webhook itself is **never** notified about its own failure. * A failed `webhook.delivery_failed` delivery is **not** re-notified — the chain stops after one hop. * Only exhausted retries fire this event; deliveries blocked by signing configuration are not re-sent (the `last_error` on the delivery explains why). * The original payload is **not** re-sent: fetch it from Activities or `GET` the delivery if you need it. Batch verify (optional) [#batch-verify-optional] Send an array of sample events to `POST /webhooks/verify-batch` with `X-Fluxy-Signature` to validate your handler accepts multiple event shapes before going live. Register [#register] ```bash curl -X POST "$WORKER_URL/webhooks/register" \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "url": "https://api.example.com/fluxy/webhook", "eventTypes": ["message.created", "room.occupied"], "secret": "whsec_your_random_secret" }' ``` See also [#see-also] * [Webhook secret migration](/docs/webhooks/catalog) * [Dashboard integration](/docs/reference/dashboard-integration) --- # DevTools inspector (/docs/guides/advanced/devtools-inspector) FluxyChat has a local DevTools inspector for agent runs. Use it on your machine. Dashboard UI [#dashboard-ui] When signed in to the console: 1. Open `/devtools` in the dashboard app. 2. Use preset prompts or custom input to stream agent responses. 3. Inspect the timeline: LLM steps, tool calls (including HITL approval), token usage, and Chat API probe results. The page uses your configured Worker URL and member JWT from the dashboard session. SDK hooks [#sdk-hooks] Capture runs programmatically for custom UIs or tests: ```typescript import { createDevToolsInspector, createDevToolsStore, DevToolsTelemetryIntegration, createTelemetryManager, registerTelemetry, } from "@fluxy-chat/sdk"; const store = createDevToolsStore(); const inspector = createDevToolsInspector(store); const telemetry = createTelemetryManager(); registerTelemetry(telemetry, new DevToolsTelemetryIntegration()); const runId = `run_${Date.now()}`; inspector.captureGenerateText(runId, 1, { model: "gpt-4o-mini", provider: "openai", input: { prompt: "Summarize this room" }, output: { text: "..." }, usage: { promptTokens: 120, completionTokens: 48, totalTokens: 168 }, durationMs: 890, }); const runs = inspector.getStore().getRuns(); ``` Connection debug [#connection-debug] Pair DevTools with `getConnectionStatusLabel()` and the connection banner patterns from the SDK testing utilities when debugging WebSocket reconnects in weak network conditions. For offline message durability, see the [React Native quickstart](/docs/guides/ecosystem/react-native-quickstart) and SDK `createMessageOutbox` transport helper. Related [#related] * [Observability (OTLP)](/docs/reference/observability-otel) — export traces to Jaeger, Tempo, or Langfuse OSS * [Testing integration](/docs/guides/testing-integration) — mock adapters and smoke patterns --- # Agent lifecycle callbacks (/docs/guides/ai-agents/agent-lifecycle) `@fluxy-chat/agent` exposes lifecycle hooks aligned with Vercel AI SDK 7 telemetry phases — use them for logging, billing, guardrails, and OpenTelemetry export. Callback phases [#callback-phases] | Phase | When | | ----------------------------------------------------- | --------------------------- | | `onStart` | Before the first model step | | `onStepStart` | Before each agent step | | `onLanguageModelCallStart` / `onLanguageModelCallEnd` | Around each LLM request | | `onToolExecutionStart` / `onToolExecutionEnd` | Around each tool call | | `onStepEnd` | After each step completes | | `onEnd` | When the run finishes | Agent loop example [#agent-loop-example] ```typescript import { runAgentLoop } from "@fluxy-chat/agent"; await runAgentLoop({ model, tools, messages, onStart: ({ callId, maxSteps }) => { console.log("run", callId, "maxSteps", maxSteps); }, onToolExecutionStart: ({ toolCall }) => { console.log("tool", toolCall.name); }, onEnd: ({ text, usage }) => { console.log("tokens", usage.totalTokens); }, }); ``` SDK telemetry bridge [#sdk-telemetry-bridge] Wire the same events to OTLP or console export: ```typescript import { createTelemetryManager, createOtlpTelemetryIntegration, } from "@fluxy-chat/sdk"; const telemetry = createTelemetryManager(); telemetry.register( createOtlpTelemetryIntegration({ endpoint: process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT!, }), ); ``` See [Observability (OTLP)](/docs/reference/observability-otel). Related [#related] * [Unified reasoning](/docs/guides/unified-reasoning) * [Tool approval HMAC](/docs/guides/ai-agents/tool-approval-hmac) --- # Agent memory (/docs/guides/ai-agents/agent-memory) `@fluxy-chat/agent` includes a provider-agnostic memory API for long-running agents: save facts, search semantically, and inject context into prompts. Quick start (in-memory) [#quick-start-in-memory] ```typescript import { InMemoryMemoryStore, createMemoryTools, } from "@fluxy-chat/agent"; const store = new InMemoryMemoryStore(); const memoryTools = createMemoryTools({ store, defaultUserId: "user_123" }); // Tools: memory_save, memory_search, memory_list, memory_delete ``` Store interface [#store-interface] Implement `AIMemoryStore` for D1, MongoDB, Mem0, or Anthropic memory backends: ```typescript interface AIMemoryStore { save(entry): Promise; search(query): Promise; get(id): Promise; list(options?): Promise; delete(id): Promise; clear(userId?): Promise; } ``` Agent loop integration [#agent-loop-integration] Pass memory tools into your agent and let the model call `memory_save` / `memory_search`: ```typescript import { runAgentLoop } from "@fluxy-chat/agent"; await runAgentLoop({ model, tools: { ...memoryTools, ...otherTools }, messages, }); ``` Related [#related] * [KB + RAG cookbook](/docs/cookbook/kb-rag-agent) * [Room → AI messages](/docs/cookbook/room-to-ai-messages) --- # Agent queue (/docs/guides/ai-agents/agent-queue) When an agent hands off, the Worker can park the conversation in an operator queue. HTTP [#http] * `GET /agent-queue` — open items, SLA timers * `GET /agent-queue/dispositions` — wrap-up codes shared with [handoff](/docs/guides/ai-agents/handoff) Claim an item in the dashboard queue, talk in the same room, then set a disposition. Related [#related] * [Handoff](/docs/guides/ai-agents/handoff) * [Moderation console](/docs/features/moderation-console) --- # Offline eval CLI (/docs/guides/ai-agents/fluxy-eval) fluxy-eval [#fluxy-eval] Offline mode scores a JSON export (status, latency, tools, output snippets) **without** calling the Worker. ```bash pnpm --filter @fluxy-chat/sdk build npx fluxy-eval ./transcript.json ``` Live replay [#live-replay] `fluxy-eval replay` POSTs `stream:false` to `/agents/:id/invoke` with a **member JWT**. It scores the live run against `cases`, then diffs tools / estimated cost / tokens vs `runs[0]` when that baseline exists. This **does** spend model tokens. Hosted is beta. ```bash npx fluxy-eval replay ./transcript.json \ --worker http://127.0.0.1:8787 \ --token "$MEMBER_JWT" \ --room lobby \ --agent assistant \ --prompt "search then answer" ``` `--prompt`, `--room`, and `--agent` can live on the JSON (`prompt`, `roomId`, `agentId`) or env (`FLUXY_PROMPT`, `FLUXY_ROOM_ID`, `FLUXY_AGENT_ID`, `FLUXY_WORKER_URL`, `FLUXY_MEMBER_JWT`). The diff is a numeric/tool-name compare, not a judge model. Streaming mid-turn is not replayed; invoke waits for the completed run payload. File shape [#file-shape] Match a case to a run by `tag` (or `id`). If there is no tag match, the CLI uses the same index in `runs`. Live replay scores every case against the **new** run. ```json { "prompt": "search then answer", "cases": [ { "tag": "search", "requiredTools": ["search"], "expectedStatus": "completed", "maxLatencyMs": 30000, "expectedOutputContains": "ok", "forbiddenOutputContains": "traceback" } ], "runs": [ { "id": "run_1", "tag": "search", "status": "completed", "latency_ms": 812, "estimated_cost": 0.01, "input_tokens": 40, "output_tokens": 80, "tool_calls": [{ "name": "search" }], "output": "looks ok" } ] } ``` Exit code `0` only when every case passes. An empty `cases` array fails. Dashboard evals still exist in the console. Use the CLI in CI on files you exported, and replay only when you intend to pay for a turn. GitHub Actions in this repo runs **offline** scoring on `packages/sdk/fixtures/eval-search.json` after the SDK build. Live `replay` is not in CI: it needs a Worker, a member JWT, and it bills a model turn. --- # AI agents and human handoff (HITL) (/docs/guides/ai-agents/handoff) FluxyChat supports Intercom-Fin-style flows: an in-room AI agent responds until a human operator takes over. Handoff pauses AI invokes, enqueues an agent task with thread context, and resumes AI when the handoff completes. Architecture [#architecture] ```mermaid sequenceDiagram participant User participant Room as Room WS participant AI as AI Agent participant Queue as Agent queue participant Human as Human operator User->>Room: message Room->>AI: invoke (if no active handoff) AI->>Room: reply Human->>Room: POST handoff (take over) Room->>Queue: create + claim task Note over AI: invoke blocked (409) Human->>Room: resolve handoff + disposition Room->>AI: invoke allowed again ``` API [#api] | Method | Path | Role | Action | | ------- | ------------------------- | --------------------- | ------------------------- | | `GET` | `/rooms/{roomId}/handoff` | member+ | Current handoff state | | `POST` | `/rooms/{roomId}/handoff` | moderator/admin/owner | Take over from AI | | `PATCH` | `/rooms/{roomId}/handoff` | moderator/admin/owner | Complete with disposition | Disposition codes: `GET /agent-queue/dispositions` (shared with agent queue wrap-up). SDK [#sdk] ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl, userId, token }); const { handoff } = await client.getRoomHandoff(roomId); await client.requestRoomHandoff(roomId, { agentId: "support_lead", note: "VIP customer — billing issue", }); await client.resolveRoomHandoff(roomId, "resolved"); ``` While handoff is active, `POST /agents/:id/invoke` and `@mention` agent invokes return `409 human_handoff_active`. Dashboard [#dashboard] | Surface | Component / route | | -------------- | ------------------------------------------------------------------------- | | Room chat | `` — Take over / Complete handoff + context preview | | Operator queue | `/agent-queue` — SLA timers, claim, disposition picker | Configure agents under **Agents** (`/agents`). Each agent has model, system prompt, tools, and room allowlist. Configure an in-room agent [#configure-an-in-room-agent] 1. Create agent in dashboard → copy agent id 2. Bind to room via project settings or `@agent` mention rules 3. Test invoke: `POST /agents/{id}/invoke` with `{ "roomId": "…", "prompt": "…" }` Human-in-the-loop patterns [#human-in-the-loop-patterns] | Pattern | When to use | | ------------------ | ---------------------------------------------------------------------------------------------------- | | **Room handoff** | Escalate entire thread from AI to human | | **Tool approvals** | AI proposes an action; human approves via card button ([tool presets](/docs/guides/ai-tool-presets)) | | **Agent queue** | Pool of operators; auto-claim on handoff | Database [#database] * Migration `0056_room_handoffs.sql` * Links to `agent_tasks` via `agent_task_id` Related [#related] * [Agent queue](/docs/guides/ai-agents/agent-queue) — SLA, dispositions, wrap-up * [Custom tools](/docs/guides/ai-agents/tool-approval-hmac) — tools the agent can call * [Thread state](/docs/guides/thread-state) — per-thread KV for agent memory --- # AI agents (/docs/guides/ai-agents) Agents live on the Worker. The browser talks to a room; `@assistant` (or your bot) replies there. * [Handoff](/docs/guides/ai-agents/handoff) * [Memory](/docs/guides/ai-agents/agent-memory) * [Lifecycle](/docs/guides/ai-agents/agent-lifecycle) * [Tool approval (HMAC)](/docs/guides/ai-agents/tool-approval-hmac) * [HITL approval chain](/docs/guides/hitl-approval-chain) * [Room agent token cap](/docs/guides/agent-budget) * [Offline eval CLI](/docs/guides/ai-agents/fluxy-eval) * [Agent queue](/docs/guides/ai-agents/agent-queue) * [Room Decisions](/docs/guides/room-decisions) LLM keys (`GROQ_API_KEY` / `OPENAI_API_KEY`) stay in Worker secrets. Groq model: `openai/gpt-oss-20b`. --- # Tool approval (HMAC) (/docs/guides/ai-agents/tool-approval-hmac) Tool approval with HMAC signatures [#tool-approval-with-hmac-signatures] FluxyChat agents support human-in-the-loop (HITL) tool execution with **HMAC-signed approval requests** — the same mental model as Vercel AI SDK 7 `toolApproval`. Per-tool approval map [#per-tool-approval-map] ```typescript import { resolveToolApproval, type ToolApprovalConfig } from "@fluxy-chat/agent"; const approval: ToolApprovalConfig = { searchWeb: "user-approval", deleteRecord: "denied", sendEmail: async (input) => { if (typeof input === "object" && input && "to" in input) return "approved"; return "denied"; }, }; const decision = await resolveToolApproval(approval, { id: "call_1", name: "searchWeb", input: { query: "weather" }, }); // decision.type === "user-approval" ``` HMAC signing [#hmac-signing] Approval payloads are signed so clients cannot forge approvals: ```typescript import { signApproval, verifyApprovalSignature, hashCanonical, } from "@fluxy-chat/agent"; const secret = process.env.TOOL_APPROVAL_HMAC_SECRET!; const signature = await signApproval({ secret, approvalId: "apr_1", toolCallId: "call_1", toolName: "searchWeb", input: { query: "weather" }, }); const valid = await verifyApprovalSignature({ secret, signature, approvalId: "apr_1", toolCallId: "call_1", toolName: "searchWeb", input: { query: "weather" }, }); ``` Dashboard UI [#dashboard-ui] The console chat embeds `ToolApprovalPanel` when HITL is enabled. Operators approve or deny pending tool calls for the active room. Set `NEXT_PUBLIC_DASHBOARD_LABS=1` and open a room with an agent that declares `user-approval` tools. Worker API [#worker-api] | Method | Path | Purpose | | ----------- | --------------------------------- | -------------------------------------- | | `GET` | `/public/hitl/tap?token=` | Email/Slack one-tap (HMAC, no session) | | `POST` | `/public/hitl/slack` | Slack interactivity (signing secret) | | `GET`/`PUT` | `/api/hitl/slack-user-map` | Slack user id → FluxyChat user | | `GET` | `/api/hitl/approvals/pending` | List pending approvals for a room | | `POST` | `/api/hitl/approvals/:id/respond` | Approve or deny with HMAC token | Related [#related] * [Handoff (HITL)](/docs/guides/ai-agents/handoff) — agent queue and human takeover * [DevTools inspector](/docs/guides/advanced/devtools-inspector) — debug tool calls locally --- # Inbox and notifications (/docs/guides/chat/inbox-notifications) FluxyChat splits **inbox** (cross-room attention) from **notifications** (delivery channels). This guide shows how to wire both in a support or team app. Mental model [#mental-model] | Layer | Purpose | Primary API | | ------------------ | ------------------------------------------ | ------------------------------------------- | | **Inbox items** | Mentions, unread rooms, snooze, follow-ups | `useInbox()` | | **Room watermark** | How far you read inside one room | `markReadRest` / `useChat().markReadLatest` | | **User channel** | Realtime inbox refresh, system alerts | `useNotifications()` / `useUserChannel()` | | **Web push** | Browser notifications when tab is closed | `useWebPush()` | Clearing inbox unread does **not** automatically advance the room watermark — call mark-read explicitly when the user opens a thread. Inbox sidebar [#inbox-sidebar] ```tsx import { useInbox } from "@fluxy-chat/react"; function InboxNav() { const { items, counter, unseen, onItem, reload } = useInbox({ pollIntervalMs: 30_000, realtime: true, onItem: (item) => { toast(`New ${item.kind} in ${item.roomName ?? item.roomId}`); reload(); }, }); return ( ); } ``` See [Inbox model](/docs/core/inbox) for item kinds and counter vs unseen. Mark read when opening a room [#mark-read-when-opening-a-room] ```tsx import { useChat } from "@fluxy-chat/react"; function RoomThread({ roomId }: { roomId: string }) { const { messages, markReadLatest } = useChat(roomId); useEffect(() => { if (messages.length > 0) markReadLatest(); }, [messages.length, markReadLatest]); return ; } ``` After mark-read, refresh inbox summary: ```ts await client.markReadRest(roomId, latestMessageId); await reloadInbox(); ``` User channel events [#user-channel-events] Subscribe to per-user realtime events (inbox pushes, mentions, system alerts): ```tsx import { useNotifications } from "@fluxy-chat/react"; useNotifications({ client, onEvent: (event) => { if (event.type === "inbox_item") reloadInbox(); if (event.type === "mention") playSound(); }, }); ``` Member JWT is required. `useInbox` opens `GET /ws/inbox` (`connectInbox`). The user channel (`/ws/user/:userId`) is still used for non-inbox user events. Web push [#web-push] ```tsx import { useWebPush } from "@fluxy-chat/react"; function PushToggle({ client }: { client: FluxyChatClient }) { const { permission, requestPermissionAndSubscribe } = useWebPush(client); if (permission === "unsupported") return null; return ( ); } ``` Configure VAPID keys on the Worker: ```ini VAPID_PUBLIC_KEY=... VAPID_PRIVATE_KEY=... ``` See [Web push (VAPID)](/docs/core/web-push). Delivery matrix [#delivery-matrix] | Channel | When it fires | Requires | | --------------- | ------------------------------- | -------------------------- | | In-app badge | Inbox counter / unseen | Active session or poll | | User channel WS | Realtime inbox item | Member JWT + WS | | Web push | Mention / DM / configured rules | VAPID + browser permission | | Email / SMS | Tenant integrations | Worker config | Dashboard parity [#dashboard-parity] The hosted console implements this stack at `/inbox` and `/notifications`. Use it as a reference implementation when building your own operator UI. See also [#see-also] * [Inbox model](/docs/core/inbox) * [Notifications](/docs/core/notifications) * [Auth & JWT](/docs/guides/auth-jwt) --- # Interactive cards end-to-end (/docs/guides/chat/interactive-cards) This guide walks through the full card lifecycle: build → send → display → handle button clicks. 1\. Compose a card [#1-compose-a-card] Use the function API from `@fluxy-chat/sdk`: ```ts import { Card, Text, Button, Actions, cardToFallbackText } from "@fluxy-chat/sdk"; const card = Card({ title: "Approve deployment?", children: [ Text({ content: "Production v2.4.1 is ready." }), Actions({ children: [ Button({ id: "approve-deploy", label: "Approve", style: "primary" }), Button({ id: "reject-deploy", label: "Reject", style: "danger" }), ], }), ], }); console.log(cardToFallbackText(card)); // plain-text fallback for SMS/email ``` See [Card Element Builder](/docs/guides/card-builder) for all element types. 2\. Send to a room [#2-send-to-a-room] ```ts import { FluxyChatClient } from "@fluxy-chat/sdk"; const client = new FluxyChatClient({ baseUrl: process.env.NEXT_PUBLIC_FLUXYCHAT_WORKER_URL!, userId: "bot_ops", token: memberJwt, }); const message = await client.sendCard("prod-alerts", card); ``` REST equivalent: ```http POST /api/cards/send Authorization: Bearer Content-Type: application/json { "roomId": "prod-alerts", "card": { "type": "card", "title": "Approve deployment?", "children": [] } } ``` The Worker stores the card JSON inside the message body with `` markers so clients can parse structured content while still showing fallback text. 3\. Render in React [#3-render-in-react] Cards arrive as messages. Parse the card payload or use the dashboard **Card Builder** (`/playground`) to preview layouts. ```tsx import { useChat } from "@fluxy-chat/react"; import { isCardElement } from "@fluxy-chat/sdk"; function Room({ roomId }: { roomId: string }) { const { messages } = useChat(roomId); return (
    {messages.map((m) => (
  • {m.card && isCardElement(m.card) ? ( ) : ( m.content )}
  • ))}
); } ``` 4\. Handle button actions [#4-handle-button-actions] When a user clicks a card button, the client emits a structured event on the room WebSocket (`type: card_action`) with the button `id` and source message id. Server-side, register a webhook or agent handler: ```ts // Worker webhook / bot handler (pseudo) if (event.type === "card_action" && event.actionId === "approve-deploy") { await triggerDeploy(event.roomId); await client.sendMessage(event.roomId, "✅ Deployment approved."); } ``` For approval gates that require human confirmation, combine cards with [AI tool presets](/docs/guides/ai-tool-presets) so destructive actions pause until a moderator approves. 5\. Test locally [#5-test-locally] 1. Start Worker: `pnpm --filter @fluxychat/worker dev` 2. Open dashboard **Card Builder** → send to `dev-local-general` 3. Click buttons and verify webhook/agent logs See also [#see-also] * [Card Element Builder](/docs/guides/card-builder) * [Adapter pattern](/docs/guides/adapter-pattern) — platform-specific card rendering * [Testing integrations](/docs/guides/testing-integration) — mock client for Vitest --- # Contributing (/docs/guides/ecosystem/contributing) FluxyChat is a monorepo (Worker + dashboard + SDK packages). Read the root [`CONTRIBUTING.md`](https://github.com/AlessandroFare/fluxychat/blob/main/CONTRIBUTING.md) for the full guide. Quick start [#quick-start] ```bash git clone cd Chat pnpm install pnpm --filter @fluxy-chat/worker dev pnpm --filter @fluxy-chat/dashboard dev ``` Verify: `pnpm first-message` against `http://127.0.0.1:8787`. Good first issues [#good-first-issues] Look for GitHub labels: * `good first issue` — scoped tasks with pointers in the issue body * `help wanted` — design agreed, needs code What we merge quickly [#what-we-merge-quickly] * Bug fixes with tests * Docs corrections aligned with current Worker routes * SDK DX improvements (types, error messages, examples) * Dashboard operator workflows (compliance, bridges, inbox) What we defer [#what-we-defer] * Marketing copy and case studies (see roadmap Fase 4 marketing) * Stripe billing production wiring (requires Stripe Business) * Paid SOC 2 attestation (product controls are in `/soc2`) Pull requests [#pull-requests] Use the PR template checklist. Link a roadmap ID (`MO-*`, `DX-*`, `MD-*`) when applicable. Code of conduct [#code-of-conduct] Be respectful in issues and reviews. Security issues: report privately, not in public issues. --- # Kotlin and Swift quickstart (/docs/guides/ecosystem/kotlin-swift-quickstart) FluxyChat ships starter native SDKs for teams that do not use React Native or Flutter: | Platform | Package | Status | | ------------- | ------------------------------ | ------------------------------------ | | Android / JVM | `packages/kotlin-sdk` | REST: list/send messages, list rooms | | iOS / macOS | `packages/swift-sdk` | REST via async/await | | Flutter | `@fluxy-chat/flutter-sdk` | Full client + WS | | React Native | `@fluxy-chat/react-native-sdk` | Hooks + reconnect | Kotlin (Android) [#kotlin-android] ```kotlin val client = FluxyChatClient( FluxyChatConfig( apiUrl = "https://your-worker.workers.dev", wsUrl = "wss://your-worker.workers.dev", projectId = "proj_id", token = jwt, ), ) client.sendMessage("room-1", "Hello") ``` See [`packages/kotlin-sdk/README.md`](https://github.com/AlessandroFare/fluxychat/blob/main/packages/kotlin-sdk/README.md). Swift (iOS) [#swift-ios] ```swift let client = FluxyChatClient(config: FluxyChatConfig( apiUrl: "https://your-worker.workers.dev", wsUrl: "wss://your-worker.workers.dev", projectId: "proj_id", token: jwt )) let data = try await client.sendMessage(roomId: "room-1", content: "Hello") ``` Run `swift test` in `packages/swift-sdk`. WebSocket [#websocket] ```kotlin client.connectRoom("room-1", listener) client.webSocket.sendMessage("Hello") ``` ```swift client.connectRoom("room-1", listener: listener) try await client.webSocket.sendMessage("Hello") ``` Frames match `@fluxy-chat/protocol` (`message`, `typing`, `ping`, `pong`, …). Import legacy history [#import-legacy-history] Admin migration: [Migrate from Pusher](/docs/guides/migrate-from-pusher) + `pnpm import-chat-history`. See also [#see-also] * [React Native quickstart](/docs/guides/ecosystem/react-native-quickstart) * [Contributing](/docs/guides/ecosystem/contributing) (monorepo setup) --- # Optional external services (/docs/guides/ecosystem/optional-integrations) Optional external services [#optional-external-services] FluxyChat runs on Cloudflare Workers. Most features work **without** third-party accounts. Connect external services only when you need that capability. *** Do I need any of these? [#do-i-need-any-of-these] | Service | Required? | When to set up | | --------------------- | -------------------- | ------------------------------------------------ | | **Cloudflare** | Yes | Always — Workers, D1, R2 | | **Clerk** | Optional | Hosted dashboard sign-in | | **Stripe** | Optional | Paid billing / checkout | | **Turnstile** | Recommended for prod | Public `/demo`, `/embed`, guest rooms | | **Langfuse** | Optional | Agent trace dashboards, eval datasets | | **Upptime** | Optional | Public status page at `status.yourdomain.com` | | **Algolia DocSearch** | Optional | Full-text search on marketing docs | | **Synapse (Matrix)** | Optional | Matrix federation bridge | | **Meta WhatsApp** | Optional | WhatsApp Business + structured forms | | **RCS provider** | Optional | RCS outbound (paid aggregator) | | **LiveKit** | Optional | WebRTC voice/video SFU | | **ClamAV** | Optional | Virus scan on uploads (EICAR blocked without it) | | **Tavily / SearXNG** | Optional | Agent web search tools | If you only use **private rooms + dashboard + agents**, you can skip everything except Cloudflare (and Clerk/Stripe if you use hosted billing). *** Turnstile (guest anti-spam) [#turnstile-guest-anti-spam] **Purpose:** Bot protection on public demo, embed widget, and guest room join. **Account:** Free at [dash.cloudflare.com](https://dash.cloudflare.com) → Turnstile → Add site. **Steps:** 1. Create a Turnstile widget → copy **Site key** and **Secret key**. 2. Worker secrets: `TURNSTILE_SECRET_KEY`, `TURNSTILE_SITE_KEY`. 3. Enable: `PUBLIC_GUEST_TURNSTILE_REQUIRED=true` (embed) and/or demo Turnstile flow. 4. Dashboard build env: `NEXT_PUBLIC_TURNSTILE_SITE_KEY` (same site key). **Verify:** Open `/embed` — badge shows Turnstile required. Complete widget → guest session mints. See also: [Public demo hardening](/docs/cookbook/public-demo-hardening). *** Langfuse (agent observability) [#langfuse-agent-observability] **Purpose:** Traces, scores, and eval datasets for agent runs. **Account:** Self-host [Langfuse OSS](https://langfuse.com) on a VPS (free license) or Langfuse Cloud. **Steps:** 1. Deploy Langfuse → note **public key**, **secret key**, **host URL**. 2. In FluxyChat console: **Agents → Observability** → **Apply Langfuse preset** (or `POST /otel/configs/langfuse`). 3. Run an agent in a room → traces appear in Langfuse. **You do not** paste Langfuse keys into Worker env if you use the dashboard OTel config store. See: [OpenTelemetry reference](/docs/reference/observability-otel). *** Upptime (public status page) [#upptime-public-status-page] **Purpose:** Public uptime history (`status.fluxychat.com` style). **Account:** GitHub (free). **Steps:** 1. Copy `.upptime/config.json` from the monorepo into a **new repo** (e.g. `yourorg/status`). 2. Enable GitHub Pages on that repo. 3. Point DNS `status.yourdomain.com` → GitHub Pages. 4. Dashboard: `NEXT_PUBLIC_STATUS_PAGE_URL=https://status.yourdomain.com` (links from Settings → Status). **Verify:** `pnpm run check:upptime` in CI validates config shape. *** Algolia DocSearch (docs search) [#algolia-docsearch-docs-search] **Purpose:** Search box on `/docs` and `/guides` marketing pages. **Account:** Apply at [docsearch.algolia.com](https://docsearch.algolia.com/apply) (free for open source). **Steps:** 1. After approval, Algolia crawls your docs site weekly. 2. Dashboard env: `NEXT_PUBLIC_ALGOLIA_APP_ID`, `NEXT_PUBLIC_ALGOLIA_API_KEY`, `NEXT_PUBLIC_ALGOLIA_INDEX_NAME`. **Without Algolia:** Local guide search still works on `/guides` and `/docs`. *** Matrix / Synapse (federation bridge) [#matrix--synapse-federation-bridge] **Purpose:** Bridge Matrix rooms ↔ FluxyChat rooms. **Account:** Self-host [Synapse](https://matrix-org.github.io/synapse/) on a VPS. **Steps:** 1. Deploy Synapse + register appservice pointing at your Worker webhook. 2. FluxyChat console: **Bridges → Matrix** → create bridge → copy **Bearer token**. 3. Synapse config: `Authorization: Bearer as_…` on `POST /webhooks/matrix/:bridgeId`. See repo runbook: `docs/MATRIX_SYNAPSE_RUNBOOK.md`. *** WhatsApp Business (structured forms) [#whatsapp-business-structured-forms] **Purpose:** Multi-step forms on WhatsApp → normalized room messages. **Account:** [Meta Business](https://developers.facebook.com/) + WhatsApp Business API. **Steps:** 1. Create app → WhatsApp product → phone number ID + permanent token. 2. Worker: `WHATSAPP_PHONE_NUMBER_ID`, `WHATSAPP_ACCESS_TOKEN`, `WHATSAPP_VERIFY_TOKEN`. 3. Register webhook URL on Meta → verify token matches. 4. Console: **Bridges → Forms** to design schemas. **Without credentials:** Dry-run mode saves payloads for testing (no Meta delivery). *** RCS (Rich Communication Services) [#rcs-rich-communication-services] **Purpose:** RCS outbound messages and forms (16th channel). **Account:** Paid — Twilio or MessageBird RCS API. **Status:** Adapter scaffold in repo; **requires vendor account** before production send. **Steps when ready:** 1. Obtain RCS sender from vendor. 2. Worker: `RCS_OUTBOUND_URL` (+ optional `RCS_API_KEY`) pointing at vendor JSON API. See: [Platform status — RCS](/docs/features/platform-status#rcs-17). *** LiveKit (voice / video SFU) [#livekit-voice--video-sfu] **Purpose:** WebRTC rooms — voice huddles, calls (not on Workers CPU). **Account:** [LiveKit Cloud](https://livekit.io) free tier or self-host. **Steps:** 1. Create project → API key, secret, `wss://` URL. 2. Worker secrets: `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `LIVEKIT_URL`. 3. Client: `useLiveKitToken` from `@fluxy-chat/react`. See: [LiveKit integration](/docs/integrations/livekit). *** ClamAV (media virus scan) [#clamav-media-virus-scan] **Purpose:** Scan uploads beyond built-in EICAR block. **Account:** Self-host ClamAV HTTP API (optional). **Steps:** 1. Deploy `clamav` + HTTP wrapper on internal network. 2. Worker: `CLAMAV_HTTP_URL`, optional `CLAMAV_HTTP_TOKEN`. See: [Media pipeline](/docs/features/media-pipeline). *** Agent web search (Tavily / SearXNG) [#agent-web-search-tavily--searxng] **Purpose:** `[web-search]` and deep research tools in agent rooms. **Account:** [Tavily](https://tavily.com) free tier and/or self-hosted SearXNG (public HTTPS). **Steps:** 1. Tavily: `TAVILY_API_KEY` on Worker. 2. SearXNG: expose HTTPS endpoint + Basic Auth → `SEARXNG_BASE_URL`, user/pass. No account needed if you disable web-search tools in agent config. --- # React Native quickstart (/docs/guides/ecosystem/react-native-quickstart) Use `@fluxy-chat/react-native-sdk` for iOS and Android chat with the same Worker backend as the web SDK. Install [#install] ```bash pnpm add @fluxy-chat/react-native-sdk @fluxy-chat/protocol ``` Peer dependencies: `react` 18+, `react-native` 0.72+. Configure the client [#configure-the-client] ```tsx import { FluxyChatClient } from "@fluxy-chat/react-native-sdk"; const client = new FluxyChatClient({ baseUrl: "https://api.fluxychat.com", userId: "user_123", token: memberJwtFromYourBackend, }); ``` Mint JWTs on your server — never ship admin keys in the mobile app. Chat hook [#chat-hook] ```tsx import { useChat } from "@fluxy-chat/react-native-sdk"; function RoomScreen({ roomId }: { roomId: string }) { const { messages, sendMessage, loadHistory, loadMore, connected, connectionStatus, } = useChat({ roomId, client, historyLimit: 50, replay: "connect", replayHistoryOnReconnect: true, }); return ( <> {connectionStatus} String(m.id)} renderItem={({ item }) => {item.content}} />