From 54866b798f19aafc88d90eb52c1d3a809ed0d95e Mon Sep 17 00:00:00 2001 From: ankurmans <12939357+ankurmans@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:47:54 +0300 Subject: [PATCH] Answer the owner-funded text AI with Anthropic first and Groq as fallback The writing tools, the support and account assistants, Reply Rules and reader translations go through one module, lib/platform-ai.js: Claude Haiku 5.5 for routine text and classification, Sonnet 5.5 for social post drafts and the account assistant, Groq GPT-OSS-20B when Anthropic can't answer, Workers AI only where neither key may be used. Briefings' own keys stay apart; embeddings and images stay on Workers AI. On FlockStack Cloud both providers wait for the 30 days' sub-processor notice (AI_PROVIDERS_NOTICE_SENT_ON), so nothing changes until the owner sets it. The privacy policy, sub-processors and regions pages say what is true before and after. Per-account provider, model, token and cost counts are kept with no text (AiUsage.spend). --- .env.example | 24 +- PORT-PLAN.md | 4 +- README.md | 34 +- app/(app)/campaigns/[id]/collaborate/page.js | 4 +- app/(app)/campaigns/[id]/edit/page.js | 4 +- app/(app)/campaigns/[id]/page.js | 4 +- app/(site)/privacy/page.js | 11 +- components/EditorRich.jsx | 2 +- components/FormReaderSettings.jsx | 2 +- components/FormReplyRules.jsx | 4 +- components/MenuFormat.jsx | 2 +- components/PanelAccountAssistant.jsx | 4 +- components/marketing/PanelSupportChat.jsx | 2 +- components/marketing/SupportChat.jsx | 6 +- docs/ACCOUNT-ASSISTANT.md | 8 +- docs/READER-LANGUAGES.md | 4 +- docs/RELEASE-QA.md | 2 +- docs/REPLY-RULES.md | 4 +- lib/account-assistant.js | 24 +- lib/actions/account-assistant.js | 2 +- lib/actions/ai.js | 24 +- lib/actions/readers.js | 4 +- lib/actions/reply-rules.js | 2 +- lib/ai-usage.js | 29 ++ lib/ai-writing.js | 2 +- lib/ai.js | 30 +- lib/briefings/prices.js | 2 + lib/briefings/providers.js | 2 +- lib/docs/regions.js | 33 +- lib/legal.js | 50 ++- lib/marketing/support-assistant.js | 50 ++- lib/marketing/support-config.js | 17 +- lib/marketing/support-prompt.js | 2 +- lib/plans.js | 2 +- lib/platform-ai.js | 240 +++++++++++++ lib/reader-translation.js | 8 +- lib/reply-rules.js | 37 +- lib/subprocessors.js | 24 +- models/AiUsage.js | 4 +- tests/account-assistant.test.mjs | 2 +- tests/ai-providers-notice.test.mjs | 90 +++++ tests/legal.test.mjs | 2 +- tests/platform-ai.test.mjs | 352 +++++++++++++++++++ tests/public-worker.test.mjs | 6 +- tests/support-chat.test.mjs | 2 +- tests/support-email.test.mjs | 11 +- 46 files changed, 975 insertions(+), 203 deletions(-) create mode 100644 lib/platform-ai.js create mode 100644 tests/ai-providers-notice.test.mjs create mode 100644 tests/platform-ai.test.mjs diff --git a/.env.example b/.env.example index 830ccc65..84598324 100644 --- a/.env.example +++ b/.env.example @@ -100,17 +100,31 @@ POSTHOG_SESSION_REPLAY= # ─── Support assistant (FlockStack Cloud only) ────────────────────────────────── -# The help chat answers from FlockStack's docs with Cloudflare Workers AI, the Worker's "ai" binding in wrangler.jsonc -# (README, Support assistant). Without the binding it doesn't render. A self-hosted server ignores both. -# Answers a day per Worker, all visitors together. Default 300, which fits Workers AI's free daily allocation. +# The help chat answers from FlockStack's docs with the text AI below (README, Support assistant). Without one it doesn't render. +# A self-hosted server ignores it. +# Answers a day per Worker, all visitors together. Default 300. SUPPORT_DAILY_LIMIT= # Where "Email a human" sends a conversation. Default hello@flockstack.io, the address on the legal pages. SUPPORT_EMAIL= # ─── AI writing tools ─────────────────────────────────────────────────────────── -# The editor's rewrite, subject line, preview text and social post tools run on Cloudflare Workers AI, the Worker's "ai" binding -# in wrangler.jsonc (README, AI writing tools). Without the binding the buttons don't render. On FlockStack Cloud each plan +# ─── Text AI ──────────────────────────────────────────────────────────────────── + +# The editor's writing tools, the support and account assistants, Reply Rules and reader-requested translations (README, Text AI). +# Your own Anthropic key first, your own Groq key if Anthropic can't answer, Workers AI (the "ai" binding in wrangler.jsonc) when +# neither is set. On FlockStack Cloud neither key is used until AI_PROVIDERS_NOTICE_SENT_ON in lib/legal.js is 30 days old. +# These are not a Briefing's keys: those are each owner's own. +ANTHROPIC_API_KEY= +GROQ_API_KEY= +# Optional model names. Defaults claude-haiku-5-5, claude-sonnet-5-5 and openai/gpt-oss-20b. +AI_MODEL_FAST= +AI_MODEL_STRONG= +AI_MODEL_FALLBACK= +# true sends all of it back to Workers AI. +AI_PROVIDERS_DISABLED= + +# Without any of the above the buttons don't render. On FlockStack Cloud each plan # has its daily requests in lib/plans.js; a self-hosted server has none, unless this is set. # AI requests a day per account, counted in UTC days. 0 turns the tools off. Empty: no limit. AI_DAILY_LIMIT= diff --git a/PORT-PLAN.md b/PORT-PLAN.md index b89d47d4..5fd9dc1a 100644 --- a/PORT-PLAN.md +++ b/PORT-PLAN.md @@ -122,11 +122,11 @@ Customers' own archive domains and shared addresses' DNS, native on Cloudflare. ## Support assistant (branch feat/support-assistant) -A help chat on FlockStack's own pages, FlockStack Cloud only (README, Support assistant), answering from the docs with Workers AI. +A help chat on FlockStack's own pages, FlockStack Cloud only (README, Support assistant), answering from the docs with the text AI (`lib/platform-ai.js`: Anthropic, then Groq, then Workers AI). - **Pieces.** `lib/marketing/support-corpus.js` reads the docs pages' and legal pages' server components as text (`support-page-text.js`, without react-dom/server), adds one chunk per API endpoint, the prices and the FAQ, and indexes them with BM25 in memory (`support-search.js`). `support-prompt.js` holds the rules and reads the model's answer and citations back; `support-context.js` the signed-in account's few facts; `support-assistant.js` the two routes' handlers, reached through `siteExtensions.supportAssistant` from `app/api/support/chat` and `app/api/support/email`. The UI is `components/marketing/SupportChat.jsx` (renders only with the `AI` binding) and `PanelSupportChat.jsx`. - **Choices.** Qwen3 30B A3B, then gpt-oss-20b, through the default AI Gateway with logs off. No Vectorize: about 300 chunks, scored in well under a millisecond. Nothing a person types is stored; the legal placeholders for it are filled. -- **Not done.** A real Workers AI call (stub only in tests). Streaming answers. Per-region wording in answers beyond what the docs say. An admin view of how often it says "I don't know" (it would need counting without the text). +- **Not done.** A real model call (stubs only in tests). Streaming answers. Per-region wording in answers beyond what the docs say. An admin view of how often it says "I don't know" (it would need counting without the text). ## Pricing v2 (branch feat/pricing-v2) diff --git a/README.md b/README.md index 5e6f0a44..2db22c25 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ FlockStack is a newsletter app: write an issue, send it to your list, publish it - **Edit a sent issue's web page.** Fix a typo or a link after sending: "Edit web version" on a sent issue's page (or `update_published_issue`) changes its title, subtitle, body, pictures, tags and search settings on the website and in the RSS feed, keeping its address and date. Emails already sent are not changed, and neither are the counts, the audience or who received it. The page as it was is kept in the issue's version history (the last 30). - **A content calendar.** Plan newsletter issues and the LinkedIn posts around them in one place: each item has its copy, hook, call to action, the reader's problem, funnel stage and pillar, references and private notes, and visuals picked from the media library with alt text. Group items in batches, give them planned days in a month, week or agenda (or move them with a form instead of dragging), keep an undated backlog, and set a recurring pattern (TOFU, MOFU, BOFU, TOFU, TOFU, or your own) that places items only when you apply it. Planned items are drawn apart from campaigns that are really scheduled or sent, and planning never sends, schedules or publishes anything. An item goes to review, and only the owner approves; editing an approved item takes the approval back and says so. Every change keeps a revision. LinkedIn is manual: copy the post, download the visuals, post it, and record its address. The REST API and MCP do all of it (`create_content_item`, `get_content_plan`, `request_batch_review` and the rest, listed in the [content calendar guide](docs/CONTENT-CALENDAR.md)), safe to repeat with an `externalId`, and a drafts only key can run a whole calendar without being able to send. - **Subject line tests and resends.** Try up to 4 subject lines on a slice of the audience; after the wait the winner, by unique clicks or opens, goes to everyone else by itself. Once an issue is out, send it again with a new subject to the readers who didn't open it, or didn't click, a day later by default. -- **AI writing tools** (Cloudflare Workers AI): select text in the editor and rewrite, shorten, expand, fix or translate it, or change its tone; get five subject lines and three preview texts from the draft, and send subject lines to the subject line test; draft LinkedIn, X, Facebook, Threads and Bluesky posts for an issue, to edit and post yourself. You see a suggestion first and nothing changes until you accept it. Each plan has a daily allowance, and a server without Workers AI hides the buttons ([AI writing tools](#ai-writing-tools)). +- **AI writing tools** (Anthropic, with Groq as the fallback): select text in the editor and rewrite, shorten, expand, fix or translate it, or change its tone; get five subject lines and three preview texts from the draft, and send subject lines to the subject line test; draft LinkedIn, X, Facebook, Threads and Bluesky posts for an issue, to edit and post yourself. You see a suggestion first and nothing changes until you accept it. Each plan has a daily allowance, and a server with no text AI (no Anthropic or Groq key, no Workers AI binding) hides the buttons ([AI writing tools](#ai-writing-tools)). - **Editor and dashboard tools.** Version history for drafts (the last 30 states, restorable), a live word count and read time, find and replace (Cmd/Ctrl+F), a media library with folders and a search by name, free Unsplash photos and GIPHY GIFs where the server has a key ([Stock photos](#stock-photos), [GIFs](#gifs)), a calendar of scheduled and sent issues, a Cmd/Ctrl+K command palette, bulk actions on campaigns (delete drafts, list, unlist, move), a link-in-bio page at `/links` on each newsletter's website, tag colors, and a dashboard that installs as an app from the browser (a manifest and icons only: no service worker, nothing works offline). All of it is in the REST API and MCP too, except the palette and the install, which are pages. - **Imports from beehiiv, Substack, Mailchimp, Kit, MailerLite, Buttondown, Ghost and EmailOctopus.** One CSV import, not a preset for each platform: it recognizes the column names their exports use (and the statuses and dates in them), so the file needs no editing, one CSV at a time (unzip an archive first; Mailchimp gives one file for each status). The names come from each platform's documentation or open-source migration tools and are tested against files built from them (`tests/import-presets.test.mjs`), not against live exports: import a few rows first. Past posts have their own import, from Substack, beehiiv, WordPress and Ghost archives. Paid subscriptions are not moved. - **Your archive comes too.** Upload a Substack, beehiiv, WordPress, Ghost or Mailchimp export (for Mailchimp, a ZIP of the campaigns CSV and each campaign's HTML): every published post becomes an issue on your website on its original date, with its pictures copied and no email sent, and each old address redirects to its new page. @@ -134,7 +134,7 @@ The EU Worker starts from nothing: `wrangler secret put --env eu` for eac - **Billing:** `POLAR_ACCESS_TOKEN` and `POLAR_WEBHOOK_SECRET` (or `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET`), and for selling, `STRIPE_CONNECT_SECRET_KEY` and `STRIPE_PAYMENTS_WEBHOOK_SECRET`. One Polar or Stripe webhook can feed both Workers, or the EU Worker can have its own endpoint. - **Optional:** `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` (add `https://eu.flockstack.io/api/auth/callback/google` to the client), `APPLE_CLIENT_ID`, `APPLE_TEAM_ID`, `APPLE_KEY_ID` and `APPLE_PRIVATE_KEY` (the same Services ID and key as the US Worker, see [Apple sign-in](#optional)), `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`, `REGION_URL_US` and `REGION_URL_EU` (default to the two addresses above). - **Analytics:** `POSTHOG_KEY`, the same project key as on the US Worker (see Product analytics below). -- **Support assistant:** nothing to set: `env.eu` has its own Workers AI binding. `SUPPORT_DAILY_LIMIT` and `SUPPORT_EMAIL` are optional (see Support assistant below). +- **Support assistant:** nothing to set beyond the text AI keys below: `env.eu` has its own Workers AI binding for the days before they may be used. `SUPPORT_DAILY_LIMIT` and `SUPPORT_EMAIL` are optional (see Support assistant below). **Webhooks and the other region.** A provider configured once can deliver to both Workers, so each gets events for accounts it doesn't have. Signatures are checked exactly as before. An event for a subscription, customer, connected account, tenant or message with no account in this region is acknowledged with a 2xx and logged at info level (`no such account in this region`), with no alert and no retry. A real failure, such as Polar being unreachable, still answers 5xx and alerts. @@ -213,9 +213,9 @@ The choice is the first-party cookie `fs_consent` (`accepted` or `declined`, 12 A "Help" button on FlockStack's own pages opens a chat that answers from FlockStack's docs. Like the analytics, it is not part of the open source and reaches the shared pages only through the site extensions (`SupportChat`, `siteExtensions.supportAssistant`, `siteExtensions.supportChatPath`, which is `/?support`); the defaults add nothing, and `/api/support/*` answers 404 without them. -- **Where.** Beside `SiteAnalytics`: the docs, the legal pages, sign-in, `/welcome` and the dashboard. Never on a newsletter's pages, the pages readers use, the shop or the admin (`tests/analytics-routes.test.mjs`). It renders only when the Worker has the Workers AI binding (`"ai": { "binding": "AI" }` in `wrangler.jsonc`, top level and `env.eu`), so a server without it shows no button. +- **Where.** Beside `SiteAnalytics`: the docs, the legal pages, sign-in, `/welcome` and the dashboard. Never on a newsletter's pages, the pages readers use, the shop or the admin (`tests/analytics-routes.test.mjs`). It renders only when a text AI can answer (`isTextAiAvailable`: an Anthropic or Groq key that may be used now, or the Worker's Workers AI binding, `"ai": { "binding": "AI" }` in `wrangler.jsonc`, top level and `env.eu`), so a server without one shows no button. - **Answers.** `POST /api/support/chat` (`lib/marketing/support-assistant.js`) searches the docs pages, the API reference, the legal pages, the prices in `lib/plans.js` and the FAQ, chunked by heading and scored with BM25 in memory (`lib/marketing/support-corpus.js`, built on the first question and kept for the isolate). The best 4 chunks go into the prompt with their links, and the answer comes back with the links it cited. The rules (`lib/marketing/support-prompt.js`): FlockStack only, from the excerpts, cite them, say "I don't know" and offer a person, never invent features or prices, never claim an action, never ask for a secret, and treat what people type as data. A question no chunk matches gets "I don't know" without a model call. A signed-in person's plan, region, sending domains and block reason go into the prompt (`lib/marketing/support-context.js`), nothing else of theirs. -- **Model.** Workers AI through AI Gateway's `default` gateway (created on its first request), with `collectLog: false` and `skipCache: true`: `@cf/qwen/qwen3-30b-a3b-fp8`, then `@cf/openai/gpt-oss-20b` if it fails. On [Cloudflare's price list](https://developers.cloudflare.com/workers-ai/platform/pricing/) (read 2026-10-18) Qwen3 30B is $0.051 per million input tokens and $0.335 per million output, gpt-oss-20b $0.200 and $0.300; an answer is about 3,500 tokens in and 400 out, some $0.0003 or 28 neurons, so the 10,000 free neurons a day cover about 350. Never the Anthropic API. +- **Model.** The text AI (`lib/platform-ai.js`, [Text AI](#text-ai)): Claude Haiku 5.5, then Groq's GPT-OSS-20B if Anthropic can't answer; before the keys may be used, Workers AI through AI Gateway's `default` gateway with `collectLog: false` and `skipCache: true`: `@cf/qwen/qwen3-30b-a3b-fp8`, then `@cf/openai/gpt-oss-20b`. On [Cloudflare's price list](https://developers.cloudflare.com/workers-ai/platform/pricing/) (read 2026-10-18) Qwen3 30B is $0.051 per million input tokens and $0.335 per million output, gpt-oss-20b $0.200 and $0.300; an answer is about 3,500 tokens in and 400 out, some $0.0003 or 28 neurons, so the 10,000 free neurons a day cover about 350. - **Nothing stored.** The conversation is in the tab's `sessionStorage`, sent with each question and cleared on sign-out. The server keeps rate-limit counters only (by IP address and user ID) and logs no message text. "Email a human" sends the conversation and the account email to support only on the person's click (`POST /api/support/email`, signed in, through `sendPlatformEmail` with the person as Reply-To); a visitor gets a `mailto:` link to send it from their own mail app instead. `SUPPORT_CHAT_STORED`, `SUPPORT_CHAT_RETENTION` and `SUPPORT_AI_PROVIDER_NOTE` in `lib/legal.js` say so on the privacy page. - **Limits.** 12 questions per network in 10 minutes and 60 a day, 30 per person an hour and 80 a day, `SUPPORT_DAILY_LIMIT` a day per Worker for everyone together, and 3 emails to support per person an hour, 6 a day. Questions up to 1,000 characters, 20 messages a conversation. - **Analytics.** `support_opened` and `support_answered`, counts with no properties; the panel has `ph-no-capture` and session recording blocks `[data-support-chat]`. @@ -225,7 +225,7 @@ A "Help" button on FlockStack's own pages opens a chat that answers from FlockSt | `SUPPORT_DAILY_LIMIT` | Answers a day per Worker, everyone together. Default 300. | | `SUPPORT_EMAIL` | Where "Email a human" sends. Default `hello@flockstack.io`, the address on the legal pages. | -**Not checked:** a real Workers AI call. The tests replace the binding with a stub, so the answer's quality, the exact output shape of each model (the code reads `response`, `choices` and the Responses API's `output`), Qwen3's `/no_think` switch on Workers AI and the gateway's options are untested against Cloudflare. +**Not checked:** a real model call. The tests replace the providers and the binding with stubs, so the answer's quality, the exact output shape of each Workers AI model (the code reads `response`, `choices` and the Responses API's `output`), Qwen3's `/no_think` switch and the gateway's options are untested against Cloudflare, and Anthropic's and Groq's answers against the real APIs. ## Audio versions @@ -285,15 +285,33 @@ No call to ElevenLabs was made: the tests stub it. So the exact bytes of a real ## AI writing tools -The editor's AI tools run on Workers AI, the same way as the support assistant but apart from it (`lib/ai.js`, no import of `lib/marketing`, which is FlockStack Cloud's): through AI Gateway's `default` gateway with `collectLog: false` and `skipCache: true`, `@cf/qwen/qwen3-30b-a3b-fp8`, then `@cf/openai/gpt-oss-20b` if it fails. Never the Anthropic API. +The editor's AI tools run on the text AI ([Text AI](#text-ai)), the same way as the support assistant but apart from it (`lib/platform-ai.js`, no import of `lib/marketing`, which is FlockStack Cloud's): Claude Haiku 5.5 for rewrites, subject lines and preview text, Claude Sonnet 5.5 for social post drafts, and Groq's GPT-OSS-20B if Anthropic can't answer. Without a key that may be used, the same requests go to Workers AI through AI Gateway's `default` gateway with `collectLog: false` and `skipCache: true`. - **What they do.** Select text, then the sparkle button in the format menu: rewrite, shorten, expand, fix grammar, friendlier, more formal, punchier, or translate into 13 languages. "Suggest subject lines" and "Suggest preview text" sit beside the two fields (five subject lines and three preview texts from the saved draft; "Test it" adds a subject to the subject line test), and "Draft social posts" is in the campaign's menu and on a sent issue's report (a LinkedIn post and a post for X by default, or any of LinkedIn, X, Facebook, Threads and Bluesky, each cut to its limit with the issue's page link at the end when it has one). A suggestion is a preview the writer replaces the selection with, adds below, tries again or discards; no tool changes the draft by itself, and nothing is ever posted. - **What the model sees.** Only the text selected, or the issue's draft (Markdown of its HTML, 12,000 characters at most), between markers the rules call data. Never a contact, an address or anything else of a reader, and nothing is kept: the server stores a counter per account per UTC day (`models/AiUsage.js`, deleted after two weeks), not the text. `AI_WRITING_STORED` in `lib/legal.js` says so on the privacy page. - **Limits.** Requests a day per account: Starter 20, Growth 60, Pro 150, Scale 300, Max 600 (`aiRequestsPerDay` in `lib/plans.js`). The count goes up before the model is asked and comes back down when neither model answered, so a failed request is free; past the limit the answer is `ai_daily_limit` (429) with the hours until midnight UTC. A self-hosted server has no limit unless `AI_DAILY_LIMIT` is set. -- **Hidden without Workers AI.** `"ai": { "binding": "AI" }` in `wrangler.jsonc` (top level and `env.eu`). A server without it shows no AI button, and the actions answer `unavailable`. The buttons also need a plan. +- **Hidden without a text AI.** An Anthropic or Groq key (below), or `"ai": { "binding": "AI" }` in `wrangler.jsonc` (top level and `env.eu`). A server with neither shows no AI button, and the actions answer `unavailable`. The buttons also need a plan. - **API and MCP.** `rewrite_text`, `suggest_subject_lines`, `suggest_preview_text`, `draft_social_posts` and `get_ai_usage`. Optional image generation is available through `generate_image`; audio versions use the separate operator-configured audio flow. -**Not checked:** a real Workers AI call. The tests stub the binding, so the quality of each tool's output, the prompts' effect on Qwen3 and gpt-oss and the counts of tokens a request costs are untested against Cloudflare. +**Not checked:** a real model call. The tests stub the providers and the binding, so the quality of each tool's output, the prompts' effect on each model and the counts of tokens a request costs are untested against the live APIs. + +## Text AI + +Everything FlockStack pays for itself in text goes through one module, `lib/platform-ai.js` (`askText`): the writing tools, the support and account assistants, Reply Rules and reader-requested translations. Order: FlockStack's own Anthropic key (`ANTHROPIC_API_KEY`; Claude Haiku 5.5 for routine text and classification, Claude Sonnet 5.5 for social post drafts and the account assistant), then its own Groq key (`GROQ_API_KEY`; `openai/gpt-oss-20b`) when Anthropic errors or times out, then Workers AI. `AI_MODEL_FAST`, `AI_MODEL_STRONG` and `AI_MODEL_FALLBACK` name other models, and `AI_PROVIDERS_DISABLED=true` puts every request back on Workers AI at once. Budgets, streaming, schemas and tool permissions are the callers' and unchanged; the daily request count still goes up once per started request, not once per provider tried. + +- **FlockStack Cloud waits for the notice.** Anthropic and Groq are new sub-processors, so on FlockStack Cloud neither is used until `AI_PROVIDERS_NOTICE_SENT_ON` in `lib/legal.js` is a date at least 30 days old (`tests/ai-providers-notice.test.mjs`). Until then a key that is set is ignored and the text AI stays on Workers AI. A self-hosted server uses a key as soon as it is set. +- **Separate from Briefings.** A Briefing runs on its owner's own key (`lib/ai-keys.js`, `lib/briefings/providers.js`). Those keys never reach these calls, and these keys are never put in a Briefing's request. Embeddings for grouping stories (`@cf/baai/bge-m3`) and image generation (FLUX.1 schnell) stay on Workers AI. +- **What is kept.** No prompt or answer. `AiUsage.spend` (`lib/ai-usage.js`) counts, per account per UTC day and per provider, model and feature, the calls, failures, input and output tokens and a cost estimate in millionths of a dollar (`lib/briefings/prices.js`); a log line per call holds the same fields and nothing of the text. `get_ai_usage` is unchanged. +- **Not on Workers AI's privacy terms.** Anthropic's and Groq's own terms apply to a request they answer, not Cloudflare's; the privacy policy, `/sub-processors` and the regions page say so. + +| Variable | | +| --- | --- | +| `ANTHROPIC_API_KEY` | The server's own Anthropic key for the text AI. Empty: not used. | +| `GROQ_API_KEY` | The server's own Groq key, tried when Anthropic can't answer. Empty: not used. | +| `AI_MODEL_FAST`, `AI_MODEL_STRONG`, `AI_MODEL_FALLBACK` | Model names. Default `claude-haiku-5-5`, `claude-sonnet-5-5`, `openai/gpt-oss-20b`. | +| `AI_PROVIDERS_DISABLED` | `true` sends the text AI back to Workers AI. | + +The two keys are secrets, never `vars` and never in the repository (`tests/ai-providers-notice.test.mjs`): `npx wrangler secret put ANTHROPIC_API_KEY`, again with `--env eu`, and on the API Workers with `--config workers/api/wrangler.jsonc [--env eu]` (`node scripts/api-env.mjs` lists them). The readers, replies and briefings Workers do not call the text AI. FlockStack Cloud's owner: send the sub-processor notice, set `AI_PROVIDERS_NOTICE_SENT_ON`, deploy, and only then set the secrets (or set them first; they stay ignored until the day plus 30). ## Stock photos diff --git a/app/(app)/campaigns/[id]/collaborate/page.js b/app/(app)/campaigns/[id]/collaborate/page.js index 011148cd..e5277e1f 100644 --- a/app/(app)/campaigns/[id]/collaborate/page.js +++ b/app/(app)/campaigns/[id]/collaborate/page.js @@ -1,6 +1,6 @@ import { listCustomFields } from "@/lib/custom-fields"; import { getNewsletterTiers } from "@/lib/tier-rules"; -import { getAiBinding } from "@/lib/ai"; +import { isTextAiAvailable } from "@/lib/platform-ai"; import { getGiphyKey } from "@/lib/giphy"; import { getUnsplashKey } from "@/lib/unsplash"; import Link from "next/link"; @@ -18,6 +18,6 @@ export default async function CollaborativeCampaignPage({ params }) { if (campaign.failure) return

