Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat: GEO infrastructure — llms.txt, Markdown docs, sitemap/robots/JSON-LD fixes and AI visit logging (MUL-9850) (#11194)

Jiayuan Zhangd36b72b3b119
diff --git a/.env.example b/.env.example
index e570d4dd89..62870f3f21 100644
--- a/.env.example
+++ b/.env.example
@@ -816,6 +816,8 @@ DO_NOT_TRACK=
# Product analytics events feed the acquisition → activation → expansion funnel.
# Leave POSTHOG_API_KEY empty for local dev / self-hosted instances; the server
# will run a no-op analytics client and ship nothing.
+# The web and docs Next.js servers read the same variables to retain
+# `ai_visit` events (AI crawler and agent traffic) from their proxies.
POSTHOG_API_KEY=
POSTHOG_HOST=https://us.i.posthog.com
# Optional override for the `environment` PostHog event property.
diff --git a/.github/ci-paths.json b/.github/ci-paths.json
index e1fbd40687..6b094df4ec 100644
--- a/.github/ci-paths.json
+++ b/.github/ci-paths.json
@@ -23,6 +23,8 @@
"server/internal/daemon/config.go",
"server/pkg/agent/builtin_runtimes.go",
"server/internal/featureflags/keys.go",
+ "packages/core/ai-traffic/**",
+ "SELF_HOSTING_AI.md",
"package.json",
".npmrc",
"pnpm-lock.yaml",
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 84c91281e7..d5ddbdee23 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -267,7 +267,8 @@ jobs:
# was too heavy (#1279). Its Vitest suite is not: it guards content such as
# unrendered CJK bold and finishes in seconds. It gets its own scope so a
# content-only PR runs it and an unrelated PR pays nothing, and installs only
- # the docs package so the job stays far off the frontend critical path.
+ # the docs package and its workspace dependencies so the job stays far off
+ # the frontend critical path.
docs-test:
needs: changes
if: ${{ needs.changes.outputs.docs == 'true' }}
@@ -286,7 +287,7 @@ jobs:
cache: pnpm
- name: Install docs dependencies
- run: pnpm install --frozen-lockfile --filter @multica/docs
+ run: pnpm install --frozen-lockfile --filter @multica/docs...
- name: Test docs
run: pnpm --filter @multica/docs test
diff --git a/apps/docs/app/[lang]/[...slug]/page.tsx b/apps/docs/app/[lang]/[...slug]/page.tsx
index 0548f3f4f6..37348c62d6 100644
--- a/apps/docs/app/[lang]/[...slug]/page.tsx
+++ b/apps/docs/app/[lang]/[...slug]/page.tsx
@@ -10,17 +10,11 @@ import defaultMdxComponents from "fumadocs-ui/mdx";
import { ImageZoom, type ImageZoomProps } from "fumadocs-ui/components/image-zoom";
import type { Metadata } from "next";
import { docsAlternates } from "@/lib/site";
-import { i18n, type Lang } from "@/lib/i18n";
+import { asLang } from "@/lib/i18n";
import { DocsLocaleProvider, LocaleLink } from "@/components/locale-link";
import { VideoEmbed } from "@/components/video-embed";
import { docsSlugStaticParams } from "@/lib/static-params";
-function asLang(lang: string): Lang {
- return (i18n.languages as readonly string[]).includes(lang)
- ? (lang as Lang)
- : (i18n.defaultLanguage as Lang);
-}
-
export default async function Page(props: {
params: Promise<{ lang: string; slug: string[] }>;
}) {
diff --git a/apps/docs/app/[lang]/llms-full.txt/route.ts b/apps/docs/app/[lang]/llms-full.txt/route.ts
new file mode 100644
index 0000000000..eced5a78d2
--- /dev/null
+++ b/apps/docs/app/[lang]/llms-full.txt/route.ts
@@ -0,0 +1,13 @@
+import { asLang, i18n } from "@/lib/i18n";
+import { docsFullMarkdown, markdownResponse } from "@/lib/llms";
+
+export const revalidate = false;
+
+export function generateStaticParams() {
+ return i18n.languages.map((lang) => ({ lang }));
+}
+
+export async function GET(_request: Request, { params }: { params: Promise<{ lang: string }> }) {
+ const { lang } = await params;
+ return markdownResponse(await docsFullMarkdown(asLang(lang)));
+}
diff --git a/apps/docs/app/[lang]/llms.mdx/[[...slug]]/route.ts b/apps/docs/app/[lang]/llms.mdx/[[...slug]]/route.ts
new file mode 100644
index 0000000000..7ec740da48
--- /dev/null
+++ b/apps/docs/app/[lang]/llms.mdx/[[...slug]]/route.ts
@@ -0,0 +1,24 @@
+import { asLang } from "@/lib/i18n";
+import { source } from "@/lib/source";
+import { absoluteDocsUrl } from "@/lib/site";
+import { markdownResponse, pageMarkdown } from "@/lib/llms";
+
+// Target of the docs proxy's `.md` and `Accept: text/markdown` rewrites.
+export const revalidate = false;
+
+export function generateStaticParams() {
+ return source.generateParams();
+}
+
+export async function GET(
+ _request: Request,
+ { params }: { params: Promise<{ lang: string; slug?: string[] }> },
+) {
+ const { lang: rawLang, slug = [] } = await params;
+ const lang = asLang(rawLang);
+ const page = source.getPage(slug, lang);
+ if (!page) return markdownResponse("# Not found\n", { status: 404 });
+ return markdownResponse(await pageMarkdown(page, lang), {
+ canonical: absoluteDocsUrl(page.url),
+ });
+}
diff --git a/apps/docs/app/[lang]/llms.txt/route.ts b/apps/docs/app/[lang]/llms.txt/route.ts
new file mode 100644
index 0000000000..5e771ed549
--- /dev/null
+++ b/apps/docs/app/[lang]/llms.txt/route.ts
@@ -0,0 +1,13 @@
+import { asLang, i18n } from "@/lib/i18n";
+import { docsIndexMarkdown, markdownResponse } from "@/lib/llms";
+
+export const revalidate = false;
+
+export function generateStaticParams() {
+ return i18n.languages.map((lang) => ({ lang }));
+}
+
+export async function GET(_request: Request, { params }: { params: Promise<{ lang: string }> }) {
+ const { lang } = await params;
+ return markdownResponse(await docsIndexMarkdown(asLang(lang)));
+}
diff --git a/apps/docs/app/[lang]/page.tsx b/apps/docs/app/[lang]/page.tsx
index a9f21798f9..c4a9b04d67 100644
--- a/apps/docs/app/[lang]/page.tsx
+++ b/apps/docs/app/[lang]/page.tsx
@@ -8,17 +8,11 @@ import { DocsHero } from "@/components/hero";
import { NumberedCards, NumberedCard, NumberedSteps, Step } from "@/components/editorial";
import { VideoEmbed } from "@/components/video-embed";
import { CommunityLinks } from "@/components/community-links";
-import { i18n, type Lang } from "@/lib/i18n";
+import { asLang, i18n } from "@/lib/i18n";
import { homeCopy } from "@/lib/translations";
import { docsAlternates } from "@/lib/site";
import { DocsLocaleProvider, LocaleLink } from "@/components/locale-link";
-function asLang(lang: string): Lang {
- return (i18n.languages as readonly string[]).includes(lang)
- ? (lang as Lang)
- : (i18n.defaultLanguage as Lang);
-}
-
// A layout's `generateStaticParams` does NOT cascade — every page that
// wants SSG must declare its own. Without this, both `/docs/` and
// `/docs/zh` (the busiest URLs on the site) render dynamically on every
diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.json
index d67506796d..b85342c8c8 100644
--- a/apps/docs/content/docs/meta.json
+++ b/apps/docs/content/docs/meta.json
@@ -54,6 +54,7 @@
"desktop-app",
"mobile-app",
"---Self-hosting---",
+ "self-hosting-ai",
"security-model",
"environment-variables",
"auth-setup",
diff --git a/apps/docs/content/docs/self-hosting-ai.mdx b/apps/docs/content/docs/self-hosting-ai.mdx
new file mode 100644
index 0000000000..e3a32881c3
--- /dev/null
+++ b/apps/docs/content/docs/self-hosting-ai.mdx
@@ -0,0 +1,6 @@
+---
+title: Self-hosting setup for AI agents
+description: Exact commands an AI agent can run to deploy Multica locally and connect the CLI.
+---
+
+<include>../../../../SELF_HOSTING_AI.md</include>
diff --git a/apps/docs/lib/i18n.ts b/apps/docs/lib/i18n.ts
index 57d047dd10..b93a4f55d4 100644
--- a/apps/docs/lib/i18n.ts
+++ b/apps/docs/lib/i18n.ts
@@ -14,3 +14,9 @@ export const i18n = defineI18n({
});
export type Lang = (typeof i18n.languages)[number];
+
+export function asLang(lang: string): Lang {
+ return (i18n.languages as readonly string[]).includes(lang)
+ ? (lang as Lang)
+ : (i18n.defaultLanguage as Lang);
+}
diff --git a/apps/docs/lib/llms.ts b/apps/docs/lib/llms.ts
new file mode 100644
index 0000000000..b2e174f24a
--- /dev/null
+++ b/apps/docs/lib/llms.ts
@@ -0,0 +1,118 @@
+import { llms } from "fumadocs-core/source/llms";
+import type { Node as PageTreeNode } from "fumadocs-core/page-tree";
+import { source } from "@/lib/source";
+import { i18n, type Lang } from "@/lib/i18n";
+import { absoluteDocsUrl, DOCS_BASE_PATH, SITE_ORIGIN } from "@/lib/site";
+import { renderPageMarkdown } from "@/lib/markdown-export";
+import { localeLabels } from "@/lib/translations";
+
+export const DOCS_URL = `${SITE_ORIGIN}${DOCS_BASE_PATH}`;
+
+type DocsPage = NonNullable<ReturnType<typeof source.getPage>>;
+
+/** Pages listed first in `llms.txt` for agents that install or operate Multica. */
+const AGENT_START_SLUGS = ["self-hosting-ai", "cloud-quickstart", "install-agent-runtime", "cli"];
+
+function langPrefix(lang: string): string {
+ return lang === i18n.defaultLanguage ? "" : `/${lang}`;
+}
+
+/** Absolute URL of a page's Markdown, e.g. `/docs/agents.md`; the home page is `/docs/index.md`. */
+export function markdownUrl(page: Pick<DocsPage, "slugs">, lang: string): string {
+ const path = page.slugs.length === 0 ? "/index" : `/${page.slugs.join("/")}`;
+ return `${DOCS_URL}${langPrefix(lang)}${path}.md`;
+}
+
+function htmlToMarkdownUrl(relative: string, lang: string): string {
+ const prefix = langPrefix(lang);
+ const path = prefix && relative.startsWith(prefix) ? relative.slice(prefix.length) : relative;
+ return `${DOCS_URL}${prefix}${path === "/" || path === "" ? "/index" : path}.md`;
+}
+
+export async function pageMarkdown(page: DocsPage, lang: string): Promise<string> {
+ const body = await renderPageMarkdown(await page.data.getText("processed"), lang, DOCS_URL);
+ const description = page.data.description ? `> ${page.data.description}\n\n` : "";
+ return `# ${page.data.title}\n\n${description}${body}\n`;
+}
+
+/** Pages in sidebar order, then any page the sidebar does not list. */
+export function orderedPages(lang: Lang): DocsPage[] {
+ const pages: DocsPage[] = [];
+ const seen = new Set<string>();
+ const add = (page: DocsPage | undefined) => {
+ if (!page || seen.has(page.url)) return;
+ seen.add(page.url);
+ pages.push(page);
+ };
+ const walk = (nodes: PageTreeNode[]) => {
+ for (const node of nodes) {
+ if (node.type === "page") add(source.getNodePage(node, lang));
+ if (node.type === "folder") {
+ if (node.index) add(source.getNodePage(node.index, lang));
+ walk(node.children);
+ }
+ }
+ };
+ walk(source.getPageTree(lang).children);
+ for (const page of source.getPages(lang)) add(page);
+ return pages;
+}
+
+export async function docsFullMarkdown(lang: Lang): Promise<string> {
+ const sections = await Promise.all(
+ orderedPages(lang).map(async (page) => {
+ const markdown = await pageMarkdown(page, lang);
+ return markdown.replace(/^(# .+\n)/, `$1\nURL: ${absoluteDocsUrl(page.url)}\n`);
+ }),
+ );
+ return `${sections.join("\n---\n\n")}`;
+}
+
+export async function docsIndexMarkdown(lang: Lang): Promise<string> {
+ const tree = await llms(source).index(lang);
+ const sections = tree
+ .split("\n")
+ .slice(1)
+ .filter((line) => !line.startsWith("> "))
+ .map((line) => line.replace(/^- \*\*(.+)\*\*$/, "## $1\n"))
+ .join("\n")
+ .replace(/\]\((\/[^)]*)\)/g, (_, href: string) => `](${htmlToMarkdownUrl(href, lang)})`)
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+
+ const agentPages = AGENT_START_SLUGS.flatMap((slug) => {
+ const page = source.getPage([slug], lang);
+ if (!page) return [];
+ const description = page.data.description ? `: ${page.data.description}` : "";
+ return [`- [${page.data.title}](${markdownUrl(page, lang)})${description}`];
+ });
+
+ const otherLanguages = i18n.languages
+ .filter((other) => other !== lang)
+ .map((other) => `[${localeLabels[other]}](${DOCS_URL}${langPrefix(other)}/llms.txt)`)
+ .join(" · ");
+
+ return [
+ "# Multica Docs",
+ "",
+ "> Multica is a source-available workspace where people assign issues to AI coding agents the way they would to a teammate. Agents run on runtimes you control, with the coding tools you already use, and report progress back on the issue. Use Multica Cloud, the desktop app, or self-host it.",
+ "",
+ `Every page below is Markdown. On the site, append \`.md\` to a page URL or request it with \`Accept: text/markdown\`. The whole documentation is in [one file](${DOCS_URL}${langPrefix(lang)}/llms-full.txt). Other languages: ${otherLanguages}.`,
+ "",
+ "## Start here (for AI agents)",
+ "",
+ ...agentPages,
+ "",
+ sections,
+ "",
+ ].join("\n");
+}
+
+export function markdownResponse(body: string, init: { status?: number; canonical?: string } = {}): Response {
+ const headers = new Headers({
+ "Content-Type": "text/markdown; charset=utf-8",
+ Vary: "Accept",
+ });
+ if (init.canonical) headers.set("Link", `<${init.canonical}>; rel="canonical"`);
+ return new Response(body, { status: init.status ?? 200, headers });
+}
diff --git a/apps/docs/lib/markdown-export.test.ts b/apps/docs/lib/markdown-export.test.ts
new file mode 100644
index 0000000000..8af9efebd7
--- /dev/null
+++ b/apps/docs/lib/markdown-export.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment node
+import { remarkLLMs } from "fumadocs-core/mdx-plugins/remark-llms";
+import remarkGfm from "remark-gfm";
+import remarkMdx from "remark-mdx";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+import { describe, expect, it } from "vitest";
+import {
+ MARKDOWN_PLACEHOLDERS,
+ absolutizeMarkdownLinks,
+ markdownElementVisibility,
+ renderPageMarkdown,
+} from "./markdown-export";
+
+const DOCS_URL = "https://www.multica.ai/docs";
+
+/** The page's Markdown as `includeProcessedMarkdown` exports it with the options in `source.config.ts`. */
+function processedMarkdown(source: string): string {
+ const tree = unified().use(remarkParse).use(remarkMdx).use(remarkGfm).parse(source);
+ const file = { data: {} as { markdown?: string }, toString: () => source };
+ remarkLLMs({
+ headingIds: false,
+ mdxAsPlaceholder: [...MARKDOWN_PLACEHOLDERS],
+ filterElement: markdownElementVisibility,
+ _data: true,
+ })(tree, file as never, () => undefined);
+ return file.data.markdown ?? "";
+}
+
+const exportPage = (source: string, lang = "en") =>
+ renderPageMarkdown(processedMarkdown(source), lang, DOCS_URL);
+
+describe("page Markdown export", () => {
+ it("turns docs components into plain Markdown and drops interactive demos", async () => {
+ const markdown = await exportPage(`import { Callout } from "fumadocs-ui/components/callout";
+import { AssignDemo } from "@/components/demos/assign-demo";
+
+Intro with a [link](/providers).
+
+<AssignDemo />
+
+<Callout type="warning">
+Back up first.
+</Callout>
+
+<Steps>
+<Step>
+
+## Install [#install]
+
+Run it.
+
+</Step>
+<Step>
+
+## Verify
+
+Check it.
+
+</Step>
+</Steps>
+
+<Tabs items={["macOS", "Windows"]}>
+<Tab value="macOS">
+
+\`\`\`bash
+brew install multica
+\`\`\`
+
+</Tab>
+</Tabs>
+
+<Accordions>
+<Accordion title={<><code>multica login</code> fails</>} id="login">
+
+Retry.
+
+</Accordion>
+</Accordions>
+`);
+
+ expect(markdown).toBe(`Intro with a [link](https://www.multica.ai/docs/providers).
+
+> **Warning:** Back up first.
+
+## Install
+
+Run it.
+
+## Verify
+
+Check it.
+
+**macOS**
+
+\`\`\`bash
+brew install multica
+\`\`\`
+
+### \`multica login\` fails
+
+Retry.`);
+ });
+
+ it("renders video embeds and community links as links", async () => {
+ const markdown = await exportPage(`<VideoEmbed provider="bilibili" id="BV1cv7Y6gEg7" title="Intro" />
+
+<CommunityLinks discordDescription="Chat." githubDescription="Code." xDescription="News." />
+`);
+ expect(markdown).toBe(`[Video: Intro](https://www.bilibili.com/video/BV1cv7Y6gEg7/)
+
+- [Discord](https://discord.gg/W8gYBn226t): Chat.
+- [GitHub](https://github.com/multica-ai/multica): Code.
+- [X](https://x.com/MulticaAI): News.`);
+ });
+
+ it("keeps the text of unknown components and drops expressions", async () => {
+ expect(await exportPage(`<Feature>Kept text</Feature>\n\n{/* note */}\n\nAfter.\n`)).toBe("Kept text\n\nAfter.");
+ });
+});
+
+describe("absolutizeMarkdownLinks", () => {
+ it("keeps page links in the page's language and images unprefixed", () => {
+ expect(
+ absolutizeMarkdownLinks("[A](/agents#setup) [B](/zh/issues) ![C](/images/docs/a.webp) [D](https://x.com)", "zh", DOCS_URL),
+ ).toBe(
+ "[A](https://www.multica.ai/docs/zh/agents#setup) [B](https://www.multica.ai/docs/zh/issues) ![C](https://www.multica.ai/docs/images/docs/a.webp) [D](https://x.com)",
+ );
+ expect(absolutizeMarkdownLinks("[Home](/) [A](/agents)", "en", DOCS_URL)).toBe(
+ "[Home](https://www.multica.ai/docs) [A](https://www.multica.ai/docs/agents)",
+ );
+ });
+
+ it("leaves code blocks untouched and collapses blank lines outside them", () => {
+ const code = "```md\n[A](/agents)\n\n\n\nend\n```";
+ expect(absolutizeMarkdownLinks(`a\n\n\n\nb\n\n${code}`, "en", DOCS_URL)).toBe(`a\n\nb\n\n${code}`);
+ });
+});
diff --git a/apps/docs/lib/markdown-export.ts b/apps/docs/lib/markdown-export.ts
new file mode 100644
index 0000000000..0f2e15769f
--- /dev/null
+++ b/apps/docs/lib/markdown-export.ts
@@ -0,0 +1,153 @@
+import {
+ renderPlaceholder,
+ type PlaceholderData,
+} from "fumadocs-core/mdx-plugins/remark-llms.runtime";
+import { i18n } from "./i18n";
+
+// Loaded by `source.config.ts` at MDX compile time, so this module only uses
+// relative imports.
+
+/**
+ * MDX components exported as placeholders and rendered to plain Markdown by
+ * `MARKDOWN_RENDERERS`, so the Markdown carries the same content as the page.
+ */
+export const MARKDOWN_PLACEHOLDERS = [
+ "Callout",
+ "Steps",
+ "Step",
+ "Tabs",
+ "Tab",
+ "Accordions",
+ "Accordion",
+ "VideoEmbed",
+ "CommunityLinks",
+] as const;
+
+const placeholderNames: ReadonlySet<string> = new Set(MARKDOWN_PLACEHOLDERS);
+
+type MarkdownNode = { type: string; name?: string | null };
+
+/**
+ * Which authored elements reach the Markdown. Interactive `*Demo` components
+ * illustrate the prose around them and have no text of their own; any other
+ * JSX keeps only its children so no markup leaks into the Markdown.
+ */
+export function markdownElementVisibility(node: MarkdownNode): boolean | "children-only" {
+ if (node.type === "mdxFlowExpression" || node.type === "mdxTextExpression") return false;
+ if (node.type !== "mdxJsxFlowElement" && node.type !== "mdxJsxTextElement") return true;
+ if (node.name && placeholderNames.has(node.name)) return true;
+ if (node.name?.endsWith("Demo")) return false;
+ return "children-only";
+}
+
+/** Plain text of a JSX attribute; expression values such as `title={<><code>x</code> y</>}` become Markdown. */
+function attributeText(value: unknown): string {
+ const raw =
+ typeof value === "string"
+ ? value
+ : value && typeof value === "object" && "value" in value && typeof value.value === "string"
+ ? value.value
+ : "";
+ return raw
+ .replace(/<code>(.*?)<\/code>/g, "`$1`")
+ .replace(/<\/?(?:[A-Za-z][^>]*)?>/g, "")
+ .trim();
+}
+
+function quote(text: string): string {
+ return text
+ .split("\n")
+ .map((line) => (line ? `> ${line}` : ">"))
+ .join("\n");
+}
+
+const CALLOUT_LABELS: Record<string, string> = {
+ info: "Note",
+ warn: "Warning",
+ warning: "Warning",
+ error: "Error",
+ success: "Tip",
+};
+
+const VIDEO_WATCH_URLS: Record<string, (id: string) => string> = {
+ bilibili: (id) => `https://www.bilibili.com/video/${id}/`,
+ youtube: (id) => `https://www.youtube.com/watch?v=${id}`,
+};
+
+const block = (text: string) => `\n${text.trim()}\n`;
+
+const MARKDOWN_RENDERERS: Record<
+ (typeof MARKDOWN_PLACEHOLDERS)[number],
+ (data: PlaceholderData) => string
+> = {
+ Callout: ({ attributes, children }) => {
+ const label = CALLOUT_LABELS[attributeText(attributes.type)] ?? "Note";
+ return block(quote(`**${label}:** ${children.trim()}`));
+ },
+ Steps: ({ children }) => block(children),
+ Step: ({ children }) => block(children),
+ Tabs: ({ children }) => block(children),
+ Tab: ({ attributes, children }) => block(`**${attributeText(attributes.value)}**\n\n${children.trim()}`),
+ Accordions: ({ children }) => block(children),
+ Accordion: ({ attributes, children }) => block(`### ${attributeText(attributes.title)}\n\n${children.trim()}`),
+ VideoEmbed: ({ attributes }) => {
+ const watchUrl = VIDEO_WATCH_URLS[attributeText(attributes.provider)];
+ const id = attributeText(attributes.id);
+ if (!watchUrl || !id) return "";
+ return block(`[Video: ${attributeText(attributes.title) || id}](${watchUrl(id)})`);
+ },
+ CommunityLinks: ({ attributes }) =>
+ block(
+ [
+ `- [Discord](https://discord.gg/W8gYBn226t): ${attributeText(attributes.discordDescription)}`,
+ `- [GitHub](https://github.com/multica-ai/multica): ${attributeText(attributes.githubDescription)}`,
+ `- [X](https://x.com/MulticaAI): ${attributeText(attributes.xDescription)}`,
+ ].join("\n"),
+ ),
+};
+
+const FENCE = /^(\s*)(`{3,}|~{3,})/;
+const MARKDOWN_LINK = /(!?\[[^\]]*\]\()(\/[^)\s]*)/g;
+
+/**
+ * Rewrites root-relative links to absolute docs URLs and collapses runs of
+ * blank lines. Page links stay in the page's language, as `LocaleLink` does on
+ * the HTML page; images do not. Code blocks are left as written.
+ */
+export function absolutizeMarkdownLinks(markdown: string, lang: string, docsUrl: string): string {
+ let fence: string | null = null;
+ const out: string[] = [];
+ for (const line of markdown.split("\n")) {
+ const marker = FENCE.exec(line)?.[2];
+ if (marker) {
+ if (fence === null) fence = marker;
+ else if (marker.startsWith(fence)) fence = null;
+ out.push(line);
+ continue;
+ }
+ if (fence !== null) {
+ out.push(line);
+ continue;
+ }
+ if (!line.trim() && !out.at(-1)?.trim()) continue;
+ out.push(
+ line.replace(MARKDOWN_LINK, (_, open: string, href: string) => {
+ const isImage = open.startsWith("!") || href.startsWith("/images/");
+ return `${open}${docsUrl}${isImage ? href : localizedPath(href, lang)}`;
+ }),
+ );
+ }
+ return out.join("\n").trim();
+}
+
+function localizedPath(href: string, lang: string): string {
+ if (lang === i18n.defaultLanguage) return href === "/" ? "" : href;
+ const first = href.split(/[/?#]/)[1] ?? "";
+ if ((i18n.languages as readonly string[]).includes(first)) return href;
+ return href === "/" ? `/${lang}` : `/${lang}${href}`;
+}
+
+/** Turns a page's processed Markdown into the clean Markdown served to agents. */
+export async function renderPageMarkdown(processed: string, lang: string, docsUrl: string): Promise<string> {
+ return absolutizeMarkdownLinks(await renderPlaceholder(processed, MARKDOWN_RENDERERS), lang, docsUrl);
+}
diff --git a/apps/docs/lib/remark-included-title.ts b/apps/docs/lib/remark-included-title.ts
new file mode 100644
index 0000000000..6d83d7eda6
--- /dev/null
+++ b/apps/docs/lib/remark-included-title.ts
@@ -0,0 +1,25 @@
+import { replaceSource } from "fumadocs-core/mdx-plugins/stringifier";
+import type { Root } from "mdast";
+
+type IncludedNode = { type: string; depth?: number; children?: IncludedNode[] };
+type SourceFile = Parameters<typeof replaceSource>[0];
+type SourceNode = Parameters<typeof replaceSource>[1];
+
+/**
+ * A Markdown file embedded with `<include>` (such as the repository's
+ * `SELF_HOSTING_AI.md`) keeps its own H1 for readers on GitHub. On a docs
+ * page the frontmatter title is the H1, so the included one is dropped from
+ * both the HTML and the exported Markdown.
+ */
+export function remarkDropIncludedTitle() {
+ return (tree: Root, file: SourceFile) => {
+ for (const node of tree.children as IncludedNode[]) {
+ // remark-include turns the `<include>` element into the included root.
+ if (node.type !== "root" || !node.children) continue;
+ const index = node.children.findIndex((child) => child.type === "heading" && child.depth === 1);
+ if (index === -1) continue;
+ const [title] = node.children.splice(index, 1);
+ replaceSource(file, title as SourceNode, "");
+ }
+ };
+}
diff --git a/apps/docs/next.config.mjs b/apps/docs/next.config.mjs
index 01e40853e3..ef522bf6ca 100644
--- a/apps/docs/next.config.mjs
+++ b/apps/docs/next.config.mjs
@@ -9,6 +9,13 @@ const config = {
// lives in the root AGENTS.md.
agentRules: false,
basePath: "/docs",
+ // Page URLs answer HTML or Markdown by `Accept` (see proxy.ts), so caches
+ // must key on it. Hosts that serve prerendered pages from their CDN apply
+ // this header there; when `next start` renders a page, Next replaces `Vary`
+ // with its own (next/dist/build/templates/app-page-runtime.js).
+ async headers() {
+ return [{ source: "/((?!_next|api)[^.]*)", headers: [{ key: "Vary", value: "Accept" }] }];
+ },
// Visiting http://host/ (outside basePath) would otherwise 404 — redirect
// to the docs root. basePath: false makes the source and destination
// literal (not re-prefixed with `/docs`), so the redirect runs before
diff --git a/apps/docs/package.json b/apps/docs/package.json
index 69f1bf83ac..aee14d1c37 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -14,6 +14,7 @@
"postinstall": "fumadocs-mdx"
},
"dependencies": {
+ "@multica/core": "workspace:*",
"@multica/ui": "workspace:*",
"fumadocs-core": "catalog:",
"fumadocs-mdx": "catalog:",
diff --git a/apps/docs/proxy.test.ts b/apps/docs/proxy.test.ts
index 7521f4064e..ee7ccac76e 100644
--- a/apps/docs/proxy.test.ts
+++ b/apps/docs/proxy.test.ts
@@ -2,9 +2,10 @@
import "next/dist/server/node-environment-baseline";
import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";
-import { describe, expect, it } from "vitest";
+import { NextRequest, type NextFetchEvent } from "next/server";
+import { afterEach, describe, expect, it, vi } from "vitest";
import nextConfig from "./next.config.mjs";
-import { config } from "./proxy";
+import { config, markdownRewritePath, proxy } from "./proxy";
describe("docs locale proxy matcher", () => {
it.each(["/docs/icon.svg", "/docs/icon.svg?icon.1234.svg"])(
@@ -14,10 +15,132 @@ describe("docs locale proxy matcher", () => {
},
);
- it.each(["/docs", "/docs/agents", "/docs/zh", "/docs/fr/agents"])(
- "keeps locale routing enabled for %s",
- (url) => {
- expect(unstable_doesMiddlewareMatch({ config, nextConfig, url })).toBe(true);
- },
- );
+ it.each([
+ "/docs",
+ "/docs/agents",
+ "/docs/zh",
+ "/docs/fr/agents",
+ "/docs/llms.txt",
+ "/docs/llms-full.txt",
+ "/docs/agents.md",
+ ])("keeps locale routing enabled for %s", (url) => {
+ expect(unstable_doesMiddlewareMatch({ config, nextConfig, url })).toBe(true);
+ });
+});
+
+describe("markdownRewritePath", () => {
+ it.each([
+ ["/agents.md", "/docs/en/llms.mdx/agents"],
+ ["/agents.mdx", "/docs/en/llms.mdx/agents"],
+ ["/developers/architecture.md", "/docs/en/llms.mdx/developers/architecture"],
+ ["/index.md", "/docs/en/llms.mdx"],
+ ["/zh/agents.md", "/docs/zh/llms.mdx/agents"],
+ ["/zh-Hant/index.md", "/docs/zh-Hant/llms.mdx"],
+ ])("serves %s as Markdown", (pathname, target) => {
+ expect(markdownRewritePath(pathname, false)).toBe(target);
+ });
+
+ it.each([
+ ["/", "/docs/en/llms.mdx"],
+ ["/agents", "/docs/en/llms.mdx/agents"],
+ ["/zh", "/docs/zh/llms.mdx"],
+ ["/ko/agents", "/docs/ko/llms.mdx/agents"],
+ ])("serves %s as Markdown when the client prefers it", (pathname, target) => {
+ expect(markdownRewritePath(pathname, true)).toBe(target);
+ });
+
+ it("leaves HTML requests and files alone", () => {
+ expect(markdownRewritePath("/agents", false)).toBeNull();
+ expect(markdownRewritePath("/llms.txt", true)).toBeNull();
+ expect(markdownRewritePath("/zh/llms-full.txt", true)).toBeNull();
+ });
+});
+
+function request(path: string, headers: Record<string, string> = {}) {
+ return new NextRequest(`https://www.multica.ai/docs${path}`, {
+ headers,
+ nextConfig: { basePath: "/docs" },
+ });
+}
+
+const BROWSER = {
+ "user-agent":
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36",
+ accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
+ "sec-fetch-mode": "navigate",
+};
+
+function rewriteTarget(response: Response): string | null {
+ const target = response.headers.get("x-middleware-rewrite");
+ return target ? new URL(target).pathname : null;
+}
+
+describe("docs proxy", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("serves the HTML page to browsers", () => {
+ expect(rewriteTarget(proxy(request("/agents", BROWSER)))).toBe("/docs/en/agents");
+ });
+
+ it("serves the page Markdown for Accept: text/markdown", () => {
+ const response = proxy(request("/agents", { accept: "text/markdown, text/html;q=0.9" }));
+ expect(rewriteTarget(response)).toBe("/docs/en/llms.mdx/agents");
+ });
+
+ it("routes llms.txt through the default-language route", () => {
+ expect(rewriteTarget(proxy(request("/llms.txt")))).toBe("/docs/en/llms.txt");
+ });
+
+ it("logs AI visits as one JSON line and stays quiet for browsers", () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ proxy(request("/agents", BROWSER));
+ expect(info).not.toHaveBeenCalled();
+
+ proxy(request("/agents.md", { "user-agent": "Claude-User/1.0", cookie: "session=secret" }));
+ expect(info).toHaveBeenCalledTimes(1);
+ const line = String(info.mock.calls[0]?.[0]);
+ expect(JSON.parse(line)).toMatchObject({
+ event: "ai_visit",
+ app: "docs",
+ path: "/docs/agents.md",
+ agent: "Claude-User",
+ format: "markdown",
+ status: null,
+ });
+ expect(line).not.toContain("secret");
+ });
+
+ it("records the status of redirects the proxy answers itself", () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ proxy(request("/en/agents", { "user-agent": "GPTBot/1.1" }));
+ expect(JSON.parse(String(info.mock.calls[0]?.[0]))).toMatchObject({ status: 307, format: "html" });
+ });
+
+ it("retains visits in PostHog after the response when a key is configured", () => {
+ vi.spyOn(console, "info").mockImplementation(() => {});
+ vi.stubEnv("POSTHOG_API_KEY", "phc_test");
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));
+ const waitUntil = vi.fn();
+ try {
+ proxy(request("/agents.md", { "user-agent": "Claude-User/1.0" }), { waitUntil } as unknown as NextFetchEvent);
+ proxy(request("/agents", BROWSER), { waitUntil } as unknown as NextFetchEvent);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ expect(waitUntil).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("docs cache keys", () => {
+ it("declares Vary: Accept on page URLs, which answer HTML or Markdown", async () => {
+ const rules = (await nextConfig.headers?.()) ?? [];
+ const rule = rules.find((entry) => entry.headers.some((header) => header.key === "Vary" && header.value === "Accept"));
+ expect(rule).toBeDefined();
+ const matches = (path: string) => new RegExp(`^${rule!.source}$`).test(path);
+ for (const page of ["/", "/agents", "/zh/agents", "/en/providers/claude-code"]) expect(matches(page)).toBe(true);
+ for (const file of ["/agents.md", "/llms.txt", "/_next/static/chunk", "/api/search", "/icon.svg"]) expect(matches(file)).toBe(false);
+ });
});
diff --git a/apps/docs/proxy.ts b/apps/docs/proxy.ts
index 235d3db774..4bafac4ec2 100644
--- a/apps/docs/proxy.ts
+++ b/apps/docs/proxy.ts
@@ -1,7 +1,33 @@
-import { NextResponse, type NextRequest } from "next/server";
+import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
+import {
+ buildAiVisitRecord,
+ prefersMarkdown,
+ reportAiVisit,
+ type AiVisitFormat,
+} from "@multica/core/ai-traffic";
import { i18n } from "@/lib/i18n";
const BASE_PATH = "/docs";
+const MARKDOWN_SUFFIX = /\.mdx?$/;
+const MARKDOWN_FILES = new Set(["llms.txt", "llms-full.txt"]);
+
+/**
+ * The Markdown route for a page requested as Markdown, either by URL
+ * (`/agents.md`, `/zh/agents.md`, `/index.md`) or by an `Accept` header that
+ * prefers Markdown. Returns null for every other request, including files
+ * such as `llms.txt`.
+ */
+export function markdownRewritePath(pathname: string, acceptsMarkdown: boolean): string | null {
+ const bySuffix = MARKDOWN_SUFFIX.test(pathname);
+ if (!bySuffix && (!acceptsMarkdown || pathname.split("/").at(-1)?.includes("."))) return null;
+
+ const segments = pathname.replace(MARKDOWN_SUFFIX, "").split("/").filter(Boolean);
+ const lang = (i18n.languages as readonly string[]).includes(segments[0] ?? "")
+ ? segments.shift()!
+ : i18n.defaultLanguage;
+ if (bySuffix && segments.at(-1) === "index") segments.pop();
+ return `${BASE_PATH}/${lang}/llms.mdx${segments.map((segment) => `/${segment}`).join("")}`;
+}
// Self-contained i18n proxy. We don't use fumadocs-core's built-in
// middleware because it isn't basePath-aware — both its rewrite targets
@@ -10,7 +36,7 @@ const BASE_PATH = "/docs";
// inside a basePath-mounted app. Logic mirrors fumadocs's default-locale
// flavor: hide `/en` prefix for the default language, keep `/zh` prefix
// for other languages.
-export function proxy(request: NextRequest) {
+function routeLocale(request: NextRequest): NextResponse {
const pathname = request.nextUrl.pathname;
const pathLocale = i18n.languages.find(
(loc) => pathname === `/${loc}` || pathname.startsWith(`/${loc}/`),
@@ -43,6 +69,29 @@ export function proxy(request: NextRequest) {
return NextResponse.next();
}
+export function proxy(request: NextRequest, event?: NextFetchEvent) {
+ const pathname = request.nextUrl.pathname;
+ const markdownPath = markdownRewritePath(pathname, prefersMarkdown(request.headers.get("accept")));
+ const response = markdownPath
+ ? NextResponse.rewrite(new URL(markdownPath, request.url))
+ : routeLocale(request);
+
+ const format: AiVisitFormat =
+ markdownPath || MARKDOWN_FILES.has(pathname.split("/").at(-1) ?? "") ? "markdown" : "html";
+ reportAiVisit(
+ buildAiVisitRecord({
+ app: "docs",
+ method: request.method,
+ pathname: `${BASE_PATH}${pathname === "/" ? "" : pathname}`,
+ headers: request.headers,
+ format,
+ status: response.headers.has("location") ? response.status : null,
+ }),
+ { env: process.env, waitUntil: event && ((promise) => event.waitUntil(promise)) },
+ );
+ return response;
+}
+
export const config = {
// Run on every path except static/api and root metadata routes. Includes
// the bare `/` root so `/docs/` lands on the English home. Metadata routes
diff --git a/apps/docs/source.config.ts b/apps/docs/source.config.ts
index 71c0f61467..a1f843a065 100644
--- a/apps/docs/source.config.ts
+++ b/apps/docs/source.config.ts
@@ -1,9 +1,23 @@
import { defineDocs, defineConfig } from "fumadocs-mdx/config";
-
+import { MARKDOWN_PLACEHOLDERS, markdownElementVisibility } from "./lib/markdown-export";
+import { remarkDropIncludedTitle } from "./lib/remark-included-title";
export const docs = defineDocs({
dir: "content/docs",
+ docs: {
+ postprocess: {
+ // Each page's Markdown, served by the `llms.txt` and `.md` routes.
+ includeProcessedMarkdown: {
+ headingIds: false,
+ mdxAsPlaceholder: [...MARKDOWN_PLACEHOLDERS],
+ filterElement: markdownElementVisibility,
+ },
+ },
+ },
});
export default defineConfig({
- mdxOptions: {},
+ mdxOptions: {
+ // Before the preset's heading plugins, so the dropped title stays out of the TOC.
+ remarkPlugins: (plugins) => [remarkDropIncludedTitle, ...plugins],
+ },
});
diff --git a/apps/docs/turbo.json b/apps/docs/turbo.json
index 49f3621c1d..407efd5478 100644
--- a/apps/docs/turbo.json
+++ b/apps/docs/turbo.json
@@ -7,7 +7,9 @@
"$TURBO_ROOT$/server/internal/daemon/agents_probe.go",
"$TURBO_ROOT$/server/internal/daemon/config.go",
"$TURBO_ROOT$/server/pkg/agent/builtin_runtimes.go",
- "$TURBO_ROOT$/server/internal/featureflags/keys.go"
+ "$TURBO_ROOT$/server/internal/featureflags/keys.go",
+ "$TURBO_ROOT$/packages/core/ai-traffic/**",
+ "$TURBO_ROOT$/SELF_HOSTING_AI.md"
]
}
}
diff --git a/apps/web/app/(landing)/layout.tsx b/apps/web/app/(landing)/layout.tsx
index 7ea9d82ef3..5e918581e2 100644
--- a/apps/web/app/(landing)/layout.tsx
+++ b/apps/web/app/(landing)/layout.tsx
@@ -1,32 +1,8 @@
import { LocaleProvider } from "@/features/landing/i18n";
import { LocaleSuggestion } from "@/features/landing/site/locale-suggestion";
+import { jsonLdScript, siteJsonLd } from "@/features/landing/structured-data";
import { getRequestLocale } from "@/lib/request-locale";
-const jsonLd = {
- "@context": "https://schema.org",
- "@graph": [
- {
- "@type": "Organization",
- name: "Multica",
- url: "https://www.multica.ai",
- sameAs: ["https://github.com/multica-ai/multica"],
- },
- {
- "@type": "SoftwareApplication",
- name: "Multica",
- applicationCategory: "ProjectManagement",
- operatingSystem: "Web",
- description:
- "Source-available project management platform that turns coding agents into real teammates.",
- offers: {
- "@type": "Offer",
- price: "0",
- priceCurrency: "USD",
- },
- },
- ],
-};
-
export default async function LandingLayout({
children,
}: {
@@ -38,7 +14,7 @@ export default async function LandingLayout({
<>
<script
type="application/ld+json"
- dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
+ dangerouslySetInnerHTML={{ __html: jsonLdScript(siteJsonLd) }}
/>
<div className="landing-light h-full overflow-x-hidden overflow-y-auto bg-white">
<LocaleProvider initialLocale={initialLocale}>
diff --git a/apps/web/app/(landing)/page.tsx b/apps/web/app/(landing)/page.tsx
index f4a258a95f..182bd9bfea 100644
--- a/apps/web/app/(landing)/page.tsx
+++ b/apps/web/app/(landing)/page.tsx
@@ -3,14 +3,23 @@ import { pageMetadata } from "@/features/landing/utils/page-metadata";
import { HomePage } from "@/features/landing/site/home-page";
import { getHomeDownload } from "@/features/landing/utils/home-download";
import { RedirectIfAuthenticated } from "@/features/landing/components/redirect-if-authenticated";
+import { createLandingDict } from "@/features/landing/i18n/dictionary";
+import { faqPageJsonLd, jsonLdScript } from "@/features/landing/structured-data";
+import { getRequestLocale } from "@/lib/request-locale";
export function generateMetadata(): Promise<Metadata> {
return pageMetadata("home", "/");
}
export default async function LandingPage() {
+ const { faq } = createLandingDict(await getRequestLocale());
+
return (
<>
+ <script
+ type="application/ld+json"
+ dangerouslySetInnerHTML={{ __html: jsonLdScript(faqPageJsonLd(faq)) }}
+ />
<RedirectIfAuthenticated />
<HomePage download={await getHomeDownload()} />
</>
diff --git a/apps/web/app/llms.txt/route.ts b/apps/web/app/llms.txt/route.ts
new file mode 100644
index 0000000000..5afebfc8d7
--- /dev/null
+++ b/apps/web/app/llms.txt/route.ts
@@ -0,0 +1,9 @@
+import { buildLlmsTxt } from "@/features/landing/llms-txt";
+
+export const dynamic = "force-static";
+
+export function GET() {
+ return new Response(buildLlmsTxt(), {
+ headers: { "Content-Type": "text/markdown; charset=utf-8" },
+ });
+}
diff --git a/apps/web/app/robots.test.ts b/apps/web/app/robots.test.ts
new file mode 100644
index 0000000000..c34af67f2e
--- /dev/null
+++ b/apps/web/app/robots.test.ts
@@ -0,0 +1,23 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import robots from "./robots";
+
+describe("robots.txt", () => {
+ const { rules, sitemap: sitemaps } = robots();
+ const groups = Array.isArray(rules) ? rules : [rules];
+
+ it("welcomes AI search and assistant crawlers to the site, docs and llms.txt", () => {
+ const ai = groups.find((group) => Array.isArray(group.userAgent) && group.userAgent.includes("ClaudeBot"));
+ expect(ai?.userAgent).toEqual(
+ expect.arrayContaining(["ClaudeBot", "Claude-User", "OAI-SearchBot", "ChatGPT-User", "PerplexityBot", "Google-Extended"]),
+ );
+ expect(ai?.allow).toEqual(expect.arrayContaining(["/", "/docs/", "/llms.txt"]));
+ });
+
+ it("keeps private app routes closed to every crawler", () => {
+ for (const group of groups) {
+ expect(group.disallow).toEqual(expect.arrayContaining(["/api/", "/auth/", "/issues", "/settings"]));
+ }
+ expect(sitemaps).toEqual(["https://www.multica.ai/sitemap.xml", "https://www.multica.ai/docs/sitemap.xml"]);
+ });
+});
diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts
index fef8582382..c6d831ca84 100644
--- a/apps/web/app/robots.ts
+++ b/apps/web/app/robots.ts
@@ -1,5 +1,36 @@
import type { MetadataRoute } from "next";
+/** Signed-in app routes; crawlers have nothing public to read there. */
+const PRIVATE_ROUTES = [
+ "/api/",
+ "/ws",
+ "/auth/",
+ "/issues",
+ "/board",
+ "/inbox",
+ "/agents",
+ "/settings",
+ "/my-issues",
+ "/runtimes",
+ "/skills",
+];
+
+/**
+ * AI search and assistant crawlers, welcomed by name. A crawler that matches
+ * its own group ignores the `*` group, so each group repeats the private
+ * routes.
+ */
+const AI_CRAWLERS = [
+ "ClaudeBot",
+ "Claude-User",
+ "Claude-SearchBot",
+ "OAI-SearchBot",
+ "ChatGPT-User",
+ "PerplexityBot",
+ "Perplexity-User",
+ "Google-Extended",
+];
+
export default function robots(): MetadataRoute.Robots {
const baseUrl = "https://www.multica.ai";
@@ -8,19 +39,12 @@ export default function robots(): MetadataRoute.Robots {
{
userAgent: "*",
allow: ["/", "/about", "/changelog"],
- disallow: [
- "/api/",
- "/ws",
- "/auth/",
- "/issues",
- "/board",
- "/inbox",
- "/agents",
- "/settings",
- "/my-issues",
- "/runtimes",
- "/skills",
- ],
+ disallow: PRIVATE_ROUTES,
+ },
+ {
+ userAgent: AI_CRAWLERS,
+ allow: ["/", "/docs/", "/llms.txt"],
+ disallow: PRIVATE_ROUTES,
},
],
sitemap: [`${baseUrl}/sitemap.xml`, `${baseUrl}/docs/sitemap.xml`],
diff --git a/apps/web/app/sitemap.test.ts b/apps/web/app/sitemap.test.ts
new file mode 100644
index 0000000000..0e2de5d275
--- /dev/null
+++ b/apps/web/app/sitemap.test.ts
@@ -0,0 +1,30 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { isLiveRoute, siteRoutes } from "@/features/landing/site/sitemap";
+import sitemap from "./sitemap";
+
+describe("sitemap.xml", () => {
+ const entries = sitemap();
+ const urls = entries.map((entry) => entry.url);
+
+ it("lists every released marketing route, including /download", () => {
+ const live = siteRoutes().filter(isLiveRoute);
+ expect(urls).toEqual(live.map((route) => (route === "/" ? "https://www.multica.ai" : `https://www.multica.ai${route}`)));
+ expect(urls).toContain("https://www.multica.ai/download");
+ expect(urls).not.toContain("https://www.multica.ai/usecases");
+ });
+
+ it("dates only the pages that change with each release", () => {
+ const dated = entries.filter((entry) => entry.lastModified).map((entry) => entry.url);
+ expect(dated).toEqual(["https://www.multica.ai", "https://www.multica.ai/changelog"]);
+ });
+
+ it("declares every language version", () => {
+ const download = entries.find((entry) => entry.url.endsWith("/download"));
+ expect(download?.alternates?.languages).toMatchObject({
+ en: "https://www.multica.ai/download",
+ "zh-Hans": "https://www.multica.ai/zh/download",
+ "x-default": "https://www.multica.ai/download",
+ });
+ });
+});
diff --git a/apps/web/app/sitemap.ts b/apps/web/app/sitemap.ts
index f3be7ead45..122d624fb6 100644
--- a/apps/web/app/sitemap.ts
+++ b/apps/web/app/sitemap.ts
@@ -1,50 +1,39 @@
import type { MetadataRoute } from "next";
import { landingAlternates } from "@/lib/landing-locale-path";
+import { createEnDict } from "@/features/landing/i18n/en";
+import { isLiveRoute, siteRoutes } from "@/features/landing/site/sitemap";
+import { SITE_ORIGIN } from "@/features/landing/structured-data";
-export default function sitemap(): MetadataRoute.Sitemap {
- const baseUrl = "https://www.multica.ai";
+type SitemapHints = Pick<MetadataRoute.Sitemap[number], "changeFrequency" | "priority">;
+
+const HINTS: Readonly<Record<string, SitemapHints>> = {
+ "/": { changeFrequency: "weekly", priority: 1.0 },
+ "/about": { changeFrequency: "monthly", priority: 0.7 },
+ "/changelog": { changeFrequency: "weekly", priority: 0.6 },
+ "/contact-sales": { changeFrequency: "monthly", priority: 0.7 },
+ "/download": { changeFrequency: "weekly", priority: 0.8 },
+ "/licensing": { changeFrequency: "monthly", priority: 0.6 },
+ "/privacy": { changeFrequency: "yearly", priority: 0.3 },
+};
+
+/** Pages that list recent releases change with each one. */
+const RELEASE_PAGES = new Set(["/", "/changelog"]);
- const pages: MetadataRoute.Sitemap = [
- {
- url: baseUrl,
- lastModified: new Date("2026-04-01"),
- changeFrequency: "weekly",
- priority: 1.0,
- },
- {
- url: `${baseUrl}/about`,
- lastModified: new Date("2026-04-01"),
- changeFrequency: "monthly",
- priority: 0.7,
- },
- {
- url: `${baseUrl}/changelog`,
- lastModified: new Date("2026-04-01"),
- changeFrequency: "weekly",
- priority: 0.6,
- },
- {
- url: `${baseUrl}/contact-sales`,
- lastModified: new Date("2026-05-21"),
- changeFrequency: "monthly",
- priority: 0.7,
- },
- {
- url: `${baseUrl}/licensing`,
- lastModified: new Date("2026-09-21"),
- changeFrequency: "monthly",
- priority: 0.6,
- },
- {
- url: `${baseUrl}/privacy`,
- lastModified: new Date("2026-09-21"),
- changeFrequency: "yearly",
- priority: 0.3,
- },
- ];
+function latestReleaseDate(): Date | undefined {
+ const dates = createEnDict().changelog.entries.map((entry) => entry.date).sort();
+ const latest = dates.at(-1);
+ return latest ? new Date(latest) : undefined;
+}
+
+export default function sitemap(): MetadataRoute.Sitemap {
+ const releasedAt = latestReleaseDate();
- return pages.map((page) => ({
- ...page,
- alternates: { languages: landingAlternates(page.url.slice(baseUrl.length) || "/", baseUrl) },
- }));
+ return siteRoutes()
+ .filter(isLiveRoute)
+ .map((route) => ({
+ url: route === "/" ? SITE_ORIGIN : `${SITE_ORIGIN}${route}`,
+ ...(RELEASE_PAGES.has(route) && releasedAt ? { lastModified: releasedAt } : {}),
+ ...(HINTS[route] ?? { changeFrequency: "monthly", priority: 0.5 }),
+ alternates: { languages: landingAlternates(route, SITE_ORIGIN) },
+ }));
}
diff --git a/apps/web/features/landing/llms-txt.test.ts b/apps/web/features/landing/llms-txt.test.ts
new file mode 100644
index 0000000000..90e8f37c17
--- /dev/null
+++ b/apps/web/features/landing/llms-txt.test.ts
@@ -0,0 +1,44 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { createEnDict } from "./i18n/en";
+import { buildLlmsTxt } from "./llms-txt";
+
+const dict = createEnDict();
+
+describe("buildLlmsTxt", () => {
+ const text = buildLlmsTxt();
+
+ it("follows the llms.txt shape: title, summary, then sections", () => {
+ expect(text.startsWith(`# Multica\n\n> ${dict.meta.home.description}\n`)).toBe(true);
+ for (const section of ["Core capabilities", "Get started", "Documentation", "FAQ", "Pages"]) {
+ expect(text).toContain(`\n## ${section}\n`);
+ }
+ });
+
+ it("states the product facts from the site copy", () => {
+ for (const item of dict.faq.items) expect(text).toContain(`### ${item.question}`);
+ for (const feature of Object.values(dict.home.features.items)) expect(text).toContain(feature.body);
+ expect(text).toMatch(/supports \d+ coding tools/);
+ expect(text).toContain("Using Multica inside your own organization is free");
+ });
+
+ it("links the docs Markdown and the agent install guide", () => {
+ expect(text).toContain("(https://www.multica.ai/docs/llms.txt)");
+ expect(text).toContain("(https://www.multica.ai/docs/llms-full.txt)");
+ expect(text).toContain("(https://www.multica.ai/docs/self-hosting-ai.md)");
+ });
+
+ it("makes every link absolute and carries no markup", () => {
+ const hrefs = [...text.matchAll(/\]\(([^)]+)\)/g)].map((match) => match[1]);
+ expect(hrefs.length).toBeGreaterThan(0);
+ for (const href of hrefs) expect(href).toMatch(/^https:\/\//);
+ expect(text).not.toMatch(/<\/?[a-z][^>]*>/i);
+ });
+
+ it("lists only released pages", () => {
+ expect(text).toContain(`- [${dict.meta.download.title}](https://www.multica.ai/download)`);
+ const unreleased = buildLlmsTxt(dict, (href) => href !== "/download");
+ expect(unreleased).toContain(`- [${dict.meta.about.title}](https://www.multica.ai/about)`);
+ expect(unreleased).not.toContain(`- [${dict.meta.download.title}]`);
+ });
+});
diff --git a/apps/web/features/landing/llms-txt.ts b/apps/web/features/landing/llms-txt.ts
new file mode 100644
index 0000000000..c5e7fbfee5
--- /dev/null
+++ b/apps/web/features/landing/llms-txt.ts
@@ -0,0 +1,83 @@
+import { parseInlineLinks } from "./components/inline-links";
+import { githubUrl } from "./components/shared";
+import { createEnDict } from "./i18n/en";
+import type { LandingDict, MetaPage } from "./i18n/types";
+import { isLiveRoute, siteRoutes } from "./site/sitemap";
+import { SITE_ORIGIN } from "./structured-data";
+
+const DOCS_URL = `${SITE_ORIGIN}/docs`;
+
+/** Marketing routes that have their own title and description. */
+const ROUTE_META: Readonly<Record<string, MetaPage>> = {
+ "/about": "about",
+ "/changelog": "changelog",
+ "/contact-sales": "contactSales",
+ "/download": "download",
+ "/licensing": "licensing",
+ "/privacy": "privacy",
+};
+
+/** Dictionary copy as Markdown, with root-relative links made absolute. */
+function markdownText(text: string): string {
+ return parseInlineLinks(text)
+ .map((segment) => {
+ if (segment.type === "text") return segment.text;
+ const href = segment.href.startsWith("/") ? `${SITE_ORIGIN}${segment.href}` : segment.href;
+ return `[${segment.label}](${href})`;
+ })
+ .join("");
+}
+
+/**
+ * `/llms.txt` for the marketing site (llmstxt.org): what Multica is, how to
+ * start, and where the Markdown docs live. Every product fact comes from the
+ * English dictionary the pages render, so the two cannot drift apart.
+ */
+export function buildLlmsTxt(
+ dict: LandingDict = createEnDict(),
+ isLive: (href: string) => boolean = isLiveRoute,
+): string {
+ const { meta, home, faq } = dict;
+ const capabilities = Object.values(home.features.items).map((item) => `- **${item.title}**: ${item.body}`);
+ const pages = siteRoutes()
+ .filter((route) => isLive(route) && ROUTE_META[route])
+ .map((route) => {
+ const page = meta[ROUTE_META[route]!];
+ return `- [${page.title}](${SITE_ORIGIN}${route}): ${page.description}`;
+ });
+ const questions = faq.items.flatMap((item) => [`### ${item.question}`, "", markdownText(item.answer), ""]);
+
+ return [
+ "# Multica",
+ "",
+ `> ${meta.home.description}`,
+ "",
+ home.hero.lead,
+ "",
+ "## Core capabilities",
+ "",
+ ...capabilities,
+ "",
+ "## Get started",
+ "",
+ `- **Multica Cloud**: Hosted by Multica. Sign in at ${SITE_ORIGIN} and follow the [Quickstart](${DOCS_URL}/cloud-quickstart.md).`,
+ `- **Desktop app**: ${meta.download.description} [Download](${SITE_ORIGIN}/download) · [Desktop docs](${DOCS_URL}/desktop-app.md)`,
+ `- **Self-host**: Run Multica on your own infrastructure with Docker Compose or Kubernetes. [Self-host quickstart](${DOCS_URL}/self-host-quickstart.md)`,
+ `- **For AI agents installing Multica**: [Self-hosting setup for AI agents](${DOCS_URL}/self-hosting-ai.md) lists the exact commands to run.`,
+ "",
+ "## Documentation",
+ "",
+ `- [Docs index](${DOCS_URL}/llms.txt): Every documentation page, as Markdown.`,
+ `- [Full documentation](${DOCS_URL}/llms-full.txt): All English docs in one Markdown file.`,
+ `- [Supported AI coding tools](${DOCS_URL}/providers.md): The coding tools Multica runs and what each supports.`,
+ `- [Source code](${githubUrl}): The public repository.`,
+ "",
+ "## FAQ",
+ "",
+ ...questions,
+ "## Pages",
+ "",
+ ...pages,
+ "",
+ ].join("\n");
+}
diff --git a/apps/web/features/landing/structured-data.test.ts b/apps/web/features/landing/structured-data.test.ts
new file mode 100644
index 0000000000..a38d2d0b54
--- /dev/null
+++ b/apps/web/features/landing/structured-data.test.ts
@@ -0,0 +1,43 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { createLandingDict } from "./i18n/dictionary";
+import { faqPageJsonLd, jsonLdScript, plainInlineText, siteJsonLd } from "./structured-data";
+
+describe("siteJsonLd", () => {
+ it("lists every platform and official profile", () => {
+ const [organization, app] = siteJsonLd["@graph"];
+ expect(app).toMatchObject({ operatingSystem: "Web, macOS, Windows, Linux, iOS" });
+ expect(organization?.sameAs).toEqual([
+ "https://github.com/multica-ai/multica",
+ "https://x.com/MulticaAI",
+ "https://discord.gg/W8gYBn226t",
+ ]);
+ });
+});
+
+describe("faqPageJsonLd", () => {
+ it.each(["en", "zh-Hans", "ja", "ko"] as const)("mirrors the %s home page FAQ", (locale) => {
+ const { faq } = createLandingDict(locale);
+ const data = faqPageJsonLd(faq);
+
+ expect(data["@type"]).toBe("FAQPage");
+ expect(data.mainEntity.map((entry) => entry.name)).toEqual(faq.items.map((item) => item.question));
+ for (const entry of data.mainEntity) {
+ expect(entry.acceptedAnswer.text).not.toMatch(/\]\(/);
+ }
+ });
+});
+
+describe("plainInlineText", () => {
+ it("keeps link labels and drops their targets", () => {
+ expect(plainInlineText("See the [licensing FAQ](/licensing) for more.")).toBe("See the licensing FAQ for more.");
+ });
+});
+
+describe("jsonLdScript", () => {
+ it("cannot close the script tag it is embedded in", () => {
+ const script = jsonLdScript({ text: "</script><script>alert(1)</script>" });
+ expect(script).not.toContain("</script>");
+ expect(JSON.parse(script)).toEqual({ text: "</script><script>alert(1)</script>" });
+ });
+});
diff --git a/apps/web/features/landing/structured-data.ts b/apps/web/features/landing/structured-data.ts
new file mode 100644
index 0000000000..d0f253d283
--- /dev/null
+++ b/apps/web/features/landing/structured-data.ts
@@ -0,0 +1,56 @@
+import { parseInlineLinks } from "./components/inline-links";
+import { discordUrl, githubUrl, twitterUrl } from "./components/shared";
+import type { LandingDict } from "./i18n/types";
+
+export const SITE_ORIGIN = "https://www.multica.ai";
+
+/** Organization and product facts shared by every marketing page. */
+export const siteJsonLd = {
+ "@context": "https://schema.org",
+ "@graph": [
+ {
+ "@type": "Organization",
+ name: "Multica",
+ url: SITE_ORIGIN,
+ sameAs: [githubUrl, twitterUrl, discordUrl],
+ },
+ {
+ "@type": "SoftwareApplication",
+ name: "Multica",
+ applicationCategory: "ProjectManagement",
+ operatingSystem: "Web, macOS, Windows, Linux, iOS",
+ description:
+ "Source-available project management platform that turns coding agents into real teammates.",
+ offers: {
+ "@type": "Offer",
+ price: "0",
+ priceCurrency: "USD",
+ },
+ },
+ ],
+};
+
+/** Dictionary copy with its `[label](href)` links reduced to their labels. */
+export function plainInlineText(text: string): string {
+ return parseInlineLinks(text)
+ .map((segment) => (segment.type === "text" ? segment.text : segment.label))
+ .join("");
+}
+
+/** The home page FAQ, from the same dictionary entries the page renders. */
+export function faqPageJsonLd(faq: LandingDict["faq"]) {
+ return {
+ "@context": "https://schema.org",
+ "@type": "FAQPage",
+ mainEntity: faq.items.map((item) => ({
+ "@type": "Question",
+ name: item.question,
+ acceptedAnswer: { "@type": "Answer", text: plainInlineText(item.answer) },
+ })),
+ };
+}
+
+/** JSON for an inline `<script type="application/ld+json">`; `<` is escaped so copy cannot close the tag. */
+export function jsonLdScript(data: unknown): string {
+ return JSON.stringify(data).replace(/</g, "\\u003c");
+}
diff --git a/apps/web/proxy.test.ts b/apps/web/proxy.test.ts
index e519dae5c9..fed558593e 100644
--- a/apps/web/proxy.test.ts
+++ b/apps/web/proxy.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";
-import { NextRequest } from "next/server";
+import { NextRequest, type NextFetchEvent } from "next/server";
import { MULTICA_LOCALE_HEADER } from "./lib/locale-routing";
import { config, proxy } from "./proxy";
@@ -357,3 +357,77 @@ describe("upload route bypasses the buffering proxy", () => {
(url) => expect(unstable_doesMiddlewareMatch({ config, url })).toBe(true),
);
});
+
+describe("proxy AI visit log", () => {
+ const CLAUDE_BOT = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; [email protected])";
+ const visit = (path: string, headers: Record<string, string>, host = "www.multica.ai") =>
+ proxy(new NextRequest(`https://${host}${path}`, { headers }));
+ const loggedLines = (info: { mock: { calls: unknown[][] } }) =>
+ info.mock.calls.map((call) => JSON.parse(String(call[0])) as Record<string, unknown>);
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it.each(["/llms.txt", "/robots.txt"])("observes %s without changing the response", (url) => {
+ expect(unstable_doesMiddlewareMatch({ config, url })).toBe(true);
+ vi.spyOn(console, "info").mockImplementation(() => {});
+ const res = visit(url, { "user-agent": CLAUDE_BOT });
+ expect(res.headers.get("x-middleware-next")).toBe("1");
+ expect(res.headers.get("x-middleware-rewrite")).toBeNull();
+ });
+
+ it("logs AI crawlers on marketing pages and root crawler files", () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ visit("/download", { "user-agent": CLAUDE_BOT, cookie: "multica_logged_in=1" });
+ visit("/zh/about", { "user-agent": "ChatGPT-User/1.0" });
+ visit("/llms.txt", { "user-agent": "curl/8.7.1" });
+
+ expect(loggedLines(info)).toEqual([
+ expect.objectContaining({ app: "web", path: "/download", agent: "ClaudeBot", format: "html", status: null }),
+ expect.objectContaining({ path: "/zh/about", agent: "ChatGPT-User" }),
+ expect.objectContaining({ path: "/llms.txt", signal: "markdown-request", format: "markdown" }),
+ ]);
+ expect(JSON.stringify(info.mock.calls)).not.toContain("multica_logged_in");
+ });
+
+ it("trusts the Host header over the address the server is bound to", () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ visit("/llms.txt", { "user-agent": CLAUDE_BOT, host: "multica.ai" }, "localhost:3000");
+ visit("/llms.txt", { "user-agent": CLAUDE_BOT, host: "localhost:3000" }, "localhost:3000");
+ expect(loggedLines(info)).toEqual([expect.objectContaining({ path: "/llms.txt", agent: "ClaudeBot" })]);
+ });
+
+ it("retains visits in PostHog after the response when a key is configured", () => {
+ vi.spyOn(console, "info").mockImplementation(() => {});
+ vi.stubEnv("POSTHOG_API_KEY", "phc_test");
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));
+ const waitUntil = vi.fn();
+ try {
+ const req = new NextRequest("https://www.multica.ai/llms.txt", { headers: { "user-agent": CLAUDE_BOT } });
+ proxy(req, { waitUntil } as unknown as NextFetchEvent);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ expect(waitUntil).toHaveBeenCalledWith(expect.any(Promise));
+ expect(fetchMock).toHaveBeenCalledWith("https://us.i.posthog.com/batch/", expect.anything());
+ });
+
+ it("records the redirect status the proxy answers with", () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ visit("/about", { "user-agent": "GPTBot/1.1", cookie: "multica-locale=ko" });
+ expect(loggedLines(info)).toEqual([expect.objectContaining({ path: "/about", status: 307 })]);
+ });
+
+ it("skips browsers, app routes, docs, and other hosts", () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ visit("/", {
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36",
+ "sec-fetch-mode": "navigate",
+ });
+ visit("/acme/issues", { "user-agent": CLAUDE_BOT });
+ visit("/docs/agents", { "user-agent": CLAUDE_BOT });
+ visit("/download", { "user-agent": CLAUDE_BOT }, "app.multica.test");
+ expect(info).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts
index d60b082e8a..6cb32104d6 100644
--- a/apps/web/proxy.ts
+++ b/apps/web/proxy.ts
@@ -1,4 +1,5 @@
-import { NextResponse, type NextRequest } from "next/server";
+import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
+import { buildAiVisitRecord, reportAiVisit, type AiVisitFormat } from "@multica/core/ai-traffic";
import { LOCALE_COOKIE, type SupportedLocale } from "@multica/core/i18n";
import {
isSupportedLocale,
@@ -10,6 +11,7 @@ import {
landingPathLocale,
localizeHref,
splitLandingLocale,
+ stripLandingLocale,
} from "./lib/landing-locale-path";
import { runtimeRewriteDestination } from "./config/runtime-urls";
import { isOfficialMarketingHost } from "./lib/public-host";
@@ -85,11 +87,40 @@ function routeLandingLocale(
return nextWithLocale(req, landingPathLocale(resolved) === "en" ? resolved : "en");
}
+/** Root files AI crawlers read; they pass through untouched and are only observed. */
+const CRAWLER_FILES: Readonly<Record<string, AiVisitFormat>> = {
+ "/llms.txt": "markdown",
+ "/robots.txt": "text",
+};
+
+// AI visits to the public site, recorded on the official host only so
+// self-hosted instances stay quiet; retained in PostHog when configured. `/docs` is logged by the docs app.
+// `next start` reports its own bind address as `nextUrl.hostname`, so the
+// Host header decides; a spoofed one can only add a log line.
+function recordAiVisit(req: NextRequest, response: NextResponse, event?: NextFetchEvent) {
+ const { pathname } = req.nextUrl;
+ const host = req.headers.get("host")?.replace(/:\d+$/, "") ?? req.nextUrl.hostname;
+ if (!isOfficialMarketingHost(host)) return;
+ const format = CRAWLER_FILES[pathname] ?? (isLandingPath(stripLandingLocale(pathname)) ? "html" : null);
+ if (!format) return;
+ reportAiVisit(
+ buildAiVisitRecord({
+ app: "web",
+ method: req.method,
+ pathname,
+ headers: req.headers,
+ format,
+ status: response.headers.has("location") ? response.status : null,
+ }),
+ { env: process.env, waitUntil: event && ((promise) => event.waitUntil(promise)) },
+ );
+}
+
// Next.js 16 renamed `middleware` → `proxy`. API surface (NextRequest /
// NextResponse / cookies / matcher) is identical; the only behavioral
// change is the runtime — proxy is forced to nodejs and cannot opt into
// edge.
-export function proxy(req: NextRequest) {
+export function proxy(req: NextRequest, event?: NextFetchEvent) {
const { pathname } = req.nextUrl;
const runtimeDestination = runtimeRewriteDestination(pathname, process.env);
if (runtimeDestination) {
@@ -98,6 +129,13 @@ export function proxy(req: NextRequest) {
return NextResponse.rewrite(url);
}
+ const response = CRAWLER_FILES[pathname] ? NextResponse.next() : routeRequest(req);
+ recordAiVisit(req, response, event);
+ return response;
+}
+
+function routeRequest(req: NextRequest): NextResponse {
+ const { pathname } = req.nextUrl;
const hasSession = req.cookies.has("multica_logged_in");
const lastSlug = req.cookies.get("last_workspace_slug")?.value;
@@ -171,6 +209,8 @@ export const config = {
"/docs/:path*",
"/ws",
"/collab",
+ "/llms.txt",
+ "/robots.txt",
"/((?!api|v1|_next/static|_next/image|favicon.ico|.*\\.).*)",
],
};
diff --git a/packages/core/ai-traffic/index.test.ts b/packages/core/ai-traffic/index.test.ts
new file mode 100644
index 0000000000..b6715f63a2
--- /dev/null
+++ b/packages/core/ai-traffic/index.test.ts
@@ -0,0 +1,313 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ aiVisitPostHogConfig,
+ aiVisitPostHogEvent,
+ buildAiVisitRecord,
+ classifyAiTraffic,
+ identifyAiAgent,
+ logAiVisit,
+ prefersMarkdown,
+ reportAiVisit,
+ sendAiVisitToPostHog,
+} from "./index";
+
+const CHROME_2026 =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36";
+const CHROME_2017 =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
+const GOOGLEBOT_SMARTPHONE =
+ "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
+
+function headers(values: Record<string, string>) {
+ return new Headers(values);
+}
+
+const browserPageLoad = {
+ "user-agent": CHROME_2026,
+ accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
+ "sec-fetch-mode": "navigate",
+};
+
+describe("identifyAiAgent", () => {
+ it.each([
+ ["Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; [email protected])", "ClaudeBot", "training"],
+ ["Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Claude-User/1.0; [email protected])", "Claude-User", "user"],
+ ["Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-SearchBot/1.0; +https://openai.com/searchbot", "OAI-SearchBot", "search"],
+ ["Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot", "ChatGPT-User", "user"],
+ ["Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot)", "PerplexityBot", "search"],
+ ["Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Perplexity-User/1.0; +https://perplexity.ai/perplexity-user)", "Perplexity-User", "user"],
+ ["Mozilla/5.0 (Linux; Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; Bytespider; [email protected])", "Bytespider", "training"],
+ ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)", "Applebot", "search"],
+ ])("recognizes %s", (userAgent, name, kind) => {
+ expect(identifyAiAgent(userAgent)).toMatchObject({ name, kind });
+ });
+
+ it("matches whole product tokens only", () => {
+ expect(identifyAiAgent("NotClaudeBot/1.0")).toBeNull();
+ expect(identifyAiAgent("ClaudeBotanist/1.0")).toBeNull();
+ expect(identifyAiAgent(CHROME_2026)).toBeNull();
+ expect(identifyAiAgent(null)).toBeNull();
+ });
+});
+
+describe("prefersMarkdown", () => {
+ it.each([
+ "text/markdown",
+ "text/markdown, text/html;q=0.9, */*;q=0.8",
+ "text/x-markdown",
+ ])("prefers Markdown for %s", (accept) => {
+ expect(prefersMarkdown(accept)).toBe(true);
+ });
+
+ it.each([
+ null,
+ "",
+ "*/*",
+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
+ "text/html, text/markdown;q=0.5",
+ "text/markdown;q=0",
+ "text/plain",
+ "application/json, text/plain, */*",
+ ])("keeps HTML for %s", (accept) => {
+ expect(prefersMarkdown(accept)).toBe(false);
+ });
+});
+
+describe("classifyAiTraffic", () => {
+ it("ignores an ordinary browser page load", () => {
+ expect(classifyAiTraffic(headers(browserPageLoad))).toBeNull();
+ expect(classifyAiTraffic(headers({ "user-agent": CHROME_2026, cookie: "a=1" }))).toBeNull();
+ });
+
+ it("names the agent and whether it asked for Markdown", () => {
+ expect(
+ classifyAiTraffic(headers({ "user-agent": "Claude-User/1.0", accept: "text/markdown" })),
+ ).toMatchObject({ signal: "ai-agent", agent: { name: "Claude-User" }, markdownRequested: true });
+ });
+
+ it("flags an unnamed client that asks for Markdown", () => {
+ expect(classifyAiTraffic(headers({ "user-agent": "node", accept: "text/markdown" }))).toMatchObject({
+ signal: "markdown-request",
+ agent: null,
+ });
+ });
+
+ it("flags a browser user agent without cookies or fetch metadata", () => {
+ expect(classifyAiTraffic(headers({ "user-agent": CHROME_2017 }))).toEqual({
+ signal: "disguised-browser",
+ agent: null,
+ markdownRequested: false,
+ legacyBrowser: true,
+ });
+ expect(classifyAiTraffic(headers({ "user-agent": CHROME_2026 }))).toMatchObject({
+ signal: "disguised-browser",
+ legacyBrowser: false,
+ });
+ });
+
+ it("does not call declared crawlers or non-browser clients disguised", () => {
+ expect(classifyAiTraffic(headers({ "user-agent": GOOGLEBOT_SMARTPHONE }))).toBeNull();
+ expect(classifyAiTraffic(headers({ "user-agent": "curl/8.7.1" }))).toBeNull();
+ });
+});
+
+describe("buildAiVisitRecord", () => {
+ it("records the visit without cookies, tokens, addresses or query strings", () => {
+ const record = buildAiVisitRecord({
+ app: "docs",
+ method: "GET",
+ pathname: "/docs/agents",
+ headers: headers({
+ "user-agent": "ChatGPT-User/1.0",
+ cookie: "multica_session=secret",
+ authorization: "Bearer secret",
+ "x-forwarded-for": "203.0.113.7",
+ }),
+ format: "html",
+ status: null,
+ now: new Date("2026-11-23T00:00:00Z"),
+ });
+
+ expect(record).toEqual({
+ event: "ai_visit",
+ time: "2026-11-23T00:00:00.000Z",
+ app: "docs",
+ method: "GET",
+ path: "/docs/agents",
+ signal: "ai-agent",
+ agent: "ChatGPT-User",
+ operator: "OpenAI",
+ kind: "user",
+ format: "html",
+ status: null,
+ legacyBrowser: false,
+ userAgent: "ChatGPT-User/1.0",
+ });
+ const serialized = JSON.stringify(record);
+ expect(serialized).not.toContain("secret");
+ expect(serialized).not.toContain("203.0.113.7");
+ });
+
+ it("records any client fetching a Markdown URL", () => {
+ expect(
+ buildAiVisitRecord({
+ app: "docs",
+ method: "GET",
+ pathname: "/docs/agents.md",
+ headers: headers({ "user-agent": "curl/8.7.1", accept: "*/*" }),
+ format: "markdown",
+ status: null,
+ }),
+ ).toMatchObject({ signal: "markdown-request", agent: null, format: "markdown" });
+ });
+
+ it("skips ordinary traffic", () => {
+ expect(
+ buildAiVisitRecord({
+ app: "web",
+ method: "GET",
+ pathname: "/",
+ headers: headers(browserPageLoad),
+ format: "html",
+ status: null,
+ }),
+ ).toBeNull();
+ });
+
+ it("bounds the path and user agent", () => {
+ const record = buildAiVisitRecord({
+ app: "web",
+ method: "GET",
+ pathname: `/${"a".repeat(2000)}`,
+ headers: headers({ "user-agent": `GPTBot/1.0 ${"x".repeat(2000)}` }),
+ format: "html",
+ status: null,
+ });
+ expect(record?.path).toHaveLength(512);
+ expect(record?.userAgent).toHaveLength(256);
+ });
+});
+
+describe("logAiVisit", () => {
+ it("writes one JSON line per record and nothing for ordinary traffic", () => {
+ const lines: string[] = [];
+ const record = buildAiVisitRecord({
+ app: "web",
+ method: "GET",
+ pathname: "/llms.txt",
+ headers: headers({ "user-agent": "PerplexityBot/1.0" }),
+ format: "markdown",
+ status: null,
+ });
+ logAiVisit(record, (line) => lines.push(line));
+ logAiVisit(null, (line) => lines.push(line));
+ expect(lines).toHaveLength(1);
+ expect(JSON.parse(lines[0]!)).toMatchObject({ agent: "PerplexityBot", path: "/llms.txt" });
+ });
+
+ it("swallows sink failures", () => {
+ const record = buildAiVisitRecord({
+ app: "web",
+ method: "GET",
+ pathname: "/",
+ headers: headers({ "user-agent": "GPTBot/1.0" }),
+ format: "html",
+ status: null,
+ });
+ expect(() =>
+ logAiVisit(record, () => {
+ throw new Error("stdout closed");
+ }),
+ ).not.toThrow();
+ });
+});
+
+describe("PostHog retention", () => {
+ const record = buildAiVisitRecord({
+ app: "docs",
+ method: "GET",
+ pathname: "/docs/agents.md",
+ headers: headers({ "user-agent": "ClaudeBot/1.0", cookie: "session=secret" }),
+ format: "markdown",
+ status: null,
+ now: new Date("2026-11-23T00:00:00.000Z"),
+ })!;
+ const config = { apiKey: "phc_test", host: "https://eu.i.posthog.com", environment: "production" } as const;
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("reads the same variables as the Go server", () => {
+ expect(aiVisitPostHogConfig({})).toBeNull();
+ expect(aiVisitPostHogConfig({ POSTHOG_API_KEY: "phc_test", ANALYTICS_DISABLED: "TRUE" })).toBeNull();
+ expect(aiVisitPostHogConfig({ POSTHOG_API_KEY: " phc_test " })).toEqual({
+ apiKey: "phc_test",
+ host: "https://us.i.posthog.com",
+ environment: "dev",
+ });
+ expect(
+ aiVisitPostHogConfig({ POSTHOG_API_KEY: "phc_test", POSTHOG_HOST: "https://eu.i.posthog.com/", APP_ENV: "prod" }),
+ ).toEqual(config);
+ expect(
+ aiVisitPostHogConfig({ POSTHOG_API_KEY: "phc_test", ANALYTICS_ENVIRONMENT: "staging", APP_ENV: "production" })
+ ?.environment,
+ ).toBe("staging");
+ });
+
+ it("captures bots without person profiles or GeoIP", () => {
+ expect(aiVisitPostHogEvent(record, "production")).toEqual({
+ event: "ai_visit",
+ distinct_id: "ai-visit:ClaudeBot",
+ timestamp: "2026-11-23T00:00:00.000Z",
+ properties: {
+ app: "docs",
+ method: "GET",
+ path: "/docs/agents.md",
+ signal: "ai-agent",
+ agent: "ClaudeBot",
+ operator: "Anthropic",
+ kind: "training",
+ format: "markdown",
+ status: null,
+ legacyBrowser: false,
+ userAgent: "ClaudeBot/1.0",
+ environment: "production",
+ $process_person_profile: false,
+ $geoip_disable: true,
+ },
+ });
+ });
+
+ it("posts to the batch endpoint and never rejects", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response("{}"));
+ await sendAiVisitToPostHog(record, config, fetchMock);
+ const [url, init] = fetchMock.mock.calls[0]!;
+ expect(url).toBe("https://eu.i.posthog.com/batch/");
+ const body = JSON.parse(String(init?.body));
+ expect(body.api_key).toBe("phc_test");
+ expect(body.batch).toEqual([aiVisitPostHogEvent(record, "production")]);
+ expect(String(init?.body)).not.toContain("secret");
+
+ await expect(
+ sendAiVisitToPostHog(record, config, vi.fn<typeof fetch>().mockRejectedValue(new Error("offline"))),
+ ).resolves.toBeUndefined();
+ });
+
+ it("hands the send to waitUntil only when PostHog is configured", () => {
+ vi.spyOn(console, "info").mockImplementation(() => {});
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response("{}"));
+ const waitUntil = vi.fn();
+
+ reportAiVisit(record, { env: {}, waitUntil, fetch: fetchMock });
+ reportAiVisit(null, { env: { POSTHOG_API_KEY: "phc_test" }, waitUntil, fetch: fetchMock });
+ expect(waitUntil).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ reportAiVisit(record, { env: { POSTHOG_API_KEY: "phc_test" }, waitUntil, fetch: fetchMock });
+ expect(waitUntil).toHaveBeenCalledWith(expect.any(Promise));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(console.info).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/core/ai-traffic/index.ts b/packages/core/ai-traffic/index.ts
new file mode 100644
index 0000000000..cda518d8c7
--- /dev/null
+++ b/packages/core/ai-traffic/index.ts
@@ -0,0 +1,319 @@
+/**
+ * Server-side classification of AI crawler and AI agent traffic on the public
+ * site and docs. Client analytics never see these requests: crawlers and
+ * real-time fetchers do not execute JavaScript.
+ */
+
+export type AiAgentKind =
+ /** Bulk crawler that collects training data. */
+ | "training"
+ /** Crawler that builds an AI search index. */
+ | "search"
+ /** Fetch made on behalf of a person, during a chat or an agent run. */
+ | "user";
+
+export type AiAgent = {
+ /** Product token as it appears in the user agent. */
+ name: string;
+ operator: string;
+ kind: AiAgentKind;
+};
+
+// Only tokens operators send as user agents. Robots-only tokens such as
+// `Google-Extended` and `Applebot-Extended` never appear on a request; their
+// traffic arrives as Googlebot or Applebot.
+export const AI_AGENTS: readonly AiAgent[] = [
+ { name: "ClaudeBot", operator: "Anthropic", kind: "training" },
+ { name: "Claude-SearchBot", operator: "Anthropic", kind: "search" },
+ { name: "Claude-User", operator: "Anthropic", kind: "user" },
+ { name: "GPTBot", operator: "OpenAI", kind: "training" },
+ { name: "OAI-SearchBot", operator: "OpenAI", kind: "search" },
+ { name: "ChatGPT-User", operator: "OpenAI", kind: "user" },
+ { name: "PerplexityBot", operator: "Perplexity", kind: "search" },
+ { name: "Perplexity-User", operator: "Perplexity", kind: "user" },
+ { name: "Bytespider", operator: "ByteDance", kind: "training" },
+ { name: "Applebot", operator: "Apple", kind: "search" },
+ { name: "meta-externalagent", operator: "Meta", kind: "training" },
+ { name: "Meta-ExternalFetcher", operator: "Meta", kind: "user" },
+ { name: "Amazonbot", operator: "Amazon", kind: "search" },
+ { name: "DuckAssistBot", operator: "DuckDuckGo", kind: "search" },
+ { name: "MistralAI-User", operator: "Mistral", kind: "user" },
+ { name: "CCBot", operator: "Common Crawl", kind: "training" },
+];
+
+const AI_AGENT_PATTERN = new RegExp(
+ `(?:^|[^a-z0-9-])(${AI_AGENTS.map((agent) => agent.name.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&")).join("|")})(?![a-z0-9-])`,
+ "i",
+);
+
+export function identifyAiAgent(userAgent: string | null | undefined): AiAgent | null {
+ if (!userAgent) return null;
+ const token = AI_AGENT_PATTERN.exec(userAgent)?.[1]?.toLowerCase();
+ if (!token) return null;
+ return AI_AGENTS.find((agent) => agent.name.toLowerCase() === token) ?? null;
+}
+
+// Not `text/plain`: generic HTTP clients (axios sends
+// `application/json, text/plain, */*`) list it without wanting Markdown.
+const MARKDOWN_MEDIA_TYPES = new Set(["text/markdown", "text/x-markdown"]);
+const HTML_MEDIA_TYPES = new Set(["text/html", "text/*", "*/*"]);
+
+/**
+ * Whether an `Accept` header ranks Markdown at least as high as HTML.
+ * Browsers list `text/html` explicitly and never `text/markdown`, so they
+ * keep getting HTML.
+ */
+export function prefersMarkdown(accept: string | null | undefined): boolean {
+ if (!accept) return false;
+ let markdown = 0;
+ let html = 0;
+ for (const section of accept.split(",")) {
+ const [rawType, ...params] = section.split(";");
+ const mediaType = rawType?.trim().toLowerCase();
+ if (!mediaType) continue;
+ let quality = 1;
+ for (const param of params) {
+ const [key, value] = param.split("=");
+ if (key?.trim().toLowerCase() !== "q") continue;
+ const parsed = Number.parseFloat(value ?? "");
+ if (!Number.isNaN(parsed)) quality = parsed;
+ }
+ if (quality <= 0) continue;
+ if (MARKDOWN_MEDIA_TYPES.has(mediaType)) markdown = Math.max(markdown, quality);
+ else if (HTML_MEDIA_TYPES.has(mediaType)) html = Math.max(html, quality);
+ }
+ return markdown > 0 && markdown >= html;
+}
+
+/** Chrome releases before this major predate 2022. */
+const LEGACY_CHROME_MAJOR = 100;
+
+function chromeMajor(userAgent: string): number | null {
+ const match = /(?:Chrome|CriOS)\/(\d+)\./.exec(userAgent);
+ return match ? Number(match[1]) : null;
+}
+
+/** Claims to be a browser and does not declare itself a bot, as Googlebot's browser-like UA does. */
+function isBrowserUserAgent(userAgent: string): boolean {
+ return (
+ /^Mozilla\/5\.0 /.test(userAgent) &&
+ /(?:Chrome|CriOS|Firefox|Safari)\//.test(userAgent) &&
+ !/bot\b|crawl|spider|compatible;/i.test(userAgent)
+ );
+}
+
+type RequestHeaders = { get(name: string): string | null };
+
+export type AiTrafficSignal =
+ /** The user agent names a known AI crawler or fetcher. */
+ | "ai-agent"
+ /** No known agent, but the client asked for Markdown, by `Accept` header or by URL. */
+ | "markdown-request"
+ /**
+ * A browser user agent with none of a browser's request traits: no cookies
+ * and no `Sec-Fetch-*` headers, which every current browser sends on page
+ * loads. AI fetchers that hide behind browser user agents look like this.
+ */
+ | "disguised-browser";
+
+export type AiTrafficClassification = {
+ signal: AiTrafficSignal;
+ agent: AiAgent | null;
+ markdownRequested: boolean;
+ /** The user agent claims a Chrome major older than 2022. */
+ legacyBrowser: boolean;
+};
+
+export function classifyAiTraffic(headers: RequestHeaders): AiTrafficClassification | null {
+ const userAgent = headers.get("user-agent") ?? "";
+ const markdownRequested = prefersMarkdown(headers.get("accept"));
+ const major = chromeMajor(userAgent);
+ const legacyBrowser = major !== null && major < LEGACY_CHROME_MAJOR;
+
+ const agent = identifyAiAgent(userAgent);
+ if (agent) return { signal: "ai-agent", agent, markdownRequested, legacyBrowser };
+ if (markdownRequested) return { signal: "markdown-request", agent: null, markdownRequested, legacyBrowser };
+ if (
+ isBrowserUserAgent(userAgent) &&
+ !headers.get("cookie") &&
+ !headers.get("sec-fetch-mode")
+ ) {
+ return { signal: "disguised-browser", agent: null, markdownRequested, legacyBrowser };
+ }
+ return null;
+}
+
+export type AiVisitFormat = "html" | "markdown" | "text";
+
+export type AiVisitRecord = {
+ event: "ai_visit";
+ time: string;
+ app: string;
+ method: string;
+ /** Pathname only; query strings can carry tokens. */
+ path: string;
+ signal: AiTrafficSignal;
+ agent: string | null;
+ operator: string | null;
+ kind: AiAgentKind | null;
+ format: AiVisitFormat;
+ /** Status when the proxy answers itself (redirects); null when the route renders it. */
+ status: number | null;
+ legacyBrowser: boolean;
+ /** Truncated user agent, kept to audit the classification. */
+ userAgent: string;
+};
+
+const MAX_PATH_LENGTH = 512;
+const MAX_USER_AGENT_LENGTH = 256;
+
+/**
+ * One log record per AI visit, or null for ordinary traffic. Never includes
+ * cookies, authorization headers, IP addresses, or query strings.
+ */
+export function buildAiVisitRecord(input: {
+ app: string;
+ method: string;
+ pathname: string;
+ headers: RequestHeaders;
+ format: AiVisitFormat;
+ status: number | null;
+ now?: Date;
+}): AiVisitRecord | null {
+ const traffic =
+ classifyAiTraffic(input.headers) ??
+ (input.format === "markdown"
+ ? { signal: "markdown-request" as const, agent: null, legacyBrowser: false }
+ : null);
+ if (!traffic) return null;
+ return {
+ event: "ai_visit",
+ time: (input.now ?? new Date()).toISOString(),
+ app: input.app,
+ method: input.method,
+ path: input.pathname.slice(0, MAX_PATH_LENGTH),
+ signal: traffic.signal,
+ agent: traffic.agent?.name ?? null,
+ operator: traffic.agent?.operator ?? null,
+ kind: traffic.agent?.kind ?? null,
+ format: input.format,
+ status: input.status,
+ legacyBrowser: traffic.legacyBrowser,
+ userAgent: (input.headers.get("user-agent") ?? "").slice(0, MAX_USER_AGENT_LENGTH),
+ };
+}
+
+/** Writes one JSON line to stdout. Never throws into the request path. */
+export function logAiVisit(record: AiVisitRecord | null, sink: (line: string) => void = console.info): void {
+ if (!record) return;
+ try {
+ sink(JSON.stringify(record));
+ } catch {
+ // Observability must not affect the response.
+ }
+}
+
+export type AiVisitPostHogConfig = {
+ apiKey: string;
+ host: string;
+ environment: "production" | "staging" | "dev";
+};
+
+type Env = Readonly<Record<string, string | undefined>>;
+
+function analyticsEnvironment(value: string | undefined): AiVisitPostHogConfig["environment"] | null {
+ switch (value?.trim().toLowerCase()) {
+ case "production":
+ case "prod":
+ return "production";
+ case "staging":
+ case "stage":
+ return "staging";
+ case "development":
+ case "dev":
+ case "test":
+ case "local":
+ return "dev";
+ default:
+ return null;
+ }
+}
+
+/**
+ * PostHog settings from the same variables the Go server reads
+ * (`server/internal/analytics`): no `POSTHOG_API_KEY`, or
+ * `ANALYTICS_DISABLED`, means nothing is sent.
+ */
+export function aiVisitPostHogConfig(env: Env): AiVisitPostHogConfig | null {
+ const apiKey = env.POSTHOG_API_KEY?.trim();
+ const disabled = env.ANALYTICS_DISABLED?.trim().toLowerCase();
+ if (!apiKey || disabled === "1" || disabled === "true") return null;
+ return {
+ apiKey,
+ host: (env.POSTHOG_HOST?.trim() || "https://us.i.posthog.com").replace(/\/+$/, ""),
+ environment: analyticsEnvironment(env.ANALYTICS_ENVIRONMENT) ?? analyticsEnvironment(env.APP_ENV) ?? "dev",
+ };
+}
+
+/**
+ * The PostHog capture for one visit. Bots are not people: one distinct id per
+ * agent (or signal), no person profile, and no GeoIP, since the request
+ * reaching PostHog comes from our server rather than the visitor.
+ */
+export function aiVisitPostHogEvent(record: AiVisitRecord, environment: AiVisitPostHogConfig["environment"]) {
+ const { event, time, ...properties } = record;
+ return {
+ event,
+ distinct_id: `ai-visit:${record.agent ?? record.signal}`,
+ timestamp: time,
+ properties: {
+ ...properties,
+ environment,
+ $process_person_profile: false,
+ $geoip_disable: true,
+ },
+ };
+}
+
+const POSTHOG_TIMEOUT_MS = 3000;
+
+/** Sends one visit to PostHog's batch endpoint. Resolves on failure too. */
+export async function sendAiVisitToPostHog(
+ record: AiVisitRecord,
+ config: AiVisitPostHogConfig,
+ fetchImpl: typeof fetch = fetch,
+): Promise<void> {
+ try {
+ const response = await fetchImpl(`${config.host}/batch/`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ api_key: config.apiKey, batch: [aiVisitPostHogEvent(record, config.environment)] }),
+ signal: AbortSignal.timeout(POSTHOG_TIMEOUT_MS),
+ });
+ // Unread bodies hold their pooled connection open.
+ await response.body?.cancel();
+ } catch {
+ // Observability must not affect the response.
+ }
+}
+
+/**
+ * Logs the visit and, when PostHog is configured, sends it for retention.
+ * The send runs after the response through `waitUntil`, so it never adds
+ * latency to the request.
+ */
+export function reportAiVisit(
+ record: AiVisitRecord | null,
+ options: { env: Env; waitUntil?: (promise: Promise<unknown>) => void; fetch?: typeof fetch },
+): void {
+ if (!record) return;
+ logAiVisit(record);
+ const config = aiVisitPostHogConfig(options.env);
+ if (!config) return;
+ const sent = sendAiVisitToPostHog(record, config, options.fetch);
+ try {
+ options.waitUntil?.(sent);
+ } catch {
+ // Observability must not affect the response.
+ }
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index ae0c9c45f4..a34d7ff82d 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -194,6 +194,7 @@
"./query-client": "./query-client.ts",
"./provider": "./provider.tsx",
"./logger": "./logger.ts",
+ "./ai-traffic": "./ai-traffic/index.ts",
"./utils": "./utils.ts",
"./security/redact-secrets": "./security/redact-secrets.ts",
"./constants/*": "./constants/*.ts",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6f86b32ab3..918aba1c6a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -451,6 +451,9 @@ importers:
apps/docs:
dependencies:
+ '@multica/core':
+ specifier: workspace:*
+ version: link:../../packages/core
'@multica/ui':
specifier: workspace:*
version: link:../../packages/ui
diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjs
index 3c944325bb..077de60918 100644
--- a/scripts/ci-scope.test.mjs
+++ b/scripts/ci-scope.test.mjs
@@ -22,6 +22,8 @@ for (const [name, files, selected] of [
["release creation", [".goreleaser.yml"], ["scripts"]],
["docs only", ["apps/docs/content/docs/guide.mdx"], ["quality", "docs"]],
["docs test", ["apps/docs/lib/unrendered-bold.test.ts"], ["quality", "docs"]],
+ ["AI traffic classifier", ["packages/core/ai-traffic/index.ts"], ["frontend", "quality", "docs"]],
+ ["self-hosting guide for agents", ["SELF_HOSTING_AI.md"], ["docs"]],
["web changelog", ["apps/web/features/landing/i18n/en.ts"], ["frontend", "quality"]],
["mobile UI", ["apps/mobile/app/index.tsx"], ["quality"]],
["collaboration service", ["apps/collab/src/documents.ts"], ["frontend", "quality"]],