Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
chore: remove the onboarding chat (#572)
Ben Senescu361d488dff89
diff --git a/compose.yaml b/compose.yamlindex 5270974f..866fd979 100644--- a/compose.yaml+++ b/compose.yaml@@ -19,7 +19,7 @@ services:- OPENSEO_TELEMETRY_DISABLED=${OPENSEO_TELEMETRY_DISABLED:-}- DO_NOT_TRACK=${DO_NOT_TRACK:-}- DATAFORSEO_API_KEY=${DATAFORSEO_API_KEY}- # Optional: AI features (SAM, onboarding chat). Without this the setup+ # Optional: AI features (the SAM agent). Without this the setup# gate in the app asks for the key, but nothing here would forward it.- OPENROUTER_API_KEY=${OPENROUTER_API_KEY:-}# Optional: Google Search Console. Seediff --git a/package.json b/package.jsonindex 485064a8..604dba32 100644--- a/package.json+++ b/package.json@@ -7,7 +7,6 @@"packageManager": "[email protected]","scripts": {"dev": "vite dev",- "dev:clear-chat": "rm -rf .wrangler/state/v3/do/open-seo-OnboardingChatAgent","dev:agents": "mkdir -p .logs && portless run vite dev 2>&1 | tee .logs/dev-server.log","dev:agents:force": "mkdir -p .logs && portless --force run vite dev 2>&1 | tee .logs/dev-server.log","build": "vite build && tsc --noEmit",@@ -77,7 +76,6 @@"dependencies": {"@ai-sdk/react": "^3.0.211","@better-auth/api-key": "1.6.22",- "@cloudflare/ai-chat": "^0.10.1","@cloudflare/think": "0.15.1","@cloudflare/workers-oauth-provider": "^0.10.2","@every-app/sdk": "^0.1.14",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 843b0542..dfa8d0b6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -30,9 +30,6 @@ importers:'@better-auth/api-key':specifier: 1.6.22version: 1.6.22(8d706e213363f271470d19db6adbe48a)- '@cloudflare/ai-chat':- specifier: ^0.10.1- version: 0.10.1(@ai-sdk/[email protected]([email protected])([email protected]))([email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])'@cloudflare/think':specifier: 0.15.1version: 0.15.1(@ai-sdk/[email protected])(@ai-sdk/[email protected]([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])@@ -669,15 +666,6 @@ packages:'@clack/[email protected]':resolution: {integrity: sha512-pMN5FcrEw9hUkZA4f+zLlzivQSeQf5dRGJjSUbvVYDLvpKCdQx5OaknvKzgbtXOizhP+SJJJjqEbOe55uKKfAw==}- '@cloudflare/[email protected]':- resolution: {integrity: sha512-kSycX0kJ93LbGCkA6j6w6nm0tieSE+MiC62EF3KyLWpsElUc0tHt7XcPs5Z300MvZU1oAoQWhRWcRK9pYHbDlQ==}- peerDependencies:- '@ai-sdk/react': ^3.0.0 || ^4.0.0- agents: '>=0.17.1 <1.0.0'- ai: ^6.0.0 || ^7.0.0- react: ^19.0.0- zod: ^4.0.0-'@cloudflare/[email protected]':resolution: {integrity: sha512-PcX5+qAvupi8p1bMLKhqvPHziZpDubbrxDIvVH+iuuNUaFyOxxWNS9HplfFqIULqUzDPdFf1w7IiSCKHp7GDgg==}peerDependencies:@@ -6660,15 +6648,6 @@ snapshots:picocolors: 1.1.1sisteransi: 1.0.5- '@cloudflare/[email protected](@ai-sdk/[email protected]([email protected])([email protected]))([email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])':- dependencies:- '@ai-sdk/react': 3.0.211([email protected])([email protected])- agents: 0.20.1(@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- ai: 6.0.199([email protected])- nanoid: 5.1.16- react: 19.2.4- zod: 4.3.6-'@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@types/json-schema': 7.0.15diff --git a/scripts/erase-user-data.ts b/scripts/erase-user-data.tsindex cb54753b..b936b0fc 100644--- a/scripts/erase-user-data.ts+++ b/scripts/erase-user-data.ts@@ -313,7 +313,6 @@ async function buildInventory(db: Db, user: UserRow) {return {organizations,- projectIds,samSessionIds: samSessions.map((row) => row.id),auditIds: audits.map((row) => row.id),r2Keys,@@ -581,7 +580,6 @@ async function main() {organizations: inventory.organizations,databaseCounts: inventory.databaseCounts,cloudflare: {- onboardingChats: inventory.projectIds.length,samChats: inventory.samSessionIds.length,auditScratchpads: inventory.auditIds.length,r2Objects: inventory.r2Keys.length,@@ -624,7 +622,6 @@ async function main() {userId: user.id,email: user.email,organizationIds,- projectIds: inventory.projectIds,samSessionIds: inventory.samSessionIds,auditIds: inventory.auditIds,activeAuditWorkflowIds: inventory.activeAuditWorkflowIds,diff --git a/src/client/components/chat/ChatMessage.tsx b/src/client/components/chat/ChatMessage.tsxindex cd2a57e3..a0290c1d 100644--- a/src/client/components/chat/ChatMessage.tsx+++ b/src/client/components/chat/ChatMessage.tsx@@ -11,16 +11,15 @@ import {} from "lucide-react";import { Markdown } from "@/client/components/Markdown";-// Shared rendering for the chat agents (onboarding + SAM). The chats differ-// only in which tools are available and how tool names become labels-// (resolveToolLabel) plus which message actions their server supports-// (onUndo/onEdit); the UI itself is identical and lives here.+// Shared chat-message rendering. A chat supplies which tools are available and+// how tool names become labels (resolveToolLabel) plus which message actions+// its server supports (onUndo/onEdit); the UI itself lives here.-export type ToolLabel = { running: string; done: string };+type ToolLabel = { running: string; done: string };// Maps a UIMessage tool part type (e.g. "tool-get_serp_results") to its label,-// or null to hide the badge entirely (onboarding hides tools it hasn't curated).-export type ResolveToolLabel = (partType: string) => ToolLabel | null;+// or null to hide the badge entirely.+type ResolveToolLabel = (partType: string) => ToolLabel | null;// Turn a tool part type ("tool-get_serp_results") into a readable label// ("Get serp results"). Used for chats that expose too many tools to curate adiff --git a/src/client/features/onboarding/OnboardingAccountMenu.tsx b/src/client/features/onboarding/OnboardingAccountMenu.tsxindex 79287dc8..cc16ee49 100644--- a/src/client/features/onboarding/OnboardingAccountMenu.tsx+++ b/src/client/features/onboarding/OnboardingAccountMenu.tsx@@ -2,9 +2,9 @@ import { Settings, User } from "lucide-react";import { ThemePreferenceMenuItems } from "@/client/components/ThemePreferenceMenuItems";import { signOutAndRedirect } from "@/lib/auth-client";-// Account dropdown shared by the onboarding wizard and the onboarding chat so a-// signed-in user can reach Settings / theme / sign out from either surface.-// Fixed top-right; renders nothing until we know the user's email.+// Account dropdown for the onboarding wizard so a signed-in user can reach+// Settings / theme / sign out from it. Fixed top-right; renders nothing until+// we know the user's email.export function OnboardingAccountMenu({email,}: {diff --git a/src/client/features/onboarding/OnboardingChat.tsx b/src/client/features/onboarding/OnboardingChat.tsxdeleted file mode 100644index 7075ec9f..00000000--- a/src/client/features/onboarding/OnboardingChat.tsx+++ /dev/null@@ -1,128 +0,0 @@-import { useMutation, useQuery } from "@tanstack/react-query";-import { useState } from "react";-import { Loader2 } from "lucide-react";-import { DEFAULT_LOCATION_CODE } from "@/shared/keyword-locations";-import { LocationSelect } from "@/client/components/LocationSelect";-import { useSession } from "@/lib/auth-client";-import { saveOnboardingSite } from "@/serverFunctions/onboardingChat";-import { OnboardingAccountMenu } from "./OnboardingAccountMenu";-import { OnboardingChatConversation } from "./OnboardingChatConversation";-import {- invalidateOnboardingChatState,- onboardingChatStateQueryOptions,-} from "./onboardingChatQueries";--// Full-viewport chat surface. Breaks out of the centered, padded AuthPageShell-// with `fixed inset-0` so the chat fills the screen. There's no header bar —-// the strategy's first message carries the context — and inner content is-// constrained to a narrow column for comfortable reading width.-function StrategyShell({ children }: { children: React.ReactNode }) {- return (- <div className="fixed inset-0 flex flex-col bg-base-100">{children}</div>- );-}--export function OnboardingChat() {- const stateQuery = useQuery(onboardingChatStateQueryOptions());- const { data: session } = useSession();- const accountMenu = <OnboardingAccountMenu email={session?.user?.email} />;-- if (stateQuery.isError) {- return (- <StrategyShell>- <div className="flex flex-1 items-center justify-center p-6 text-sm text-error">- Couldn’t load your strategy. Please refresh to try again.- </div>- </StrategyShell>- );- }-- if (!stateQuery.data) {- return (- <StrategyShell>- <div className="flex flex-1 items-center justify-center gap-2 p-6 text-sm text-base-content/60">- <Loader2 className="size-4 animate-spin" />- Loading…- </div>- </StrategyShell>- );- }-- const { projectId, domain } = stateQuery.data;-- return (- <StrategyShell>- {accountMenu}- {!domain ? (- <SiteForm projectId={projectId} />- ) : (- <OnboardingChatConversation projectId={projectId} domain={domain} />- )}- </StrategyShell>- );-}--function SiteForm({ projectId }: { projectId: string }) {- const [domain, setDomain] = useState("");- const [locationCode, setLocationCode] = useState(DEFAULT_LOCATION_CODE);-- const save = useMutation({- mutationFn: () =>- saveOnboardingSite({ data: { projectId, domain, locationCode } }),- onSuccess: invalidateOnboardingChatState,- });-- return (- <div className="flex flex-1 items-center justify-center overflow-y-auto p-6">- <form- className="w-full max-w-md space-y-6"- onSubmit={(event) => {- event.preventDefault();- if (domain.trim()) {- save.mutate();- }- }}- >- <div className="space-y-3 text-center">- <img- src="/transparent-logo.png"- alt="OpenSEO"- className="mx-auto size-10 rounded-lg"- />- <h1 className="text-xl font-semibold">Tell us about your website.</h1>- <p className="text-sm text-base-content/60">- If you have multiple websites, you can set that up later.- </p>- </div>-- <div className="space-y-4 rounded-lg border border-base-300 bg-base-100 p-5 shadow-sm">- <label className="block space-y-1">- <span className="text-sm font-medium">Your website</span>- <input- type="text"- className="input input-bordered w-full"- placeholder="example.com"- value={domain}- onChange={(event) => setDomain(event.target.value)}- />- </label>-- <label className="block space-y-1">- <span className="text-sm font-medium">- This is the country we will use when getting SEO data.- </span>- <LocationSelect value={locationCode} onChange={setLocationCode} />- </label>-- <button- type="submit"- className="btn btn-primary w-full"- disabled={!domain.trim() || save.isPending}- >- {save.isPending ? "Saving…" : "Continue"}- </button>- </div>- </form>- </div>- );-}diff --git a/src/client/features/onboarding/OnboardingChatConversation.tsx b/src/client/features/onboarding/OnboardingChatConversation.tsxdeleted file mode 100644index 248fa0fc..00000000--- a/src/client/features/onboarding/OnboardingChatConversation.tsx+++ /dev/null@@ -1,278 +0,0 @@-import { useAgent } from "agents/react";-import { useAgentChat } from "@cloudflare/ai-chat/react";-import { useCustomer } from "autumn-js/react";-import { useState } from "react";-import {- ChatMessage,- messageHasVisibleContent,- type ResolveToolLabel,-} from "@/client/components/chat/ChatMessage";-import { useStickToBottom } from "@/client/components/chat/useStickToBottom";-import { captureClientEvent } from "@/client/lib/posthog";-import { getStandardErrorMessage } from "@/client/lib/error-messages";-import { buildCheckoutSuccessUrl } from "@/client/features/billing/checkout-url";-import {- AUTUMN_CHECKOUT_SESSION_PARAMS,- AUTUMN_PAID_PLAN_ID,-} from "@/shared/billing";-import { FREE_ONBOARDING_QUESTION_LIMIT } from "@/shared/onboardingChat";-import {- ChatComposer,- ChatGate,- SuggestedQuestions,- UpgradeSidebar,- WelcomeMessage,-} from "./OnboardingChatParts";--// Friendly labels for each tool Sam can run, so the chat shows what it's doing-// rather than going silent while it gathers site data. `running` shows while the-// call is in flight; `done` stays as a persistent badge once it finishes.-const TOOL_LABELS: Record<string, { running: string; done: string }> = {- "tool-read_website": { running: "Reading site", done: "Read site" },- "tool-get_seo_metrics": {- running: "Getting SEO metrics",- done: "SEO metrics",- },- "tool-research_keywords": {- running: "Researching keywords",- done: "Keyword research",- },- "tool-get_domain_overview": {- running: "Analyzing domain",- done: "Domain overview",- },- "tool-get_serp_results": {- running: "Checking search results",- done: "Search results",- },- "tool-find_serp_competitors": {- running: "Finding competitors",- done: "Competitors",- },- "tool-get_competitor_keywords": {- running: "Analyzing competitor",- done: "Competitor keywords",- },- "tool-get_backlinks_overview": {- running: "Checking backlinks",- done: "Backlinks overview",- },-};--// Onboarding curates a label per tool and hides any tool it hasn't named, so-// the pre-paywall preview only shows the handful it means to surface.-const resolveToolLabel: ResolveToolLabel = (partType) =>- TOOL_LABELS[partType] ?? null;--const SUGGESTED_QUESTIONS = [- "How will OpenSEO help me get more traffic?",- "Compare OpenSEO and Claude",- "What do I get after I upgrade?",- "How does the Google Search Console integration work?",- "Right fit for consultants and agencies?",-];--// Highlighted (primary) chips shown first, before the general questions.-// STRATEGY_SUGGESTION drops out once the user has asked for their strategy.-const STRATEGY_SUGGESTION = "What do you recommend for my site?";-const COMPETITOR_SUGGESTION = "Compare against my competitors";-const PRIMARY_SUGGESTIONS = [STRATEGY_SUGGESTION, COMPETITOR_SUGGESTION];--export function OnboardingChatConversation({- projectId,- domain,-}: {- projectId: string;- domain: string;-}) {- // The conversation lives in a Durable Object (Agents SDK), keyed by projectId,- // so history persists across reloads. The WebSocket connection is authorized- // in the Worker (src/server.ts) before it reaches the DO; billing gates come- // back as normal assistant messages rather than HTTP errors.- const agent = useAgent({ agent: "onboarding-chat", name: projectId });- // Same constraint as SAM: dense tool-input deltas fan out one store update- // per chunk and trip React #185 unthrottled (cloudflare/agents#1361).- const { messages, sendMessage, status } = useAgentChat({- agent,- experimental_throttle: 50,- });-- // This chat is only ever the pre-upgrade free preview: once a user upgrades- // they are routed into the GSC onboarding step and never return here, so- // there's no "paid" state to model — the question cap always applies.- const customerQuery = useCustomer();- const [checkoutError, setCheckoutError] = useState<string | null>(null);- const [isStartingCheckout, setIsStartingCheckout] = useState(false);- const [usedSuggestions, setUsedSuggestions] = useState<string[]>([]);- // Set once the user asks for their strategy (welcome CTA or the strategy- // chip) so we don't keep offering the "What do you recommend" chip.- const [strategyRequested, setStrategyRequested] = useState(false);-- const questionsUsed = messages.filter((m) => m.role === "user").length;- const remaining = Math.max(0, FREE_ONBOARDING_QUESTION_LIMIT - questionsUsed);- const isLocked = remaining <= 0;- // Nudge once they're within the last few questions, not from the start.- const showRemainingHint = remaining > 0 && remaining <= 3;-- const isBusy = status === "submitted" || status === "streaming";- const { scrollRef, onScroll, pinToBottom } = useStickToBottom(- messages,- status,- );- const sendText = (text: string) => {- pinToBottom();- void sendMessage({ text });- };- async function startCheckout() {- setCheckoutError(null);- setIsStartingCheckout(true);- try {- captureClientEvent("billing:checkout_start");- // After payment, re-enter onboarding at the GSC step (not back into- // this chat) so the user finishes connecting Search Console + MCP.- await customerQuery.attach({- planId: AUTUMN_PAID_PLAN_ID,- redirectMode: "always",- successUrl: buildCheckoutSuccessUrl("/onboarding?step=3"),- checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,- });- } catch (checkoutErr) {- setCheckoutError(- getStandardErrorMessage(- checkoutErr,- "We couldn't start checkout. Please refresh and try again.",- ),- );- setIsStartingCheckout(false);- }- }-- const lastMessage = messages[messages.length - 1];- const suggestionPool = [- ...(strategyRequested ? [] : [STRATEGY_SUGGESTION]),- COMPETITOR_SUGGESTION,- ...SUGGESTED_QUESTIONS,- ];- const remainingSuggestions = suggestionPool.filter(- (question) => !usedSuggestions.includes(question),- );- // Show the typing indicator from the moment the user sends until the- // assistant's reply shows something — covers the "submitted" wait (last- // message is still the user's own) and the gap before any text or tool badge- // renders. Once a tool badge is in flight, it carries the progress, so the- // dots would just double up.- const showTyping =- isBusy &&- (lastMessage?.role !== "assistant" ||- !messageHasVisibleContent(lastMessage));- // Show the chips up front (before the first message) and after each assistant- // reply, but not while a reply is mid-flight.- const showSuggestions =- remainingSuggestions.length > 0 &&- !isBusy &&- (messages.length === 0 || lastMessage?.role === "assistant");-- return (- <div className="flex min-h-0 flex-1">- <UpgradeSidebar- domain={domain}- questionsUsed={questionsUsed}- isStartingCheckout={isStartingCheckout}- onUpgrade={() => void startCheckout()}- />-- <div className="flex min-w-0 flex-1 flex-col">- <div- ref={scrollRef}- onScroll={onScroll}- className="flex-1 overflow-y-auto px-5 py-6"- >- <div className="mx-auto max-w-2xl space-y-6">- <WelcomeMessage- domain={domain}- checkoutError={checkoutError}- isStartingCheckout={isStartingCheckout}- onUpgrade={() => void startCheckout()}- />-- {messages.map((message, index) => (- <ChatMessage- key={message.id}- message={message}- resolveToolLabel={resolveToolLabel}- streaming={- isBusy &&- index === messages.length - 1 &&- message.role === "assistant"- }- />- ))}-- {showTyping ? (- <div className="flex items-center gap-2 pt-1 text-base-content/40">- <span className="flex items-center gap-1.5">- <span className="size-1.5 animate-bounce rounded-full bg-current [animation-delay:-0.3s]" />- <span className="size-1.5 animate-bounce rounded-full bg-current [animation-delay:-0.15s]" />- <span className="size-1.5 animate-bounce rounded-full bg-current" />- </span>- </div>- ) : null}-- {status === "error" ? (- <p className="text-sm text-error">- {/* Billing gates (free-question cap / out-of-credits) come- back as normal assistant messages now, so this only covers- genuine failures. */}- Something went wrong. Please refresh and try again.- </p>- ) : null}-- {showSuggestions ? (- <SuggestedQuestions- questions={remainingSuggestions}- primaryQuestions={PRIMARY_SUGGESTIONS}- onSelect={(question) => {- setUsedSuggestions((current) =>- current.includes(question)- ? current- : [...current, question],- );- if (question === STRATEGY_SUGGESTION) {- setStrategyRequested(true);- }- sendText(question);- }}- />- ) : null}- </div>- </div>-- {isLocked ? (- <ChatGate- isStartingCheckout={isStartingCheckout}- onUpgrade={() => void startCheckout()}- />- ) : (- <div className="flex-shrink-0 border-t border-base-300 px-5 py-3">- <div className="mx-auto w-full max-w-2xl space-y-2">- {showRemainingHint ? (- <p className="px-1 text-xs text-base-content/50">- {remaining} free question{remaining === 1 ? "" : "s"} left.{" "}- <button- type="button"- className="link link-primary"- disabled={isStartingCheckout}- onClick={() => void startCheckout()}- >- Upgrade for full access- </button>- </p>- ) : null}- <ChatComposer busy={isBusy} onSend={sendText} />- </div>- </div>- )}- </div>- </div>- );-}diff --git a/src/client/features/onboarding/OnboardingChatParts.tsx b/src/client/features/onboarding/OnboardingChatParts.tsxdeleted file mode 100644index 3dbb14b0..00000000--- a/src/client/features/onboarding/OnboardingChatParts.tsx+++ /dev/null@@ -1,320 +0,0 @@-import {- useLayoutEffect,- useRef,- useState,- type FormEvent,- type KeyboardEvent,-} from "react";-import { ArrowUp, Check, Globe, Loader2, Sparkles } from "lucide-react";-import { FREE_ONBOARDING_QUESTION_LIMIT } from "@/shared/onboardingChat";--const DISCORD_URL = "https://discord.gg/c9uGs3cFXr";--export function SuggestedQuestions({- questions,- primaryQuestions = [],- onSelect,-}: {- questions: string[];- primaryQuestions?: string[];- onSelect: (question: string) => void;-}) {- return (- <div className="ml-10 flex flex-wrap gap-2">- {questions.map((question) =>- primaryQuestions.includes(question) ? (- <button- key={question}- type="button"- className="inline-flex items-center gap-1.5 rounded-full border border-primary/40 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary transition-colors hover:bg-primary/15"- onClick={() => onSelect(question)}- >- <Sparkles className="size-3.5" />- {question}- </button>- ) : (- <button- key={question}- type="button"- className="rounded-full border border-base-300 bg-base-100 px-3 py-1.5 text-xs font-medium text-base-content/70 transition-colors hover:border-primary/50 hover:text-base-content"- onClick={() => onSelect(question)}- >- {question}- </button>- ),- )}- </div>- );-}--export function WelcomeMessage({- domain,- checkoutError,- isStartingCheckout,- onUpgrade,-}: {- domain: string;- checkoutError: string | null;- isStartingCheckout: boolean;- onUpgrade: () => void;-}) {- return (- <div className="flex gap-3">- <div className="flex size-7 flex-shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">- <Sparkles className="size-4" />- </div>- <div className="min-w-0 flex-1 space-y-3 pt-0.5 text-sm">- <div className="space-y-3 text-base-content/80">- <p>Hey, I’m Sam — welcome to OpenSEO.</p>- <p>- To get full access to OpenSEO, you need to upgrade to the paid plan.- But, I’m here if you have any questions.- </p>- <p>- You can also{" "}- <a- href={DISCORD_URL}- target="_blank"- rel="noreferrer"- className="link link-primary"- >- join the Discord- </a>{" "}- or email{" "}- <a href="mailto:[email protected]" className="link link-primary">- </a>{" "}- if you have any questions I can’t help you with.- </p>- <p>- Want me to analyze{" "}- <span className="font-medium text-base-content">{domain}</span> and- draft a strategy, or do you have questions first? Pick one below to- get started.- </p>- </div>-- <div className="rounded-box border border-base-300 bg-base-200/50 p-3 text-xs lg:hidden">- <p className="font-medium">Want Sam to keep going?</p>- <p className="mt-0.5 text-base-content/70">- Upgrade to run keyword research, rank tracking, and site audits on{" "}- {domain}.- </p>- <button- type="button"- className="btn btn-primary btn-xs mt-2"- disabled={isStartingCheckout}- onClick={onUpgrade}- >- {isStartingCheckout ? "Redirecting..." : "Upgrade"}- </button>- {checkoutError ? (- <p className="mt-2 text-error">{checkoutError}</p>- ) : null}- </div>- </div>- </div>- );-}--// Left-rail upgrade CTA. Hidden below `lg` (the inline callout + remaining-// hint cover narrow viewports).-export function UpgradeSidebar({- domain,- questionsUsed,- isStartingCheckout,- onUpgrade,-}: {- domain: string;- questionsUsed: number;- isStartingCheckout: boolean;- onUpgrade: () => void;-}) {- const features = [- "Keyword research, backlinks, rank tracking & site audits",- "Google Search Console — read-only, no credits, no Google Cloud setup",- "Connect Claude, Cursor, Codex & other MCP clients",- "Top-up credits roll over and never expire",- ];- const used = Math.min(questionsUsed, FREE_ONBOARDING_QUESTION_LIMIT);- const progress = (used / FREE_ONBOARDING_QUESTION_LIMIT) * 100;-- return (- <aside className="hidden w-96 flex-shrink-0 flex-col border-r border-base-300 bg-base-200/20 lg:flex">- <div className="flex items-center gap-2.5 border-b border-base-300 px-6 py-4 text-xs text-base-content/55">- <span className="inline-flex size-8 items-center justify-center rounded-full border border-base-300 bg-base-100 text-primary">- <Globe className="size-4" />- </span>- <div className="min-w-0">- <p className="font-medium text-base-content/80">Previewing OpenSEO</p>- <p className="truncate" title={domain}>- {domain}- </p>- </div>- </div>-- <div className="flex flex-1 flex-col gap-5 px-6 py-6">- <div>- <div className="flex items-baseline gap-1.5">- <span className="text-3xl font-semibold tracking-tight">$10</span>- <span className="text-sm text-base-content/55">/month</span>- </div>- <p className="mt-1.5 text-xs leading-relaxed text-base-content/55">- Includes $10 of usage credits every month, plus a 30-day money-back- guarantee.- </p>- </div>-- <ul className="space-y-3 border-t border-base-300 pt-5">- {features.map((label) => (- <li- key={label}- className="flex gap-2.5 text-sm leading-snug text-base-content/75"- >- <Check className="mt-0.5 size-4 flex-shrink-0 text-primary" />- <span>{label}</span>- </li>- ))}- </ul>-- <div className="mt-auto space-y-3 pt-2">- <button- type="button"- className="btn btn-primary w-full"- disabled={isStartingCheckout}- onClick={onUpgrade}- >- {isStartingCheckout ? "Redirecting..." : "Upgrade to continue"}- </button>- <p className="text-center text-xs leading-relaxed text-base-content/55">- Want advice from other OpenSEO users?{" "}- <a- href={DISCORD_URL}- target="_blank"- rel="noreferrer"- className="link link-primary"- >- Join the Discord- </a>- .- </p>- </div>- </div>-- <div className="space-y-1.5 border-t border-base-300 px-6 py-4">- <div className="h-1 w-full overflow-hidden rounded-full bg-base-300">- <div- className="h-full rounded-full bg-primary transition-all"- style={{ width: `${progress}%` }}- />- </div>- <p className="text-xs text-base-content/55">- {used} of {FREE_ONBOARDING_QUESTION_LIMIT} free questions used- </p>- </div>- </aside>- );-}--// Replaces the composer once a free user exhausts their question allowance.-export function ChatGate({- isStartingCheckout,- onUpgrade,-}: {- isStartingCheckout: boolean;- onUpgrade: () => void;-}) {- return (- <div className="flex-shrink-0 border-t border-base-300 px-5 py-4">- <div className="mx-auto w-full max-w-2xl rounded-box border border-primary/30 bg-primary/5 p-4 text-center">- <p className="text-sm font-medium">- That’s all {FREE_ONBOARDING_QUESTION_LIMIT} free questions- </p>- <p className="mx-auto mt-1 max-w-md text-xs text-base-content/70">- Upgrade to keep working with Sam and unlock the full OpenSEO app.- </p>- <button- type="button"- className="btn btn-primary btn-sm mt-3"- disabled={isStartingCheckout}- onClick={onUpgrade}- >- {isStartingCheckout ? "Redirecting..." : "Upgrade to continue"}- </button>- <p className="mt-2 text-xs text-base-content/45">- 30-day money-back guarantee- </p>- </div>- </div>- );-}--export function ChatComposer({- busy,- onSend,- placeholder = "Ask Sam about your strategy or OpenSEO…",-}: {- busy: boolean;- onSend: (text: string) => void;- placeholder?: string;-}) {- const [value, setValue] = useState("");- const textareaRef = useRef<HTMLTextAreaElement>(null);-- // Auto-grow the textarea up to a few lines, then scroll. Resetting height to- // `auto` first lets it shrink as well as grow.- useLayoutEffect(() => {- const ta = textareaRef.current;- if (!ta) return;- ta.style.height = "auto";- ta.style.height = `${Math.min(ta.scrollHeight, 160)}px`;- }, [value]);-- function submit() {- const text = value.trim();- if (!text || busy) return;- onSend(text);- setValue("");- }-- function handleSubmit(event: FormEvent) {- event.preventDefault();- submit();- }-- function handleKey(event: KeyboardEvent<HTMLTextAreaElement>) {- if (event.key === "Enter" && !event.shiftKey) {- event.preventDefault();- submit();- }- }-- return (- <form- onSubmit={handleSubmit}- className="flex items-end gap-2 rounded-box border border-base-300 bg-base-100 px-3 py-2 focus-within:border-primary"- >- <textarea- ref={textareaRef}- value={value}- onChange={(event) => setValue(event.target.value)}- onKeyDown={handleKey}- rows={1}- placeholder={placeholder}- className="max-h-40 flex-1 resize-none border-0 bg-transparent px-1 py-1 text-sm leading-relaxed outline-none placeholder:text-base-content/50 focus:outline-none"- />- <button- type="submit"- aria-label="Send message"- disabled={busy || !value.trim()}- className="btn btn-primary btn-circle btn-sm"- >- {busy ? (- <Loader2 className="size-4 animate-spin" />- ) : (- <ArrowUp className="size-4" />- )}- </button>- </form>- );-}diff --git a/src/client/features/onboarding/onboardingChatQueries.ts b/src/client/features/onboarding/onboardingChatQueries.tsdeleted file mode 100644index 54c909d2..00000000--- a/src/client/features/onboarding/onboardingChatQueries.ts+++ /dev/null@@ -1,13 +0,0 @@-import { queryOptions } from "@tanstack/react-query";-import { queryClient } from "@/client/tanstack-db";-import { getOnboardingChatState } from "@/serverFunctions/onboardingChat";--export const onboardingChatStateQueryOptions = () =>- queryOptions({- queryKey: ["onboardingChatState"],- queryFn: () => getOnboardingChatState(),- });--export function invalidateOnboardingChatState() {- void queryClient.invalidateQueries({ queryKey: ["onboardingChatState"] });-}diff --git a/src/client/features/sam/ChatComposer.tsx b/src/client/features/sam/ChatComposer.tsxnew file mode 100644index 00000000..fe635880--- /dev/null+++ b/src/client/features/sam/ChatComposer.tsx@@ -0,0 +1,78 @@+import {+ useLayoutEffect,+ useRef,+ useState,+ type FormEvent,+ type KeyboardEvent,+} from "react";+import { ArrowUp, Loader2 } from "lucide-react";++export function ChatComposer({+ busy,+ onSend,+ placeholder = "Ask Sam about your strategy or OpenSEO…",+}: {+ busy: boolean;+ onSend: (text: string) => void;+ placeholder?: string;+}) {+ const [value, setValue] = useState("");+ const textareaRef = useRef<HTMLTextAreaElement>(null);++ // Auto-grow the textarea up to a few lines, then scroll. Resetting height to+ // `auto` first lets it shrink as well as grow.+ useLayoutEffect(() => {+ const ta = textareaRef.current;+ if (!ta) return;+ ta.style.height = "auto";+ ta.style.height = `${Math.min(ta.scrollHeight, 160)}px`;+ }, [value]);++ function submit() {+ const text = value.trim();+ if (!text || busy) return;+ onSend(text);+ setValue("");+ }++ function handleSubmit(event: FormEvent) {+ event.preventDefault();+ submit();+ }++ function handleKey(event: KeyboardEvent<HTMLTextAreaElement>) {+ if (event.key === "Enter" && !event.shiftKey) {+ event.preventDefault();+ submit();+ }+ }++ return (+ <form+ onSubmit={handleSubmit}+ className="flex items-end gap-2 rounded-box border border-base-300 bg-base-100 px-3 py-2 focus-within:border-primary"+ >+ <textarea+ ref={textareaRef}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={handleKey}+ rows={1}+ placeholder={placeholder}+ className="max-h-40 flex-1 resize-none border-0 bg-transparent px-1 py-1 text-sm leading-relaxed outline-none placeholder:text-base-content/50 focus:outline-none"+ />+ <button+ type="submit"+ aria-label="Send message"+ disabled={busy || !value.trim()}+ className="btn btn-primary btn-circle btn-sm"+ >+ {busy ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <ArrowUp className="size-4" />+ )}+ </button>+ </form>+ );+}diff --git a/src/client/features/sam/SamConversation.tsx b/src/client/features/sam/SamConversation.tsxindex 27408454..62adfcec 100644--- a/src/client/features/sam/SamConversation.tsx+++ b/src/client/features/sam/SamConversation.tsx@@ -3,7 +3,7 @@ import { useAgent } from "agents/react";// variant skips the client->server transcript sync Think doesn't support.import { useAgentChat } from "@cloudflare/think/react";import { useEffect, useRef } from "react";-import { ChatComposer } from "@/client/features/onboarding/OnboardingChatParts";+import { ChatComposer } from "@/client/features/sam/ChatComposer";import { invalidateSamSessions } from "@/client/features/sam/samQueries";import {ChatMessage,diff --git a/src/env.d.ts b/src/env.d.tsindex db7d478b..8816c0bf 100644--- a/src/env.d.ts+++ b/src/env.d.ts@@ -6,9 +6,6 @@ declare namespace Cloudflare {R2: R2Bucket;OAUTH_KV: KVNamespace;- // Durable Object backing the onboarding strategy chat (see wrangler.jsonc).- ONBOARDING_CHAT: DurableObjectNamespace;-// Durable Object backing the SAM in-app agent (see wrangler.jsonc).SAM_CHAT: DurableObjectNamespace;@@ -58,7 +55,7 @@ declare namespace Cloudflare {// DataForSEO API Basic auth value (base64 of login:password)DATAFORSEO_API_KEY: string;- // OpenRouter API key for the in-app chat agents (onboarding + SAM).+ // OpenRouter API key for the SAM in-app chat agent.OPENROUTER_API_KEY?: string;// Optional OpenRouter model slug override (defaults in openrouter.ts).OPENROUTER_MODEL?: string;diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 6e8d9645..700c0181 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -35,7 +35,6 @@ import { Route as AuthenticatedOnboardingIndexRouteImport } from './routes/_authimport { Route as AppSettingsIndexRouteImport } from './routes/_app/settings/index'import { Route as ApiAutumnSplatRouteImport } from './routes/api/autumn/$'import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'-import { Route as AuthenticatedOnboardingChatRouteImport } from './routes/_authenticated.onboarding.chat'import { Route as AppSettingsOrganizationRouteImport } from './routes/_app/settings/organization'import { Route as AppHelpOpenrouterApiKeyRouteImport } from './routes/_app/help/openrouter-api-key'import { Route as AppHelpDataforseoApiKeyRouteImport } from './routes/_app/help/dataforseo-api-key'@@ -191,12 +190,6 @@ const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({path: '/api/auth/$',getParentRoute: () => rootRouteImport,} as any)-const AuthenticatedOnboardingChatRoute =- AuthenticatedOnboardingChatRouteImport.update({- id: '/onboarding/chat',- path: '/onboarding/chat',- getParentRoute: () => AuthenticatedRoute,- } as any)const AppSettingsOrganizationRoute = AppSettingsOrganizationRouteImport.update({id: '/organization',path: '/organization',@@ -360,7 +353,6 @@ export interface FileRoutesByFullPath {'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute'/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute'/settings/organization': typeof AppSettingsOrganizationRoute- '/onboarding/chat': typeof AuthenticatedOnboardingChatRoute'/api/auth/$': typeof ApiAuthSplatRoute'/api/autumn/$': typeof ApiAutumnSplatRoute'/settings/': typeof AppSettingsIndexRoute@@ -408,7 +400,6 @@ export interface FileRoutesByTo {'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute'/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute'/settings/organization': typeof AppSettingsOrganizationRoute- '/onboarding/chat': typeof AuthenticatedOnboardingChatRoute'/api/auth/$': typeof ApiAuthSplatRoute'/api/autumn/$': typeof ApiAutumnSplatRoute'/settings': typeof AppSettingsIndexRoute@@ -460,7 +451,6 @@ export interface FileRoutesById {'/_app/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute'/_app/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute'/_app/settings/organization': typeof AppSettingsOrganizationRoute- '/_authenticated/onboarding/chat': typeof AuthenticatedOnboardingChatRoute'/api/auth/$': typeof ApiAuthSplatRoute'/api/autumn/$': typeof ApiAutumnSplatRoute'/_app/settings/': typeof AppSettingsIndexRoute@@ -512,7 +502,6 @@ export interface FileRouteTypes {| '/help/dataforseo-api-key'| '/help/openrouter-api-key'| '/settings/organization'- | '/onboarding/chat'| '/api/auth/$'| '/api/autumn/$'| '/settings/'@@ -560,7 +549,6 @@ export interface FileRouteTypes {| '/help/dataforseo-api-key'| '/help/openrouter-api-key'| '/settings/organization'- | '/onboarding/chat'| '/api/auth/$'| '/api/autumn/$'| '/settings'@@ -611,7 +599,6 @@ export interface FileRouteTypes {| '/_app/help/dataforseo-api-key'| '/_app/help/openrouter-api-key'| '/_app/settings/organization'- | '/_authenticated/onboarding/chat'| '/api/auth/$'| '/api/autumn/$'| '/_app/settings/'@@ -841,13 +828,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ApiAuthSplatRouteImportparentRoute: typeof rootRouteImport}- '/_authenticated/onboarding/chat': {- id: '/_authenticated/onboarding/chat'- path: '/onboarding/chat'- fullPath: '/onboarding/chat'- preLoaderRoute: typeof AuthenticatedOnboardingChatRouteImport- parentRoute: typeof AuthenticatedRoute- }'/_app/settings/organization': {id: '/_app/settings/organization'path: '/organization'@@ -1188,14 +1168,12 @@ const AuthRouteWithChildren = AuthRoute._addFileChildren(AuthRouteChildren)interface AuthenticatedRouteChildren {AuthenticatedOauthConsentRoute: typeof AuthenticatedOauthConsentRouteAuthenticatedSubscribeRoute: typeof AuthenticatedSubscribeRoute- AuthenticatedOnboardingChatRoute: typeof AuthenticatedOnboardingChatRouteAuthenticatedOnboardingIndexRoute: typeof AuthenticatedOnboardingIndexRoute}const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {AuthenticatedOauthConsentRoute: AuthenticatedOauthConsentRoute,AuthenticatedSubscribeRoute: AuthenticatedSubscribeRoute,- AuthenticatedOnboardingChatRoute: AuthenticatedOnboardingChatRoute,AuthenticatedOnboardingIndexRoute: AuthenticatedOnboardingIndexRoute,}diff --git a/src/routes/_authenticated.onboarding.chat.tsx b/src/routes/_authenticated.onboarding.chat.tsxdeleted file mode 100644index 30d85688..00000000--- a/src/routes/_authenticated.onboarding.chat.tsx+++ /dev/null@@ -1,14 +0,0 @@-import { createFileRoute, redirect } from "@tanstack/react-router";-import { OnboardingChat } from "@/client/features/onboarding/OnboardingChat";-import { isHostedClientAuthMode } from "@/lib/auth-mode";--export const Route = createFileRoute("/_authenticated/onboarding/chat")({- // The strategy chat is hosted-only (managed LLM + trial credits). Self-hosted- // has no business here — send it back to the onboarding wizard.- beforeLoad: () => {- if (!isHostedClientAuthMode()) {- throw redirect({ to: "/onboarding", search: { step: 3 }, replace: true });- }- },- component: OnboardingChat,-});diff --git a/src/server.ts b/src/server.tsindex a832e4da..4d6b9250 100644--- a/src/server.ts+++ b/src/server.ts@@ -31,42 +31,12 @@ import { GDPR_STORAGE_ERASURE_PATH } from "@/shared/gdpr-erasure";const appFetch = createStartHandler(defaultStreamHandler);const openSeoOAuthProvider = createOpenSeoOAuthProvider(appFetch);-// Authorize an onboarding-chat connection in the Worker, before it reaches the-// Durable Object. The DO instance name is the projectId (set client-side); we-// resolve the session here and confirm the caller's org owns that project, so-// the DO can trust its `name`. Returning a Response rejects; void lets it through.-async function authorizeOnboardingChat(- request: Request,- projectId: string,-): Promise<Response | undefined> {- let context;- try {- context = await resolveUserContextFromHeaders(request.headers);- } catch {- return new Response("Unauthorized", { status: 401 });- }- const project = await ProjectRepository.getProjectForOrganization(- projectId,- context.organizationId,- );- if (!project) {- return new Response("Forbidden", { status: 403 });- }- // Ensure the org's Autumn customer exists (and gets its default onboarding-plan- // credits) before the DO checks the balance — otherwise a brand-new org's first- // message can hit a false "out of credits" gate. Hosted-only; self-hosted has- // no Autumn.- if (await isHostedServerAuthMode()) {- await getOrCreateOrganizationCustomer(context);- }- return undefined;-}-// Authorize a SAM agent connection in the Worker, before it reaches the Durable// Object. The DO instance name is the sessionId (set client-side); we resolve// the session here and authorize the caller against the session's project via// the same canonical project-access check the rest of the app uses, so the DO// can trust its `name` and derive org/project/user from the session row.+// Returning a Response rejects; void lets it through.async function authorizeSamChat(request: Request,sessionId: string,@@ -90,35 +60,31 @@ async function authorizeSamChat(if (!session || !project) {return new Response("Forbidden", { status: 403 });}- // Same as onboarding above: make sure the Autumn customer (and its default- // free-plan credits) exists before the DO's balance gate runs, or a brand-new- // org's first message hits a false "out of credits".+ // Make sure the Autumn customer (and its default free-plan credits) exists+ // before the DO's balance gate runs, or a brand-new org's first message hits+ // a false "out of credits". Hosted-only; self-hosted has no Autumn.if (await isHostedServerAuthMode()) {await getOrCreateOrganizationCustomer(context);}return undefined;}-// Both chat DOs live behind /agents/*. Dispatch on the DO binding partyserver+// The chat DO lives behind /agents/*. Dispatch on the DO binding partyserver// resolved for the request (rather than re-parsing the path), and fail closed// on anything unrecognized.function authorizeChatAgent(request: Request,lobby: { className: string; name: string },): Promise<Response | undefined> | Response {- switch (lobby.className) {- case "SAM_CHAT":- return authorizeSamChat(request, lobby.name);- case "ONBOARDING_CHAT":- return authorizeOnboardingChat(request, lobby.name);- default:- return new Response("Forbidden", { status: 403 });+ if (lobby.className === "SAM_CHAT") {+ return authorizeSamChat(request, lobby.name);}+ return new Response("Forbidden", { status: 403 });}-// Route /agents/* to the onboarding and SAM chat DOs. Auth happens here (both-// the WS upgrade and any HTTP message-history fetch), keeping it off the OAuth-// wrapper and TanStack route guard below.+// Route /agents/* to the SAM chat DO. Auth happens here (both the WS upgrade+// and any HTTP message-history fetch), keeping it off the OAuth wrapper and+// TanStack route guard below.async function routeChatAgents(request: Request, env: Env): Promise<Response> {const response = await routeAgentRequest(request, env, {onBeforeConnect: (req, lobby) => authorizeChatAgent(req, lobby),@@ -182,8 +148,6 @@ function handleFetch(// AuditScratchpad DO live in the open-seo-audit aux worker// (src/audit-worker.ts); this worker reaches them via cross-script bindings.export { RankCheckWorkflow } from "./server/workflows/RankCheckWorkflow";-// Durable Object class for the onboarding strategy chat (Agents SDK).-export { OnboardingChatAgent } from "./server/features/onboarding/OnboardingChatAgent";// Durable Object class for the SAM in-app agent (Agents SDK).export { SamChatAgent } from "./server/features/sam/SamChatAgent";diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.tsindex bca30996..15eb92b1 100644--- a/src/server/billing/subscription.ts+++ b/src/server/billing/subscription.ts@@ -224,7 +224,7 @@ export async function assertUsageCreditsAvailable(* Deducts a USD provider cost from the org's shared usage-credit pool: applies* the platform markup, converts to credits, spends monthly `usage_credits`* first then `topup_credits`, and emits the usage:credits_consume event. Both- * DataForSEO and onboarding-LLM spend route through here, so they draw from the+ * DataForSEO and agent-LLM spend route through here, so they draw from the* one pool. Pass `monthlyRemaining` from the balance check that gated the call.*/export async function trackUsageCreditSpend(args: {diff --git a/src/server/features/backlinks/services/BacklinksService.ts b/src/server/features/backlinks/services/BacklinksService.tsindex 4fbd331f..f724871b 100644--- a/src/server/features/backlinks/services/BacklinksService.ts+++ b/src/server/features/backlinks/services/BacklinksService.ts@@ -40,7 +40,7 @@ function createBacklinksService(cache: BacklinksCache = defaultCache) {async profileOverview(input: BacklinksLookupInput,billingCustomer: BillingCustomerContext,- // Lets a caller (e.g. onboarding) attribute the spend to its own credit+ // Lets a caller (e.g. the SAM agent) attribute the spend to its own credit// feature. Applied to the DataForSEO calls, not the cache key, so cached// results stay shared across callers.creditFeature?: CreditFeature,diff --git a/src/server/features/domain/services/DomainService.ts b/src/server/features/domain/services/DomainService.tsindex 9f5dcac0..bc2c9111 100644--- a/src/server/features/domain/services/DomainService.ts+++ b/src/server/features/domain/services/DomainService.ts@@ -12,7 +12,7 @@ import { mapKeywordItem } from "@/server/features/domain/services/domainKeywordMimport { getKeywordsPage } from "@/server/features/domain/services/domainKeywordsPage";import { getPagesPage } from "@/server/features/domain/services/domainPagesPage";-// Lets a caller attribute spend to its own feature (e.g. onboarding). Applied+// Lets a caller attribute spend to its own feature (e.g. the SAM agent). Applied// to the DataForSEO call, not the cache key, so cached results are shared// across callers.type MeteringOverrides = {diff --git a/src/server/features/keywords/services/research/research-data.ts b/src/server/features/keywords/services/research/research-data.tsindex ad74f25b..c7508a71 100644--- a/src/server/features/keywords/services/research/research-data.ts+++ b/src/server/features/keywords/services/research/research-data.ts@@ -19,7 +19,7 @@ type FetchResearchRowsParams = {resultLimit: number;source: KeywordSource;includeClickstreamData?: boolean;- // Attribute the DataForSEO spend to a specific feature (e.g. "onboarding");+ // Attribute the DataForSEO spend to a specific feature (e.g. "agent");// defaults to the path-derived feature when omitted.creditFeature?: CreditFeature;};diff --git a/src/server/features/onboarding/OnboardingChatAgent.ts b/src/server/features/onboarding/OnboardingChatAgent.tsdeleted file mode 100644index 3d5921a2..00000000--- a/src/server/features/onboarding/OnboardingChatAgent.ts+++ /dev/null@@ -1,211 +0,0 @@-import { AIChatAgent } from "@cloudflare/ai-chat";-import {- convertToModelMessages,- stepCountIs,- streamText,- type StreamTextOnFinishCallback,- type ToolSet,-} from "ai";-import type { OnChatMessageOptions } from "@cloudflare/ai-chat";-import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";-import { buildOnboardingTools } from "@/server/features/onboarding/onboardingChatTools";-import { getChatAgentModel } from "@/server/lib/openrouter";-import {- openRouterCostUsd,- staticAssistantResponse,-} from "@/server/lib/chatAgent";-import { isHostedServerAuthMode } from "@/server/lib/runtime-env";-import {- customerHasManagedAccess,- checkUsageCreditsDepleted,- trackUsageCreditSpend,-} from "@/server/billing/subscription";-import { FREE_ONBOARDING_QUESTION_LIMIT } from "@/shared/onboardingChat";-import openSeoFactSheet from "@/server/features/onboarding/openseo-fact-sheet.md?raw";--function buildSystemPrompt(domain: string | null): string {- return [- "You are Sam, the SEO onboarding agent inside OpenSEO. Introduce yourself as Sam if the user asks who you are.",- "Write for a founder who is new to SEO, not an expert: default to short, scannable, persuasive answers. Lead with a one-sentence direct answer, then at most 2-3 short paragraphs OR a few bullets — aim for under ~150 words unless the user explicitly asks you to go deep. Keep paragraphs to 2-3 sentences, use bullets for any list, and bold only the few words that carry the point. Prefer bullets over a wall of prose.",- "Explain SEO jargon in plain language the first time it comes up (e.g. topical authority, head terms, KD/keyword difficulty), and tie each point back to a concrete outcome the user cares about — more of the right visitors, less wasted effort. Be persuasive through specifics and honesty, never hype or overpromising.",- "Write in plain prose and Markdown. Do not use decorative emoji or symbol markers (✅, ✔, 🚀, etc.) in your responses, including inside tables — they make replies look cluttered. Convey status and emphasis with words.",- "Only answer questions related to SEO, OpenSEO, OpenSEO setup, MCP/AI-agent SEO workflows, Google Search Console in OpenSEO, or open-source/self-hosting topics. If the user asks about anything else, politely say you're here to help them get up and running with OpenSEO and ask what they want to know about OpenSEO or SEO.",- "For OpenSEO product questions, use the OpenSEO Fact Sheet below as your source of truth. Do not invent product facts, feature details, pricing, limits, integrations, or support claims. If the fact sheet does not support the answer, say you are not sure and suggest contacting [email protected].",- "When users want advice from people in the community, a second opinion, or help beyond this onboarding chat, mention the OpenSEO Discord from the fact sheet.",- "When the user asks how OpenSEO helps them get traffic or rank higher, keep the same short, scannable format: open with one plain-language sentence on how traffic actually grows (earning topical authority in Google and AI answers — i.e. becoming a trusted source on a focused set of topics), then a few bullets tying OpenSEO's role to that path: find winnable keywords, focus early topics, expand into broader searches, track what moves. Do not write a multi-paragraph essay and do not answer as only a feature list.",- "This chat is the free onboarding preview: the user hasn't upgraded yet. Here you can answer questions and analyze their site with your tools, but they can't act inside OpenSEO yet — connecting Google Search Console, rank tracking, content tools, and the full research workflows all unlock on the paid plan. In ANY reply, you may describe what OpenSEO will do for them after they upgrade, but never tell them to do those things now and never hand them a to-do list of off-platform SEO work. Be direct that these unlock on the paid plan, but do not hard-sell.",- "Keep recommendations inside OpenSEO; don't point users to other SEO tools.",- "When a request is beyond your preview tools, don't conclude OpenSEO can't do it — describe what the full product does per the fact sheet, and don't claim capabilities the fact sheet doesn't list.",- "You have tools to pull real search data. Never state a metric, search volume, keyword difficulty, ranking, or competitor figure you did not get from a tool.",- "Core tools for THIS user's own site — use these freely whenever the user asks you to analyze their site, recommend a strategy, or for any site-specific advice:",- "- read_website: reads web pages as plain text. With no arguments it reads the user's own site; when the user names or pastes specific page URLs (their own pages or a competitor's), pass those as `urls` to read exactly those pages. Always available, no credits — use it whenever the user points you at specific URLs.",- "- get_seo_metrics: their estimated organic traffic, ranking-keyword count, and the keywords they already rank for (each with real search volume and difficulty). May report it's unavailable for brand-new sites or unsupported markets.",- "- research_keywords: given one seed topic from their site, returns related keywords each with real monthly search volume and difficulty (KD). Use it to ground keyword suggestions in real data — especially when get_seo_metrics shows no rankings. Seed it with the site's primary topic; call it again only for a clearly distinct second theme.",- "Market & competitor tools — these cost more credits, so use them SPARINGLY and only when the user's question is specifically about competitors, the live SERP, or backlinks. Do NOT call them just to enrich a routine strategy, and never call more than one or two per reply. The core site tools above answer most questions on their own.",- "- get_domain_overview: organic footprint (traffic, keyword count, backlinks) for ANY domain. Use only to compare the user against a competitor they name, or one clear market leader — not a roster of competitors.",- "- get_serp_results: live Google results for 1-3 keywords, showing who ranks on page one. Use only when the user wants to see the actual SERP for a specific term.",- "- find_serp_competitors: given 2-5 of the user's target keywords, returns the domains competing with them. Use only when the user asks who their SEO competitors are; call it once.",- "- get_competitor_keywords: the keywords one competitor domain ranks for, for gap analysis. Use only when the user wants to know what a specific competitor wins; limit to one or two domains total.",- "- get_backlinks_overview: backlinks/referring-domain counts for a domain (the most expensive tool). Use only when the user explicitly asks about backlinks or site authority.",- "When the user asks for a strategy, recommendations, or an analysis of their site, first gather data with the tools, then write a concise, honest strategy specific to THIS site (never generic) in Markdown with exactly these sections, under ~350 words total:",- "'## Positioning' — one paragraph on what the site does and how it should position itself in search.",- "'## Themes' — 3-5 content/topic themes worth owning, each a bullet with a one-line rationale.",- "'## Target keywords' — a short Markdown table with columns Keyword | Volume | KD | Why it fits. Every keyword, and its Volume and KD, must come from a tool (get_seo_metrics, research_keywords, or get_competitor_keywords) — never invent, estimate, or leave these numbers blank. For keywords they already rank for, note it plainly in the 'Why it fits' column (e.g. 'you rank #17') — do not add emoji or symbol markers to the keyword. If you genuinely could not get keyword data for their market, say so in one line instead of showing a table with made-up numbers.",- "Close with a single short sentence offering to go deeper on any theme or keyword — not a 'next steps' or homework list.",- domain- ? `The user's website is ${domain}.`- : "If you need the user's website before answering, ask for it briefly.",- `OpenSEO Fact Sheet:\n\n${openSeoFactSheet}`,- ].join("\n\n");-}--/**- * Durable Object backing the onboarding strategy chat. The conversation is- * persisted automatically in the DO's SQLite (`this.messages`), so it survives- * reloads. One instance per project: the DO instance name IS the projectId, set- * by the client (`useAgent({ name: projectId })`) and authorized in the Worker- * (`onBeforeConnect`) before any connection reaches here — so the DO trusts that- * its caller may act on `this.name` and derives the org/domain from the project.- */-export class OnboardingChatAgent extends AIChatAgent {- // Cap stored history; the onboarding chat is short and pre-paywall.- maxPersistedMessages = 60;-- /** Permanently remove this project's transcript for an account erasure. */- async destroyForErasure(): Promise<void> {- for (const socket of this.ctx.getWebSockets()) {- socket.close(1000, "Account erased");- }- this.abortAllRequests("GDPR erasure");- this.resetTurnState();- await this.waitUntilStable({ timeout: 5_000 });- await this.ctx.storage.deleteAlarm();- await this.ctx.storage.deleteAll();- }-- // The base class persists each message as its own bounded SQLite row, so DO- // storage occasionally returns a transient internal error (code 10001) that- // clears on retry. Retry the message-write path a couple of times before- // surfacing the failure, rethrowing on non-transient errors or the last try.- async persistMessages(- ...args: Parameters<AIChatAgent["persistMessages"]>- ): Promise<void> {- const maxAttempts = 3;- for (let attempt = 1; ; attempt++) {- try {- await super.persistMessages(...args);- return;- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- const transient =- message.includes("internal error") || message.includes("10001");- if (!transient || attempt >= maxAttempts) throw error;- await new Promise((resolve) => setTimeout(resolve, 50 * attempt));- }- }- }-- async onChatMessage(- onFinish: StreamTextOnFinishCallback<ToolSet>,- options?: OnChatMessageOptions,- ): Promise<Response | undefined> {- const project = await ProjectRepository.getProjectById(this.name);- if (!project) {- return staticAssistantResponse(- "I couldn't find your project. Please refresh and try again.",- );- }- const { organizationId } = project;- const billingCustomer = {- // The org is the Autumn customer; userId is only an analytics distinctId.- userId: organizationId,- // The DO only knows the org/project, not the user, so it has no real email- // to attach. The org's Autumn customer is already created with the real- // email by the Worker's authorize step before any message reaches here, so- // this placeholder is only ever seen by a get-on-existing (never persisted)- // — Autumn rejects an empty string. Mirrors the scheduled rank-check job's- // user-less metering, but onboarding-specific so it's identifiable in- // Autumn logs.- userEmail: "[email protected]",- organizationId,- projectId: project.id,- };-- // In hosted mode, gate every turn on billing: past the free-question cap the- // user must have paid access, and either way the org must still have credits- // — LLM tokens and DataForSEO tool calls all draw down the same- // onboarding-plan balance. Self-hosted has no Autumn balance and brings its- // own provider keys, so it's ungated. Captured for metering in onFinish.- let creditCustomerId: string | null = null;- let monthlyCreditsRemaining = 0;- if (await isHostedServerAuthMode()) {- const questionCount = this.messages.filter(- (message) => message.role === "user",- ).length;- if (- questionCount > FREE_ONBOARDING_QUESTION_LIMIT &&- !(await customerHasManagedAccess(organizationId))- ) {- return staticAssistantResponse(- "You've used all your free strategy questions. Subscribe to continue.",- );- }-- const { depleted, monthlyRemaining } =- await checkUsageCreditsDepleted(billingCustomer);- if (depleted) {- return staticAssistantResponse(- "You've used your onboarding credits. Subscribe to continue.",- );- }- creditCustomerId = organizationId;- monthlyCreditsRemaining = monthlyRemaining;- }-- const model = await getChatAgentModel();-- const result = streamText({- model,- system: buildSystemPrompt(project.domain),- messages: await convertToModelMessages(this.messages),- // Cancel the (billable) LLM call if the user aborts/navigates away.- abortSignal: options?.abortSignal,- // Budget shared by reasoning + visible output. Reasoning tokens (enabled- // on the model) eat into this, and at max effort they dwarf the ~350-word- // strategy — the old 4000 cap left almost no answer headroom and- // truncated mid-table once the model had spent the budget thinking.- // Deliberately roomy: it's a per-step ceiling, not a target — the model- // only generates (and we only bill) what it actually uses.- maxOutputTokens: 32_000,- stopWhen: stepCountIs(5),- // Meter LLM spend against the same credit pool as DataForSEO: sum the real- // per-step cost OpenRouter reports and deduct it. Best-effort, hosted-only.- onFinish: async (event) => {- if (creditCustomerId !== null) {- const costUsd = event.steps.reduce(- (sum, step) => sum + openRouterCostUsd(step.providerMetadata),- 0,- );- await trackUsageCreditSpend({- customer: billingCustomer,- customerId: creditCustomerId,- creditFeature: "onboarding",- costUsd,- monthlyRemaining: monthlyCreditsRemaining,- properties: { provider: "openrouter" },- });- }- // Persist the assistant turn to this.messages (DO SQLite).- await onFinish(event);- },- tools: buildOnboardingTools({ project, billingCustomer }),- });-- return result.toUIMessageStreamResponse({- onError: (error) => {- console.error("[onboarding] chat stream error", error);- return "The assistant hit an error. Please try again.";- },- });- }-}diff --git a/src/server/features/onboarding/onboardingChatTools.ts b/src/server/features/onboarding/onboardingChatTools.tsdeleted file mode 100644index 787f5b97..00000000--- a/src/server/features/onboarding/onboardingChatTools.ts+++ /dev/null@@ -1,258 +0,0 @@-import { tool, type ToolSet } from "ai";-import { sort } from "remeda";-import { z } from "zod";-import { AppError } from "@/server/lib/errors";-import { MAX_PAGES, readPages, readSite } from "@/server/lib/scrape";-import { DomainService } from "@/server/features/domain/services/DomainService";-import { KeywordResearchService } from "@/server/features/keywords/services/KeywordResearchService";-import { createDataforseoClient } from "@/server/lib/dataforseo";-import { marketTools } from "@/server/features/onboarding/onboardingMarketTools";-import { isLabsLocationCode, LOCATIONS } from "@/shared/keyword-locations";-import type { BillingCustomerContext } from "@/server/billing/subscription";--// Just the project fields the tools read; the caller passes the full project row.-type OnboardingProject = {- id: string;- domain: string | null;- locationCode: number;- languageCode: string;- organizationId: string;-};--// Shared context derived once per turn and passed to each tool group.-export type ToolContext = {- project: OnboardingProject;- organizationId: string;- billingCustomer: BillingCustomerContext;- metering: { creditFeature: "onboarding" };- dfsClient: ReturnType<typeof createDataforseoClient>;- isSameDomain: (domain: unknown) => boolean;-};--/**- * Builds the tool set the onboarding chat agent hands to `streamText`. Split out- * of OnboardingChatAgent so the agent file (and onChatMessage) stays readable.- *- * Two tiers: the core tools analyze the user's own site; the market tools look- * at any domain and cost more credits — the system prompt tells Sam to use them- * sparingly. Every metered DataForSEO call is attributed to the "onboarding"- * credit feature. The result is widened to ToolSet so streamText infers a- * generic tool set, keeping its onFinish event assignable to the- * StreamTextOnFinishCallback<ToolSet> the agent forwards for persistence.- */-export function buildOnboardingTools({- project,- billingCustomer,-}: {- project: OnboardingProject;- billingCustomer: BillingCustomerContext;-}): ToolSet {- // Normalized form of the user's own domain, used to drop self-matches from- // competitor results.- const ownDomain = project.domain- ? project.domain.replace(/^www\./, "").toLowerCase()- : null;- const ctx: ToolContext = {- project,- organizationId: project.organizationId,- billingCustomer,- metering: { creditFeature: "onboarding" },- // Each metered call passes `creditFeature: "onboarding"` so spend lands on- // the onboarding line; the org's balance is asserted by the agent first.- dfsClient: createDataforseoClient(billingCustomer),- isSameDomain: (domain) =>- ownDomain != null &&- typeof domain === "string" &&- domain.replace(/^www\./, "").toLowerCase() === ownDomain,- };-- return { ...coreSiteTools(ctx), ...marketTools(ctx) } as ToolSet;-}--// Tools that analyze the user's own site (read_website, get_seo_metrics,-// research_keywords). Used freely per the system prompt.-function coreSiteTools(ctx: ToolContext): ToolSet {- const { project, organizationId, billingCustomer, metering } = ctx;- return {- read_website: tool({- description:- "Read web pages as plain text to ground advice. With no arguments, reads the user's own site (homepage plus a few pages from its sitemap) from the project's saved domain. Pass `urls` to read specific pages the user names instead — particular pages of their site, or a competitor's page to compare. Always available; uses no credits.",- inputSchema: z.object({- urls: z- .array(z.string().url())- .max(MAX_PAGES)- .optional()- .describe(- `Specific page URLs to read (max ${MAX_PAGES}). Omit to read the user's own site from its saved domain.`,- ),- }),- execute: async ({ urls }) => {- const site =- urls && urls.length > 0- ? await readPages(urls)- : project.domain- ? await readSite(project.domain)- : null;- if (!site) {- throw new AppError(- "VALIDATION_ERROR",- "Provide page URLs to read, or set a website domain first.",- );- }- if (site.blocked) {- return {- blocked: true,- pages: [],- note: "Could not read the requested page(s). Ask the user to describe what they cover, and keep the advice high-level.",- };- }- return {- blocked: false,- pages: site.pages.map((page) => ({- url: page.url,- title: page.title,- text: page.text,- })),- };- },- }),- get_seo_metrics: tool({- description:- "Get search-data signal for the user's own site: estimated organic traffic, number of ranking keywords, and the keywords they already rank for (top by traffic). Use to ground strategy in real rankings. May report unavailable for brand-new sites or unsupported markets.",- inputSchema: z.object({}),- execute: async () => {- if (!project.domain) {- throw new AppError("VALIDATION_ERROR", "Set a website domain first");- }- // Domain endpoints are Labs-only, so an unsupported market gets- // content-only advice. Spend is bounded by the org's credit balance,- // already asserted for the turn.- if (!isLabsLocationCode(project.locationCode)) {- return {- available: false,- reason:- "Ranking data isn't available for this market yet. Work from the site content instead.",- };- }-- try {- // Fetch the overview and ranked keywords in parallel so the tool- // doesn't block on the two DataForSEO calls in series. Trade-off:- // this always issues the (metered) ranked-keywords call, even for- // sites with no rankings where the sequential version skipped it.- const [overview, ranked] = await Promise.all([- DomainService.getOverview(- {- projectId: project.id,- domain: project.domain,- scope: "domain",- locationCode: project.locationCode,- languageCode: project.languageCode,- },- billingCustomer,- metering,- ),- DomainService.getSuggestedKeywords(- {- domain: project.domain,- locationCode: project.locationCode,- languageCode: project.languageCode,- organizationId,- projectId: project.id,- },- billingCustomer,- metering,- ),- ]);-- const rankedKeywords = overview.hasData- ? ranked.slice(0, 20).map((kw) => ({- keyword: kw.keyword,- position: kw.position,- searchVolume: kw.searchVolume,- keywordDifficulty: kw.keywordDifficulty,- }))- : [];-- return {- available: true,- market: LOCATIONS[project.locationCode] ?? "your market",- hasRankings: overview.hasData,- organicTraffic: overview.organicTraffic,- organicKeywords: overview.organicKeywords,- rankedKeywords,- };- } catch (error) {- console.error("[onboarding] get_seo_metrics failed", {- domain: project.domain,- locationCode: project.locationCode,- languageCode: project.languageCode,- error,- });- throw error;- }- },- }),- research_keywords: tool({- description:- "Research real keyword ideas for the user's site. Given one seed topic drawn from their content, returns related keywords each with monthly search volume, keyword difficulty (KD), and intent. Use to ground keyword suggestions in real data, especially when the site has no rankings yet.",- inputSchema: z.object({- seed: z- .string()- .min(1)- .describe(- "A short seed topic or phrase from the site's content (e.g. 'agentless PAM').",- ),- }),- execute: async ({ seed }) => {- if (!project.domain) {- throw new AppError("VALIDATION_ERROR", "Set a website domain first");- }- try {- const researchResult = await KeywordResearchService.research(- {- projectId: project.id,- keywords: [seed],- locationCode: project.locationCode,- languageCode: project.languageCode,- resultLimit: 150,- // One source (keyword_ideas) keeps onboarding spend to a single- // DataForSEO call; research() routes unsupported markets to the- // Google Ads fallback automatically.- mode: "ideas",- clickstream: false,- },- billingCustomer,- "onboarding",- );-- // Keep only keywords with a real volume — the strategy table shows- // volume + KD, so a null-volume row can't be grounded.- const withVolume = researchResult.rows.filter(- (row) => row.searchVolume != null,- );- const keywords = sort(- withVolume,- (a, b) => (b.searchVolume ?? 0) - (a.searchVolume ?? 0),- ).map((row) => ({- keyword: row.keyword,- searchVolume: row.searchVolume,- keywordDifficulty: row.keywordDifficulty,- intent: row.intent,- }));-- return { available: keywords.length > 0, keywords };- } catch (error) {- console.error("[onboarding] research_keywords failed", {- domain: project.domain,- seed,- locationCode: project.locationCode,- languageCode: project.languageCode,- error,- });- throw error;- }- },- }),- } as ToolSet;-}diff --git a/src/server/features/onboarding/onboardingMarketTools.ts b/src/server/features/onboarding/onboardingMarketTools.tsdeleted file mode 100644index 54ebfd0b..00000000--- a/src/server/features/onboarding/onboardingMarketTools.ts+++ /dev/null@@ -1,242 +0,0 @@-import { tool, type ToolSet } from "ai";-import { sort } from "remeda";-import { z } from "zod";-import { DomainService } from "@/server/features/domain/services/DomainService";-import { BacklinksService } from "@/server/features/backlinks/services/BacklinksService";-import { isLabsLocationCode, LOCATIONS } from "@/shared/keyword-locations";-import type { ToolContext } from "@/server/features/onboarding/onboardingChatTools";--// Tools that analyze any domain / the wider market (domain overview, SERP,-// competitors, competitor keywords, backlinks). These cost more credits, so the-// system prompt tells Sam to use them sparingly.-export function marketTools(ctx: ToolContext): ToolSet {- const { project, organizationId, billingCustomer, metering, dfsClient } = ctx;- const { isSameDomain } = ctx;- return {- get_domain_overview: tool({- description:- "Get a high-level organic-search footprint for ANY domain (estimated organic traffic and ranking-keyword count). Use it to compare the user against a named competitor or reference site. For backlinks/authority use get_backlinks_overview. Costs credits — only call when the user asks how they compare to a competitor or about the wider market.",- inputSchema: z.object({- domain: z- .string()- .min(1)- .describe(- "The competitor or reference domain to look up, e.g. 'cyberark.com'.",- ),- }),- execute: async ({ domain }) => {- if (!isLabsLocationCode(project.locationCode)) {- return {- available: false,- reason:- "Competitor data isn't available for this market yet. Work from the site content instead.",- };- }- try {- const overview = await DomainService.getOverview(- {- projectId: project.id,- domain,- scope: "domain",- locationCode: project.locationCode,- languageCode: project.languageCode,- },- billingCustomer,- metering,- );- return {- available: true,- domain,- market: LOCATIONS[project.locationCode] ?? "your market",- hasData: overview.hasData,- organicTraffic: overview.organicTraffic,- organicKeywords: overview.organicKeywords,- };- } catch (error) {- console.error("[onboarding] get_domain_overview failed", {- domain,- error,- });- throw error;- }- },- }),- get_serp_results: tool({- description:- "Fetch live Google search results for 1-3 keywords to show who currently ranks on page one. Use it when the user wants to see the real SERP for a target term or judge how hard a keyword looks. Costs credits per keyword — keep to the few keywords that matter.",- inputSchema: z.object({- keywords: z- .array(z.string().min(1))- .min(1)- .max(3)- .describe("1-3 search queries to inspect."),- }),- execute: async ({ keywords }) => {- const results = await Promise.all(- keywords.map(async (keyword) => {- try {- const items = await dfsClient.serp.live({- keyword,- locationCode: project.locationCode,- languageCode: project.languageCode,- creditFeature: "onboarding",- });- return {- keyword,- ok: true as const,- results: items- .filter((item) => item.type === "organic")- .slice(0, 10)- .map((item) => ({- rank: item.rank_group ?? item.rank_absolute ?? null,- domain: item.domain ?? null,- title: item.title ?? null,- url: item.url ?? null,- })),- };- } catch (error) {- return {- keyword,- ok: false as const,- error: error instanceof Error ? error.message : "failed",- };- }- }),- );- return { results };- },- }),- find_serp_competitors: tool({- description:- "Given a small set of the user's target keywords, find the domains that compete with them in Google results (with each competitor's keyword coverage and estimated traffic). Use it when the user asks who their SEO competitors are. Costs credits — call once with the best 2-5 keywords, not repeatedly.",- inputSchema: z.object({- keywords: z- .array(z.string().min(1))- .min(1)- .max(5)- .describe(- "2-5 of the user's most important target keywords, drawn from their site or rankings.",- ),- }),- execute: async ({ keywords }) => {- if (!isLabsLocationCode(project.locationCode)) {- return {- available: false,- reason: "Competitor data isn't available for this market yet.",- };- }- try {- const competitors = await dfsClient.labs.serpCompetitors({- keywords,- locationCode: project.locationCode,- languageCode: project.languageCode,- limit: 50,- creditFeature: "onboarding",- });- const top = sort(- competitors.filter((c) => !isSameDomain(c.domain)),- (a, b) => (b.etv ?? 0) - (a.etv ?? 0),- )- .slice(0, 10)- .map((c) => ({- domain: c.domain ?? null,- keywordsCount: c.keywords_count ?? null,- avgPosition: c.avg_position ?? null,- estimatedTraffic: c.etv ?? null,- }));- return { available: true, competitors: top };- } catch (error) {- console.error("[onboarding] find_serp_competitors failed", {- keywords,- error,- });- throw error;- }- },- }),- get_competitor_keywords: tool({- description:- "List the keywords a competitor or reference domain already ranks for (keyword, position, search volume, difficulty). Use it to find gaps — terms a competitor wins that the user could target. Costs credits — call for at most one or two competitor domains.",- inputSchema: z.object({- domain: z- .string()- .min(1)- .describe("The competitor domain to inspect, e.g. 'cyberark.com'."),- }),- execute: async ({ domain }) => {- if (!isLabsLocationCode(project.locationCode)) {- return {- available: false,- reason: "Competitor data isn't available for this market yet.",- };- }- try {- // Reuse the shared service (12h cache + mapKeywordItem) so this- // matches get_seo_metrics rather than re-parsing raw SDK rows.- const ranked = await DomainService.getSuggestedKeywords(- {- domain,- locationCode: project.locationCode,- languageCode: project.languageCode,- organizationId,- projectId: project.id,- },- billingCustomer,- metering,- );- const keywords = ranked.slice(0, 25).map((kw) => ({- keyword: kw.keyword,- position: kw.position,- searchVolume: kw.searchVolume,- keywordDifficulty: kw.keywordDifficulty,- }));- return {- available: keywords.length > 0,- domain,- keywords,- };- } catch (error) {- console.error("[onboarding] get_competitor_keywords failed", {- domain,- error,- });- throw error;- }- },- }),- get_backlinks_overview: tool({- description:- "Get a backlinks summary for the user's site or a competitor (total backlinks, referring domains). Backlinks signal how much authority a site has earned. Costs credits (this is the most expensive tool) — only call when the user explicitly asks about backlinks or authority.",- inputSchema: z.object({- domain: z- .string()- .min(1)- .describe(- "Domain to analyze. Use the user's own domain unless they name a competitor.",- ),- }),- execute: async ({ domain }) => {- try {- const { overview } = await BacklinksService.profileOverview(- { target: domain, scope: "subdomains" },- billingCustomer,- "onboarding",- );- return {- available: true,- domain,- backlinks: overview.summary.backlinks,- referringDomains: overview.summary.referringDomains,- referringPages: overview.summary.referringPages,- };- } catch (error) {- console.error("[onboarding] get_backlinks_overview failed", {- domain,- error,- });- throw error;- }- },- }),- } as ToolSet;-}diff --git a/src/server/features/projects/repositories/ProjectRepository.ts b/src/server/features/projects/repositories/ProjectRepository.tsindex ab05869c..a9f18924 100644--- a/src/server/features/projects/repositories/ProjectRepository.ts+++ b/src/server/features/projects/repositories/ProjectRepository.ts@@ -46,8 +46,8 @@ async function getProjectForOrganization(// Look up a project by id alone (no org scoping). Only for trusted server// contexts that have already authorized access another way — e.g. the-// onboarding chat Durable Object, whose connections are authorized in the-// Worker before they reach the DO, and which derives its org from the project.+// SAM chat Durable Object, whose connections are authorized in the Worker+// before they reach the DO, and which derives its org from the project.async function getProjectById(projectId: string) {const [project] = await db.select()diff --git a/src/server/features/onboarding/openseo-fact-sheet.md b/src/server/features/sam/openseo-fact-sheet.mdsimilarity index 100%rename from src/server/features/onboarding/openseo-fact-sheet.mdrename to src/server/features/sam/openseo-fact-sheet.mddiff --git a/src/server/features/sam/samChatTools.ts b/src/server/features/sam/samChatTools.tsindex 7f8120dd..8739dafe 100644--- a/src/server/features/sam/samChatTools.ts+++ b/src/server/features/sam/samChatTools.ts@@ -58,10 +58,10 @@ import {} from "@/server/mcp/tools/search-console-tools";import { whoamiTool } from "@/server/mcp/tools/whoami";import { discoverSiteUrls, readPages, readSite } from "@/server/lib/scrape";-import openSeoFactSheet from "@/server/features/onboarding/openseo-fact-sheet.md?raw";+import openSeoFactSheet from "@/server/features/sam/openseo-fact-sheet.md?raw";-// SAM reads more of a site than the onboarding preview: enough pages to work-// out what a business does, sells, and positions against on its own.+// Enough pages for SAM to work out what a business does, sells, and positions+// against on its own.const SAM_MAX_SCRAPE_PAGES = 10;const SAM_MAX_MAPPED_URLS = 60;@@ -213,9 +213,9 @@ export function waitingAuditStatusTool(};}-// Free (credit-less) site-reading tools, mirroring the onboarding agent's-// read_website but split into discovery + reading so the model can pick which-// pages to read instead of blindly taking the first N sitemap entries.+// Free (credit-less) site-reading tools, split into discovery + reading so the+// model can pick which pages to read instead of blindly taking the first N+// sitemap entries.function scrapeTools(projectDomain: string | null): ToolSet {return {map_links: tool({diff --git a/src/server/features/sam/samSystemPrompt.ts b/src/server/features/sam/samSystemPrompt.tsindex 19f3c3cc..5d49a853 100644--- a/src/server/features/sam/samSystemPrompt.ts+++ b/src/server/features/sam/samSystemPrompt.ts@@ -12,8 +12,7 @@ type SamProjectContext = {* SAM's "soul" — the identity block of the system prompt. The project's shared* memory is a separate, read-only context block (rendered from* ProjectContextService); this block carries the identity, tool rules, and the- * discipline for keeping that memory current. Kept deliberately close to the- * onboarding agent's voice, minus the pre-paywall framing.+ * discipline for keeping that memory current.*/export function buildSamSystemPrompt(project: SamProjectContext,diff --git a/src/server/gdpr/storage-erasure.ts b/src/server/gdpr/storage-erasure.tsindex cad9cc0b..927917f9 100644--- a/src/server/gdpr/storage-erasure.ts+++ b/src/server/gdpr/storage-erasure.ts@@ -1,5 +1,4 @@import { getAuth } from "@/lib/auth";-import type { OnboardingChatAgent } from "@/server/features/onboarding/OnboardingChatAgent";import type { SamChatAgent } from "@/server/features/sam/SamChatAgent";import { captureServerError } from "@/server/lib/posthog";import {@@ -197,14 +196,6 @@ async function eraseStorage(env: Env, payload: GdprStorageErasurePayload) {for (const sessionId of payload.samSessionIds) {await samChat.get(samChat.idFromName(sessionId)).destroyForErasure();}- const onboardingChat =- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the binding is declared as this class in wrangler.jsonc- env.ONBOARDING_CHAT as unknown as DurableObjectNamespace<OnboardingChatAgent>;- for (const projectId of payload.projectIds) {- await onboardingChat- .get(onboardingChat.idFromName(projectId))- .destroyForErasure();- }for (const auditId of payload.auditIds) {// The scratchpad DO lives in the open-seo-audit worker; destroy is the// same full wipe destroyForErasure performs.@@ -240,7 +231,6 @@ async function eraseStorage(env: Env, payload: GdprStorageErasurePayload) {},durableObjects: {sam: payload.samSessionIds.length,- onboarding: payload.projectIds.length,auditScratchpads: payload.auditIds.length,},kv: {diff --git a/src/server/lib/chatAgent.ts b/src/server/lib/chatAgent.tsindex cd588c88..bf6123ea 100644--- a/src/server/lib/chatAgent.ts+++ b/src/server/lib/chatAgent.ts@@ -1,16 +1,15 @@import type { LanguageModelV3 } from "@openrouter/ai-sdk-provider";import { subscribe } from "agents/observability";-import { createUIMessageStream, createUIMessageStreamResponse } from "ai";import { z } from "zod";-// The chat agents' most common failure modes — a provider stream dying+// The chat agent's most common failure modes — a provider stream dying// mid-turn ("chat:request:failed", stage "stream") and a DO restart whose// recovery gives up ("chat:recovery:exhausted") — never reach an onChatError// hook; their only signal is the agents:chat diagnostics channel, which is// silent without a subscriber. This module-level subscription puts them in-// the Workers logs for every chat DO in the isolate (SAM + onboarding). The-// user-visible residue of these is the replayed "Something went wrong"-// banner plus a partially-streamed assistant message.+// the Workers logs for every chat DO in the isolate. The user-visible residue+// of these is the replayed "Something went wrong" banner plus a+// partially-streamed assistant message.subscribe("chat", (event) => {if (event.type === "chat:request:failed" ||@@ -25,8 +24,8 @@ subscribe("chat", (event) => {});// OpenRouter (with usage accounting on) reports the real USD cost of each-// response under providerMetadata.openrouter.usage.cost. Shared by the chat-// agents (onboarding + SAM) that meter LLM spend against the credit pool.+// response under providerMetadata.openrouter.usage.cost. Used by SAM to meter+// LLM spend against the credit pool.const openRouterUsageSchema = z.object({openrouter: z.object({ usage: z.object({ cost: z.number() }) }),});@@ -36,21 +35,6 @@ export function openRouterCostUsd(providerMetadata: unknown): number {return parsed.success ? parsed.data.openrouter.usage.cost : 0;}-// A non-LLM assistant turn streamed back over the chat protocol. Used to surface-// gates ("Subscribe to continue") without spending an LLM call — the client-// renders it as a normal assistant message.-export function staticAssistantResponse(text: string): Response {- const stream = createUIMessageStream({- execute: ({ writer }) => {- const id = crypto.randomUUID();- writer.write({ type: "text-start", id });- writer.write({ type: "text-delta", id, delta: text });- writer.write({ type: "text-end", id });- },- });- return createUIMessageStreamResponse({ stream });-}-// The provider package re-exports only LanguageModelV3 itself, so the stream// shape is derived from the interface.type StreamResult = Awaited<ReturnType<LanguageModelV3["doStream"]>>;diff --git a/src/server/lib/openrouter.ts b/src/server/lib/openrouter.tsindex f06cafc5..464c1a77 100644--- a/src/server/lib/openrouter.ts+++ b/src/server/lib/openrouter.ts@@ -2,27 +2,17 @@ import {createOpenRouter,type LanguageModelV3,} from "@openrouter/ai-sdk-provider";-import {- getOptionalEnvValue,- getRequiredEnvValue,-} from "@/server/lib/runtime-env";-// OpenRouter model slug used for the in-app chat agents (onboarding + SAM).-// Override with OPENROUTER_MODEL to swap models without a code change.+// OpenRouter model slug used for the SAM in-app chat agent. Override with+// OPENROUTER_MODEL to swap models without a code change.const DEFAULT_CHAT_AGENT_MODEL = "openai/gpt-5.6-luna";// Previous default; kept reachable via OPENROUTER_MODEL for rollback. Its// routing needs the ZDR/provider tuning below.const MINIMAX_M3 = "minimax/minimax-m3";-export async function getChatAgentModel(): Promise<LanguageModelV3> {- const apiKey = await getRequiredEnvValue("OPENROUTER_API_KEY");- const modelId = await getOptionalEnvValue("OPENROUTER_MODEL");- return buildChatAgentModel(apiKey, modelId);-}-/**- * Returns the AI SDK LanguageModel for the chat agents. `usage: { include: true }`+ * Returns the AI SDK LanguageModel for the chat agent. `usage: { include: true }`* turns on OpenRouter usage accounting so each response carries its real USD* cost (providerMetadata.openrouter.usage.cost) — which we meter against the* shared usage-credit pool.diff --git a/src/server/lib/scrape.ts b/src/server/lib/scrape.tsindex 7a8da8f1..dfdded36 100644--- a/src/server/lib/scrape.ts+++ b/src/server/lib/scrape.ts@@ -7,7 +7,7 @@import { normalizeAndValidateStartUrl } from "@/server/lib/audit/url-policy";-export const MAX_PAGES = 5;+const MAX_PAGES = 5;const PER_PAGE_CHAR_LIMIT = 4000;const FETCH_TIMEOUT_MS = 10_000;const MAX_RESPONSE_BYTES = 2_000_000;diff --git a/src/server/lib/workers-ai-provider-stub.ts b/src/server/lib/workers-ai-provider-stub.tsindex de14bd7e..91a87e2c 100644--- a/src/server/lib/workers-ai-provider-stub.ts+++ b/src/server/lib/workers-ai-provider-stub.ts@@ -5,15 +5,15 @@* `@cloudflare/think` eagerly imports all three (~540 kB with the @ai-sdk/* openai + @ai-sdk/anthropic providers they pull in) solely to build its lazy* default provider in `resolveModel()` — which only runs when `getModel()`- * returns a bare model-id string. Both our chat agents (SamChatAgent,- * OnboardingChatAgent) return a constructed OpenRouter LanguageModel instead,- * so the default provider is dead code; this stub keeps it out of the eager- * worker bundle. Same pattern as just-bash-stub.ts.+ * returns a bare model-id string. Our chat agent (SamChatAgent) returns a+ * constructed OpenRouter LanguageModel instead, so the default provider is+ * dead code; this stub keeps it out of the eager worker bundle. Same pattern+ * as just-bash-stub.ts.*/const STUBBED_MESSAGE ="workers-ai-provider is stubbed out of the worker bundle to keep it out of " +"the eager isolate startup graph (see vite-plugin-lean-worker-bundle.ts); " +- "SamChatAgent/OnboardingChatAgent override getModel with OpenRouter";+ "SamChatAgent overrides getModel with OpenRouter";// Covers every named import in the dependency graph: `createWorkersAI` (root),// `anthropic` (/anthropic) and `openai` (/openai).diff --git a/src/serverFunctions/onboardingChat.ts b/src/serverFunctions/onboardingChat.tsdeleted file mode 100644index 69adf03d..00000000--- a/src/serverFunctions/onboardingChat.ts+++ /dev/null@@ -1,71 +0,0 @@-import { createServerFn } from "@tanstack/react-start";-import { and, eq } from "drizzle-orm";-import { z } from "zod";-import { db } from "@/db";-import { projects } from "@/db/schema";-import { requireAuthenticatedContext } from "@/serverFunctions/middleware";-import { AppError } from "@/server/lib/errors";-import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";-import { ProjectService } from "@/server/features/projects/services/ProjectService";-import { normalizeDomainInput } from "@/server/lib/domainUtils";-import {- getLanguageCode,- isSupportedLocationCode,-} from "@/shared/keyword-locations";--// Returns the onboarding project (id + domain). Uses the org's default project;-// onboarding targets a single project in v1.-export const getOnboardingChatState = createServerFn({ method: "GET" })- .middleware(requireAuthenticatedContext)- .handler(async ({ context }) => {- const [project] = await ProjectService.listProjectsEnsuringOne(- context.organizationId,- );- if (!project) {- throw new AppError("NOT_FOUND");- }- return {- projectId: project.id,- domain: project.domain,- };- });--const saveSiteSchema = z.object({- projectId: z.string().min(1),- domain: z.string().min(1),- locationCode: z.number().int(),-});--// Persists the site + default location for the onboarding project.-export const saveOnboardingSite = createServerFn({ method: "POST" })- .middleware(requireAuthenticatedContext)- .validator(saveSiteSchema)- .handler(async ({ data, context }) => {- const project = await ProjectRepository.getProjectForOrganization(- data.projectId,- context.organizationId,- );- if (!project) {- throw new AppError("NOT_FOUND");- }-- if (!isSupportedLocationCode(data.locationCode)) {- throw new AppError("VALIDATION_ERROR", "Unsupported location");- }- const newDomain = normalizeDomainInput(data.domain, false);- await db- .update(projects)- .set({- domain: newDomain,- locationCode: data.locationCode,- languageCode: getLanguageCode(data.locationCode),- })- .where(- and(- eq(projects.id, data.projectId),- eq(projects.organizationId, context.organizationId),- ),- );-- return { ok: true };- });diff --git a/src/shared/billing-credit-features.ts b/src/shared/billing-credit-features.tsindex e4f7172e..b6723fa9 100644--- a/src/shared/billing-credit-features.ts+++ b/src/shared/billing-credit-features.ts@@ -7,7 +7,6 @@ export type CreditFeature =| "ai_citations"| "ai_prompt_responses"| "local_seo"- | "onboarding"| "agent";const CREDIT_FEATURE_LABELS: Record<string, string> = {@@ -20,6 +19,8 @@ const CREDIT_FEATURE_LABELS: Record<string, string> = {ai_prompt_responses: "AI Prompt Responses",ai_search: "AI Search",local_seo: "Local SEO",+ // The onboarding chat is gone, but historical usage events still carry this+ // key — keep the label so old billing breakdowns don't render "Other".onboarding: "Onboarding",agent: "SAM Agent",};diff --git a/src/shared/billing.ts b/src/shared/billing.tsindex d1bd6969..b672b688 100644--- a/src/shared/billing.ts+++ b/src/shared/billing.ts@@ -8,7 +8,7 @@ export const AUTUMN_PAID_PLAN_FEATURE_ID = "paid_plan";// user gets it) and the paid base plan. It's the floor for using the managed// service at all — paid-only features gate on AUTUMN_PAID_PLAN_FEATURE_ID.export const AUTUMN_MANAGED_ACCESS_FEATURE_ID = "managed_service_access";-// The shared usage-credit pool. Both DataForSEO and onboarding-LLM spend deduct+// The shared usage-credit pool. Both DataForSEO and agent-LLM spend deduct// from these (monthly usage_credits first, then rolled-over topup_credits).export const AUTUMN_SEO_DATA_BALANCE_FEATURE_ID = "usage_credits";export const AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID = "topup_credits";diff --git a/src/shared/gdpr-erasure.ts b/src/shared/gdpr-erasure.tsindex 6c5a7c09..8734e451 100644--- a/src/shared/gdpr-erasure.ts+++ b/src/shared/gdpr-erasure.ts@@ -12,7 +12,6 @@ export const gdprStorageErasurePayloadSchema = zuserId: z.string().min(1).max(512),email: z.string().email().max(512),organizationIds: boundedIds,- projectIds: boundedIds,samSessionIds: boundedIds,auditIds: boundedIds,activeAuditWorkflowIds: boundedIds,diff --git a/src/shared/onboardingChat.ts b/src/shared/onboardingChat.tsdeleted file mode 100644index 06447415..00000000--- a/src/shared/onboardingChat.ts+++ /dev/null@@ -1,8 +0,0 @@-// Free-plan users get a bounded number of strategy-refinement questions in the-// onboarding chat before they're nudged to subscribe. Shared so the client gate-// (disables the composer, shows "N left") and the server-side re-check agree on-// the same number. NOTE: the server counts client-supplied chat history, so a-// crafted client can keep the count low — this cap is a conversion nudge, not a-// security boundary. The real spend bound is the org's credit balance (asserted-// server-side on every turn and inside each DataForSEO call).-export const FREE_ONBOARDING_QUESTION_LIMIT = 7;diff --git a/wrangler.jsonc b/wrangler.jsoncindex 50a53494..b4a3171f 100644--- a/wrangler.jsonc+++ b/wrangler.jsonc@@ -37,19 +37,13 @@"class_name": "RankCheckWorkflow",},],- // Durable Object backing the onboarding strategy chat (Agents SDK- // AIChatAgent). One instance per project; messages persist in the DO's- // SQLite. SQLite-backed classes must be declared in `migrations` below for- // the wrangler/workerd surfaces (local dev, Docker self-host); Alchemy- // deploys derive SQLite backing on their own.+ // Durable Object backing the SAM in-app agent (Agents SDK AIChatAgent). One+ // instance per chat session; messages persist in the DO's SQLite.+ // SQLite-backed classes must be declared in `migrations` below for the+ // wrangler/workerd surfaces (local dev, Docker self-host); Alchemy deploys+ // derive SQLite backing on their own."durable_objects": {"bindings": [- {- "name": "ONBOARDING_CHAT",- "class_name": "OnboardingChatAgent",- },- // SAM in-app agent. One instance per chat session; messages persist in the- // DO's SQLite. SQLite-backed classes must be declared in `migrations`.{"name": "SAM_CHAT","class_name": "SamChatAgent",@@ -90,6 +84,13 @@"tag": "v4","deleted_classes": ["AuditScratchpad"],},+ // The onboarding strategy chat was removed: the namespace had had zero+ // invocations for months. Deleting the class destroys every instance's+ // stored conversation, which is the intent — nothing else reads it.+ {+ "tag": "v5",+ "deleted_classes": ["OnboardingChatAgent"],+ },],"triggers": {// Every 5 min: rank checks + stale-audit reconcile. Daily: OAuth KV GC.