{campaign.failure.message}

; openNewsletter(context, campaign.output.newsletterId, `/campaigns/${id}/collaborate`); if (process.env.COLLABORATION_ENABLED !== "true" || campaign.output.status !== "draft" || campaign.output.format !== "rich") return

Realtime editing needs a rich-text draft and the optional collaboration Worker enabled on this server.

Return to issue
; - const [collaborators, snippets, fields, ai] = await Promise.all([runDashboardAction("list_editor_collaborators", { id }), runDashboardAction("list_snippets", { newsletter: campaign.output.newsletterId }), listCustomFields(context.account, campaign.output.newsletterId), getAiBinding()]); + const [collaborators, snippets, fields, ai] = await Promise.all([runDashboardAction("list_editor_collaborators", { id }), runDashboardAction("list_snippets", { newsletter: campaign.output.newsletterId }), listCustomFields(context.account, campaign.output.newsletterId), isTextAiAvailable()]); return
({ key, label, type })), snippets: (snippets.output?.snippets ?? []).map(({ name, content }) => ({ name, content })), tiers: getNewsletterTiers(context.selected), isAiEnabled: Boolean(ai), hasStockPhotos: Boolean(getUnsplashKey()), hasGifs: Boolean(getGiphyKey()) }} />
; } diff --git a/app/(app)/campaigns/[id]/edit/page.js b/app/(app)/campaigns/[id]/edit/page.js index f66774ec..70dc2ebd 100644 --- a/app/(app)/campaigns/[id]/edit/page.js +++ b/app/(app)/campaigns/[id]/edit/page.js @@ -3,7 +3,7 @@ import { notFound, redirect } from "next/navigation"; import FormPublishedIssue from "@/components/FormPublishedIssue"; import { scoped } from "@/lib/account-scope"; import { runAction } from "@/lib/actions/run-action"; -import { getAiBinding } from "@/lib/ai"; +import { isTextAiAvailable } from "@/lib/platform-ai"; import { hasActiveSubscription } from "@/lib/account-state"; import { getArchiveUrls } from "@/lib/archive-hosts"; import { listCustomFields } from "@/lib/custom-fields"; @@ -31,7 +31,7 @@ export default async function EditPublishedPage({ params }) { if (!newsletter) notFound(); const [ai, fields, { snippets }] = await Promise.all([ - getAiBinding(), + isTextAiAvailable(), listCustomFields(account, newsletter._id), runAction("list_snippets", { account, user, via: "dashboard", input: { newsletter: String(newsletter._id) } }), ]); diff --git a/app/(app)/campaigns/[id]/page.js b/app/(app)/campaigns/[id]/page.js index 30dd087a..692665c0 100644 --- a/app/(app)/campaigns/[id]/page.js +++ b/app/(app)/campaigns/[id]/page.js @@ -11,7 +11,7 @@ import FormCampaign from "@/components/FormCampaign"; import FormShortPost from "@/components/FormShortPost"; import { htmlToMarkdown } from "@/lib/html-to-markdown"; import { scoped } from "@/lib/account-scope"; -import { getAiBinding } from "@/lib/ai"; +import { isTextAiAvailable } from "@/lib/platform-ai"; import { getAccountSendProblem, hasActiveSubscription, isBlocked } from "@/lib/account-state"; import { getArchiveUrls } from "@/lib/archive-hosts"; import { runAction } from "@/lib/actions/run-action"; @@ -55,7 +55,7 @@ export default async function CampaignPage({ params }) { // The previews and the checks show the address its emails print. const newsletter = { ...stored, postalAddress: getPostalAddress(stored, siteExtensions.defaultPostalAddress) }; if (campaign.kind === "note") return ; - const [plan, ai] = await Promise.all([getPlanState(account), getAiBinding()]); + const [plan, ai] = await Promise.all([getPlanState(account), isTextAiAvailable()]); const isAiEnabled = Boolean(ai) && hasActiveSubscription(account); const audioProps = await getAudioCardProps({ account, user, campaign, newsletter }); const authorControl = ["draft", "scheduled", "sent"].includes(campaign.status) ?
: null; diff --git a/app/(site)/privacy/page.js b/app/(site)/privacy/page.js index 0bf49155..571a89aa 100644 --- a/app/(site)/privacy/page.js +++ b/app/(site)/privacy/page.js @@ -35,6 +35,8 @@ import { TERMS_CHANGE_NOTICE, TRANSFER_SAFEGUARDS, getElevenLabsStatus, + getAiProvidersStatus, + TEXT_AI_DESTINATION, isLegalPublished, } from "@/lib/legal"; import { REGION_NAMES } from "@/lib/region"; @@ -122,12 +124,15 @@ export default function PrivacyPage() {
  • The support assistant: FlockStack's own assistant answers from our docs and from what you type to it. It runs - on Cloudflare Workers AI, which runs on Cloudflare's global network, so what you type may be processed outside your region. + on the text AI ({TEXT_AI_DESTINATION}), so what you type may be processed outside your region. Stored: {SUPPORT_CHAT_STORED}. How long: {SUPPORT_CHAT_RETENTION} {SUPPORT_AI_PROVIDER_NOTE}
  • +
  • + The text AI providers: {getAiProvidersStatus()} Anthropic and Groq are listed on the sub-processors page. +
  • The AI writing tools: in the editor you can ask for a rewrite of the text you selected, subject lines, preview - text and drafts of social posts. They run on Cloudflare Workers AI, which runs on Cloudflare's global network, so what you + text and drafts of social posts. They run on the text AI ({TEXT_AI_DESTINATION}), so what you send may be processed outside your region. Stored: {AI_WRITING_STORED}. How long: {AI_WRITING_RETENTION}
  • @@ -139,7 +144,7 @@ export default function PrivacyPage() {
  • Reader-requested translations: Stored and sent: {READER_TRANSLATIONS_STORED}. How long: {READER_TRANSLATIONS_RETENTION}. - Workers AI runs on Cloudflare's global network, so this text may be processed outside your region. + The text AI ({TEXT_AI_DESTINATION}) may process this text outside your region.
  • Audio versions: Stored and sent: {AUDIO_VERSIONS_STORED}. How long: {AUDIO_VERSIONS_RETENTION}. {getElevenLabsStatus()} diff --git a/components/EditorRich.jsx b/components/EditorRich.jsx index 20c6e99e..11cdabd1 100644 --- a/components/EditorRich.jsx +++ b/components/EditorRich.jsx @@ -32,7 +32,7 @@ import { IMAGE_TYPES, getDisplaySize, prepareImage, uploadAttachment, uploadImag const MIN_HEIGHT = "min-h-[560px]"; // newsletterId and campaignId: where a poll made in this editor belongs. Without a newsletter, there's no poll block. -// isAiEnabled: the selection's AI menu (rewrite, shorten, tone, translate), only where the server has Workers AI. +// isAiEnabled: the selection's AI menu (rewrite, shorten, tone, translate), only where the server has a text AI. // hasStockPhotos: the image picker also searches Unsplash, only where the server has an Unsplash key; hasGifs: and GIPHY, with a GIPHY key. export default function EditorRich({ collaboration = null, content, onChange, fields = [], snippets = [], newsletterId = null, campaignId = null, tiers = [], isAiEnabled = false, hasStockPhotos = false, hasGifs = false }) { const [isEditingLink, setIsEditingLink] = useState(false); diff --git a/components/FormReaderSettings.jsx b/components/FormReaderSettings.jsx index 680bf0cf..4565343d 100644 --- a/components/FormReaderSettings.jsx +++ b/components/FormReaderSettings.jsx @@ -4,5 +4,5 @@ import { useActionState } from "react"; import { saveReaderSettings } from "@/app/(app)/reader-settings/actions"; export default function FormReaderSettings({ settings }) { const [state, action, pending] = useActionState(saveReaderSettings, null); - return

    Applies to reader controls and built-in subscription messages. Your issue copy and custom emails keep their own words.

    0 turns metered reading off. Signed-in free readers explicitly claim up to this many paid web issues each UTC calendar month. Issues restricted to a specific tier, email, audio and perks stay paid-only. Turning this off revokes the current month’s free access. Each reader’s claimed issue IDs are kept until seven days after the month ends.

    Each new translation uses one of your daily AI requests. Cached translations are kept for seven days. Only text the reader can access is sent to Cloudflare Workers AI; processing may occur outside your storage region. The original is unchanged. Issues up to 12,000 characters are supported.

    {!settings.translationsAvailable &&

    Workers AI must be configured first.

    }{!settings.repliesAvailable &&

    The server owner must configure the inbound domain and Email Worker first.

    }

    Replies are plain text, without attachments, kept for 90 days. Turning capture off stops accepting replies at these addresses. It never sends an automatic answer.

    {state?.error &&

    {state.error}

    }{state?.ok &&

    Saved.

    }
    ; + return

    Applies to reader controls and built-in subscription messages. Your issue copy and custom emails keep their own words.

    0 turns metered reading off. Signed-in free readers explicitly claim up to this many paid web issues each UTC calendar month. Issues restricted to a specific tier, email, audio and perks stay paid-only. Turning this off revokes the current month’s free access. Each reader’s claimed issue IDs are kept until seven days after the month ends.

    Each new translation uses one of your daily AI requests. Cached translations are kept for seven days. Only text the reader can access is sent to FlockStack's text AI (Anthropic, Groq, or Cloudflare Workers AI until Anthropic and Groq may be used); processing may occur outside your storage region. The original is unchanged. Issues up to 12,000 characters are supported.

    {!settings.translationsAvailable &&

    Workers AI must be configured first.

    }{!settings.repliesAvailable &&

    The server owner must configure the inbound domain and Email Worker first.

    }

    Replies are plain text, without attachments, kept for 90 days. Turning capture off stops accepting replies at these addresses. It never sends an automatic answer.

    {state?.error &&

    {state.error}

    }{state?.ok &&

    Saved.

    }
    ; } diff --git a/components/FormReplyRules.jsx b/components/FormReplyRules.jsx index 42c7e802..9f472aba 100644 --- a/components/FormReplyRules.jsx +++ b/components/FormReplyRules.jsx @@ -21,8 +21,8 @@ export default function FormReplyRules({ newsletter, settings, canEdit }) {