Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: ai chat ui (#2145)
Maximilian Kaskec3853c55bb3b
diff --git a/CLAUDE.md b/CLAUDE.mdindex c11a24ddd..44b6b35f9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -105,6 +105,16 @@ pnpm test- **Code Generation:** The project uses `drizzle-kit` for database schema migrations.- **API:** The backend API is built using Hono and tRPC. The API is documented using OpenAPI.+## Type Cast Discipline++`as unknown as X`, `as never`, and `as any` are sometimes unavoidable — usually at boundaries with external SDKs (AI SDK, third-party libs) or at registry-style dispatch where TypeScript can't link a runtime string to a literal-keyed map. When you need one:++- **Centralize the cast in a named helper.** Don't scatter the same cast across call sites. Wrap it in a small function whose name describes the intent (`asUIMessages`, `findRenderer`, `renderToolDraft`).+- **Comment the runtime guarantee.** Above the helper, write one or two lines explaining *why the cast is safe at runtime* (e.g. "the persisted shape is validated on write by `storedMessageSchema`, so reads return SDK-conforming rows"). Future readers can verify the invariant or notice when it breaks.+- **Examples:** `apps/dashboard/src/components/chat/use-chat-session.ts` (`asUIMessages`); `apps/dashboard/src/components/chat/tool-renderers/index.tsx` (`renderToolDraft` / `renderToolResult` / `summarizeToolOutput`). Both eliminate scattered casts in the consuming components.++A scattered `as never` is usually a missing helper.+## Services & Audit Log PatternAll workspace-scoped business logic lives in `packages/services` — **not** in tRPC routers. Routers stay thin: validate input, call a service verb, map errors. This keeps logic reusable across tRPC, Hono, and background jobs, and keeps it Edge-safe (the dashboard runs tRPC on Next.js Edge, so service code must avoid `node:*` imports).diff --git a/apps/dashboard/.env.example b/apps/dashboard/.env.exampleindex 21407096e..761228c8d 100644--- a/apps/dashboard/.env.example+++ b/apps/dashboard/.env.example@@ -81,4 +81,7 @@ OPENPANEL_CLIENT_SECRET=something# used to fix the SVG import issue on Vercel# https://github.com/ExodusOSS/bytes/issues/13#issuecomment-3965264022-NODE_OPTIONS=--experimental-require-module\ No newline at end of file+NODE_OPTIONS=--experimental-require-module++# chat model via AI Gateway+AI_GATEWAY_API_KEY=\ No newline at end of filediff --git a/apps/dashboard/next-env.d.ts b/apps/dashboard/next-env.d.tsindex c4b7818fb..9edff1c7c 100644--- a/apps/dashboard/next-env.d.ts+++ b/apps/dashboard/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/dev/types/routes.d.ts";+import "./.next/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/apps/dashboard/package.json b/apps/dashboard/package.jsonindex ada6cb98d..bd035c05b 100644--- a/apps/dashboard/package.json+++ b/apps/dashboard/package.json@@ -10,6 +10,7 @@"tsc": "tsc --noEmit"},"dependencies": {+ "@ai-sdk/react": "3.0.96","@auth/core": "0.40.0","@auth/drizzle-adapter": "1.10.0","@date-fns/tz": "1.2.0",@@ -28,10 +29,11 @@"@openstatus/db": "workspace:*","@openstatus/emails": "workspace:*","@openstatus/error": "workspace:*",- "@openstatus/locales": "workspace:*","@openstatus/header-analysis": "workspace:*","@openstatus/icons": "workspace:*","@openstatus/importers": "workspace:*",+ "@openstatus/locales": "workspace:*",+ "@openstatus/notification-bird-whatsapp": "workspace:*","@openstatus/notification-discord": "workspace:*","@openstatus/notification-emails": "workspace:*","@openstatus/notification-google-chat": "workspace:*",@@ -41,7 +43,6 @@"@openstatus/notification-pagerduty": "workspace:*","@openstatus/notification-slack": "workspace:*","@openstatus/notification-telegram": "workspace:*",- "@openstatus/notification-bird-whatsapp": "workspace:*","@openstatus/notification-webhook": "workspace:*","@openstatus/react": "workspace:*","@openstatus/regions": "workspace:*",@@ -70,6 +71,7 @@"@trpc/server": "11.4.4","@trpc/tanstack-react-query": "11.4.4","@unkey/api": "2.2.0",+ "ai": "6.0.94","class-variance-authority": "0.7.1","clsx": "2.1.1","cmdk": "1.1.1",diff --git a/apps/dashboard/src/app/(dashboard)/agents/breadcrumb.tsx b/apps/dashboard/src/app/(dashboard)/agents/breadcrumb.tsxindex 5ca9121bb..7242d4a13 100644--- a/apps/dashboard/src/app/(dashboard)/agents/breadcrumb.tsx+++ b/apps/dashboard/src/app/(dashboard)/agents/breadcrumb.tsx@@ -5,6 +5,8 @@ import { Bot } from "lucide-react";export function Breadcrumb() {return (- <NavBreadcrumb items={[{ type: "page", label: "Agents", icon: Bot }]} />+ <NavBreadcrumb+ items={[{ type: "page", label: "Slack agent", icon: Bot }]}+ />);}diff --git a/apps/dashboard/src/app/(dashboard)/agents/page.tsx b/apps/dashboard/src/app/(dashboard)/agents/page.tsxindex afe4b8538..98b92e5b4 100644--- a/apps/dashboard/src/app/(dashboard)/agents/page.tsx+++ b/apps/dashboard/src/app/(dashboard)/agents/page.tsx@@ -44,7 +44,7 @@ export default function Page() {<SectionGroup><Section><SectionHeader>- <SectionTitle>Agents</SectionTitle>+ <SectionTitle>Slack agent</SectionTitle><SectionDescription>Use our Slack agent to manage your status pages and incidents.{" "}<Linkdiff --git a/apps/dashboard/src/app/(dashboard)/chat/[id]/layout.tsx b/apps/dashboard/src/app/(dashboard)/chat/[id]/layout.tsxnew file mode 100644index 000000000..063893b89--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/chat/[id]/layout.tsx@@ -0,0 +1,21 @@+import { notFound } from "next/navigation";++import { HydrateClient, fetchQueryOrNotFound, trpc } from "@/lib/trpc/server";++export default async function Layout({+ children,+ params,+}: {+ children: React.ReactNode;+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;+ const sessionId = Number.parseInt(id, 10);+ if (!Number.isInteger(sessionId) || sessionId <= 0) notFound();++ // `fetchQueryOrNotFound` throws `notFound()` for missing/forbidden rows,+ // so the route renders 404 instead of a half-rehydrated chat.+ await fetchQueryOrNotFound(trpc.chatSession.get.queryOptions({ sessionId }));++ return <HydrateClient>{children}</HydrateClient>;+}diff --git a/apps/dashboard/src/app/(dashboard)/chat/[id]/page.tsx b/apps/dashboard/src/app/(dashboard)/chat/[id]/page.tsxnew file mode 100644index 000000000..b7a5b709a--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/chat/[id]/page.tsx@@ -0,0 +1,14 @@+import { notFound } from "next/navigation";++import { ChatSessionClient } from "@/components/chat/chat-session-client";++export default async function Page({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;+ const sessionId = Number.parseInt(id, 10);+ if (!Number.isInteger(sessionId) || sessionId <= 0) notFound();+ return <ChatSessionClient sessionId={sessionId} />;+}diff --git a/apps/dashboard/src/app/(dashboard)/chat/breadcrumb.tsx b/apps/dashboard/src/app/(dashboard)/chat/breadcrumb.tsxnew file mode 100644index 000000000..b4903dff2--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/chat/breadcrumb.tsx@@ -0,0 +1,42 @@+"use client";++import { skipToken, useQuery } from "@tanstack/react-query";+import { MessageSquare } from "lucide-react";++import { useChatSessionContext } from "@/components/chat/chat-session-context";+import { NavBreadcrumb } from "@/components/nav/nav-breadcrumb";+import { useTRPC } from "@/lib/trpc/client";++export function Breadcrumb() {+ // Context (not `useParams`) so we follow runtime `replaceState` URL swaps.+ const { sessionId } = useChatSessionContext();++ const trpc = useTRPC();+ const { data: session } = useQuery(+ trpc.chatSession.get.queryOptions(+ sessionId !== undefined ? { sessionId } : skipToken,+ ),+ );++ if (sessionId === undefined) {+ return (+ <NavBreadcrumb+ items={[{ type: "page", label: "Assistant", icon: MessageSquare }]}+ />+ );+ }++ return (+ <NavBreadcrumb+ items={[+ {+ type: "link",+ label: "Assistant",+ href: "/chat",+ icon: MessageSquare,+ },+ { type: "page", label: session?.title ?? "New chat" },+ ]}+ />+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/chat/layout.tsx b/apps/dashboard/src/app/(dashboard)/chat/layout.tsxnew file mode 100644index 000000000..dd3e9bab4--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/chat/layout.tsx@@ -0,0 +1,61 @@+import { SidebarProvider } from "@openstatus/ui/components/ui/sidebar";++import { ChatSessionProvider } from "@/components/chat/chat-session-context";+import {+ AppHeader,+ AppHeaderActions,+ AppHeaderContent,+} from "@/components/nav/app-header";+import { AppSidebarTrigger } from "@/components/nav/app-sidebar";+import {+ RIGHT_SIDEBAR_COOKIE,+ getSidebarDefaultOpen,+} from "@/lib/sidebar-cookie";+import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";++import { Breadcrumb } from "./breadcrumb";+import { NavActions } from "./nav-actions";+import { Sidebar } from "./sidebar";++export default async function Layout({+ children,+}: {+ children: React.ReactNode;+}) {+ // Prefetch the conversation list so the right sidebar paints immediately.+ const queryClient = getQueryClient();+ await queryClient.prefetchQuery(trpc.chatSession.list.queryOptions());+ const defaultOpen = await getSidebarDefaultOpen(RIGHT_SIDEBAR_COOKIE, false);++ return (+ <HydrateClient>+ <ChatSessionProvider>+ <AppHeader>+ <AppHeaderContent>+ <AppSidebarTrigger />+ <Breadcrumb />+ </AppHeaderContent>+ <AppHeaderActions>+ <NavActions />+ </AppHeaderActions>+ </AppHeader>+ {/*+ The shadcn SidebarProvider wraps children in `min-h-svh`. Inside the+ dashboard's flex-col SidebarInset (which already sits below the+ AppHeader), that pushes the page past the viewport and adds spurious+ scroll. Override to flex-fit the remaining space.+ */}+ <SidebarProvider+ defaultOpen={defaultOpen}+ cookieName={RIGHT_SIDEBAR_COOKIE}+ className="min-h-0 flex-1 [--sidebar-width:18rem] 2xl:[--sidebar-width:24rem]"+ >+ <main className="w-full flex-1">{children}</main>+ <div className="hidden lg:block">+ <Sidebar />+ </div>+ </SidebarProvider>+ </ChatSessionProvider>+ </HydrateClient>+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/chat/nav-actions.tsx b/apps/dashboard/src/app/(dashboard)/chat/nav-actions.tsxnew file mode 100644index 000000000..768c5c97f--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/chat/nav-actions.tsx@@ -0,0 +1,9 @@+import { NavFeedback } from "@/components/nav/nav-feedback";++export function NavActions() {+ return (+ <div className="flex items-center gap-2 text-sm">+ <NavFeedback />+ </div>+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/chat/page.tsx b/apps/dashboard/src/app/(dashboard)/chat/page.tsxnew file mode 100644index 000000000..d3f87aa3a--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/chat/page.tsx@@ -0,0 +1,5 @@+import { ChatNewClient } from "@/components/chat/chat-new-client";++export default function Page() {+ return <ChatNewClient />;+}diff --git a/apps/dashboard/src/app/(dashboard)/chat/sidebar.tsx b/apps/dashboard/src/app/(dashboard)/chat/sidebar.tsxnew file mode 100644index 000000000..b7d662b30--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/chat/sidebar.tsx@@ -0,0 +1,96 @@+"use client";++import {+ skipToken,+ useMutation,+ useQuery,+ useQueryClient,+} from "@tanstack/react-query";+import { formatDistanceToNow } from "date-fns";+import { Plus } from "lucide-react";+import { useRouter } from "next/navigation";++import { useChatSessionContext } from "@/components/chat/chat-session-context";+import type { SidebarMetadataProps } from "@/components/nav/sidebar-metadata";+import { SidebarRight } from "@/components/nav/sidebar-right";+import { useTRPC } from "@/lib/trpc/client";++export function Sidebar() {+ const router = useRouter();+ const { sessionId: activeId } = useChatSessionContext();++ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const { data: sessions } = useQuery(trpc.chatSession.list.queryOptions());+ const { data: activeSession } = useQuery(+ trpc.chatSession.get.queryOptions(+ activeId !== undefined ? { sessionId: activeId } : skipToken,+ ),+ );++ const deleteMutation = useMutation(+ trpc.chatSession.delete.mutationOptions({+ onSuccess: (_, variables) => {+ queryClient.invalidateQueries({+ queryKey: trpc.chatSession.list.queryKey(),+ });+ if (variables.sessionId === activeId) router.push("/chat");+ },+ }),+ );++ const metadata: SidebarMetadataProps[] = [];+ if (activeSession) {+ metadata.push({+ label: "Details",+ items: [+ { label: "Title", value: activeSession.title },+ {+ label: "Created",+ value: formatDistanceToNow(activeSession.createdAt, {+ addSuffix: true,+ }),+ },+ {+ label: "Updated",+ value: formatDistanceToNow(activeSession.updatedAt, {+ addSuffix: true,+ }),+ },+ ],+ });+ }+ metadata.push({+ label: "Recent",+ type: "list",+ items: (sessions ?? []).map((s) => ({+ id: s.id,+ label: s.title,+ meta: formatDistanceToNow(s.updatedAt, { addSuffix: true }),+ href: `/chat/${s.id}`,+ active: s.id === activeId,+ actions: [],+ deleteAction: {+ submitAction: async () => {+ await deleteMutation.mutateAsync({ sessionId: s.id });+ },+ },+ })),+ });++ return (+ <SidebarRight+ header="Conversations"+ metadata={metadata}+ footerButton={{+ onClick: () => router.push("/chat"),+ children: (+ <>+ <Plus />+ <span>New chat</span>+ </>+ ),+ }}+ />+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/layout.tsx b/apps/dashboard/src/app/(dashboard)/layout.tsxindex a203abd69..4d04c2468 100644--- a/apps/dashboard/src/app/(dashboard)/layout.tsx+++ b/apps/dashboard/src/app/(dashboard)/layout.tsx@@ -1,25 +1,27 @@import { AppSidebar } from "@/components/nav/app-sidebar";+import {+ LEFT_SIDEBAR_COOKIE,+ getSidebarDefaultOpen,+} from "@/lib/sidebar-cookie";import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";import {SidebarInset,SidebarProvider,} from "@openstatus/ui/components/ui/sidebar";-import { cookies } from "next/headers";export default async function Layout({children,}: {children: React.ReactNode;}) {- const cookieStore = await cookies();- const hasState = cookieStore.has("sidebar_state");- const defaultOpen = hasState- ? cookieStore.get("sidebar_state")?.value === "true"- : true;+ const defaultOpen = await getSidebarDefaultOpen(LEFT_SIDEBAR_COOKIE, true);return (<HydrateSidebar>- <SidebarProvider defaultOpen={defaultOpen}>+ <SidebarProvider+ defaultOpen={defaultOpen}+ cookieName={LEFT_SIDEBAR_COOKIE}+ ><AppSidebar /><SidebarInset>{children}</SidebarInset></SidebarProvider>diff --git a/apps/dashboard/src/app/(dashboard)/monitors/[id]/incidents/layout.tsx b/apps/dashboard/src/app/(dashboard)/monitors/[id]/incidents/layout.tsxindex 14492579b..800b53103 100644--- a/apps/dashboard/src/app/(dashboard)/monitors/[id]/incidents/layout.tsx+++ b/apps/dashboard/src/app/(dashboard)/monitors/[id]/incidents/layout.tsx@@ -1,3 +1,7 @@+import {+ RIGHT_SIDEBAR_COOKIE,+ getSidebarDefaultOpen,+} from "@/lib/sidebar-cookie";import { getQueryClient, trpc } from "@/lib/trpc/server";import { SidebarProvider } from "@openstatus/ui/components/ui/sidebar";import { Sidebar } from "../sidebar";@@ -14,9 +18,14 @@ export default async function Layout({await queryClient.prefetchQuery(trpc.incident.list.queryOptions({ monitorId: Number.parseInt(id) }),);+ const defaultOpen = await getSidebarDefaultOpen(RIGHT_SIDEBAR_COOKIE, false);return (- <SidebarProvider defaultOpen={false}>+ <SidebarProvider+ defaultOpen={defaultOpen}+ cookieName={RIGHT_SIDEBAR_COOKIE}+ className="min-h-0 flex-1 [--sidebar-width:18rem] 2xl:[--sidebar-width:24rem]"+ ><div className="w-full flex-1">{children}</div><div className="hidden lg:block"><Sidebar />diff --git a/apps/dashboard/src/app/(dashboard)/monitors/[id]/overview/layout.tsx b/apps/dashboard/src/app/(dashboard)/monitors/[id]/overview/layout.tsxindex 12e2b6b8b..bbeede521 100644--- a/apps/dashboard/src/app/(dashboard)/monitors/[id]/overview/layout.tsx+++ b/apps/dashboard/src/app/(dashboard)/monitors/[id]/overview/layout.tsx@@ -1,9 +1,22 @@+import {+ RIGHT_SIDEBAR_COOKIE,+ getSidebarDefaultOpen,+} from "@/lib/sidebar-cookie";import { SidebarProvider } from "@openstatus/ui/components/ui/sidebar";import { Sidebar } from "../sidebar";-export default function Layout({ children }: { children: React.ReactNode }) {+export default async function Layout({+ children,+}: {+ children: React.ReactNode;+}) {+ const defaultOpen = await getSidebarDefaultOpen(RIGHT_SIDEBAR_COOKIE, false);return (- <SidebarProvider defaultOpen={false}>+ <SidebarProvider+ defaultOpen={defaultOpen}+ cookieName={RIGHT_SIDEBAR_COOKIE}+ className="min-h-0 flex-1 [--sidebar-width:18rem] 2xl:[--sidebar-width:24rem]"+ >{/* blur-2xl */}<div className="w-full flex-1">{children}</div><div className="hidden lg:block">diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/layout.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/layout.tsxindex 0d0e58a5e..527f0f846 100644--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/layout.tsx+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/layout.tsx@@ -1,3 +1,7 @@+import {+ RIGHT_SIDEBAR_COOKIE,+ getSidebarDefaultOpen,+} from "@/lib/sidebar-cookie";import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";import { SidebarProvider } from "@openstatus/ui/components/ui/sidebar";import { Sidebar } from "../sidebar";@@ -21,10 +25,15 @@ export default async function Layout({trpc.pageComponent.list.queryOptions({ pageId: Number.parseInt(id) }),),]);+ const defaultOpen = await getSidebarDefaultOpen(RIGHT_SIDEBAR_COOKIE, false);return (<HydrateClient>- <SidebarProvider defaultOpen={false}>+ <SidebarProvider+ defaultOpen={defaultOpen}+ cookieName={RIGHT_SIDEBAR_COOKIE}+ className="min-h-0 flex-1 [--sidebar-width:18rem] 2xl:[--sidebar-width:24rem]"+ ><div className="w-full flex-1">{children}</div><div className="hidden lg:block"><Sidebar />diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/layout.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/layout.tsxindex 94ee94a05..3b4a23ed9 100644--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/layout.tsx+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/layout.tsx@@ -1,3 +1,7 @@+import {+ RIGHT_SIDEBAR_COOKIE,+ getSidebarDefaultOpen,+} from "@/lib/sidebar-cookie";import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";import { SidebarProvider } from "@openstatus/ui/components/ui/sidebar";import { Sidebar } from "../sidebar";@@ -17,10 +21,15 @@ export default async function Layout({pageId: Number.parseInt(id),}),);+ const defaultOpen = await getSidebarDefaultOpen(RIGHT_SIDEBAR_COOKIE, false);return (<HydrateClient>- <SidebarProvider defaultOpen={false}>+ <SidebarProvider+ defaultOpen={defaultOpen}+ cookieName={RIGHT_SIDEBAR_COOKIE}+ className="min-h-0 flex-1 [--sidebar-width:18rem] 2xl:[--sidebar-width:24rem]"+ ><div className="w-full flex-1">{children}</div><div className="hidden lg:block"><Sidebar />diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/layout.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/layout.tsxindex 0916ab65d..267bfbaa9 100644--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/layout.tsx+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/layout.tsx@@ -1,3 +1,7 @@+import {+ RIGHT_SIDEBAR_COOKIE,+ getSidebarDefaultOpen,+} from "@/lib/sidebar-cookie";import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";import { SidebarProvider } from "@openstatus/ui/components/ui/sidebar";import { Sidebar } from "../sidebar";@@ -14,10 +18,15 @@ export default async function Layout({await queryClient.prefetchQuery(trpc.statusReport.list.queryOptions({ pageId: Number.parseInt(id) }),);+ const defaultOpen = await getSidebarDefaultOpen(RIGHT_SIDEBAR_COOKIE, false);return (<HydrateClient>- <SidebarProvider defaultOpen={false}>+ <SidebarProvider+ defaultOpen={defaultOpen}+ cookieName={RIGHT_SIDEBAR_COOKIE}+ className="min-h-0 flex-1 [--sidebar-width:18rem] 2xl:[--sidebar-width:24rem]"+ ><div className="w-full flex-1">{children}</div><div className="hidden lg:block"><Sidebar />diff --git a/apps/dashboard/src/app/api/chat/route.ts b/apps/dashboard/src/app/api/chat/route.tsnew file mode 100644index 000000000..2a41ba2ce--- /dev/null+++ b/apps/dashboard/src/app/api/chat/route.ts@@ -0,0 +1,243 @@+import { cookies } from "next/headers";+import { type NextRequest, NextResponse } from "next/server";++import {+ type ChatStoredMessage,+ storedMessageSchema,+} from "@openstatus/db/src/schema";+import {+ agentTools,+ buildAgentSystemPrompt,+} from "@openstatus/services/agent-tools";+import {+ createChatSession,+ getChatSession,+ setChatSessionMessages,+} from "@openstatus/services/chat-session";+import {+ type UIMessage,+ convertToModelMessages,+ stepCountIs,+ streamText,+} from "ai";+import { z } from "zod";++import { toAiSdkTools } from "@/lib/agent-tools/adapter";+import { getChatServiceContext } from "@/lib/agent-tools/context";+import { chatRateLimit } from "@/lib/rate-limit/chat";++export const runtime = "edge";++const CHAT_MODEL_FREE = "anthropic/claude-haiku-4.5";+const CHAT_MODEL_PAID = "anthropic/claude-sonnet-4.5";++// Drop tool parts that have no result the SDK can turn into a tool_result+// block. `ignoreIncompleteToolCalls` doesn't cover `approval-requested`, so+// a mid-confirmation reload would otherwise replay an orphan `tool_use` to+// Anthropic. `approval-responded` IS kept — the SDK resumes execute on it.+const KEEP_TOOL_STATES = new Set([+ "output-available",+ "output-error",+ "output-denied",+ "approval-responded",+]);++const requestSchema = z.object({+ messages: z+ .array(+ z.object({+ id: z.string(),+ role: z.enum(["user", "assistant", "system"]),+ parts: z.array(z.unknown()),+ }),+ )+ .min(1),+ sessionId: z.number().int().optional(),+});++export async function POST(req: NextRequest) {+ if (!process.env.AI_GATEWAY_API_KEY) {+ return NextResponse.json(+ { error: "Chat is not configured on this deployment." },+ { status: 503 },+ );+ }++ const workspaceSlug = (await cookies()).get("workspace-slug")?.value;+ const ctx = await getChatServiceContext({ workspaceSlug });+ if (!ctx || ctx.actor.type !== "user") {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ let body: z.infer<typeof requestSchema>;+ try {+ body = requestSchema.parse(await req.json());+ } catch {+ return NextResponse.json({ error: "Bad request" }, { status: 400 });+ }++ const plan = ctx.workspace.plan ?? "free";++ // Skip the LLM-cost cap entirely in non-prod so testing doesn't+ // burn through the daily allowance. The Redis counter still+ // increments in prod where it matters.+ if (process.env.NODE_ENV === "production") {+ const limit = await chatRateLimit({ ctx });+ if (!limit.success) {+ // AI SDK surfaces `error` as Error.message and drops sibling keys, so embed `reset` in the string.+ const resetIso = new Date(limit.reset).toISOString();+ return NextResponse.json(+ {+ error: `Rate limit exceeded. Reset at ${resetIso}`,+ reset: limit.reset,+ },+ { status: 429 },+ );+ }+ }++ const originalMessages = body.messages as UIMessage[];++ // Resolve session BEFORE streaming.+ //+ // - With a sessionId, validate it belongs to the caller.+ // - Without one, eagerly create the session from the latest user+ // message. The new id is then known when `messageMetadata` fires+ // on `start`, so the client can navigate to `/chat/{id}` while+ // the response is still streaming.+ let sessionId: number;+ if (body.sessionId !== undefined) {+ try {+ await getChatSession({ ctx, input: { sessionId: body.sessionId } });+ } catch {+ return NextResponse.json({ error: "Session not found" }, { status: 404 });+ }+ sessionId = body.sessionId;+ } else {+ const latestUser = [...originalMessages]+ .reverse()+ .find((m) => m.role === "user");+ if (!latestUser) {+ return NextResponse.json({ error: "Bad request" }, { status: 400 });+ }+ const seed = storedMessageSchema.safeParse(trimMessage(latestUser));+ if (!seed.success || seed.data.parts.length === 0) {+ return NextResponse.json({ error: "Bad request" }, { status: 400 });+ }+ const created = await createChatSession({+ ctx,+ input: { firstMessage: seed.data },+ });+ sessionId = created.id;+ }++ const tools = toAiSdkTools(agentTools, ctx);+ const safeMessages = originalMessages.map((m) => ({+ ...m,+ parts: (m.parts ?? []).filter((p) => {+ if (!p || typeof (p as { type?: unknown }).type !== "string")+ return false;+ const part = p as { type: string; state?: string };+ if (part.type === "text" || part.type === "step-start") return true;+ if (!part.type.startsWith("tool-")) return false;+ return KEEP_TOOL_STATES.has(part.state ?? "");+ }),+ }));+ const modelMessages = await convertToModelMessages(+ safeMessages as UIMessage[],+ { tools, ignoreIncompleteToolCalls: true },+ );++ const result = streamText({+ model: plan === "free" ? CHAT_MODEL_FREE : CHAT_MODEL_PAID,+ system: buildAgentSystemPrompt({+ workspaceName: ctx.workspace.name ?? "Unknown",+ surface: "dashboard",+ canNotifySubscribers: ctx.workspace.limits["status-subscribers"] === true,+ }),+ messages: modelMessages,+ tools,+ stopWhen: stepCountIs(10),+ });++ return result.toUIMessageStreamResponse({+ originalMessages,+ // Force a non-empty id on every response message — without this+ // the SDK can emit `id: ""` for the assistant turn, which causes+ // React's key-collision warning when multiple turns coexist and+ // makes downstream message lookups ambiguous.+ generateMessageId: () => crypto.randomUUID(),+ // Attach `{ sessionId }` to the start chunk so the client can+ // swap `/chat` → `/chat/{id}` after the first turn.+ messageMetadata: ({ part }) => {+ if (part.type === "start") return { sessionId };+ return undefined;+ },+ onFinish: async ({ messages }) => {+ try {+ await persistFullConversation({+ ctx,+ sessionId,+ messages: messages as UIMessage[],+ });+ } catch (err) {+ console.warn("chat onFinish persistence failed", err);+ }+ },+ });+}++/**+ * Strip parts the SDK emits that don't belong in persistent storage+ * (`reasoning`, `source-*`, `file`, `data-*`). We KEEP `step-start`+ * parts: AI SDK's `convertToModelMessages` uses them as block+ * delimiters when emitting Anthropic-shaped messages — without them,+ * an assistant turn that contains both a tool call and a follow-up+ * text reply collapses into a single `[tool_use, text]` ModelMessage,+ * which Anthropic rejects (`tool_use` must be the last content block+ * before the matching `tool_result`).+ */+function trimMessage(m: UIMessage): UIMessage {+ const parts = (m.parts ?? []).filter((p) => {+ if (!p || typeof (p as { type?: unknown }).type !== "string") return false;+ const type = (p as { type: string }).type;+ return type === "text" || type === "step-start" || type.startsWith("tool-");+ });+ // Stamp `createdAt` so the persisted message satisfies the (now+ // required) schema. The service-layer `mergeTimestamps` overrides+ // this with the existing row's stamp when the message id already+ // appears, so this `Date.now()` only "sticks" for brand-new+ // messages.+ const incoming = m as UIMessage & { createdAt?: number };+ return {+ ...m,+ parts,+ createdAt: incoming.createdAt ?? Date.now(),+ } as UIMessage;+}++/**+ * Replace the session's full message list with the trimmed snapshot+ * from the SDK. Idempotent: HITL flows fire `onFinish` multiple times+ * for the same logical turn (paused before confirm, resumed after);+ * full-replace lets each fire be the canonical state without drifting+ * orphans into the row.+ */+async function persistFullConversation(args: {+ ctx: NonNullable<Awaited<ReturnType<typeof getChatServiceContext>>>;+ sessionId: number;+ messages: UIMessage[];+}) {+ const trimmed: ChatStoredMessage[] = [];+ for (const m of args.messages) {+ const parsed = storedMessageSchema.safeParse(trimMessage(m));+ if (parsed.success && parsed.data.parts.length > 0) {+ trimmed.push(parsed.data);+ }+ }+ if (trimmed.length === 0) return;+ await setChatSessionMessages({+ ctx: args.ctx,+ input: { sessionId: args.sessionId, messages: trimmed },+ });+}diff --git a/apps/dashboard/src/components/chat/chat-conversation.tsx b/apps/dashboard/src/components/chat/chat-conversation.tsxnew file mode 100644index 000000000..0314be216--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-conversation.tsx@@ -0,0 +1,93 @@+import { TextShimmer } from "@openstatus/ui/components/custom/text-shimmer";+import { type UIMessage, isToolUIPart } from "ai";+import { useEffect } from "react";++import { Message, MessageContent, MessageMarkdown } from "./chat-message";+import { ChatToolPart } from "./chat-tool-part";++type Props = {+ messages: UIMessage[];+ status: "submitted" | "streaming" | "ready" | "error";+};++export function ChatConversation({ messages, status }: Props) {+ // No inner overflow container — pin the window itself.+ // biome-ignore lint/correctness/useExhaustiveDependencies: deps are change triggers, not reads+ useEffect(() => {+ if (typeof window === "undefined") return;+ window.scrollTo({ top: document.body.scrollHeight });+ }, [messages, status]);++ const last = messages[messages.length - 1];+ const lastIsEmptyAssistant =+ last != null && last.role === "assistant" && !hasAssistantContent(last);+ const showThinking =+ (status === "submitted" || status === "streaming") &&+ (last == null || last.role === "user" || lastIsEmptyAssistant);+ // Hide the empty assistant placeholder so the shimmer doesn't jump down when+ // the SDK appends the empty row before the first token arrives.+ const visibleMessages = lastIsEmptyAssistant+ ? messages.slice(0, -1)+ : messages;++ return (+ <div className="flex-1">+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-4 p-4">+ {visibleMessages.map((m, mIdx) => {+ const createdAt = (m as { createdAt?: number }).createdAt;+ const tooltip =+ createdAt != null+ ? new Date(createdAt).toLocaleString()+ : undefined;+ return (+ // Older persisted rows can have `id: ""` (pre-`generateMessageId`).+ <Message key={m.id || `msg-${mIdx}`} from={m.role} title={tooltip}>+ <MessageContent>+ {(m.parts ?? []).map((part, idx) => {+ if (part.type === "text") {+ if (m.role === "user") {+ return (+ <span key={idx} className="whitespace-pre-wrap">+ {part.text}+ </span>+ );+ }+ return (+ <MessageMarkdown key={idx}>{part.text}</MessageMarkdown>+ );+ }+ if (isToolUIPart(part)) {+ return <ChatToolPart key={idx} part={part} />;+ }+ return null;+ })}+ </MessageContent>+ </Message>+ );+ })}+ {showThinking ? (+ <p>+ <TextShimmer>Thinking…</TextShimmer>+ </p>+ ) : null}+ </div>+ </div>+ );+}++function hasAssistantContent(m: UIMessage): boolean {+ if (m.role !== "assistant") return false;+ for (const part of m.parts ?? []) {+ if (+ part.type === "text" &&+ typeof (part as { text?: string }).text === "string" &&+ (part as { text: string }).text.length > 0+ ) {+ return true;+ }+ if (isToolUIPart(part)) {+ return true;+ }+ }+ return false;+}diff --git a/apps/dashboard/src/components/chat/chat-error-banner.tsx b/apps/dashboard/src/components/chat/chat-error-banner.tsxnew file mode 100644index 000000000..b265fe56b--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-error-banner.tsx@@ -0,0 +1,29 @@+type Props = {+ error: Error;+};++const RATE_LIMIT_RESET_RE = /Reset at (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/;++export function ChatErrorBanner({ error }: Props) {+ const message = error.message ?? "";+ const isRateLimit = /Rate limit/i.test(message);+ return (+ <div className="border-t bg-destructive/10 px-4 py-2 text-destructive text-sm">+ {isRateLimit+ ? `You've hit the daily message cap${formatResetSuffix(message)}.`+ : "The assistant encountered an error. Try again."}+ </div>+ );+}++function formatResetSuffix(message: string): string {+ const match = message.match(RATE_LIMIT_RESET_RE);+ if (!match) return "";+ const resetAt = new Date(match[1]);+ if (Number.isNaN(resetAt.getTime())) return "";+ const time = resetAt.toLocaleTimeString([], {+ hour: "2-digit",+ minute: "2-digit",+ });+ return ` — try again at ${time}`;+}diff --git a/apps/dashboard/src/components/chat/chat-error-boundary.tsx b/apps/dashboard/src/components/chat/chat-error-boundary.tsxnew file mode 100644index 000000000..d1d21eb1d--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-error-boundary.tsx@@ -0,0 +1,36 @@+"use client";++import { Component, type ErrorInfo, type ReactNode } from "react";++type Props = {+ children: ReactNode;+};++type State = {+ error: Error | null;+};++export class ChatErrorBoundary extends Component<Props, State> {+ state: State = { error: null };++ static getDerivedStateFromError(error: Error): State {+ return { error };+ }++ componentDidCatch(error: Error, info: ErrorInfo) {+ console.warn("chat render crash", error, info);+ }++ render() {+ if (this.state.error) {+ return (+ <div className="mx-auto max-w-3xl p-6 text-sm">+ <div className="rounded-md border bg-destructive/10 p-4 text-destructive">+ The conversation failed to render. Reload to recover.+ </div>+ </div>+ );+ }+ return this.props.children;+ }+}diff --git a/apps/dashboard/src/components/chat/chat-history.tsx b/apps/dashboard/src/components/chat/chat-history.tsxnew file mode 100644index 000000000..313e32076--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-history.tsx@@ -0,0 +1,57 @@+"use client";++import { Link } from "@/components/common/link";+import { useSidebar } from "@openstatus/ui/components/ui/sidebar";+import { useQuery } from "@tanstack/react-query";+import { formatDistanceToNow } from "date-fns";++import { useTRPC } from "@/lib/trpc/client";++const MAX_VISIBLE = 5;++export function ChatHistory() {+ const trpc = useTRPC();+ const { data } = useQuery(trpc.chatSession.list.queryOptions());+ const { setOpen } = useSidebar();+ const sessions = data ?? [];+ const recent = sessions.slice(0, MAX_VISIBLE);+ const extra = Math.max(sessions.length - MAX_VISIBLE, 0);++ if (recent.length === 0) return null;++ return (+ <div className="flex w-full max-w-xl flex-col gap-2">+ <div className="flex items-center justify-between">+ <span className="font-mono text-muted-foreground text-xs uppercase tracking-wide">+ Recent+ </span>+ </div>+ <ul className="flex flex-col gap-2">+ {recent.map((s) => (+ <li key={s.id}>+ <Link+ href={`/chat/${s.id}`}+ className="flex items-center justify-between gap-3 text-muted-foreground text-sm hover:text-foreground"+ >+ <span className="truncate">{s.title}</span>+ <span className="shrink-0 font-commit-mono text-muted-foreground text-xs">+ {formatDistanceToNow(new Date(s.updatedAt), {+ addSuffix: true,+ })}+ </span>+ </Link>+ </li>+ ))}+ </ul>+ {extra > 0 ? (+ <button+ type="button"+ onClick={() => setOpen(true)}+ className="self-start font-mono text-muted-foreground text-xs hover:text-foreground"+ >+ {extra} more {extra === 1 ? "conversation" : "conversations"}+ </button>+ ) : null}+ </div>+ );+}diff --git a/apps/dashboard/src/components/chat/chat-message.tsx b/apps/dashboard/src/components/chat/chat-message.tsxnew file mode 100644index 000000000..9ab2b5ad4--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-message.tsx@@ -0,0 +1,117 @@+import { cn } from "@openstatus/ui/lib/utils";+import type { UIMessage } from "ai";+import NextLink from "next/link";+import type {+ AnchorHTMLAttributes,+ ComponentProps,+ HTMLAttributes,+} from "react";+import { Fragment, createElement, useDeferredValue, useMemo } from "react";+import { jsx, jsxs } from "react/jsx-runtime";+import rehypeReact from "rehype-react";+import remarkGfm from "remark-gfm";+import remarkParse from "remark-parse";+import remarkRehype from "remark-rehype";+import { unified } from "unified";++type MessageProps = HTMLAttributes<HTMLDivElement> & {+ from: UIMessage["role"];+};++export function Message({ className, from, ...props }: MessageProps) {+ return (+ <div+ data-from={from}+ className={cn(+ "group flex max-w-[95%] flex-col gap-2",+ from === "user" ? "ml-auto items-end" : "w-full items-start",+ className,+ )}+ {...props}+ />+ );+}++export function MessageContent({+ className,+ children,+ ...props+}: ComponentProps<"div"> & { from?: UIMessage["role"] }) {+ return (+ <div+ className={cn(+ "flex max-w-full flex-col gap-2 overflow-hidden text-sm",+ "group-data-[from=user]:rounded-xl group-data-[from=user]:bg-secondary group-data-[from=user]:px-4 group-data-[from=user]:py-3",+ "group-data-[from=assistant]:w-full",+ className,+ )}+ {...props}+ >+ {children}+ </div>+ );+}++const processor = unified()+ .use(remarkParse)+ .use(remarkGfm)+ .use(remarkRehype)+ .use(rehypeReact, {+ createElement,+ Fragment,+ jsx,+ jsxs,+ components: {+ a: ({ href, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>) => {+ if (href?.startsWith("/")) {+ return <NextLink href={href} className="underline" {...props} />;+ }+ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer"+ className="underline"+ {...props}+ />+ );+ },+ code: (props: HTMLAttributes<HTMLElement>) => (+ <code+ className="rounded bg-muted px-1 py-0.5 font-mono text-[0.9em]"+ {...props}+ />+ ),+ pre: (props: HTMLAttributes<HTMLPreElement>) => (+ <pre+ className="overflow-x-auto rounded-md border bg-muted p-3 text-xs"+ {...props}+ />+ ),+ } as { [key: string]: React.ComponentType<unknown> },+ });++export function MessageMarkdown({ children }: { children: string }) {+ // Defer the parse so streaming token updates don't block the main thread.+ // Each chunk-driven re-render runs at high priority with the stale value;+ // the parse re-runs in a low-priority pass that React can interrupt.+ const deferred = useDeferredValue(children);+ const rendered = useMemo(+ () => processor.processSync(deferred).result,+ [deferred],+ );+ return (+ <div+ className={cn(+ "space-y-2 leading-relaxed",+ "[&_li]:ml-4 [&_li]:list-disc [&_ol]:list-decimal",+ "[&_strong]:font-semibold",+ "[&_table]:my-2 [&_table]:w-full [&_table]:border-collapse [&_table]:text-xs",+ "[&_th]:border [&_th]:bg-muted/50 [&_th]:px-2 [&_th]:py-1 [&_th]:text-left [&_th]:font-medium",+ "[&_td]:border [&_td]:px-2 [&_td]:py-1",+ )}+ >+ {rendered}+ </div>+ );+}diff --git a/apps/dashboard/src/components/chat/chat-new-client.tsx b/apps/dashboard/src/components/chat/chat-new-client.tsxnew file mode 100644index 000000000..2bb51f884--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-new-client.tsx@@ -0,0 +1,67 @@+"use client";++import { useCallback, useMemo } from "react";++import { ChatConversation } from "./chat-conversation";+import { ChatErrorBanner } from "./chat-error-banner";+import { ChatErrorBoundary } from "./chat-error-boundary";+import { ChatHistory } from "./chat-history";+import { ChatPromptInput } from "./chat-prompt-input";+import { ChatSuggestions } from "./chat-suggestions";+import {+ type ChatToolContextValue,+ ChatToolProvider,+} from "./chat-tool-context";+import { useChatSession } from "./use-chat-session";++export function ChatNewClient() {+ const {+ messages,+ sendMessage,+ status,+ error,+ addToolApprovalResponse,+ stop,+ } = useChatSession({ sessionId: undefined });++ const onSubmit = useCallback(+ (text: string) => {+ if (!text.trim()) return;+ sendMessage({ text });+ },+ [sendMessage],+ );++ const tool = useMemo<ChatToolContextValue>(+ () => ({+ confirmTool: (approvalId) =>+ addToolApprovalResponse({ id: approvalId, approved: true }),+ cancelTool: (approvalId, reason = "Cancelled by user.") =>+ addToolApprovalResponse({+ id: approvalId,+ approved: false,+ reason,+ }),+ }),+ [addToolApprovalResponse],+ );++ return (+ <ChatToolProvider value={tool}>+ <div className="flex min-h-[calc(100svh-3.5rem)] flex-col">+ {messages.length === 0 ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-10 p-6">+ <ChatSuggestions onSelect={onSubmit} />+ <ChatHistory />+ </div>+ ) : (+ <ChatErrorBoundary>+ <ChatConversation messages={messages} status={status} />+ </ChatErrorBoundary>+ )}+ {error ? <ChatErrorBanner error={error} /> : null}+ <ChatPromptInput onSubmit={onSubmit} status={status} onStop={stop} />+ </div>+ </ChatToolProvider>+ );+}diff --git a/apps/dashboard/src/components/chat/chat-prompt-input.tsx b/apps/dashboard/src/components/chat/chat-prompt-input.tsxnew file mode 100644index 000000000..05c3d79dd--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-prompt-input.tsx@@ -0,0 +1,105 @@+import { Button } from "@openstatus/ui/components/ui/button";+import {+ InputGroup,+ InputGroupAddon,+ InputGroupTextarea,+} from "@openstatus/ui/components/ui/input-group";+import { Spinner } from "@openstatus/ui/components/ui/spinner";+import { CornerDownLeftIcon, SquareIcon, XIcon } from "lucide-react";+import {+ type FormEvent,+ type KeyboardEvent,+ useCallback,+ useState,+} from "react";++type ChatStatus = "submitted" | "streaming" | "ready" | "error";++type Props = {+ onSubmit: (text: string) => void;+ onStop?: () => void;+ status?: ChatStatus;+};++export function ChatPromptInput({ onSubmit, onStop, status }: Props) {+ const [value, setValue] = useState("");+ const isGenerating = status === "submitted" || status === "streaming";++ const submit = useCallback(() => {+ const text = value.trim();+ if (!text || isGenerating) return;+ onSubmit(text);+ setValue("");+ }, [value, isGenerating, onSubmit]);++ const handleSubmit = useCallback(+ (e: FormEvent<HTMLFormElement>) => {+ e.preventDefault();+ submit();+ },+ [submit],+ );++ const handleKeyDown = useCallback(+ (e: KeyboardEvent<HTMLTextAreaElement>) => {+ // IMEs (CJK input) finalize a candidate with Enter; don't submit mid-composition.+ if (e.nativeEvent.isComposing) return;+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ submit();+ }+ },+ [submit],+ );++ const handleClick = useCallback(() => {+ if (isGenerating && onStop) {+ onStop();+ }+ }, [isGenerating, onStop]);++ return (+ <div className="sticky bottom-0 z-10 border-t bg-background px-3 pt-3 pb-2">+ <div className="mx-auto flex max-w-3xl flex-col gap-1">+ <form onSubmit={handleSubmit}>+ <InputGroup>+ <InputGroupTextarea+ placeholder="Ask openstatus…"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={handleKeyDown}+ // Override the workspace `min-h-16` so an empty input is one row tall.+ className="min-h-0"+ />+ <InputGroupAddon+ align="block-end"+ className="justify-end px-2 py-2"+ >+ <Button+ type={isGenerating && onStop ? "button" : "submit"}+ size="icon-sm"+ onClick={handleClick}+ disabled={!isGenerating && !value.trim()}+ aria-label={isGenerating ? "Stop" : "Send"}+ >+ {status === "submitted" ? (+ <Spinner />+ ) : status === "streaming" ? (+ <SquareIcon className="size-4" />+ ) : status === "error" ? (+ <XIcon className="size-4" />+ ) : (+ <CornerDownLeftIcon className="size-4" />+ )}+ </Button>+ </InputGroupAddon>+ </InputGroup>+ </form>+ <p className="text-center text-muted-foreground text-xs">+ Powered by Claude. AI responses may contain errors, double-check+ results.+ </p>+ </div>+ </div>+ );+}diff --git a/apps/dashboard/src/components/chat/chat-session-client.tsx b/apps/dashboard/src/components/chat/chat-session-client.tsxnew file mode 100644index 000000000..67133614b--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-session-client.tsx@@ -0,0 +1,58 @@+"use client";++import { useCallback, useMemo } from "react";++import { ChatConversation } from "./chat-conversation";+import { ChatErrorBanner } from "./chat-error-banner";+import { ChatErrorBoundary } from "./chat-error-boundary";+import { ChatPromptInput } from "./chat-prompt-input";+import {+ type ChatToolContextValue,+ ChatToolProvider,+} from "./chat-tool-context";+import { useChatSession } from "./use-chat-session";++export function ChatSessionClient({ sessionId }: { sessionId: number }) {+ const {+ messages,+ sendMessage,+ status,+ error,+ addToolApprovalResponse,+ stop,+ } = useChatSession({ sessionId });++ const onSubmit = useCallback(+ (text: string) => {+ if (!text.trim()) return;+ sendMessage({ text });+ },+ [sendMessage],+ );++ const tool = useMemo<ChatToolContextValue>(+ () => ({+ confirmTool: (approvalId) =>+ addToolApprovalResponse({ id: approvalId, approved: true }),+ cancelTool: (approvalId, reason = "Cancelled by user.") =>+ addToolApprovalResponse({+ id: approvalId,+ approved: false,+ reason,+ }),+ }),+ [addToolApprovalResponse],+ );++ return (+ <ChatToolProvider value={tool}>+ <div className="flex min-h-[calc(100svh-3.5rem)] flex-col">+ <ChatErrorBoundary>+ <ChatConversation messages={messages} status={status} />+ </ChatErrorBoundary>+ {error ? <ChatErrorBanner error={error} /> : null}+ <ChatPromptInput onSubmit={onSubmit} status={status} onStop={stop} />+ </div>+ </ChatToolProvider>+ );+}diff --git a/apps/dashboard/src/components/chat/chat-session-context.tsx b/apps/dashboard/src/components/chat/chat-session-context.tsxnew file mode 100644index 000000000..8460cf873--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-session-context.tsx@@ -0,0 +1,37 @@+"use client";++import { useParams } from "next/navigation";+import { type ReactNode, createContext, useContext } from "react";++type ChatSessionContextValue = {+ sessionId: number | undefined;+};++const ChatSessionContext = createContext<ChatSessionContextValue | null>(null);++export function ChatSessionProvider({ children }: { children: ReactNode }) {+ const params = useParams<{ id?: string | string[] }>();+ // Mirror the dynamic layout's `parseInt`-acceptance so the sidebar's+ // `active` highlight stays in sync. `parseInt` would truncate+ // "123abc" → 123; the digit-only guard prevents that leak.+ const urlSessionId =+ typeof params.id === "string" && /^\d+$/.test(params.id)+ ? Number.parseInt(params.id, 10) || undefined+ : undefined;++ return (+ <ChatSessionContext.Provider value={{ sessionId: urlSessionId }}>+ {children}+ </ChatSessionContext.Provider>+ );+}++export function useChatSessionContext(): ChatSessionContextValue {+ const ctx = useContext(ChatSessionContext);+ if (!ctx) {+ throw new Error(+ "useChatSessionContext must be used within <ChatSessionProvider>",+ );+ }+ return ctx;+}diff --git a/apps/dashboard/src/components/chat/chat-suggestions.tsx b/apps/dashboard/src/components/chat/chat-suggestions.tsxnew file mode 100644index 000000000..2cb8382b9--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-suggestions.tsx@@ -0,0 +1,53 @@+import { Button } from "@openstatus/ui/components/ui/button";++import {+ Section,+ SectionDescription,+ SectionHeader,+ SectionTitle,+} from "@/components/content/section";+import { Badge } from "@openstatus/ui/components/ui/badge";++const SUGGESTIONS = [+ "Show me my status pages",+ "What status reports are open?",+ "Draft a status report",+ "Schedule a maintenance window",+];++type Props = {+ onSelect: (text: string) => void;+};++export function ChatSuggestions({ onSelect }: Props) {+ return (+ <Section className="flex w-full max-w-3xl flex-col items-center">+ <SectionHeader className="max-w-2xl text-center">+ <SectionTitle>openstatus assistant</SectionTitle>+ <SectionDescription>+ Ask about your workspace, draft status reports, or schedule+ maintenance windows.{" "}+ <span className="text-muted-foreground/80">+ Status pages only - more tools soon.+ </span>{" "}+ <Badge variant="secondary" className="bg-info/10 text-info">+ BETA+ </Badge>+ </SectionDescription>+ </SectionHeader>+ <div className="flex flex-wrap items-center justify-center gap-2">+ {SUGGESTIONS.map((s) => (+ <Button+ key={s}+ variant="outline"+ size="sm"+ className="rounded-full px-4"+ onClick={() => onSelect(s)}+ >+ {s}+ </Button>+ ))}+ </div>+ </Section>+ );+}diff --git a/apps/dashboard/src/components/chat/chat-tool-context.tsx b/apps/dashboard/src/components/chat/chat-tool-context.tsxnew file mode 100644index 000000000..a086549b9--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-tool-context.tsx@@ -0,0 +1,35 @@+"use client";++import { type ReactNode, createContext, useContext } from "react";++type ChatToolContextValue = {+ /** `approvalId` is the SDK's `approval.id`, NOT `toolCallId`. */+ confirmTool: (approvalId: string) => void;+ cancelTool: (approvalId: string, reason?: string) => void;+};++const ChatToolContext = createContext<ChatToolContextValue | null>(null);++export function ChatToolProvider({+ value,+ children,+}: {+ value: ChatToolContextValue;+ children: ReactNode;+}) {+ return (+ <ChatToolContext.Provider value={value}>+ {children}+ </ChatToolContext.Provider>+ );+}++export type { ChatToolContextValue };++export function useChatTool(): ChatToolContextValue {+ const ctx = useContext(ChatToolContext);+ if (!ctx) {+ throw new Error("useChatTool must be used within <ChatToolProvider>");+ }+ return ctx;+}diff --git a/apps/dashboard/src/components/chat/chat-tool-part.tsx b/apps/dashboard/src/components/chat/chat-tool-part.tsxnew file mode 100644index 000000000..8455efebf--- /dev/null+++ b/apps/dashboard/src/components/chat/chat-tool-part.tsx@@ -0,0 +1,287 @@+import { Button } from "@openstatus/ui/components/ui/button";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@openstatus/ui/components/ui/collapsible";+import { Tabs, TabsList, TabsTrigger } from "@openstatus/ui/components/ui/tabs";+import { cn } from "@openstatus/ui/lib/utils";+import {+ type DynamicToolUIPart,+ type ToolUIPart,+ type UITools,+ getToolName,+} from "ai";+import { BracesIcon, ChevronDownIcon, TableIcon } from "lucide-react";+import { type KeyboardEvent, useEffect, useRef, useState } from "react";++import { ChangesTable } from "@/components/common/changes-table";++import { useChatTool } from "./chat-tool-context";+import {+ renderToolDraft,+ renderToolResult,+ summarizeToolOutput,+} from "./tool-renderers";++// SDK tool-part state machine: input-streaming/-available → in-flight;+// approval-requested → HITL gate; approval-responded → about to execute;+// output-available/-error/-denied → terminal.++type ToolState = NonNullable<ToolUIPart["state"]>;++type Props = {+ part: ToolUIPart<UITools> | DynamicToolUIPart;+};++export function ChatToolPart({ part }: Props) {+ const toolName = getToolName(part);+ const { confirmTool, cancelTool } = useChatTool();++ if (part.state === "approval-requested" && part.approval?.id) {+ return (+ <ApprovalCard+ approvalId={part.approval.id}+ toolName={toolName}+ input={part.input}+ confirmTool={confirmTool}+ cancelTool={cancelTool}+ />+ );+ }++ return <ToolDisclosure part={part} toolName={toolName} />;+}++function ApprovalCard({+ approvalId,+ toolName,+ input,+ confirmTool,+ cancelTool,+}: {+ approvalId: string;+ toolName: string;+ input: unknown;+ confirmTool: (id: string) => void;+ cancelTool: (id: string, reason?: string) => void;+}) {+ // Scope key handling to the card so batched approvals / popovers don't share a window listener.+ const cardRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ cardRef.current?.focus();+ }, []);++ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ confirmTool(approvalId);+ } else if (e.key === "Escape") {+ e.preventDefault();+ cancelTool(approvalId);+ }+ };++ const draft = renderToolDraft(toolName, input);+ return (+ <div+ ref={cardRef}+ tabIndex={-1}+ onKeyDown={onKeyDown}+ className="not-prose w-full overflow-hidden rounded-xl border bg-background outline-none"+ >+ <div className="flex items-center gap-2 p-3 text-sm">+ <ToolStateDot state="approval-requested" />+ <span className="font-commit-mono font-medium">{toolName}</span>+ </div>+ <div className="border-t p-3">+ {draft ? (+ <ChangesTable changes={draft} />+ ) : (+ <pre className="max-h-64 overflow-auto rounded bg-muted/50 p-2 text-xs">+ {JSON.stringify(input, null, 2)}+ </pre>+ )}+ </div>+ <div className="flex items-center justify-end gap-3 border-t bg-muted/30 p-3">+ <span className="text-muted-foreground text-xs">+ <kbd className="rounded border bg-background px-1 font-mono">Esc</kbd>{" "}+ to cancel ·{" "}+ <kbd className="rounded border bg-background px-1 font-mono">⌘ ↵</kbd>{" "}+ to apply+ </span>+ <div className="flex gap-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() => cancelTool(approvalId)}+ >+ Cancel+ </Button>+ <Button size="sm" onClick={() => confirmTool(approvalId)}>+ Apply+ </Button>+ </div>+ </div>+ </div>+ );+}++function ToolDisclosure({+ part,+ toolName,+}: {+ part: ToolUIPart<UITools> | DynamicToolUIPart;+ toolName: string;+}) {+ const state: ToolState = part.state ?? "output-available";+ const rich = renderToolResult(toolName, part.input, part.output);+ const summary =+ summarizeToolOutput(toolName, part.output) ??+ (state === "output-denied" ? "Cancelled" : undefined);+ // Open by default when a rich renderer has data. During streaming the tool+ // mounts with `output === undefined` (so `rich` is undefined) — auto-open+ // on the first transition to defined, but only once, so a user-driven close+ // afterwards isn't reverted by subsequent output chunks.+ const richDefined = rich !== undefined;+ const [open, setOpen] = useState(richDefined);+ const hasAutoOpened = useRef(richDefined);+ useEffect(() => {+ if (!hasAutoOpened.current && richDefined) {+ hasAutoOpened.current = true;+ setOpen(true);+ }+ }, [richDefined]);+ // Gate the height animation behind a post-mount flag so a tool that mounts+ // already-open doesn't play the open animation on first paint.+ const [mounted, setMounted] = useState(false);+ useEffect(() => {+ setMounted(true);+ }, []);+ const [view, setView] = useState<"rich" | "raw">("rich");+ const showRich = rich !== undefined && view === "rich";++ return (+ <Collapsible+ open={open}+ onOpenChange={setOpen}+ className="not-prose group w-full rounded-xl border"+ >+ <div className="flex items-center gap-2 p-3 text-sm">+ <CollapsibleTrigger className="flex flex-1 items-center gap-2 rounded text-left">+ <ToolStateDot state={state} />+ <span className="font-commit-mono font-medium">{toolName}</span>+ {summary ? (+ <span className="text-muted-foreground">· {summary}</span>+ ) : null}+ </CollapsibleTrigger>+ {open && rich !== undefined ? (+ <Tabs+ value={view}+ onValueChange={(v) => setView(v as "rich" | "raw")}+ >+ <TabsList className="h-6 p-[2px]">+ <TabsTrigger+ value="rich"+ aria-label="Rich view"+ className="h-[18px] px-1 [&_svg:not([class*='size-'])]:size-3"+ >+ <TableIcon />+ </TabsTrigger>+ <TabsTrigger+ value="raw"+ aria-label="Raw view"+ className="h-[18px] px-1 [&_svg:not([class*='size-'])]:size-3"+ >+ <BracesIcon />+ </TabsTrigger>+ </TabsList>+ </Tabs>+ ) : null}+ <CollapsibleTrigger+ aria-label={open ? "Collapse" : "Expand"}+ className="inline-flex size-6 items-center justify-center rounded text-muted-foreground hover:text-foreground"+ >+ <ChevronDownIcon+ className={cn("size-4 transition-transform", open && "rotate-180")}+ />+ </CollapsibleTrigger>+ </div>+ <CollapsibleContent+ data-animate={mounted}+ className={cn(+ "overflow-hidden",+ "data-[animate=true]:data-[state=closed]:animate-collapsible-up data-[animate=true]:data-[state=open]:animate-collapsible-down",+ )}+ >+ <div className="space-y-3 p-3 pt-0">+ {showRich ? (+ rich+ ) : (+ <>+ {part.input !== undefined ? (+ <ToolPanel label="Parameters" body={part.input} />+ ) : null}+ {part.output !== undefined ? (+ <ToolPanel label="Result" body={part.output} />+ ) : null}+ </>+ )}+ {part.state === "output-error" && part.errorText ? (+ <div className="rounded-md bg-destructive/10 p-2 text-destructive text-xs">+ {part.errorText}+ </div>+ ) : null}+ {state === "output-denied" && part.approval?.reason ? (+ <div className="rounded-md bg-muted/50 p-2 text-muted-foreground text-xs">+ {part.approval.reason}+ </div>+ ) : null}+ </div>+ </CollapsibleContent>+ </Collapsible>+ );+}++function ToolPanel({ label, body }: { label: string; body: unknown }) {+ return (+ <div className="space-y-1">+ <h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">+ {label}+ </h4>+ <pre className="overflow-x-auto rounded-md bg-muted/50 p-2 text-xs">+ {typeof body === "string" ? body : JSON.stringify(body, null, 2)}+ </pre>+ </div>+ );+}++function ToolStateDot({ state }: { state: ToolState }) {+ const isLoading =+ state === "input-streaming" ||+ state === "input-available" ||+ state === "approval-responded";+ const color =+ state === "output-error"+ ? "bg-destructive"+ : state === "output-denied"+ ? "bg-muted-foreground"+ : state === "output-available"+ ? "bg-success"+ : state === "approval-requested"+ ? "bg-warning"+ : "bg-muted-foreground";+ return (+ <span className="relative inline-flex size-2 shrink-0">+ {isLoading ? (+ <span+ className={cn(+ "absolute inline-flex size-full animate-ping rounded-full opacity-75",+ color,+ )}+ />+ ) : null}+ <span className={cn("relative inline-flex size-2 rounded-full", color)} />+ </span>+ );+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/add-status-report-update.tsx b/apps/dashboard/src/components/chat/tool-renderers/add-status-report-update.tsxnew file mode 100644index 000000000..c02152201--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/add-status-report-update.tsx@@ -0,0 +1,29 @@+import type { AgentToolInput } from "@openstatus/services/agent-tools";++import type { ChangeRow } from "@/components/common/changes-table";++type Input = AgentToolInput<"add_status_report_update">;++type Applied = {+ statusReportUpdateId: number;+ notified?: boolean;+};++export function addStatusReportUpdateChanges(+ input: Input,+ applied?: Applied,+): ChangeRow[] {+ const changes: ChangeRow[] = [+ { field: "statusReportId", after: input.statusReportId },+ { field: "status", after: input.status },+ { field: "message", after: input.message },+ {+ field: "notify",+ after: applied?.notified !== undefined ? applied.notified : input.notify,+ },+ ];+ if (input.date) {+ changes.push({ field: "date", after: input.date });+ }+ return changes;+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/create-maintenance.tsx b/apps/dashboard/src/components/chat/tool-renderers/create-maintenance.tsxnew file mode 100644index 000000000..6238775bf--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/create-maintenance.tsx@@ -0,0 +1,28 @@+import type { AgentToolInput } from "@openstatus/services/agent-tools";++import type { ChangeRow } from "@/components/common/changes-table";++type Input = AgentToolInput<"create_maintenance">;++type Applied = {+ id: number;+ notified?: boolean;+};++export function createMaintenanceChanges(+ input: Input,+ applied?: Applied,+): ChangeRow[] {+ return [+ { field: "title", after: input.title },+ { field: "message", after: input.message },+ { field: "from", after: input.from },+ { field: "to", after: input.to },+ { field: "pageId", after: input.pageId },+ { field: "pageComponentIds", after: input.pageComponentIds },+ {+ field: "notify",+ after: applied?.notified !== undefined ? applied.notified : input.notify,+ },+ ];+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/create-status-report.tsx b/apps/dashboard/src/components/chat/tool-renderers/create-status-report.tsxnew file mode 100644index 000000000..1833987f6--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/create-status-report.tsx@@ -0,0 +1,43 @@+import type { AgentToolInput } from "@openstatus/services/agent-tools";++import type { ChangeRow } from "@/components/common/changes-table";++type Input = AgentToolInput<"create_status_report">;++type Applied = {+ id: number;+ notified?: boolean;+ /**+ * Server-set creation timestamp. Used as the fallback `date` value+ * when the input didn't override (server defaults `date` to `now()`).+ */+ createdAt?: string | null;+};++export function createStatusReportChanges(+ input: Input,+ applied?: Applied,+): ChangeRow[] {+ const changes: ChangeRow[] = [+ { field: "title", after: input.title },+ { field: "status", after: input.status },+ { field: "message", after: input.message },+ { field: "pageId", after: input.pageId },+ { field: "pageComponentIds", after: input.pageComponentIds },+ {+ field: "notify",+ after: applied?.notified !== undefined ? applied.notified : input.notify,+ },+ ];++ const resolvedDate = input.date ?? undefined;+ if (resolvedDate !== undefined) {+ changes.push({ field: "date", after: resolvedDate });+ }++ if (applied?.createdAt) {+ changes.push({ field: "createdAt", after: applied.createdAt });+ }++ return changes;+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/index.tsx b/apps/dashboard/src/components/chat/tool-renderers/index.tsxnew file mode 100644index 000000000..1e42271cc--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/index.tsx@@ -0,0 +1,175 @@+import type {+ AgentToolInput,+ AgentToolName,+ AgentToolOutput,+} from "@openstatus/services/agent-tools";+import type { ReactNode } from "react";++import {+ type ChangeRow,+ ChangesTable,+} from "@/components/common/changes-table";++import { addStatusReportUpdateChanges } from "./add-status-report-update";+import { createMaintenanceChanges } from "./create-maintenance";+import { createStatusReportChanges } from "./create-status-report";+import { listMaintenancesTable } from "./list-maintenances";+import { listStatusPagesTable } from "./list-status-pages";+import { listStatusReportsTable } from "./list-status-reports";+import { resolveStatusReportChanges } from "./resolve-status-report";+import { ResultTable } from "./result-table";+import { updateStatusReportChanges } from "./update-status-report";++/**+ * Per-tool renderer keyed by `AgentToolName` so each entry's input/output+ * carry the tool's concrete schema — schema drift becomes a type error here.+ * Tools without an entry fall back to the raw JSON disclosure.+ */+export type ToolRenderer<N extends AgentToolName> = {+ renderDraft?: (input: AgentToolInput<N>) => ChangeRow[];+ renderResult?: (params: {+ input: AgentToolInput<N>;+ output: AgentToolOutput<N>;+ }) => ReactNode;+ summary?: (output: AgentToolOutput<N>) => string | undefined;+};++/**+ * Required map (no `?`) so adding a tool to `agentTools` without a+ * renderer entry is a TS error here. Tools that don't need a custom+ * renderer can opt in with `{}` — explicit, not silent.+ */+export type ToolRendererRegistry = {+ [N in AgentToolName]: ToolRenderer<N>;+};++export const toolRenderers: ToolRendererRegistry = {+ // ── Read tools ───────────────────────────────────────────────+ list_status_pages: {+ renderResult: ({ output }) => (+ <ResultTable {...listStatusPagesTable(output)} />+ ),+ summary: (o) => itemsCountSummary(o.items),+ },+ list_status_reports: {+ renderResult: ({ output }) => (+ <ResultTable {...listStatusReportsTable(output)} />+ ),+ summary: (o) => itemsCountSummary(o.items),+ },+ list_maintenances: {+ renderResult: ({ output }) => (+ <ResultTable {...listMaintenancesTable(output)} />+ ),+ summary: (o) => itemsCountSummary(o.items),+ },++ // ── Destructive tools ────────────────────────────────────────+ create_status_report: {+ renderDraft: (input) => createStatusReportChanges(input),+ renderResult: ({ input, output }) => (+ <ChangesTable+ changes={createStatusReportChanges(input, {+ id: output.statusReport.id,+ notified: output.notified,+ createdAt: output.statusReport.createdAt,+ })}+ />+ ),+ summary: (o) => `ID ${o.statusReport.id}`,+ },+ add_status_report_update: {+ renderDraft: (input) => addStatusReportUpdateChanges(input),+ renderResult: ({ input, output }) => (+ <ChangesTable+ changes={addStatusReportUpdateChanges(input, {+ statusReportUpdateId: output.statusReportUpdateId,+ notified: output.notified,+ })}+ />+ ),+ summary: (o) => `update #${o.statusReportUpdateId}`,+ },+ update_status_report: {+ renderDraft: (input) => updateStatusReportChanges(input),+ renderResult: ({ input }) => (+ <ChangesTable changes={updateStatusReportChanges(input)} />+ ),+ summary: (o) => `ID ${o.id}`,+ },+ resolve_status_report: {+ renderDraft: (input) => resolveStatusReportChanges(input),+ renderResult: ({ input, output }) => (+ <ChangesTable+ changes={resolveStatusReportChanges(input, {+ statusReportUpdateId: output.statusReportUpdateId,+ notified: output.notified,+ })}+ />+ ),+ summary: (o) => `resolved · update #${o.statusReportUpdateId}`,+ },+ create_maintenance: {+ renderDraft: (input) => createMaintenanceChanges(input),+ renderResult: ({ input, output }) => (+ <ChangesTable+ changes={createMaintenanceChanges(input, {+ id: output.id,+ notified: output.notified,+ })}+ />+ ),+ summary: (o) => `ID ${o.id}`,+ },+};++function itemsCountSummary(items: unknown[] | undefined): string | undefined {+ if (!items) return undefined;+ return `${items.length} result${items.length === 1 ? "" : "s"}`;+}++// String-keyed dispatch — these helpers own the `as never` cast that+// bridges runtime `string` to the registry's per-tool literal types.+// Safe because the registry is authored against the same `AgentToolName`+// union the server emits.++// Dedup so streaming doesn't re-warn for the same unknown tool on every render.+const warnedToolNames = new Set<string>();++function findRenderer(toolName: string) {+ const renderer = toolRenderers[toolName as AgentToolName];+ if (!renderer && !warnedToolNames.has(toolName)) {+ warnedToolNames.add(toolName);+ console.warn(+ `chat: no renderer for tool "${toolName}" — falling back to raw JSON. Add an entry to toolRenderers.`,+ );+ }+ return renderer;+}++export function renderToolDraft(+ toolName: string,+ input: unknown,+): ChangeRow[] | undefined {+ return findRenderer(toolName)?.renderDraft?.(input as never);+}++export function renderToolResult(+ toolName: string,+ input: unknown,+ output: unknown,+): ReactNode | undefined {+ if (output === undefined) return undefined;+ return findRenderer(toolName)?.renderResult?.({+ input: input as never,+ output: output as never,+ });+}++export function summarizeToolOutput(+ toolName: string,+ output: unknown,+): string | undefined {+ if (output === undefined) return undefined;+ return findRenderer(toolName)?.summary?.(output as never);+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/list-maintenances.tsx b/apps/dashboard/src/components/chat/tool-renderers/list-maintenances.tsxnew file mode 100644index 000000000..7d8e6598f--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/list-maintenances.tsx@@ -0,0 +1,46 @@+import type { AgentToolOutput } from "@openstatus/services/agent-tools";+import { formatDistanceStrict } from "date-fns";++import { TableCellDate } from "@/components/data-table/table-cell-date";+import { TableCellNumber } from "@/components/data-table/table-cell-number";+import { TableCellText } from "@/components/data-table/table-cell-text";++import type { ResultTableData } from "./result-table";++type Output = AgentToolOutput<"list_maintenances">;++export function listMaintenancesTable(+ output: Output,+): ResultTableData<"title" | "from" | "duration" | "page" | "id"> {+ const items = output?.items ?? [];+ return {+ empty: "No maintenance windows.",+ columns: [+ { key: "title", header: "Title" },+ { key: "from", header: "Start" },+ { key: "duration", header: "Duration" },+ { key: "page", header: "Page" },+ { key: "id", header: "ID" },+ ],+ rows: items.map((m) => {+ const from = new Date(m.from);+ const to = new Date(m.to);+ const [amount, unit] = formatDistanceStrict(from, to).split(" ");+ return {+ id: m.id,+ cells: {+ title: <TableCellText value={m.title} />,+ from: <TableCellDate value={from} />,+ duration: <TableCellNumber value={amount} unit={unit} />,+ page:+ m.pageId !== null ? (+ <TableCellNumber value={m.pageId} />+ ) : (+ <TableCellText value={null} />+ ),+ id: <TableCellNumber value={m.id} />,+ },+ };+ }),+ };+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/list-status-pages.tsx b/apps/dashboard/src/components/chat/tool-renderers/list-status-pages.tsxnew file mode 100644index 000000000..31cb04489--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/list-status-pages.tsx@@ -0,0 +1,41 @@+import type { AgentToolOutput } from "@openstatus/services/agent-tools";++import { TableCellLink } from "@/components/data-table/table-cell-link";+import { TableCellNumber } from "@/components/data-table/table-cell-number";+import { TableCellText } from "@/components/data-table/table-cell-text";++import type { ResultTableData } from "./result-table";++type Output = AgentToolOutput<"list_status_pages">;++export function listStatusPagesTable(+ output: Output,+): ResultTableData<"title" | "slug" | "id"> {+ const items = output?.items ?? [];+ return {+ empty: "No status pages.",+ columns: [+ { key: "title", header: "Title" },+ { key: "slug", header: "Slug" },+ { key: "id", header: "ID" },+ ],+ rows: items.map((p) => ({+ id: p.id,+ cells: {+ title: (+ <TableCellLink+ href={`/status-pages/${p.id}/status-reports`}+ value={p.title}+ />+ ),+ slug: (+ <TableCellText+ value={p.slug}+ className="font-mono text-muted-foreground"+ />+ ),+ id: <TableCellNumber value={p.id} />,+ },+ })),+ };+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/list-status-reports.tsx b/apps/dashboard/src/components/chat/tool-renderers/list-status-reports.tsxnew file mode 100644index 000000000..7934a59e9--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/list-status-reports.tsx@@ -0,0 +1,57 @@+import type { AgentToolOutput } from "@openstatus/services/agent-tools";+import { cn } from "@openstatus/ui/lib/utils";++import { TableCellLink } from "@/components/data-table/table-cell-link";+import { TableCellNumber } from "@/components/data-table/table-cell-number";+import { TableCellText } from "@/components/data-table/table-cell-text";+import { colors } from "@/data/status-report-updates.client";++import type { ResultTableData } from "./result-table";++type Output = AgentToolOutput<"list_status_reports">;++export function listStatusReportsTable(+ output: Output,+): ResultTableData<"title" | "status" | "page" | "id"> {+ const items = output?.items ?? [];+ return {+ empty: "No status reports.",+ columns: [+ { key: "title", header: "Title" },+ { key: "status", header: "Status" },+ { key: "page", header: "Page" },+ { key: "id", header: "ID" },+ ],+ rows: items.map((r) => ({+ id: r.id,+ cells: {+ title:+ r.pageId !== null ? (+ <TableCellLink+ href={`/status-pages/${r.pageId}/status-reports/${r.id}`}+ value={r.title}+ />+ ) : (+ <TableCellText value={r.title} />+ ),+ status: (+ <div+ className={cn(+ "font-mono capitalize",+ colors[r.status as keyof typeof colors],+ )}+ >+ {r.status}+ </div>+ ),+ page:+ r.pageId !== null ? (+ <TableCellNumber value={r.pageId} />+ ) : (+ <TableCellText value={null} />+ ),+ id: <TableCellNumber value={r.id} />,+ },+ })),+ };+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/resolve-status-report.tsx b/apps/dashboard/src/components/chat/tool-renderers/resolve-status-report.tsxnew file mode 100644index 000000000..fa2357839--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/resolve-status-report.tsx@@ -0,0 +1,29 @@+import type { AgentToolInput } from "@openstatus/services/agent-tools";++import type { ChangeRow } from "@/components/common/changes-table";++type Input = AgentToolInput<"resolve_status_report">;++type Applied = {+ statusReportUpdateId: number;+ notified?: boolean;+};++export function resolveStatusReportChanges(+ input: Input,+ applied?: Applied,+): ChangeRow[] {+ const changes: ChangeRow[] = [+ { field: "statusReportId", after: input.statusReportId },+ { field: "status", after: "resolved" },+ { field: "message", after: input.message },+ {+ field: "notify",+ after: applied?.notified !== undefined ? applied.notified : input.notify,+ },+ ];+ if (input.date) {+ changes.push({ field: "date", after: input.date });+ }+ return changes;+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/result-table.tsx b/apps/dashboard/src/components/chat/tool-renderers/result-table.tsxnew file mode 100644index 000000000..a871100b8--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/result-table.tsx@@ -0,0 +1,79 @@+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@openstatus/ui/components/ui/table";+import type { ReactNode } from "react";++/**+ * Tabular result view used by `list_*` chat tool renderers — the read-side+ * counterpart to `ChangesTable`. Each tool ships a descriptor (e.g.+ * `listStatusPagesTable`) that maps the tool's output to columns + rows;+ * the registry consumes it via `<ResultTable {...descriptor(output)} />`.+ *+ * `cellClassName` on a column applies to every cell in that column — keep+ * per-row formatting (mono, badges) in the column definition rather than in+ * each row's cell.+ */+export type ResultColumn<K extends string = string> = {+ key: K;+ header: string;+ cellClassName?: string;+};++export type ResultRow<K extends string = string> = {+ id: string | number;+ cells: Record<K, ReactNode>;+};++export type ResultTableData<K extends string = string> = {+ columns: ResultColumn<K>[];+ rows: ResultRow<K>[];+ empty: string;+};++export function ResultTable<K extends string>({+ columns,+ rows,+ empty,+}: ResultTableData<K>) {+ if (rows.length === 0) {+ return (+ <div className="rounded-md border bg-background p-3 text-muted-foreground text-sm">+ {empty}+ </div>+ );+ }+ return (+ <div className="overflow-hidden rounded-md border bg-background">+ <Table>+ <TableHeader>+ <TableRow className="bg-muted/40 hover:bg-muted/40">+ {columns.map((col) => (+ <TableHead+ key={col.key}+ className="font-mono text-muted-foreground"+ >+ {col.header}+ </TableHead>+ ))}+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row) => (+ <TableRow key={row.id}>+ {columns.map((col) => (+ <TableCell key={col.key} className={col.cellClassName}>+ {row.cells[col.key]}+ </TableCell>+ ))}+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ );+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/update-status-report.tsx b/apps/dashboard/src/components/chat/tool-renderers/update-status-report.tsxnew file mode 100644index 000000000..c7c70af33--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/update-status-report.tsx@@ -0,0 +1,26 @@+import type { AgentToolInput } from "@openstatus/services/agent-tools";++import type { ChangeRow } from "@/components/common/changes-table";++type Input = AgentToolInput<"update_status_report">;++/**+ * Metadata edit on an existing status report. Only fields the model+ * actually proposed surface as rows — leaves other fields untouched in+ * the diff (the model is allowed to send a partial input).+ */+export function updateStatusReportChanges(input: Input): ChangeRow[] {+ const changes: ChangeRow[] = [+ { field: "statusReportId", after: input.statusReportId },+ ];+ if (input.title !== undefined) {+ changes.push({ field: "title", after: input.title });+ }+ if (input.status !== undefined) {+ changes.push({ field: "status", after: input.status });+ }+ if (input.pageComponentIds !== undefined) {+ changes.push({ field: "pageComponentIds", after: input.pageComponentIds });+ }+ return changes;+}diff --git a/apps/dashboard/src/components/chat/use-chat-session.ts b/apps/dashboard/src/components/chat/use-chat-session.tsnew file mode 100644index 000000000..2a0eb62fe--- /dev/null+++ b/apps/dashboard/src/components/chat/use-chat-session.ts@@ -0,0 +1,124 @@+"use client";++import { useChat } from "@ai-sdk/react";+import {+ type ChatStoredMessage,+ chatStoredMessagesSchema,+} from "@openstatus/db/src/schema";+import { skipToken, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ DefaultChatTransport,+ type UIMessage,+ lastAssistantMessageIsCompleteWithApprovalResponses,+} from "ai";+import { useRouter } from "next/navigation";+import { useEffect, useMemo, useRef } from "react";++import { useTRPC } from "@/lib/trpc/client";++// `storedMessageSchema` is a structural subset of `UIMessage` — the SDK reads `.id`, `.role`, `.parts`.+// `safeParse` surfaces drift as a console warning instead of a silent render failure.+function asUIMessages(+ rows: ChatStoredMessage[] | undefined,+): UIMessage[] | undefined {+ if (rows === undefined) return undefined;+ const parsed = chatStoredMessagesSchema.safeParse(rows);+ if (!parsed.success) {+ console.warn(+ "chat: stored messages failed schema validation",+ parsed.error.issues,+ );+ }+ return rows as unknown as UIMessage[];+}++export function useChatSession({ sessionId }: { sessionId?: number }) {+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const router = useRouter();++ const activeSession = useQuery(+ trpc.chatSession.get.queryOptions(+ sessionId !== undefined ? { sessionId } : skipToken,+ ),+ );++ // Ref so the transport closure sees mid-stream id changes without recreating `useChat`.+ const sessionIdRef = useRef<number | undefined>(sessionId);+ useEffect(() => {+ sessionIdRef.current = sessionId;+ }, [sessionId]);++ const transport = useMemo(+ () =>+ new DefaultChatTransport({+ api: "/api/chat",+ prepareSendMessagesRequest({ messages, body }) {+ return {+ body: { ...body, messages, sessionId: sessionIdRef.current },+ };+ },+ }),+ [],+ );++ const chat = useChat({+ transport,+ id: sessionId !== undefined ? `chat-${sessionId}` : "chat-new",+ // Synchronous seed from the prefetched cache — without it the first render+ // is empty and the cache-miss effect below produces a visible flash.+ messages:+ sessionId !== undefined+ ? asUIMessages(activeSession.data?.messages)+ : undefined,+ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,+ onFinish: () => {+ queryClient.invalidateQueries({+ queryKey: trpc.chatSession.list.queryKey(),+ });+ const id = sessionIdRef.current;+ if (id == null) return;+ queryClient.invalidateQueries({+ queryKey: trpc.chatSession.get.queryKey({ sessionId: id }),+ });+ if (sessionId === undefined) {+ router.replace(`/chat/${id}`);+ }+ },+ });++ const { messages, setMessages, stop } = chat;++ // Cache-miss fallback for soft nav (no prefetch). No-op when the seed above hit.+ useEffect(() => {+ if (sessionId === undefined) return;+ if (!activeSession.data?.messages) return;+ if (messages.length > 0) return;+ const next = asUIMessages(activeSession.data.messages);+ if (next) setMessages(next);+ }, [sessionId, activeSession.data, messages.length, setMessages]);++ // Abort in-flight stream on unmount — otherwise `onFinish` still writes to the DB after navigation.+ useEffect(+ () => () => {+ void stop();+ },+ [stop],+ );++ // Server stamps the new id on the first message's metadata; mirror it so a+ // follow-up message sent before `onFinish` navigates still carries the id.+ useEffect(() => {+ if (sessionId !== undefined) return;+ if (sessionIdRef.current !== undefined) return;+ for (const m of messages) {+ const meta = (m as { metadata?: { sessionId?: number } }).metadata;+ if (meta?.sessionId != null) {+ sessionIdRef.current = meta.sessionId;+ return;+ }+ }+ }, [messages, sessionId]);++ return chat;+}diff --git a/apps/dashboard/src/components/common/changes-table.tsx b/apps/dashboard/src/components/common/changes-table.tsxnew file mode 100644index 000000000..d2223be9c--- /dev/null+++ b/apps/dashboard/src/components/common/changes-table.tsx@@ -0,0 +1,82 @@+import { cn } from "@/lib/utils";++/**+ * Field-level diff row used by the audit-log "CHANGES" view and the+ * chat tool draft/result cards.+ *+ * - Provide both `before` and `after` for an update (renders both lines,+ * strikethrough on the removed value).+ * - Provide only `after` for a create (renders a single `+ value` line).+ * - Provide only `before` for a delete (renders a single `- value` line).+ *+ * Use `"before" in row` / `"after" in row` to distinguish "absent" from+ * "explicitly null" — null/undefined render as `—`.+ */+export type ChangeRow = {+ field: string;+ before?: unknown;+ after?: unknown;+};++export function ChangesTable({ changes }: { changes: ChangeRow[] }) {+ if (changes.length === 0) return null;+ return (+ <div className="overflow-hidden rounded-md border bg-background text-sm">+ {changes.map((change, idx) => (+ <div+ key={change.field}+ className={cn(+ "grid grid-cols-1 md:grid-cols-4",+ idx > 0 && "border-t",+ )}+ >+ <div className="truncate border-r bg-muted/40 px-3 py-2 font-mono text-muted-foreground md:col-span-1">+ {change.field}+ </div>+ <div className="grid truncate md:col-span-3">+ {"before" in change ? (+ <DiffLine kind="removed" value={change.before} />+ ) : null}+ {"after" in change ? (+ <DiffLine kind="added" value={change.after} />+ ) : null}+ </div>+ </div>+ ))}+ </div>+ );+}++function DiffLine({+ kind,+ value,+}: {+ kind: "added" | "removed";+ value: unknown;+}) {+ const sign = kind === "added" ? "+" : "-";+ return (+ <div+ className="group flex items-start gap-2 px-3 py-2 font-mono has-[+[data-kind=added]]:pb-0"+ data-kind={kind}+ >+ <span className="select-none text-muted-foreground group-data-[kind=added]:text-success group-data-[kind=removed]:text-destructive">+ {sign}+ </span>+ <span className="whitespace-pre-wrap break-all group-data-[kind=added]:text-foreground group-data-[kind=removed]:text-muted-foreground group-data-[kind=removed]:line-through">+ {formatValue(value)}+ </span>+ </div>+ );+}++export function formatValue(value: unknown): string {+ if (value === null || value === undefined) return "—";+ if (value instanceof Date) return value.toISOString();+ if (typeof value === "string") return value === "" ? "—" : value;+ if (typeof value === "number" || typeof value === "boolean") {+ return String(value);+ }+ if (Array.isArray(value) && value.length === 0) return "—";+ return JSON.stringify(value);+}diff --git a/apps/dashboard/src/components/common/pill.tsx b/apps/dashboard/src/components/common/pill.tsxnew file mode 100644index 000000000..b9f8a3bfe--- /dev/null+++ b/apps/dashboard/src/components/common/pill.tsx@@ -0,0 +1,37 @@+import { cn } from "@openstatus/ui/lib/utils";+import type { ReactNode } from "react";++type Props = {+ label: ReactNode;+ value?: ReactNode;+ className?: string;+ /** Visual emphasis. `default` matches the audit-log palette. */+ variant?: "default" | "outline";+};++/**+ * Two-part chip: muted label cell + mono value cell, separated by a+ * vertical border. Returns `null` when `value` is empty so callers can map+ * over a heterogeneous metadata bag without filtering first.+ */+export function Pill({ label, value, className, variant = "default" }: Props) {+ if (value === undefined || value === null || value === "") return null;+ return (+ <div+ className={cn(+ "inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap rounded-md border font-medium text-xs transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",+ className,+ )}+ >+ <div+ className={cn(+ "border-r py-0.5 pr-1 pl-2 text-foreground/70",+ variant === "default" && "bg-muted",+ )}+ >+ {label}+ </div>+ <div className="py-0.5 pr-2 pl-1 font-mono">{value}</div>+ </div>+ );+}diff --git a/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsxindex 2b00a76e3..d950afb66 100644--- a/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx+++ b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx@@ -1,17 +1,14 @@"use client";+import {+ type ChangeRow,+ ChangesTable,+} from "@/components/common/changes-table";import { CopyRow } from "@/components/common/copy-row";-import { cn } from "@/lib/utils";import type { RouterOutputs } from "@openstatus/api";type AuditLog = RouterOutputs["auditLog"]["list"]["items"][number];-type ChangeRow = {- field: string;- before?: unknown;- after?: unknown;-};-/*** Fields we never surface in the CHANGES view.*@@ -82,17 +79,6 @@ function buildChanges(row: AuditLog): ChangeRow[] {return [];}-function formatValue(value: unknown): string {- if (value === null || value === undefined) return "—";- if (value instanceof Date) return value.toISOString();- if (typeof value === "string") return value === "" ? "—" : value;- if (typeof value === "number" || typeof value === "boolean") {- return String(value);- }- if (Array.isArray(value) && value.length === 0) return "—";- return JSON.stringify(value);-}-export function DataTableRowDetails({ row }: { row: AuditLog }) {const changes = buildChanges(row);@@ -104,29 +90,7 @@ export function DataTableRowDetails({ row }: { row: AuditLog }) {<div className="font-medium text-muted-foreground text-xs uppercase tracking-wider">Changes</div>- <div className="overflow-hidden rounded-md border bg-background text-sm">- {changes.map((change, idx) => (- <div- key={change.field}- className={cn(- "grid grid-cols-1 md:grid-cols-4",- idx > 0 && "border-t",- )}- >- <div className="truncate border-r bg-muted/40 px-3 py-2 font-mono text-muted-foreground md:col-span-1">- {change.field}- </div>- <div className="grid truncate md:col-span-3">- {"before" in change ? (- <DiffLine kind="removed" value={change.before} />- ) : null}- {"after" in change ? (- <DiffLine kind="added" value={change.after} />- ) : null}- </div>- </div>- ))}- </div>+ <ChangesTable changes={changes} /></div><div className="flex flex-col gap-2"><div className="font-medium text-muted-foreground text-xs uppercase tracking-wider">@@ -150,26 +114,3 @@ export function DataTableRowDetails({ row }: { row: AuditLog }) {</div>);}--function DiffLine({- kind,- value,-}: {- kind: "added" | "removed";- value: unknown;-}) {- const sign = kind === "added" ? "+" : "-";- return (- <div- className="group flex items-start gap-2 px-3 py-2 font-mono has-[+[data-kind=added]]:pb-0"- data-kind={kind}- >- <span className="select-none text-muted-foreground group-data-[kind=added]:text-success group-data-[kind=removed]:text-destructive">- {sign}- </span>- <span className="whitespace-pre-wrap break-all group-data-[kind=added]:text-foreground group-data-[kind=removed]:text-muted-foreground group-data-[kind=removed]:line-through">- {formatValue(value)}- </span>- </div>- );-}diff --git a/apps/dashboard/src/components/data-table/audit-logs/columns.tsx b/apps/dashboard/src/components/data-table/audit-logs/columns.tsxindex 83798aed1..417c24ae8 100644--- a/apps/dashboard/src/components/data-table/audit-logs/columns.tsx+++ b/apps/dashboard/src/components/data-table/audit-logs/columns.tsx@@ -1,6 +1,7 @@"use client";import { HoverCardTimestamp } from "@/components/common/hover-card-timestamp";+import { Pill } from "@/components/common/pill";import { TableCellDate } from "@/components/data-table/table-cell-date";import { config, getMetadata } from "@/data/audit-logs.client";import { cn } from "@/lib/utils";@@ -100,18 +101,3 @@ export function getColumns(},];}--function Pill({ label, value }: { label: string; value?: string }) {- if (!value) return null;- return (- <div className="inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap rounded-md border font-medium text-xs transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3">- <div className="border-r bg-muted py-0.5 pr-1 pl-2 text-foreground/70">- {label}- </div>- <div className="py-0.5 pr-2 pl-1 font-mono">- {/* NOTE: if we have more number values, we might wanna change it */}- {value}- </div>- </div>- );-}diff --git a/apps/dashboard/src/components/data-table/table-cell-text.tsx b/apps/dashboard/src/components/data-table/table-cell-text.tsxnew file mode 100644index 000000000..8d77923af--- /dev/null+++ b/apps/dashboard/src/components/data-table/table-cell-text.tsx@@ -0,0 +1,27 @@+import { cn } from "@/lib/utils";++export function TableCellText({+ value,+ className,+ ...props+}: React.ComponentProps<"div"> & { value: unknown }) {+ if (typeof value === "string" && value.length > 0) {+ return (+ <div className={cn(className)} {...props}>+ {value}+ </div>+ );+ }+ if (typeof value === "number") {+ return (+ <div className={cn(className)} {...props}>+ {value}+ </div>+ );+ }+ return (+ <div className={cn("text-muted-foreground", className)} {...props}>+ -+ </div>+ );+}diff --git a/apps/dashboard/src/components/dropdowns/quick-actions.tsx b/apps/dashboard/src/components/dropdowns/quick-actions.tsxindex 8b04ccd59..e600275c9 100644--- a/apps/dashboard/src/components/dropdowns/quick-actions.tsx+++ b/apps/dashboard/src/components/dropdowns/quick-actions.tsx@@ -51,8 +51,9 @@ interface QuickActionsProps extends React.ComponentProps<typeof Button> {deleteAction?: {/*** The value that must be typed to confirm deletion. Also used in the dialog title.+ * If omitted, no type-to-confirm step is shown.*/- confirmationValue: string;+ confirmationValue?: string;submitAction?: () => Promise<void>;};}@@ -154,14 +155,16 @@ export function QuickActions({><AlertDialogHeader><AlertDialogTitle>- Are you sure about deleting `{deleteAction?.confirmationValue}`?+ {deleteAction?.confirmationValue+ ? `Are you sure about deleting \`${deleteAction.confirmationValue}\`?`+ : "Are you sure?"}</AlertDialogTitle><AlertDialogDescription>This action cannot be undone. This will permanently remove the entryfrom the database.</AlertDialogDescription></AlertDialogHeader>- {deleteAction?.confirmationValue && (+ {deleteAction?.confirmationValue ? (<form id="form-alert-dialog" className="space-y-1.5"><p className="text-muted-foreground text-sm">Type{" "}@@ -183,7 +186,7 @@ export function QuickActions({</p><Input value={value} onChange={(e) => setValue(e.target.value)} /></form>- )}+ ) : null}<AlertDialogFooter><AlertDialogCancel onClick={(e) => e.stopPropagation()}>Canceldiff --git a/apps/dashboard/src/components/nav/app-sidebar.tsx b/apps/dashboard/src/components/nav/app-sidebar.tsxindex c404b6c78..edd37f9d8 100644--- a/apps/dashboard/src/components/nav/app-sidebar.tsx+++ b/apps/dashboard/src/components/nav/app-sidebar.tsx@@ -7,6 +7,7 @@ import {Cog,Globe,LayoutGrid,+ MessageSquare,PanelTop,ScanEye,Terminal,@@ -83,7 +84,12 @@ const data = {icon: ScanEye,},{- name: "Agents",+ name: "Assistant",+ url: "/chat",+ icon: MessageSquare,+ },+ {+ name: "Slack agent",url: "/agents",icon: Bot,},diff --git a/apps/dashboard/src/components/nav/nav-overview.tsx b/apps/dashboard/src/components/nav/nav-overview.tsxindex eb865943f..4083e2ca4 100644--- a/apps/dashboard/src/components/nav/nav-overview.tsx+++ b/apps/dashboard/src/components/nav/nav-overview.tsx@@ -13,6 +13,10 @@ import {import Link from "next/link";import { usePathname } from "next/navigation";+function topSegment(url: string) {+ return url.split("/")[1] ?? "";+}+export function NavOverview({items,}: {@@ -24,6 +28,7 @@ export function NavOverview({}) {const pathname = usePathname();const { setOpenMobile } = useSidebar();+ const currentTop = topSegment(pathname);return (<SidebarGroup><SidebarGroupLabel>Workspace</SidebarGroupLabel>@@ -31,8 +36,9 @@ export function NavOverview({{items.map((item) => (<SidebarMenuItem key={item.name}><SidebarMenuButton- // FIXME: check with settings as exception (as it includes subpages)- isActive={pathname === item.url}+ isActive={+ currentTop !== "" && currentTop === topSegment(item.url)+ }asChildtooltip={item.name}>diff --git a/apps/dashboard/src/components/nav/sidebar-metadata.tsx b/apps/dashboard/src/components/nav/sidebar-metadata.tsxindex ea44667d3..917b612d8 100644--- a/apps/dashboard/src/components/nav/sidebar-metadata.tsx+++ b/apps/dashboard/src/components/nav/sidebar-metadata.tsx@@ -1,10 +1,9 @@-import { ChevronRight } from "lucide-react";+import type { LucideIcon } from "lucide-react";+import { ChevronRight, MoreHorizontal } from "lucide-react";+import Link from "next/link";import * as React from "react";-import {- EmptyStateContainer,- EmptyStateDescription,-} from "@/components/content/empty-state";+import { QuickActions } from "@/components/dropdowns/quick-actions";import {Collapsible,CollapsibleContent,@@ -14,6 +13,10 @@ import {SidebarGroup,SidebarGroupContent,SidebarGroupLabel,+ SidebarMenu,+ SidebarMenuAction,+ SidebarMenuButton,+ SidebarMenuItem,} from "@openstatus/ui/components/ui/sidebar";import {Table,@@ -32,16 +35,59 @@ import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";import { cn } from "@openstatus/ui/lib/utils";import { TooltipProvider } from "@radix-ui/react-tooltip";-export type SidebarMetadataProps = {+export type SidebarMetadataItem = {label: string;- items?: {+ value: React.ReactNode;+ isNested?: boolean;+};++export type SidebarMetadataListItem = {+ /** Stable React key + handle for `active` matching. */+ id: string | number;+ label: React.ReactNode;+ /** Trailing meta on the row (e.g. "2m ago"). */+ meta?: React.ReactNode;+ /** Optional small leading icon. */+ icon?: LucideIcon;+ /** Click target — renders as `next/link` when set. */+ href?: string;+ /** Marks this row as the current selection. */+ active?: boolean;+ /** Hover-revealed `…` button that opens a `QuickActions` dropdown. */+ actions?: {+ id: string;label: string;- value: React.ReactNode;- isNested?: boolean;+ icon: LucideIcon;+ variant: "default" | "destructive";+ onClick?: () => Promise<void> | void;}[];+ /** Destructive item in the same `…` dropdown, with confirmation dialog. */+ deleteAction?: {+ confirmationValue?: string;+ submitAction: () => Promise<void>;+ };};-export function SidebarMetadata({ label, items }: SidebarMetadataProps) {+/**+ * Metadata section in `SidebarRight`. Two shapes:+ * - `type: "table"` (default) — label/value rows with copy-on-tap.+ * - `type: "list"` — clickable rows with optional active state, leading+ * icon, trailing meta and a hover-revealed action.+ */+export type SidebarMetadataProps =+ | {+ label: string;+ type?: "table";+ items?: SidebarMetadataItem[];+ }+ | {+ label: string;+ type: "list";+ items?: SidebarMetadataListItem[];+ };++export function SidebarMetadata(props: SidebarMetadataProps) {+ const { label } = props;return (<SidebarGroup className="p-0"><Collapsible defaultOpen className="group/collapsible border-b">@@ -56,12 +102,10 @@ export function SidebarMetadata({ label, items }: SidebarMetadataProps) {</SidebarGroupLabel><CollapsibleContent><SidebarGroupContent className="border-t">- {items && items.length > 0 ? (- <SidebarMetadataTable items={items} />+ {props.type === "list" ? (+ <SidebarMetadataList items={props.items ?? []} />) : (- <EmptyStateContainer className="m-2">- <EmptyStateDescription>No {label}</EmptyStateDescription>- </EmptyStateContainer>+ <SidebarMetadataTable items={props.items ?? []} />)}</SidebarGroupContent></CollapsibleContent>@@ -107,6 +151,71 @@ function SidebarMetadataTable({);}+function SidebarMetadataList({ items }: { items: SidebarMetadataListItem[] }) {+ return (+ <SidebarGroup className="p-0">+ <SidebarMenu className="gap-0">+ {items.map((item) => {+ const inner = (+ <>+ {item.icon ? <item.icon className="size-3.5 shrink-0" /> : null}+ <span className="flex-1 truncate">{item.label}</span>+ {item.meta != null ? (+ <span className="ml-auto shrink-0 font-mono text-muted-foreground text-xs">+ {item.meta}+ </span>+ ) : null}+ </>+ );+ const hasMenu =+ (item.actions?.length ?? 0) > 0 || !!item.deleteAction;+ return (+ <SidebarMenuItem key={item.id} className="border-b last:border-b-0">+ <SidebarMenuButton+ asChild+ isActive={item.active}+ // Flat row treatment to match `SidebarMetadataTable`: no+ // rounded corners, edge-to-edge, table-cell padding.+ className="h-9 rounded-none px-2 group-has-data-[sidebar=menu-action]/menu-item:pr-2"+ >+ {item.href ? (+ <Link href={item.href}>{inner}</Link>+ ) : (+ <button type="button">{inner}</button>+ )}+ </SidebarMenuButton>+ {hasMenu ? (+ <QuickActions+ actions={item.actions}+ deleteAction={item.deleteAction}+ side="right"+ align="start"+ >+ <SidebarMenuAction+ showOnHover+ // Solid backdrop + left-side gradient so the dots cover+ // the meta timestamp underneath when revealed.+ // `ring-inset` keeps the focus ring within the button so+ // it doesn't bleed past the sidebar's right edge.+ // V-center: the default action `top` is driven by a+ // `peer-data-[size=...]/menu-button` variant tuned for+ // the shorter button sizes; we use a taller `h-9` row,+ // so override the variant directly and re-anchor at 50%.+ className="before:-left-6 -translate-y-1/2 bg-sidebar-accent before:absolute before:inset-y-0 before:right-full before:bg-gradient-to-l before:from-sidebar-accent before:to-transparent focus-visible:ring-inset peer-data-[size=default]/menu-button:top-1/2"+ >+ <MoreHorizontal />+ <span className="sr-only">More</span>+ </SidebarMenuAction>+ </QuickActions>+ ) : null}+ </SidebarMenuItem>+ );+ })}+ </SidebarMenu>+ </SidebarGroup>+ );+}+function SidebarMetadataTableCell({className,...propsdiff --git a/apps/dashboard/src/components/nav/sidebar-right.tsx b/apps/dashboard/src/components/nav/sidebar-right.tsxindex 980f7c2fd..08655e6a4 100644--- a/apps/dashboard/src/components/nav/sidebar-right.tsx+++ b/apps/dashboard/src/components/nav/sidebar-right.tsx@@ -11,7 +11,6 @@ import {SidebarMenu,SidebarMenuButton,SidebarMenuItem,- SidebarProvider,SidebarSeparator,useSidebar,} from "@openstatus/ui/components/ui/sidebar";@@ -21,17 +20,12 @@ import {TooltipProvider,TooltipTrigger,} from "@openstatus/ui/components/ui/tooltip";-import { useMediaQuery } from "@openstatus/ui/hooks/use-media-query";-import { useIsMobile } from "@openstatus/ui/hooks/use-mobile";import { cn } from "@openstatus/ui/lib/utils";import { PanelRight } from "lucide-react";import { Kbd } from "../common/kbd";import { SidebarMetadata, type SidebarMetadataProps } from "./sidebar-metadata";const SIDEBAR_KEYBOARD_SHORTCUT = "]";-const SIDEBAR_WIDTH = "18rem";-const SIDEBAR_WIDTH_2XL = "24rem";-const SIDEBAR_WIDTH_MOBILE = "18rem";type SidebarRightProps = React.ComponentProps<typeof Sidebar> & {header: string;@@ -45,68 +39,52 @@ export function SidebarRight({footerButton,...props}: SidebarRightProps) {- const isMobile = useIsMobile();- const is2XL = useMediaQuery("(min-width: 1536px)");return (- <SidebarProvider- style={- {- "--sidebar-width": isMobile- ? SIDEBAR_WIDTH_MOBILE- : is2XL- ? SIDEBAR_WIDTH_2XL- : SIDEBAR_WIDTH,- } as React.CSSProperties- }- defaultOpen={false}- cookieName="sidebar_state_right"+ <Sidebar+ collapsible="offcanvas"+ side="right"+ className="top-14 flex h-[calc(100svh_-_56px)]"+ {...props}>- <Sidebar- collapsible="offcanvas"- side="right"- className="top-14 flex h-[calc(100svh_-_56px)]"- {...props}- >- <SidebarHeader className="relative border-sidebar-border border-b">- {header}- <div className="-left-9 absolute inset-y-0 z-10 flex items-center justify-center">- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <SidebarTrigger />- </TooltipTrigger>- <TooltipContent side="left">- <p className="mr-px inline-flex items-center">- Toggle Sidebar{" "}- <Kbd className="border-muted-foreground bg-primary font-mono text-background">- ⌘- </Kbd>- <Kbd className="border-muted-foreground bg-primary font-mono text-background">- {SIDEBAR_KEYBOARD_SHORTCUT}- </Kbd>- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </SidebarHeader>- <SidebarContent className="flex flex-col gap-0">- {metadata.map((item) => (- <SidebarMetadata key={item.label} {...item} />- ))}- </SidebarContent>- <SidebarSeparator className="mx-0" />- {footerButton ? (- <SidebarFooter>- <SidebarMenu>- <SidebarMenuItem>- <SidebarMenuButton {...footerButton} />- </SidebarMenuItem>- </SidebarMenu>- </SidebarFooter>- ) : null}- </Sidebar>- </SidebarProvider>+ <SidebarHeader className="relative border-sidebar-border border-b">+ {header}+ <div className="-left-9 absolute inset-y-0 z-10 flex items-center justify-center">+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <SidebarTrigger />+ </TooltipTrigger>+ <TooltipContent side="left">+ <p className="mr-px inline-flex items-center">+ Toggle Sidebar{" "}+ <Kbd className="border-muted-foreground bg-primary font-mono text-background">+ ⌘+ </Kbd>+ <Kbd className="border-muted-foreground bg-primary font-mono text-background">+ {SIDEBAR_KEYBOARD_SHORTCUT}+ </Kbd>+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </SidebarHeader>+ <SidebarContent className="flex flex-col gap-0">+ {metadata.map((item) => (+ <SidebarMetadata key={item.label} {...item} />+ ))}+ </SidebarContent>+ <SidebarSeparator className="mx-0" />+ {footerButton ? (+ <SidebarFooter>+ <SidebarMenu>+ <SidebarMenuItem>+ <SidebarMenuButton {...footerButton} />+ </SidebarMenuItem>+ </SidebarMenu>+ </SidebarFooter>+ ) : null}+ </Sidebar>);}@@ -117,7 +95,6 @@ export function SidebarTrigger({}: React.ComponentProps<typeof Button>) {const { toggleSidebar } = useSidebar();- // Adds a keyboard shortcut to toggle the sidebar.React.useEffect(() => {const handleKeyDown = (event: KeyboardEvent) => {if (diff --git a/apps/dashboard/src/lib/agent-tools/adapter.ts b/apps/dashboard/src/lib/agent-tools/adapter.tsnew file mode 100644index 000000000..c4ba216b1--- /dev/null+++ b/apps/dashboard/src/lib/agent-tools/adapter.ts@@ -0,0 +1,45 @@+import type { ServiceContext } from "@openstatus/services";+import type {+ AgentToolRegistry,+ AnyAgentTool,+} from "@openstatus/services/agent-tools";+import { type Tool, tool } from "ai";++/**+ * Convert a registry entry to the AI SDK's `Tool` shape.+ *+ * Read tools execute server-side as soon as the model emits them.+ *+ * Destructive tools opt into the SDK's *approval flow* via+ * `needsApproval: true`. The SDK pauses with `state: "approval-requested"`+ * before the tool executes; the client renders a confirm card and+ * resolves via `addToolApprovalResponse({ id, approved, reason })`. On+ * approve the SDK runs `execute` itself on the next stream; on deny+ * the part transitions to `output-denied` (a first-class cancel state)+ * and `execute` is never invoked. This replaces the older "omit+ * `execute` + custom `/api/chat/confirm`" pattern, which forced us to+ * reinvent cancel semantics in user-land.+ */+export function toAiSdkTools(+ registry: AgentToolRegistry,+ ctx: ServiceContext,+): Record<string, Tool> {+ const out: Record<string, Tool> = {};+ for (const name in registry) {+ const t = registry[name];+ if (!t) continue;+ out[name] = toolToAiSdkTool(t, ctx);+ }+ return out;+}++function toolToAiSdkTool(t: AnyAgentTool, ctx: ServiceContext): Tool {+ return tool({+ description: t.description,+ inputSchema: t.inputSchema,+ needsApproval: t.destructive,+ execute: async (input: unknown) => {+ return t.run({ ctx, input: t.inputSchema.parse(input) });+ },+ });+}diff --git a/apps/dashboard/src/lib/agent-tools/context.ts b/apps/dashboard/src/lib/agent-tools/context.tsnew file mode 100644index 000000000..ea3325d04--- /dev/null+++ b/apps/dashboard/src/lib/agent-tools/context.ts@@ -0,0 +1,31 @@+import { resolveActiveWorkspace } from "@openstatus/api/src/auth/resolve-active-workspace";+import type { ServiceContext } from "@openstatus/services";++import { auth } from "@/lib/auth";++/**+ * Build a `ServiceContext` for a dashboard chat request. Re-uses the+ * canonical `resolveActiveWorkspace` helper that backs `enforceUserIsAuthed`+ * so both surfaces resolve the same workspace from the same `workspace-slug`+ * cookie. Returns `null` when the user is unauthenticated or has no+ * active workspace — caller renders 401.+ */+export async function getChatServiceContext(args: {+ workspaceSlug?: string;+}): Promise<ServiceContext | null> {+ const session = await auth();+ if (!session?.user?.id) return null;+ const userId = Number(session.user.id);+ if (!Number.isInteger(userId)) return null;++ const resolved = await resolveActiveWorkspace({+ userId,+ workspaceSlug: args.workspaceSlug,+ });+ if (!resolved.ok) return null;++ return {+ workspace: resolved.value.workspace,+ actor: { type: "user", userId },+ };+}diff --git a/apps/dashboard/src/lib/rate-limit/chat.ts b/apps/dashboard/src/lib/rate-limit/chat.tsnew file mode 100644index 000000000..c78c2631b--- /dev/null+++ b/apps/dashboard/src/lib/rate-limit/chat.ts@@ -0,0 +1,64 @@+import type { WorkspacePlan } from "@openstatus/db/src/schema";+import { type ServiceContext, tryGetActorUserId } from "@openstatus/services";+import { redis } from "@openstatus/upstash";++const WINDOW_SECONDS = 60 * 60 * 24; // 24h++// Free is throttled hard to keep LLM spend bounded; paid plans get a+// looser cap that's still cheaper than the worst-case unbounded loop.+const DAILY_LIMIT_BY_PLAN: Record<WorkspacePlan, number> = {+ free: 20,+ starter: 50,+ team: 50,+};++export type ChatRateLimitResult = {+ success: boolean;+ limit: number;+ remaining: number;+ reset: number; // ms epoch when the window resets+};++// INCR + conditional EXPIRE in a single round-trip. A separate+// `incr` then `expire` is not atomic: if the process dies (or the+// upstream call fails) between the two, the key keeps incrementing+// forever with no TTL, locking the user out. Lua scripts run+// atomically on the Redis server, so the TTL is guaranteed to be+// set the same logical step that creates the key.+const INCR_WITH_TTL = `+ local count = redis.call('INCR', KEYS[1])+ if count == 1 then+ redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))+ end+ local ttl = redis.call('TTL', KEYS[1])+ return {count, ttl}+`;++export async function chatRateLimit(args: {+ ctx: ServiceContext;+}): Promise<ChatRateLimitResult> {+ const userId = tryGetActorUserId(args.ctx.actor);+ if (userId == null) {+ throw new Error("chatRateLimit requires a user actor");+ }+ const plan = args.ctx.workspace.plan ?? "free";+ const limit = DAILY_LIMIT_BY_PLAN[plan];+ // Bucket per (workspace, user): the limit is plan-specific, so a+ // user-only key would leak quota across workspaces (e.g. a `team`+ // workspace's higher cap would carry over into the same user's+ // `free` workspace).+ const key = `ratelimit:chat:ws:${args.ctx.workspace.id}:user:${userId}`;+ const now = Date.now();+ const [count, ttl] = await redis.eval<[number], [number, number]>(+ INCR_WITH_TTL,+ [key],+ [WINDOW_SECONDS],+ );+ const reset = now + (ttl > 0 ? ttl * 1000 : WINDOW_SECONDS * 1000);+ return {+ success: count <= limit,+ limit,+ remaining: Math.max(0, limit - count),+ reset,+ };+}diff --git a/apps/dashboard/src/lib/sidebar-cookie.ts b/apps/dashboard/src/lib/sidebar-cookie.tsnew file mode 100644index 000000000..bec441dd5--- /dev/null+++ b/apps/dashboard/src/lib/sidebar-cookie.ts@@ -0,0 +1,16 @@+import { cookies } from "next/headers";++// Must match the upstream shadcn `SIDEBAR_COOKIE_NAME` default; that constant+// is not exported from `@openstatus/ui`.+export const LEFT_SIDEBAR_COOKIE = "sidebar_state";+export const RIGHT_SIDEBAR_COOKIE = "sidebar_state_right";++export async function getSidebarDefaultOpen(+ cookieName: string,+ fallback: boolean,+) {+ const cookieStore = await cookies();+ const cookie = cookieStore.get(cookieName);+ if (!cookie) return fallback;+ return cookie.value === "true";+}diff --git a/apps/dashboard/src/lib/trpc/server.tsx b/apps/dashboard/src/lib/trpc/server.tsxindex 3528c246d..91aebb40f 100644--- a/apps/dashboard/src/lib/trpc/server.tsx+++ b/apps/dashboard/src/lib/trpc/server.tsx@@ -33,7 +33,9 @@ export const trpc = createTRPCOptionsProxy<AppRouter>({headers: {"x-trpc-source": "server",},- fetch: async (url, options) => {+ // `typeof fetch` carries a `preconnect` static (React 19 typings) that+ // tRPC's link will never invoke — cast the call-signature wrapper.+ fetch: (async (url, options) => {const cookieStore = await cookies();console.log("[dashboard trpc server] fetch", {hasSessionToken:@@ -48,7 +50,7 @@ export const trpc = createTRPCOptionsProxy<AppRouter>({cookie: cookieStore.toString(),},});- },+ }) as typeof fetch,}),],}),diff --git a/apps/server/src/routes/mcp/tools/maintenance.ts b/apps/server/src/routes/mcp/tools/maintenance.tsindex 8a8bb74d1..f038a0392 100644--- a/apps/server/src/routes/mcp/tools/maintenance.ts+++ b/apps/server/src/routes/mcp/tools/maintenance.ts@@ -1,241 +1,21 @@-import { getLogger } from "@logtape/logtape";import type {McpServer,RegisteredTool,} from "@modelcontextprotocol/sdk/server/mcp.js";import type { ServiceContext } from "@openstatus/services";import {- createMaintenance,- listMaintenances,- notifyMaintenance,-} from "@openstatus/services/maintenance";-import { z } from "zod";+ createMaintenanceTool,+ listMaintenancesTool,+} from "@openstatus/services/agent-tools";-import { runTool } from "../adapter";-import { registerScopedTool } from "./register-scoped";--const logger = getLogger("api-server");--const PER_PAGE_DEFAULT = 50;-const PER_PAGE_MAX = 200;+import { registerRegistryTools } from "./registry-adapter";export function registerMaintenanceTools(server: McpServer,ctx: ServiceContext,): Map<string, RegisteredTool> {- const registered = new Map<string, RegisteredTool>();-- const t_listMaintenances = registerScopedTool(- server,- ctx,- "list_maintenances",- {- scope: "read",- description:- "List maintenance windows in this workspace, newest first. Paginated via `page` (1-indexed) and `perPage`. The response's `pagination` object carries `totalSize`, `totalPages`, `page`, and `perPage` so the LLM can decide whether to fetch the next page or warn the user that the result is paginated.",- annotations: { readOnlyHint: true, openWorldHint: false },- inputSchema: {- pageId: z- .number()- .int()- .optional()- .describe("If set, only maintenances attached to this page id."),- page: z- .number()- .int()- .min(1)- .default(1)- .describe("1-indexed page number (default 1)."),- perPage: z- .number()- .int()- .min(1)- .max(PER_PAGE_MAX)- .default(PER_PAGE_DEFAULT)- .describe(- `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,- ),- },- outputSchema: {- items: z.array(- z.object({- id: z.number().int(),- title: z.string(),- message: z.string(),- from: z.string(),- to: z.string(),- pageId: z.number().int().nullable(),- pageComponentIds: z.array(z.number().int()),- }),- ),- pagination: z.object({- page: z.number().int(),- perPage: z.number().int(),- totalSize: z.number().int(),- totalPages: z.number().int(),- }),- },- },- async ({ pageId, page, perPage }) =>- runTool(- () =>- listMaintenances({- ctx,- input: {- limit: perPage ?? PER_PAGE_DEFAULT,- offset: ((page ?? 1) - 1) * (perPage ?? PER_PAGE_DEFAULT),- pageId,- order: "desc",- },- }),- ({ items, totalSize }) => {- const currentPage = page ?? 1;- const size = perPage ?? PER_PAGE_DEFAULT;- const summarised = items.map((m) => ({- id: m.id,- title: m.title,- message: m.message,- from: m.from.toISOString(),- to: m.to.toISOString(),- pageId: m.pageId,- pageComponentIds: m.pageComponentIds,- }));- const out = {- items: summarised,- pagination: {- page: currentPage,- perPage: size,- totalSize,- totalPages: Math.max(1, Math.ceil(totalSize / size)),- },- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- );- if (t_listMaintenances)- registered.set("list_maintenances", t_listMaintenances);-- const t_createMaintenance = registerScopedTool(- server,- ctx,- "create_maintenance",- {- scope: "write",- description:- "Schedule a maintenance window on a status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the title, message, and time window (ISO 8601 from/to).\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers (email + integrations) about this maintenance window? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively for an existing window. There is NO separate notify tool. If notify is false here, this window will never reach subscribers. Note: the maintenance row persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.\n\npageId MUST come from list_status_pages — never guess.",- annotations: {- readOnlyHint: false,- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- title: z- .string()- .min(1)- .max(256)- .describe("Short, public-facing title for the maintenance window."),- message: z- .string()- .min(1)- .describe("Public message describing the work, shown on the page."),- from: z.iso- .datetime()- .describe("Start time, ISO 8601 (e.g. 2026-04-30T14:00:00Z)."),- to: z.iso- .datetime()- .describe(- "End time, ISO 8601. Must be strictly after `from` — service rejects otherwise.",- ),- pageId: z- .number()- .int()- .describe(- "Status page to attach the maintenance to. Resolve via list_status_pages — do not guess.",- ),- pageComponentIds: z- .array(z.number().int())- .default([])- .describe(- "Optional component ids affected by the maintenance. Must belong to pageId.",- ),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications for the new window. You MUST ask the user before deciding — do not infer. true = notify on creation. false = create silently; subscribers will NEVER be notified about this window (you cannot notify retroactively).",- ),- },- outputSchema: {- id: z.number().int(),- title: z.string(),- from: z.string(),- to: z.string(),- pageId: z.number().int().nullable(),- notified: z.boolean(),- },- },- async (input) =>- runTool(- async () => {- const record = await createMaintenance({- ctx,- input: {- title: input.title,- message: input.message,- from: new Date(input.from),- to: new Date(input.to),- pageId: input.pageId,- pageComponentIds: input.pageComponentIds ?? [],- },- });- // The maintenance row is already persisted; a notify- // dispatch failure must not propagate as a tool error.- // Otherwise the LLM treats the whole call as failed and- // may retry, double-publishing the window. Report- // partial success via `notified: false`.- let notified = false;- if (input.notify) {- try {- await notifyMaintenance({- ctx,- input: { maintenanceId: record.id },- });- notified = true;- } catch (err) {- logger.error(- "notifyMaintenance failed after create_maintenance {*}",- {- err,- workspaceId: ctx.workspace.id,- maintenanceId: record.id,- },- );- }- }- return { record, notified };- },- ({ record, notified }) => {- const out = {- id: record.id,- title: record.title,- from: record.from.toISOString(),- to: record.to.toISOString(),- pageId: record.pageId,- notified,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- );- if (t_createMaintenance)- registered.set("create_maintenance", t_createMaintenance);-- return registered;+ return registerRegistryTools(server, ctx, [+ listMaintenancesTool,+ createMaintenanceTool,+ ]);}diff --git a/apps/server/src/routes/mcp/tools/page.ts b/apps/server/src/routes/mcp/tools/page.tsindex fda77a249..15884c19a 100644--- a/apps/server/src/routes/mcp/tools/page.ts+++ b/apps/server/src/routes/mcp/tools/page.ts@@ -3,64 +3,20 @@ import type {RegisteredTool,} from "@modelcontextprotocol/sdk/server/mcp.js";import type { ServiceContext } from "@openstatus/services";-import { listPages } from "@openstatus/services/page";-import { z } from "zod";+import { listStatusPagesTool } from "@openstatus/services/agent-tools";-import { runTool } from "../adapter";-import { registerScopedTool } from "./register-scoped";+import { registerRegistryTools } from "./registry-adapter";// Pages carry secrets (`password`, `customDomain` access controls) that-// must never reach an LLM client. Output is a deliberately slim shape-// (id, title, slug only) rather than the full row.+// must never reach an LLM client. The registry tool projects to a slim+// `{ id, title, slug }` shape; full row never leaves the service.//-// No `limit` input: pages are low-cardinality (workspaces have a-// handful), and `listPages` doesn't support `limit` push-down. A-// client-side slice would lie about the cap. Add real pagination if a-// workspace ever hits a problematic page count.-+// No pagination input — pages are low-cardinality and `listPages`+// doesn't push a limit through. Add real pagination if a workspace ever+// hits a problematic count.export function registerPageTools(server: McpServer,ctx: ServiceContext,): Map<string, RegisteredTool> {- const registered = new Map<string, RegisteredTool>();-- const t_listStatusPages = registerScopedTool(- server,- ctx,- "list_status_pages",- {- scope: "read",- description:- "List status pages in this workspace with their slug and ids. Use to discover the pageId required by create_status_report and create_maintenance.",- annotations: { readOnlyHint: true, openWorldHint: false },- inputSchema: {},- outputSchema: {- items: z.array(- z.object({- id: z.number().int(),- title: z.string(),- slug: z.string(),- }),- ),- },- },- async () =>- runTool(- () => listPages({ ctx, input: { order: "desc" } }),- (pages) => {- const items = pages.map((p) => ({- id: p.id,- title: p.title,- slug: p.slug,- }));- return {- content: [{ type: "text", text: JSON.stringify({ items }) }],- structuredContent: { items },- };- },- ),- );- if (t_listStatusPages) registered.set("list_status_pages", t_listStatusPages);-- return registered;+ return registerRegistryTools(server, ctx, [listStatusPagesTool]);}diff --git a/apps/server/src/routes/mcp/tools/registry-adapter.ts b/apps/server/src/routes/mcp/tools/registry-adapter.tsnew file mode 100644index 000000000..e069638f4--- /dev/null+++ b/apps/server/src/routes/mcp/tools/registry-adapter.ts@@ -0,0 +1,97 @@+import type {+ McpServer,+ RegisteredTool,+} from "@modelcontextprotocol/sdk/server/mcp.js";+import type { ServiceContext } from "@openstatus/services";+import type { AnyAgentTool } from "@openstatus/services/agent-tools";+import { ZodObject, type ZodRawShape, type ZodType } from "zod";++import { runTool } from "../adapter";+import { registerScopedTool } from "./register-scoped";++/**+ * Map a single registry tool into the MCP server. Handles:+ * - converting the registry's flat ZodObject input/output schemas into+ * the SDK's `ZodRawShape` (it expects a `.shape` map, not the object)+ * - mirroring the tool's `destructive` flag onto the MCP `annotations`+ * so external clients (Claude Desktop, Cursor) get the standard+ * readOnly/destructive hints+ * - wrapping `tool.run` through `runTool` so service errors map to+ * either recoverable `CallToolResult.isError` or thrown `McpError`s.+ */+export function registerRegistryTool(+ server: McpServer,+ ctx: ServiceContext,+ tool: AnyAgentTool,+): RegisteredTool | undefined {+ const inputShape = assertShape(tool.inputSchema, tool.name, "input");+ const outputShape = assertShape(tool.outputSchema, tool.name, "output");++ return registerScopedTool(+ server,+ ctx,+ tool.name,+ {+ scope: tool.scope,+ description: tool.description,+ annotations: {+ readOnlyHint: tool.scope === "read",+ destructiveHint: tool.destructive,+ idempotentHint: !tool.destructive,+ // Closed-world: every registry tool only touches resources in+ // the caller's workspace (status pages, reports, maintenances) —+ // none reach out to an unbounded set of external entities the+ // way web search or arbitrary URL fetch would.+ openWorldHint: false,+ },+ inputSchema: inputShape,+ outputSchema: outputShape,+ },+ async (input: unknown) =>+ runTool(+ () => tool.run({ ctx, input: tool.inputSchema.parse(input) }),+ (value) => {+ const out = tool.outputSchema.parse(value);+ return {+ content: [{ type: "text", text: JSON.stringify(out) }],+ structuredContent: out as Record<string, unknown>,+ };+ },+ ),+ );+}++/**+ * Register every tool whose name appears in `names`. Returns the+ * `RegisteredTool` map (keyed by tool name) so callers can keep their+ * existing shape for tests / debugging.+ */+export function registerRegistryTools(+ server: McpServer,+ ctx: ServiceContext,+ tools: AnyAgentTool[],+): Map<string, RegisteredTool> {+ const registered = new Map<string, RegisteredTool>();+ for (const tool of tools) {+ const handle = registerRegistryTool(server, ctx, tool);+ if (handle) registered.set(tool.name, handle);+ }+ return registered;+}++// The MCP SDK requires a `ZodRawShape` (flat key→ZodType map), so the+// registry contract is "schemas are ZodObject". A union/intersection at+// the root would silently produce `shape: undefined` and an unusable+// MCP tool — fail loudly at registration instead.+function assertShape(+ schema: ZodType,+ toolName: string,+ kind: "input" | "output",+): ZodRawShape {+ if (!(schema instanceof ZodObject)) {+ throw new Error(+ `MCP tool "${toolName}" has non-ZodObject ${kind} schema; the registry adapter requires a flat ZodObject root.`,+ );+ }+ return schema.shape as ZodRawShape;+}diff --git a/apps/server/src/routes/mcp/tools/status-report.ts b/apps/server/src/routes/mcp/tools/status-report.tsindex 56f9e7316..ca5f7a450 100644--- a/apps/server/src/routes/mcp/tools/status-report.ts+++ b/apps/server/src/routes/mcp/tools/status-report.ts@@ -1,558 +1,27 @@-import { getLogger } from "@logtape/logtape";import type {McpServer,RegisteredTool,} from "@modelcontextprotocol/sdk/server/mcp.js";-import { statusReportStatusSchema } from "@openstatus/db/src/schema";import type { ServiceContext } from "@openstatus/services";import {- addStatusReportUpdate,- createStatusReport,- listStatusReports,- notifyStatusReport,- resolveStatusReport,- updateStatusReport,-} from "@openstatus/services/status-report";-import { z } from "zod";+ addStatusReportUpdateTool,+ createStatusReportTool,+ listStatusReportsTool,+ resolveStatusReportTool,+ updateStatusReportTool,+} from "@openstatus/services/agent-tools";-import { runTool } from "../adapter";-import { registerScopedTool } from "./register-scoped";--const logger = getLogger("api-server");--const PER_PAGE_DEFAULT = 50;-const PER_PAGE_MAX = 200;--/**- * "Active" = every status except `resolved`. Computed from the schema- * so adding a new variant (e.g. `degraded`) automatically extends the- * filter without touching this file.- */-const ACTIVE_STATUSES = statusReportStatusSchema.options.filter(- (s) => s !== "resolved",-);+import { registerRegistryTools } from "./registry-adapter";export function registerStatusReportTools(server: McpServer,ctx: ServiceContext,): Map<string, RegisteredTool> {- const registered = new Map<string, RegisteredTool>();-- const t_listStatusReports = registerScopedTool(- server,- ctx,- "list_status_reports",- {- scope: "read",- description:- "List status reports in this workspace, newest first. Filter by status (e.g. exclude 'resolved' to see active incidents). Returns the most recent update per report so the LLM can see the current public message without a follow-up call. Paginated via `page` (1-indexed) and `perPage`. The response's `pagination` object carries `totalSize`, `totalPages`, `page`, and `perPage` so the LLM can decide whether to fetch the next page or warn the user.",- annotations: { readOnlyHint: true, openWorldHint: false },- inputSchema: {- filter: z- .enum(["active", "all"])- .default("active")- .describe(- "active = exclude resolved reports (default). all = every report regardless of status.",- ),- pageId: z- .number()- .int()- .optional()- .describe("If set, only reports attached to this page id."),- page: z- .number()- .int()- .min(1)- .default(1)- .describe("1-indexed page number (default 1)."),- perPage: z- .number()- .int()- .min(1)- .max(PER_PAGE_MAX)- .default(PER_PAGE_DEFAULT)- .describe(- `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,- ),- },- outputSchema: {- items: z.array(- z.object({- id: z.number().int(),- title: z.string(),- status: statusReportStatusSchema,- pageId: z.number().int().nullable(),- createdAt: z.string().nullable(),- updatedAt: z.string().nullable(),- latestUpdate: z- .object({- message: z.string(),- status: statusReportStatusSchema,- date: z.string().nullable(),- })- .nullable(),- }),- ),- pagination: z.object({- page: z.number().int(),- perPage: z.number().int(),- totalSize: z.number().int(),- totalPages: z.number().int(),- }),- },- },- async ({ filter, pageId, page, perPage }) =>- runTool(- () =>- listStatusReports({- ctx,- input: {- limit: perPage ?? PER_PAGE_DEFAULT,- offset: ((page ?? 1) - 1) * (perPage ?? PER_PAGE_DEFAULT),- statuses: filter === "active" ? ACTIVE_STATUSES : [],- pageId,- order: "desc",- },- }),- ({ items, totalSize }) => {- const currentPage = page ?? 1;- const size = perPage ?? PER_PAGE_DEFAULT;- const summarised = items.map((r) => {- const latestUpdate = r.updates[0] ?? null;- return {- id: r.id,- title: r.title,- status: r.status,- pageId: r.pageId,- createdAt: r.createdAt?.toISOString() ?? null,- updatedAt: r.updatedAt?.toISOString() ?? null,- latestUpdate: latestUpdate- ? {- message: latestUpdate.message,- status: latestUpdate.status,- date: latestUpdate.date?.toISOString() ?? null,- }- : null,- };- });- const out = {- items: summarised,- pagination: {- page: currentPage,- perPage: size,- totalSize,- totalPages: Math.max(1, Math.ceil(totalSize / size)),- },- };- return {- content: [- {- type: "text",- text: JSON.stringify(out),- },- ],- structuredContent: out,- };- },- ),- );- if (t_listStatusReports)- registered.set("list_status_reports", t_listStatusReports);-- const t_createStatusReport = registerScopedTool(- server,- ctx,- "create_status_report",- {- scope: "write",- description:- "Create a new status report on a public status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the title, status, message, and affected components.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers (email + integrations) for this report? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively for an existing update. There is NO separate notify tool. If notify is false here, that update will never reach subscribers. Note: the report persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.\n\npageId MUST come from list_status_pages — never guess. pageComponentIds (if supplied) MUST belong to the same page.",- annotations: {- readOnlyHint: false,- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- title: z- .string()- .min(1)- .max(256)- .describe("Short, public-facing title for the incident."),- status: statusReportStatusSchema.describe(- "Initial status for the report.",- ),- message: z- .string()- .min(1)- .describe(- "Initial public update message customers will see on the status page.",- ),- pageId: z- .number()- .int()- .describe(- "Status page to attach the report to. Resolve via list_status_pages — do not guess.",- ),- pageComponentIds: z- .array(z.number().int())- .default([])- .describe(- "Optional component ids affected by the incident. Must belong to pageId.",- ),- date: z.iso- .datetime()- .optional()- .describe(- "Override the initial update's date. Defaults to now if omitted.",- ),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications (email + integrations) for the initial update. You MUST ask the user before deciding — do not infer. true = notify on creation. false = create silently; subscribers will NEVER be notified about this update (you cannot notify retroactively). No-op if the workspace plan has subscriptions disabled.",- ),- },- outputSchema: {- statusReport: z.object({- id: z.number().int(),- title: z.string(),- status: statusReportStatusSchema,- pageId: z.number().int().nullable(),- createdAt: z.string().nullable(),- }),- initialUpdateId: z.number().int(),- notified: z.boolean(),- },- },- async (input) =>- runTool(- async () => {- const result = await createStatusReport({- ctx,- input: {- title: input.title,- status: input.status,- message: input.message,- pageId: input.pageId,- pageComponentIds: input.pageComponentIds ?? [],- date: input.date ? new Date(input.date) : new Date(),- },- });- // Mutation succeeded; the row exists. A notify failure- // here must NOT propagate as a tool error — that would- // leave the LLM thinking the whole call failed and- // possibly retrying create, double-publishing the- // report. Report partial success via `notified: false`.- let notified = false;- if (input.notify) {- try {- await notifyStatusReport({- ctx,- input: { statusReportUpdateId: result.initialUpdate.id },- });- notified = true;- } catch (err) {- logger.error(- "notifyStatusReport failed after create_status_report {*}",- {- err,- workspaceId: ctx.workspace.id,- statusReportId: result.statusReport.id,- statusReportUpdateId: result.initialUpdate.id,- },- );- }- }- return { ...result, notified };- },- ({ statusReport, initialUpdate, notified }) => {- const out = {- statusReport: {- id: statusReport.id,- title: statusReport.title,- status: statusReport.status,- pageId: statusReport.pageId,- createdAt: statusReport.createdAt?.toISOString() ?? null,- },- initialUpdateId: initialUpdate.id,- notified,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- );- if (t_createStatusReport)- registered.set("create_status_report", t_createStatusReport);-- const t_addStatusReportUpdate = registerScopedTool(- server,- ctx,- "add_status_report_update",- {- scope: "write",- description:- "Append a new public update to an existing status report. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects. Sets the report's status to the new value (use resolve_status_report instead if the new status would be 'resolved').\n\nMANDATORY workflow before calling:\n1. Draft the new status and message.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers about this update? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively. There is NO separate notify tool. If notify is false here, this update will never reach subscribers. Note: the update persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.",- annotations: {- readOnlyHint: false,- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- statusReportId: z- .number()- .int()- .describe(- "Status report to update. Resolve via list_status_reports — do not guess.",- ),- status: statusReportStatusSchema.describe(- "New status to set on the report. The update entry inherits this status.",- ),- message: z- .string()- .min(1)- .describe("Public update message customers will see."),- date: z.iso- .datetime()- .optional()- .describe("Override the update's date. Defaults to now."),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications for this update. You MUST ask the user before deciding — do not infer. true = notify now. false = append silently; subscribers will NEVER be notified about this update (you cannot notify retroactively).",- ),- },- outputSchema: {- statusReportUpdateId: z.number().int(),- notified: z.boolean(),- },- },- async (input) =>- runTool(- async () => {- const result = await addStatusReportUpdate({- ctx,- input: {- statusReportId: input.statusReportId,- status: input.status,- message: input.message,- date: input.date ? new Date(input.date) : undefined,- },- });- // See `create_status_report` for the rationale: the- // update is already persisted, so a notify dispatch- // failure must not propagate as a tool error.- let notified = false;- if (input.notify) {- try {- await notifyStatusReport({- ctx,- input: {- statusReportUpdateId: result.statusReportUpdate.id,- },- });- notified = true;- } catch (err) {- logger.error(- "notifyStatusReport failed after add_status_report_update {*}",- {- err,- workspaceId: ctx.workspace.id,- statusReportId: result.statusReport.id,- statusReportUpdateId: result.statusReportUpdate.id,- },- );- }- }- return { ...result, notified };- },- ({ statusReportUpdate, notified }) => {- const out = {- statusReportUpdateId: statusReportUpdate.id,- notified,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- );- if (t_addStatusReportUpdate)- registered.set("add_status_report_update", t_addStatusReportUpdate);-- const t_updateStatusReport = registerScopedTool(- server,- ctx,- "update_status_report",- {- scope: "write",- description:- "Edit metadata on an existing status report (title, status, affected components). Does NOT add a public update — use add_status_report_update for that. Does NOT and CANNOT notify subscribers — there is no notify path on this tool because metadata edits do not create a new update entry to dispatch. If subscribers need to hear about a change, use add_status_report_update instead with notify: true. Audit-logged.\n\nMANDATORY workflow: draft the change, show it to the user, confirm before calling.",- annotations: {- readOnlyHint: false,- destructiveHint: true,- idempotentHint: true,- openWorldHint: false,- },- inputSchema: {- statusReportId: z- .number()- .int()- .describe("Report to edit. Resolve via list_status_reports."),- title: z.string().min(1).max(256).optional().describe("New title."),- // Guard against `status: "resolved"` — that would flip the- // report's status without publishing a resolution update,- // leaving the public page in a divergent state (status- // reads "resolved" but no resolution message). Force the- // LLM to use resolve_status_report (which appends the- // final update) instead. The tool description already- // says this; the refine is the runtime backstop.- status: statusReportStatusSchema- .refine((s) => s !== "resolved", {- error:- "update_status_report cannot set status to 'resolved' — use resolve_status_report instead, which also publishes a final resolution update.",- })- .optional()- .describe(- "New status (without appending a public update entry). Cannot be 'resolved' — use resolve_status_report for that.",- ),- pageComponentIds: z- .array(z.number().int())- .optional()- .describe(- "Replace the full set of associated component ids. Empty array clears the association.",- ),- },- outputSchema: {- id: z.number().int(),- title: z.string(),- status: statusReportStatusSchema,- },- },- async (input) =>- runTool(- () =>- updateStatusReport({- ctx,- input: {- id: input.statusReportId,- title: input.title,- status: input.status,- pageComponentIds: input.pageComponentIds,- },- }),- (report) => {- const out = {- id: report.id,- title: report.title,- status: report.status,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- );- if (t_updateStatusReport)- registered.set("update_status_report", t_updateStatusReport);-- const t_resolveStatusReport = registerScopedTool(- server,- ctx,- "resolve_status_report",- {- scope: "write",- description:- "Resolve an active status report. Appends a final public update with the supplied message and flips status to 'resolved'. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the resolution message.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers that this incident is resolved? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the message AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively. There is NO separate notify tool. If notify is false here, the resolution will never reach subscribers. Note: the report flips to resolved even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.",- annotations: {- readOnlyHint: false,- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- statusReportId: z- .number()- .int()- .describe("Report to resolve. Resolve via list_status_reports."),- message: z- .string()- .min(1)- .describe(- "Resolution message customers will see explaining what was fixed.",- ),- date: z.iso- .datetime()- .optional()- .describe("Override the resolution date. Defaults to now."),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications for the resolution update. You MUST ask the user before deciding — do not infer. true = notify now. false = resolve silently; subscribers will NEVER hear about this resolution (you cannot notify retroactively).",- ),- },- outputSchema: {- statusReportUpdateId: z.number().int(),- notified: z.boolean(),- },- },- async (input) =>- runTool(- async () => {- const result = await resolveStatusReport({- ctx,- input: {- statusReportId: input.statusReportId,- message: input.message,- date: input.date ? new Date(input.date) : undefined,- },- });- // See `create_status_report` for the rationale: the- // resolution update is already persisted, so a notify- // dispatch failure must not propagate as a tool error.- let notified = false;- if (input.notify) {- try {- await notifyStatusReport({- ctx,- input: {- statusReportUpdateId: result.statusReportUpdate.id,- },- });- notified = true;- } catch (err) {- logger.error(- "notifyStatusReport failed after resolve_status_report {*}",- {- err,- workspaceId: ctx.workspace.id,- statusReportId: result.statusReport.id,- statusReportUpdateId: result.statusReportUpdate.id,- },- );- }- }- return { ...result, notified };- },- ({ statusReportUpdate, notified }) => {- const out = {- statusReportUpdateId: statusReportUpdate.id,- notified,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- );- if (t_resolveStatusReport)- registered.set("resolve_status_report", t_resolveStatusReport);-- return registered;+ return registerRegistryTools(server, ctx, [+ listStatusReportsTool,+ createStatusReportTool,+ addStatusReportUpdateTool,+ updateStatusReportTool,+ resolveStatusReportTool,+ ]);}diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/apps/web/next-env.d.ts+++ b/apps/web/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/apps/web/src/content/pages/home.mdx b/apps/web/src/content/pages/home.mdxindex d94e2f210..f1d36f3ea 100644--- a/apps/web/src/content/pages/home.mdx+++ b/apps/web/src/content/pages/home.mdx@@ -21,6 +21,12 @@ faq:answer: "Yes. All paid plans are available with monthly or annual billing. Choose annual billing to get 2 months free — that's Starter at $300/year ($25/mo) and Pro at $1,000/year (~$83/mo). You can switch between billing cycles at any time."- question: "Can I self-host openstatus?"answer: "Yes. Openstatus is fully open source and can be self-hosted using its 8.5MB Docker image. You can also deploy private monitoring locations behind your firewall for internal services. The source code is available on GitHub."+ - question: "Does openstatus have an API?"+ answer: "Yes. Openstatus exposes a typed JSON-over-HTTP API powered by ConnectRPC, with a published OpenAPI spec at api.openstatus.dev/openapi. Every action in the dashboard — managing monitors, status pages, status reports, maintenance windows, and notification channels — is reachable from the API. The same API key works across the API, CLI, Node SDK, Terraform provider, and MCP server, and every mutation lands in the audit log."+ - question: "Can I manage openstatus from Claude or ChatGPT?"+ answer: "Yes. Openstatus ships a remote MCP (Model Context Protocol) server at api.openstatus.dev/mcp that connects Claude Desktop, ChatGPT, Cursor, and any MCP-compatible client to your workspace. The assistant can list status pages, create and resolve status reports, and schedule maintenance windows. Every mutation tool requires the assistant to explicitly choose whether to notify subscribers, and every call is recorded in the audit log."+ - question: "Can I manage monitors as code?"+ answer: "Yes. Openstatus offers two ways to treat monitoring as code: a CLI with YAML config that lives in your repo (`openstatus monitors apply`), and a Terraform provider for HCL-managed infrastructure. Run `openstatus terraform generate` from the CLI to bootstrap an HCL file from an existing workspace."---<div className="space-x-2">@@ -79,6 +85,17 @@ Monitor your endpoints from 28 regions across multiple clouds. Get alerted on SlRead more about [uptime monitoring](/uptime-monitoring).+## Managing openstatus — for humans and agents++Every action in the dashboard is reachable programmatically. One API key, four ways in:++- **[CLI](/tooling/cli)** — manage from your terminal+- **[API](/tooling/api)** — typed HTTP endpoints with an [OpenAPI spec](https://api.openstatus.dev/openapi)+- **[MCP server](/tooling/mcp-server)** — let Claude, ChatGPT, or Cursor run your monitoring+- **[Terraform provider](/tooling/terraform)** — version monitors as HCL++Read more about our [tooling](/tooling).+---Check your website's latency@@ -215,3 +232,30 @@ Yes. Openstatus is fully open source and can be self-hosted using its **8.5MB DoThe source code is available on [GitHub](https://openstatus.dev/github).</Details>++<Details summary="Does openstatus have an API?">++Yes. Openstatus exposes a typed **JSON-over-HTTP API** powered by [ConnectRPC](/blog/migrating-from-zod-openapi-to-connectrpc), with a published [OpenAPI spec](https://api.openstatus.dev/openapi).++Every action in the dashboard — managing monitors, status pages, status reports, maintenance windows, and notification channels — is reachable from the API. The same API key works across the [API](/tooling/api), [CLI](/tooling/cli), Node SDK, [Terraform provider](/tooling/terraform), and [MCP server](/tooling/mcp-server), and every mutation lands in the audit log.++</Details>++<Details summary="Can I manage openstatus from Claude or ChatGPT?">++Yes. Openstatus ships a remote [MCP server](/tooling/mcp-server) at `api.openstatus.dev/mcp` that connects **Claude Desktop**, **ChatGPT**, **Cursor**, and any [Model Context Protocol](https://modelcontextprotocol.io) client to your workspace.++The assistant can list status pages, create and resolve status reports, and schedule maintenance windows. Every mutation tool requires the assistant to explicitly choose whether to notify subscribers — models can't quietly fan out an alert — and every call is recorded in the audit log under `actor_type = 'mcp'`.++</Details>++<Details summary="Can I manage monitors as code?">++Yes. Openstatus offers two ways to treat monitoring as code:++- **YAML + [CLI](/tooling/cli)** — keep your monitor configuration in your repo and sync with `openstatus monitors apply`. Lighter to adopt, ships with a GitHub Action for CI/CD.+- **[Terraform provider](/tooling/terraform)** — for teams already managing infrastructure in HCL. Same plan-and-apply lifecycle as the rest of your stack.++Already have monitors in the dashboard? Run `openstatus terraform generate` from the CLI to bootstrap an HCL file with cross-references and import blocks — no hand-writing required.++</Details>diff --git a/packages/api/src/auth/index.ts b/packages/api/src/auth/index.tsnew file mode 100644index 000000000..b6067bfff--- /dev/null+++ b/packages/api/src/auth/index.ts@@ -0,0 +1,6 @@+export {+ type ActiveWorkspace,+ type ResolveActiveWorkspaceFailure,+ type ResolveActiveWorkspaceResult,+ resolveActiveWorkspace,+} from "./resolve-active-workspace";diff --git a/packages/api/src/auth/resolve-active-workspace.ts b/packages/api/src/auth/resolve-active-workspace.tsnew file mode 100644index 000000000..400ac9f01--- /dev/null+++ b/packages/api/src/auth/resolve-active-workspace.ts@@ -0,0 +1,58 @@+import { db, eq, schema } from "@openstatus/db";+import type { User, Workspace } from "@openstatus/db/src/schema";++/**+ * Result of resolving the active workspace for an authenticated user.+ * Both fields are guaranteed non-null on success.+ */+export type ActiveWorkspace = {+ user: User;+ workspace: Workspace;+};++export type ResolveActiveWorkspaceFailure =+ | { kind: "user_not_found" }+ | { kind: "workspace_not_found" };++export type ResolveActiveWorkspaceResult =+ | { ok: true; value: ActiveWorkspace }+ | { ok: false; error: ResolveActiveWorkspaceFailure };++/**+ * Canonical workspace-from-cookie resolver — looks up the+ * `workspace-slug` cookie and falls back to the user's first workspace+ * when the cookie is missing or stale (cookie manipulation, deleted slug).+ */+export async function resolveActiveWorkspace(args: {+ userId: number;+ workspaceSlug?: string;+}): Promise<ResolveActiveWorkspaceResult> {+ const userAndWorkspace = await db.query.user.findFirst({+ where: eq(schema.user.id, args.userId),+ with: {+ usersToWorkspaces: {+ with: { workspace: true },+ },+ },+ });++ if (!userAndWorkspace) {+ return { ok: false, error: { kind: "user_not_found" } };+ }++ const { usersToWorkspaces, ...userProps } = userAndWorkspace;++ const activeWorkspace =+ usersToWorkspaces?.find(({ workspace }) => {+ if (args.workspaceSlug) return workspace.slug === args.workspaceSlug;+ return true;+ })?.workspace ?? usersToWorkspaces?.[0]?.workspace;++ if (!activeWorkspace) {+ return { ok: false, error: { kind: "workspace_not_found" } };+ }++ const user = schema.selectUserSchema.parse(userProps);+ const workspace = schema.selectWorkspaceSchema.parse(activeWorkspace);+ return { ok: true, value: { user, workspace } };+}diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.tsindex 5acebe3d9..a78c2ea2e 100644--- a/packages/api/src/edge.ts+++ b/packages/api/src/edge.ts@@ -1,4 +1,5 @@import { auditLogRouter } from "./router/auditLog";+import { chatSessionRouter } from "./router/chatSession";import { checkerRouter } from "./router/checker";import { domainRouter } from "./router/domain";import { feedbackRouter } from "./router/feedback";@@ -44,4 +45,5 @@ export const edgeRouter = createTRPCRouter({privateLocation: privateLocationRouter,import: importRouter,auditLog: auditLogRouter,+ chatSession: chatSessionRouter,});diff --git a/packages/api/src/router/chatSession.ts b/packages/api/src/router/chatSession.tsnew file mode 100644index 000000000..04bd879bd--- /dev/null+++ b/packages/api/src/router/chatSession.ts@@ -0,0 +1,40 @@+import {+ DeleteChatSessionInput,+ GetChatSessionInput,+ deleteChatSession,+ getChatSession,+ listChatSessions,+} from "@openstatus/services/chat-session";++import { toServiceCtx, toTRPCError } from "../service-adapter";+import { createTRPCRouter, protectedProcedure } from "../trpc";++export const chatSessionRouter = createTRPCRouter({+ list: protectedProcedure.query(async ({ ctx }) => {+ try {+ return await listChatSessions({ ctx: toServiceCtx(ctx) });+ } catch (err) {+ toTRPCError(err);+ }+ }),++ get: protectedProcedure+ .input(GetChatSessionInput)+ .query(async ({ ctx, input }) => {+ try {+ return await getChatSession({ ctx: toServiceCtx(ctx), input });+ } catch (err) {+ toTRPCError(err);+ }+ }),++ delete: protectedProcedure+ .input(DeleteChatSessionInput)+ .mutation(async ({ ctx, input }) => {+ try {+ await deleteChatSession({ ctx: toServiceCtx(ctx), input });+ } catch (err) {+ toTRPCError(err);+ }+ }),+});diff --git a/packages/api/src/router/statusReport.ts b/packages/api/src/router/statusReport.tsindex 6c5c690df..b1d0aecac 100644--- a/packages/api/src/router/statusReport.ts+++ b/packages/api/src/router/statusReport.ts@@ -210,7 +210,11 @@ export const statusReportRouter = createTRPCRouter({statuses: [],},});- return items.map(narrowPage);+ // Legacy data (pre-pageId-required) can have `pageId = null`, so the+ // list endpoint silently filters those rows rather than 500-ing the+ // whole response. `get` still throws — a direct fetch of an orphan+ // is a real data-integrity signal.+ return items.filter(hasPage);} catch (err) {toTRPCError(err);}@@ -233,3 +237,9 @@ function narrowPage<T extends { id: number; page: unknown }>(}return report as T & { page: NonNullable<T["page"]> };}++function hasPage<T extends { page: unknown }>(+ report: T,+): report is T & { page: NonNullable<T["page"]> } {+ return report.page != null;+}diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.tsindex 44f07a733..d93c5d2b4 100644--- a/packages/api/src/trpc.ts+++ b/packages/api/src/trpc.ts@@ -9,9 +9,11 @@ import {parseInputToProps,setupAnalytics,} from "@openstatus/analytics";-import { db, eq, schema } from "@openstatus/db";+import { db } from "@openstatus/db";import type { User, Workspace } from "@openstatus/db/src/schema";+import { resolveActiveWorkspace } from "./auth/resolve-active-workspace";+// Generic session type that works with both User and Viewertype Session = {user?: {@@ -166,67 +168,35 @@ const enforceUserIsAuthed = t.middleware(async (opts) => {});}- // /**- // * Attach `user` and `workspace` | `activeWorkspace` infos to context by- // * comparing the `user.tenantId` to clerk's `auth.userId`- // */- const userAndWorkspace = await db.query.user.findFirst({- where: eq(schema.user.id, Number(ctx.session.user.id)),- with: {- usersToWorkspaces: {- with: {- workspace: true,- },- },- },- });-- const { usersToWorkspaces, ...userProps } = userAndWorkspace || {};-/**- * We need to include the active "workspace-slug" cookie in the request found in the- * `/app/[workspaceSlug]/.../`routes. We pass them either via middleware if it's a- * server request or via the client cookie, set via `<WorspaceClientCookie />`- * if it's a client request.- *- * REMINDER: We only need the client cookie because of client side mutations.+ * The active "workspace-slug" cookie is set in the dashboard middleware+ * for server requests and in `<WorkspaceClientCookie />` for client+ * requests; we read the same cookie either way.*/const workspaceSlug = ctx.req?.cookies.get("workspace-slug")?.value;- // if (!workspaceSlug) {- // throw new TRPCError({- // code: "UNAUTHORIZED",- // message: "Workspace Slug Not Found",- // });- // }-- // NOTE: if no workspace slug fit (cookie manipulation), use the first workspace- const activeWorkspace =- usersToWorkspaces?.find(({ workspace }) => {- // If there is a workspace slug in the cookie, use it to find the workspace- if (workspaceSlug) return workspace.slug === workspaceSlug;- return true;- })?.workspace ?? usersToWorkspaces?.[0]?.workspace;-- if (!activeWorkspace) {+ const resolved = await resolveActiveWorkspace({+ userId: Number(ctx.session.user.id),+ workspaceSlug,+ });++ if (!resolved.ok) {throw new TRPCError({code: "UNAUTHORIZED",- message: "Workspace Not Found",+ message:+ resolved.error.kind === "user_not_found"+ ? "User Not Found"+ : "Workspace Not Found",});}- if (activeWorkspace.slug !== workspaceSlug) {- // properly set the workspace slug cookie- ctx.req?.cookies.set("workspace-slug", activeWorkspace.slug);- }+ const { user, workspace } = resolved.value;- if (!userProps) {- throw new TRPCError({ code: "UNAUTHORIZED", message: "User Not Found" });+ if (workspace.slug !== workspaceSlug) {+ // properly set the workspace slug cookie+ ctx.req?.cookies.set("workspace-slug", workspace.slug);}- const user = schema.selectUserSchema.parse(userProps);- const workspace = schema.selectWorkspaceSchema.parse(activeWorkspace);-const result = await opts.next({ ctx: { ...ctx, user, workspace } });if (process.env.NODE_ENV === "test") {diff --git a/packages/db/drizzle/0068_smooth_spacker_dave.sql b/packages/db/drizzle/0068_smooth_spacker_dave.sqlnew file mode 100644index 000000000..113058dd2--- /dev/null+++ b/packages/db/drizzle/0068_smooth_spacker_dave.sql@@ -0,0 +1,13 @@+CREATE TABLE `chat_session` (+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,+ `workspace_id` integer NOT NULL,+ `user_id` integer NOT NULL,+ `title` text NOT NULL,+ `messages` text NOT NULL,+ `created_at` integer NOT NULL,+ `updated_at` integer NOT NULL,+ FOREIGN KEY (`workspace_id`) REFERENCES `workspace`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX `chat_session_workspace_user_updated_idx` ON `chat_session` (`workspace_id`,`user_id`,`updated_at`);\ No newline at end of filediff --git a/packages/db/drizzle/meta/0068_snapshot.json b/packages/db/drizzle/meta/0068_snapshot.jsonnew file mode 100644index 000000000..986b922ac--- /dev/null+++ b/packages/db/drizzle/meta/0068_snapshot.json@@ -0,0 +1,4009 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "ea8f3dea-b840-4c50-bf13-fdf040455196",+ "prevId": "0fb8640e-5483-4343-bef6-2982c5cbe88b",+ "tables": {+ "workspace": {+ "name": "workspace",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripe_id": {+ "name": "stripe_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_until": {+ "name": "paid_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "limits": {+ "name": "limits",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "workspace_stripe_id_unique": {+ "name": "workspace_stripe_id_unique",+ "columns": [+ "stripe_id"+ ],+ "isUnique": true+ },+ "workspace_id_dsn_unique": {+ "name": "workspace_id_dsn_unique",+ "columns": [+ "id",+ "dsn"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "account": {+ "name": "account",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_account_id": {+ "name": "provider_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "account_provider_provider_account_id_pk": {+ "columns": [+ "provider",+ "provider_account_id"+ ],+ "name": "account_provider_provider_account_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "last_name": {+ "name": "last_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "photo_url": {+ "name": "photo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_tenant_id_unique": {+ "name": "user_tenant_id_unique",+ "columns": [+ "tenant_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users_to_workspaces": {+ "name": "users_to_workspaces",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "users_to_workspaces_workspace_id_idx": {+ "name": "users_to_workspaces_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "users_to_workspaces_user_id_user_id_fk": {+ "name": "users_to_workspaces_user_id_user_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "users_to_workspaces_workspace_id_workspace_id_fk": {+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "users_to_workspaces_user_id_workspace_id_pk": {+ "columns": [+ "user_id",+ "workspace_id"+ ],+ "name": "users_to_workspaces_user_id_workspace_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification_token": {+ "name": "verification_token",+ "columns": {+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "verification_token_identifier_token_pk": {+ "columns": [+ "identifier",+ "token"+ ],+ "name": "verification_token_identifier_token_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report": {+ "name": "status_report",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "status_report_workspace_created_idx": {+ "name": "status_report_workspace_created_idx",+ "columns": [+ "workspace_id",+ "created_at"+ ],+ "isUnique": false+ },+ "status_report_page_id_idx": {+ "name": "status_report_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "status_report_workspace_id_workspace_id_fk": {+ "name": "status_report_workspace_id_workspace_id_fk",+ "tableFrom": "status_report",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "status_report_page_id_page_id_fk": {+ "name": "status_report_page_id_page_id_fk",+ "tableFrom": "status_report",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report_update": {+ "name": "status_report_update",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_report_id": {+ "name": "status_report_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "status_report_update_status_report_id_idx": {+ "name": "status_report_update_status_report_id_idx",+ "columns": [+ "status_report_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "status_report_update_status_report_id_status_report_id_fk": {+ "name": "status_report_update_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_update",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "integration": {+ "name": "integration",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "credential": {+ "name": "credential",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "integration_workspace_id_idx": {+ "name": "integration_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "integration_workspace_id_workspace_id_fk": {+ "name": "integration_workspace_id_workspace_id_fk",+ "tableFrom": "integration",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page": {+ "name": "page",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "icon": {+ "name": "icon",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "slug": {+ "name": "slug",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "custom_domain": {+ "name": "custom_domain",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "published": {+ "name": "published",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "force_theme": {+ "name": "force_theme",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'system'"+ },+ "password": {+ "name": "password",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password_protected": {+ "name": "password_protected",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "access_type": {+ "name": "access_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'public'"+ },+ "auth_email_domains": {+ "name": "auth_email_domains",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "allowed_ip_ranges": {+ "name": "allowed_ip_ranges",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "homepage_url": {+ "name": "homepage_url",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "contact_url": {+ "name": "contact_url",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "default_locale": {+ "name": "default_locale",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "locales": {+ "name": "locales",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "legacy_page": {+ "name": "legacy_page",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "configuration": {+ "name": "configuration",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "allow_index": {+ "name": "allow_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "show_monitor_values": {+ "name": "show_monitor_values",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_slug_unique": {+ "name": "page_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "page_lower_slug_idx": {+ "name": "page_lower_slug_idx",+ "columns": [+ "LOWER(\"slug\")"+ ],+ "isUnique": false+ },+ "page_lower_custom_domain_idx": {+ "name": "page_lower_custom_domain_idx",+ "columns": [+ "LOWER(\"custom_domain\")"+ ],+ "isUnique": false+ },+ "page_workspace_id_idx": {+ "name": "page_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "page_workspace_id_workspace_id_fk": {+ "name": "page_workspace_id_workspace_id_fk",+ "tableFrom": "page",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor": {+ "name": "monitor",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'http'"+ },+ "periodicity": {+ "name": "periodicity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "active": {+ "name": "active",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(2048)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "external_name": {+ "name": "external_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "timeout": {+ "name": "timeout",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 45000+ },+ "degraded_after": {+ "name": "degraded_after",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "assertions": {+ "name": "assertions",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_endpoint": {+ "name": "otel_endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_headers": {+ "name": "otel_headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "public": {+ "name": "public",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "retry": {+ "name": "retry",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 3+ },+ "follow_redirects": {+ "name": "follow_redirects",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "monitor_workspace_id_active_idx": {+ "name": "monitor_workspace_id_active_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false,+ "where": "\"monitor\".\"deleted_at\" IS NULL"+ }+ },+ "foreignKeys": {+ "monitor_workspace_id_workspace_id_fk": {+ "name": "monitor_workspace_id_workspace_id_fk",+ "tableFrom": "monitor",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_subscriber": {+ "name": "page_subscriber",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "channel_type": {+ "name": "channel_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'email'"+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "channel_config": {+ "name": "channel_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'self_signup'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "unsubscribed_at": {+ "name": "unsubscribed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "idx_page_subscriber_email_page_active": {+ "name": "idx_page_subscriber_email_page_active",+ "columns": [+ "LOWER(\"email\")",+ "page_id"+ ],+ "isUnique": true,+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'email'"+ },+ "idx_page_subscriber_webhook_page_active": {+ "name": "idx_page_subscriber_webhook_page_active",+ "columns": [+ "LOWER(\"webhook_url\")",+ "page_id"+ ],+ "isUnique": true,+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'webhook'"+ }+ },+ "foreignKeys": {+ "page_subscriber_page_id_page_id_fk": {+ "name": "page_subscriber_page_id_page_id_fk",+ "tableFrom": "page_subscriber",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {+ "page_subscriber_channel_check": {+ "name": "page_subscriber_channel_check",+ "value": "(\"page_subscriber\".\"channel_type\" = 'email' AND \"page_subscriber\".\"email\" IS NOT NULL AND \"page_subscriber\".\"webhook_url\" IS NULL) OR (\"page_subscriber\".\"channel_type\" = 'webhook' AND \"page_subscriber\".\"webhook_url\" IS NOT NULL AND \"page_subscriber\".\"email\" IS NULL)"+ }+ }+ },+ "page_subscriber_to_page_component": {+ "name": "page_subscriber_to_page_component",+ "columns": {+ "page_subscriber_id": {+ "name": "page_subscriber_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk": {+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk",+ "tableFrom": "page_subscriber_to_page_component",+ "tableTo": "page_subscriber",+ "columnsFrom": [+ "page_subscriber_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_subscriber_to_page_component_page_component_id_page_component_id_fk": {+ "name": "page_subscriber_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "page_subscriber_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk": {+ "columns": [+ "page_subscriber_id",+ "page_component_id"+ ],+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification": {+ "name": "notification",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'{}'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "notification_workspace_id_idx": {+ "name": "notification_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "notification_workspace_id_workspace_id_fk": {+ "name": "notification_workspace_id_workspace_id_fk",+ "tableFrom": "notification",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification_trigger": {+ "name": "notification_trigger",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "notification_id_monitor_id_crontimestampe": {+ "name": "notification_id_monitor_id_crontimestampe",+ "columns": [+ "notification_id",+ "monitor_id",+ "cron_timestamp"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "notification_trigger_monitor_id_monitor_id_fk": {+ "name": "notification_trigger_monitor_id_monitor_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_trigger_notification_id_notification_id_fk": {+ "name": "notification_trigger_notification_id_notification_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notifications_to_monitors": {+ "name": "notifications_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "notifications_to_monitors_notification_id_idx": {+ "name": "notifications_to_monitors_notification_id_idx",+ "columns": [+ "notification_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "notifications_to_monitors_monitor_id_monitor_id_fk": {+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notifications_to_monitors_notification_id_notification_id_fk": {+ "name": "notifications_to_monitors_notification_id_notification_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "notifications_to_monitors_monitor_id_notification_id_pk": {+ "columns": [+ "monitor_id",+ "notification_id"+ ],+ "name": "notifications_to_monitors_monitor_id_notification_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_status": {+ "name": "monitor_status",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_status_idx": {+ "name": "monitor_status_idx",+ "columns": [+ "monitor_id",+ "region"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_status_monitor_id_monitor_id_fk": {+ "name": "monitor_status_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_status",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_status_monitor_id_region_pk": {+ "columns": [+ "monitor_id",+ "region"+ ],+ "name": "monitor_status_monitor_id_region_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "invitation": {+ "name": "invitation",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "invitation_workspace_id_idx": {+ "name": "invitation_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "incident": {+ "name": "incident",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'triage'"+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "acknowledged_by": {+ "name": "acknowledged_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_by": {+ "name": "resolved_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "incident_screenshot_url": {+ "name": "incident_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recovery_screenshot_url": {+ "name": "recovery_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_resolved": {+ "name": "auto_resolved",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "incident_workspace_id_idx": {+ "name": "incident_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "incident_monitor_id_started_at_unique": {+ "name": "incident_monitor_id_started_at_unique",+ "columns": [+ "monitor_id",+ "started_at"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "incident_monitor_id_monitor_id_fk": {+ "name": "incident_monitor_id_monitor_id_fk",+ "tableFrom": "incident",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set default",+ "onUpdate": "no action"+ },+ "incident_workspace_id_workspace_id_fk": {+ "name": "incident_workspace_id_workspace_id_fk",+ "tableFrom": "incident",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_acknowledged_by_user_id_fk": {+ "name": "incident_acknowledged_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "acknowledged_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_resolved_by_user_id_fk": {+ "name": "incident_resolved_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "resolved_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag": {+ "name": "monitor_tag",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_tag_workspace_id_idx": {+ "name": "monitor_tag_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_tag_workspace_id_workspace_id_fk": {+ "name": "monitor_tag_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_tag",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag_to_monitor": {+ "name": "monitor_tag_to_monitor",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_tag_id": {+ "name": "monitor_tag_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_tag_to_monitor_monitor_tag_id_idx": {+ "name": "monitor_tag_to_monitor_monitor_tag_id_idx",+ "columns": [+ "monitor_tag_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor_tag",+ "columnsFrom": [+ "monitor_tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk": {+ "columns": [+ "monitor_id",+ "monitor_tag_id"+ ],+ "name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "application": {+ "name": "application",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "application_dsn_unique": {+ "name": "application_dsn_unique",+ "columns": [+ "dsn"+ ],+ "isUnique": true+ },+ "application_workspace_id_idx": {+ "name": "application_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "application_workspace_id_workspace_id_fk": {+ "name": "application_workspace_id_workspace_id_fk",+ "tableFrom": "application",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance": {+ "name": "maintenance",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "from": {+ "name": "from",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to": {+ "name": "to",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "maintenance_page_id_idx": {+ "name": "maintenance_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ },+ "maintenance_workspace_id_idx": {+ "name": "maintenance_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "maintenance_workspace_id_workspace_id_fk": {+ "name": "maintenance_workspace_id_workspace_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "maintenance_page_id_page_id_fk": {+ "name": "maintenance_page_id_page_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "check": {+ "name": "check",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(4096)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "count_requests": {+ "name": "count_requests",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "check_workspace_id_idx": {+ "name": "check_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "check_workspace_id_workspace_id_fk": {+ "name": "check_workspace_id_workspace_id_fk",+ "tableFrom": "check",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_run": {+ "name": "monitor_run",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "runned_at": {+ "name": "runned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_run_workspace_id_idx": {+ "name": "monitor_run_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "monitor_run_monitor_id_idx": {+ "name": "monitor_run_monitor_id_idx",+ "columns": [+ "monitor_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_run_workspace_id_workspace_id_fk": {+ "name": "monitor_run_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "monitor_run_monitor_id_monitor_id_fk": {+ "name": "monitor_run_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location": {+ "name": "private_location",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "private_location_workspace_id_idx": {+ "name": "private_location_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "private_location_workspace_id_workspace_id_fk": {+ "name": "private_location_workspace_id_workspace_id_fk",+ "tableFrom": "private_location",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location_to_monitor": {+ "name": "private_location_to_monitor",+ "columns": {+ "private_location_id": {+ "name": "private_location_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "private_location_to_monitor_private_location_id_idx": {+ "name": "private_location_to_monitor_private_location_id_idx",+ "columns": [+ "private_location_id"+ ],+ "isUnique": false+ },+ "private_location_to_monitor_monitor_id_idx": {+ "name": "private_location_to_monitor_monitor_id_idx",+ "columns": [+ "monitor_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "private_location_to_monitor_private_location_id_private_location_id_fk": {+ "name": "private_location_to_monitor_private_location_id_private_location_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "private_location",+ "columnsFrom": [+ "private_location_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "private_location_to_monitor_monitor_id_monitor_id_fk": {+ "name": "private_location_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_group": {+ "name": "monitor_group",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_group_workspace_id_idx": {+ "name": "monitor_group_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "monitor_group_page_id_idx": {+ "name": "monitor_group_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_group_workspace_id_workspace_id_fk": {+ "name": "monitor_group_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_group_page_id_page_id_fk": {+ "name": "monitor_group_page_id_page_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer": {+ "name": "viewer",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "viewer_email_unique": {+ "name": "viewer_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_accounts": {+ "name": "viewer_accounts",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "providerAccountId": {+ "name": "providerAccountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_accounts_user_id_viewer_id_fk": {+ "name": "viewer_accounts_user_id_viewer_id_fk",+ "tableFrom": "viewer_accounts",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "viewer_accounts_provider_providerAccountId_pk": {+ "columns": [+ "provider",+ "providerAccountId"+ ],+ "name": "viewer_accounts_provider_providerAccountId_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_session": {+ "name": "viewer_session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_session_user_id_viewer_id_fk": {+ "name": "viewer_session_user_id_viewer_id_fk",+ "tableFrom": "viewer_session",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "api_key": {+ "name": "api_key",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "hashed_token": {+ "name": "hashed_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_id": {+ "name": "created_by_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[\"write\"]'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "api_key_prefix_unique": {+ "name": "api_key_prefix_unique",+ "columns": [+ "prefix"+ ],+ "isUnique": true+ },+ "api_key_hashed_token_unique": {+ "name": "api_key_hashed_token_unique",+ "columns": [+ "hashed_token"+ ],+ "isUnique": true+ },+ "api_key_prefix_idx": {+ "name": "api_key_prefix_idx",+ "columns": [+ "prefix"+ ],+ "isUnique": false+ },+ "api_key_workspace_id_idx": {+ "name": "api_key_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "api_key_workspace_id_workspace_id_fk": {+ "name": "api_key_workspace_id_workspace_id_fk",+ "tableFrom": "api_key",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "api_key_created_by_id_user_id_fk": {+ "name": "api_key_created_by_id_user_id_fk",+ "tableFrom": "api_key",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance_to_page_component": {+ "name": "maintenance_to_page_component",+ "columns": {+ "maintenance_id": {+ "name": "maintenance_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "maintenance_to_page_component_page_component_id_idx": {+ "name": "maintenance_to_page_component_page_component_id_idx",+ "columns": [+ "page_component_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "maintenance_to_page_component_maintenance_id_maintenance_id_fk": {+ "name": "maintenance_to_page_component_maintenance_id_maintenance_id_fk",+ "tableFrom": "maintenance_to_page_component",+ "tableTo": "maintenance",+ "columnsFrom": [+ "maintenance_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "maintenance_to_page_component_page_component_id_page_component_id_fk": {+ "name": "maintenance_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "maintenance_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "maintenance_to_page_component_maintenance_id_page_component_id_pk": {+ "columns": [+ "maintenance_id",+ "page_component_id"+ ],+ "name": "maintenance_to_page_component_maintenance_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_component": {+ "name": "page_component",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'monitor'"+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "group_id": {+ "name": "group_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_order": {+ "name": "group_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_component_workspace_id_idx": {+ "name": "page_component_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "page_component_page_id_monitor_id_unique": {+ "name": "page_component_page_id_monitor_id_unique",+ "columns": [+ "page_id",+ "monitor_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "page_component_workspace_id_workspace_id_fk": {+ "name": "page_component_workspace_id_workspace_id_fk",+ "tableFrom": "page_component",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_page_id_page_id_fk": {+ "name": "page_component_page_id_page_id_fk",+ "tableFrom": "page_component",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_monitor_id_monitor_id_fk": {+ "name": "page_component_monitor_id_monitor_id_fk",+ "tableFrom": "page_component",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_group_id_page_component_groups_id_fk": {+ "name": "page_component_group_id_page_component_groups_id_fk",+ "tableFrom": "page_component",+ "tableTo": "page_component_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {+ "page_component_type_check": {+ "name": "page_component_type_check",+ "value": "\"page_component\".\"type\" = 'monitor' AND \"page_component\".\"monitor_id\" IS NOT NULL OR \"page_component\".\"type\" = 'static' AND \"page_component\".\"monitor_id\" IS NULL"+ }+ }+ },+ "status_report_to_page_component": {+ "name": "status_report_to_page_component",+ "columns": {+ "status_report_id": {+ "name": "status_report_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "status_report_to_page_component_page_component_id_idx": {+ "name": "status_report_to_page_component_page_component_id_idx",+ "columns": [+ "page_component_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "status_report_to_page_component_status_report_id_status_report_id_fk": {+ "name": "status_report_to_page_component_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_to_page_component",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "status_report_to_page_component_page_component_id_page_component_id_fk": {+ "name": "status_report_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "status_report_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "status_report_to_page_component_status_report_id_page_component_id_pk": {+ "columns": [+ "status_report_id",+ "page_component_id"+ ],+ "name": "status_report_to_page_component_status_report_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_component_groups": {+ "name": "page_component_groups",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "default_open": {+ "name": "default_open",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_component_groups_page_id_idx": {+ "name": "page_component_groups_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ },+ "page_component_groups_workspace_id_idx": {+ "name": "page_component_groups_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "page_component_groups_workspace_id_workspace_id_fk": {+ "name": "page_component_groups_workspace_id_workspace_id_fk",+ "tableFrom": "page_component_groups",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_groups_page_id_page_id_fk": {+ "name": "page_component_groups_page_id_page_id_fk",+ "tableFrom": "page_component_groups",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "feedback": {+ "name": "feedback",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "blocker": {+ "name": "blocker",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "feedback_workspace_id_idx": {+ "name": "feedback_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "feedback_workspace_id_workspace_id_fk": {+ "name": "feedback_workspace_id_workspace_id_fk",+ "tableFrom": "feedback",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "feedback_user_id_user_id_fk": {+ "name": "feedback_user_id_user_id_fk",+ "tableFrom": "feedback",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_log": {+ "name": "audit_log",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entity_type": {+ "name": "entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entity_id": {+ "name": "entity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "before": {+ "name": "before",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "after": {+ "name": "after",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "changed_fields": {+ "name": "changed_fields",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_log_workspace_created_idx": {+ "name": "audit_log_workspace_created_idx",+ "columns": [+ "workspace_id",+ "created_at"+ ],+ "isUnique": false+ },+ "audit_log_entity_idx": {+ "name": "audit_log_entity_idx",+ "columns": [+ "workspace_id",+ "entity_type",+ "entity_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "chat_session": {+ "name": "chat_session",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "messages": {+ "name": "messages",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "chat_session_workspace_user_updated_idx": {+ "name": "chat_session_workspace_user_updated_idx",+ "columns": [+ "workspace_id",+ "user_id",+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "chat_session_workspace_id_workspace_id_fk": {+ "name": "chat_session_workspace_id_workspace_id_fk",+ "tableFrom": "chat_session",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_session_user_id_user_id_fk": {+ "name": "chat_session_user_id_user_id_fk",+ "tableFrom": "chat_session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {+ "page_lower_slug_idx": {+ "columns": {+ "LOWER(\"slug\")": {+ "isExpression": true+ }+ }+ },+ "page_lower_custom_domain_idx": {+ "columns": {+ "LOWER(\"custom_domain\")": {+ "isExpression": true+ }+ }+ },+ "idx_page_subscriber_email_page_active": {+ "columns": {+ "LOWER(\"email\")": {+ "isExpression": true+ }+ }+ },+ "idx_page_subscriber_webhook_page_active": {+ "columns": {+ "LOWER(\"webhook_url\")": {+ "isExpression": true+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 1ea75018a..29f41fccb 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -477,6 +477,13 @@"when": 1778179053701,"tag": "0067_grey_hellfire_club","breakpoints": true+ },+ {+ "idx": 68,+ "version": "6",+ "when": 1778310822215,+ "tag": "0068_smooth_spacker_dave",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/chat_sessions/chat_session.ts b/packages/db/src/schema/chat_sessions/chat_session.tsnew file mode 100644index 000000000..9e2e2fdad--- /dev/null+++ b/packages/db/src/schema/chat_sessions/chat_session.ts@@ -0,0 +1,47 @@+import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";++import { user } from "../users";+import { workspace } from "../workspaces";+import type { ChatStoredMessage } from "./validation";++/**+ * Surrogate-PK row per dashboard chat conversation. Many rows per+ * (workspace, user). Bounded by application logic on insert+ * (`MAX_CHAT_SESSIONS_PER_USER`); per-row payload bounded by+ * `MAX_CHAT_MESSAGES` and a tool-result compaction policy in the service+ * layer.+ */+export const chatSession = sqliteTable(+ "chat_session",+ {+ id: integer("id").primaryKey({ autoIncrement: true }),+ workspaceId: integer("workspace_id")+ .notNull()+ .references(() => workspace.id, { onDelete: "cascade" }),+ userId: integer("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ title: text("title").notNull(),+ messages: text("messages", { mode: "json" })+ .$type<ChatStoredMessage[]>()+ .notNull(),+ createdAt: integer("created_at", { mode: "timestamp_ms" })+ .notNull()+ .$defaultFn(() => new Date()),+ updatedAt: integer("updated_at", { mode: "timestamp_ms" })+ .notNull()+ .$defaultFn(() => new Date()),+ },+ (t) => [+ // Sidebar / picker query: list a user's conversations newest first.+ // Also covers the cap-enforcement query ("oldest row for this pair").+ index("chat_session_workspace_user_updated_idx").on(+ t.workspaceId,+ t.userId,+ t.updatedAt,+ ),+ ],+);++export type ChatSessionRow = typeof chatSession.$inferSelect;+export type NewChatSessionRow = typeof chatSession.$inferInsert;diff --git a/packages/db/src/schema/chat_sessions/constants.ts b/packages/db/src/schema/chat_sessions/constants.tsnew file mode 100644index 000000000..216519eec--- /dev/null+++ b/packages/db/src/schema/chat_sessions/constants.ts@@ -0,0 +1,17 @@+/**+ * Verbatim message cap on the JSON column. When a session crosses this+ * threshold, the oldest entries are dropped on the next `append` so the+ * stored payload stays bounded.+ */+export const MAX_CHAT_MESSAGES = 20;++/**+ * Per (workspace, user) cap on chat sessions. Inserting a 21st row drops+ * the oldest by `updated_at` in the same transaction.+ */+export const MAX_CHAT_SESSIONS_PER_USER = 20;++/**+ * Title truncation length — first user message clipped to this many chars.+ */+export const CHAT_TITLE_MAX_LENGTH = 60;diff --git a/packages/db/src/schema/chat_sessions/index.ts b/packages/db/src/schema/chat_sessions/index.tsnew file mode 100644index 000000000..dc560e747--- /dev/null+++ b/packages/db/src/schema/chat_sessions/index.ts@@ -0,0 +1,3 @@+export * from "./chat_session";+export * from "./constants";+export * from "./validation";diff --git a/packages/db/src/schema/chat_sessions/validation.ts b/packages/db/src/schema/chat_sessions/validation.tsnew file mode 100644index 000000000..22d978df1--- /dev/null+++ b/packages/db/src/schema/chat_sessions/validation.ts@@ -0,0 +1,55 @@+import { createInsertSchema, createSelectSchema } from "drizzle-zod";+import { z } from "zod";++import { chatSession } from "./chat_session";+import { CHAT_TITLE_MAX_LENGTH, MAX_CHAT_MESSAGES } from "./constants";++/**+ * Persisted message-part shape. Mirrors AI SDK v6 `UIMessagePart` —+ * which is a union of `text`, `tool-<name>`, `reasoning`, `source-*`,+ * `file`, `data-*`, `step-start`. We don't enumerate them: storage+ * accepts any `{ type: string }` shape (`passthrough()` keeps unknown+ * fields). The route handler filters to the parts we actually need+ * for re-render (text + tool-*) before persisting.+ *+ * Also covers our compaction marker `tool-summary` — same loose shape.+ */+export const messagePartSchema = z.looseObject({+ type: z.string(),+});++export type ChatMessagePart = z.infer<typeof messagePartSchema>;++export const storedMessageSchema = z.object({+ id: z.string(),+ role: z.enum(["user", "assistant", "system"]),+ parts: z.array(messagePartSchema),+ /**+ * Server-stamped epoch ms of when this message was first persisted.+ * The service layer stamps `Date.now()` and preserves the original+ * value across the full-replace persistence, so older messages keep+ * their first-seen timestamp instead of being re-stamped per turn.+ */+ createdAt: z.number().int(),+});++export type ChatStoredMessage = z.infer<typeof storedMessageSchema>;++export const chatStoredMessagesSchema = z+ .array(storedMessageSchema)+ .max(MAX_CHAT_MESSAGES);++export const chatTitleSchema = z.string().min(1).max(CHAT_TITLE_MAX_LENGTH);++export const insertChatSessionSchema = createInsertSchema(chatSession, {+ title: chatTitleSchema,+ messages: chatStoredMessagesSchema,+});++export const selectChatSessionSchema = createSelectSchema(chatSession, {+ title: chatTitleSchema,+ messages: chatStoredMessagesSchema,+});++export type InsertChatSession = z.infer<typeof insertChatSessionSchema>;+export type ChatSession = z.infer<typeof selectChatSessionSchema>;diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex f85ab9315..7972335f7 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -23,3 +23,4 @@ export * from "./page_components";export * from "./page_component_groups";export * from "./feedbacks";export * from "./audit_logs";+export * from "./chat_sessions";diff --git a/packages/services/package.json b/packages/services/package.jsonindex bfd8a9c45..a7f80405e 100644--- a/packages/services/package.json+++ b/packages/services/package.json@@ -53,6 +53,14 @@"import": "./src/api-key/index.ts","types": "./src/api-key/index.ts"},+ "./chat-session": {+ "import": "./src/chat-session/index.ts",+ "types": "./src/chat-session/index.ts"+ },+ "./agent-tools": {+ "import": "./src/agent-tools/index.ts",+ "types": "./src/agent-tools/index.ts"+ },"./import": {"import": "./src/import/index.ts","types": "./src/import/index.ts"@@ -95,7 +103,8 @@}},"scripts": {- "test": "bun test"+ "test": "bun test",+ "tsc": "tsc --noEmit"},"dependencies": {"@openstatus/assertions": "workspace:*",diff --git a/packages/services/src/agent-tools/index.ts b/packages/services/src/agent-tools/index.tsnew file mode 100644index 000000000..622e183fa--- /dev/null+++ b/packages/services/src/agent-tools/index.ts@@ -0,0 +1,76 @@+import type { z } from "zod";++import { createMaintenanceTool, listMaintenancesTool } from "./maintenance";+import { listStatusPagesTool } from "./page";+import {+ addStatusReportUpdateTool,+ createStatusReportTool,+ listStatusReportsTool,+ resolveStatusReportTool,+ updateStatusReportTool,+} from "./status-report";+import type { AnyAgentTool } from "./types";++export {+ createMaintenanceTool,+ listMaintenancesTool,+} from "./maintenance";+export { listStatusPagesTool } from "./page";+export {+ addStatusReportUpdateTool,+ createStatusReportTool,+ listStatusReportsTool,+ resolveStatusReportTool,+ updateStatusReportTool,+} from "./status-report";+export type {+ AgentTool,+ AgentToolRegistry,+ AnyAgentTool,+ InferAgentToolInput,+ InferAgentToolOutput,+} from "./types";+export {+ type AgentSystemPromptOptions,+ buildAgentSystemPrompt,+} from "./prompt";++/**+ * Aggregate registry. Adding a tool here surfaces it on every adapter+ * (MCP + dashboard chat).+ *+ * `satisfies` (not a typed assignment) keeps the literal-keyed object+ * type intact, so `keyof typeof agentTools` is the union of tool names+ * and `(typeof agentTools)[N]["inputSchema"]` carries through to the+ * concrete schema for that specific tool. Consumers can then `z.infer`+ * per tool name without any casts.+ */+export const agentTools = {+ list_status_pages: listStatusPagesTool,+ list_status_reports: listStatusReportsTool,+ create_status_report: createStatusReportTool,+ add_status_report_update: addStatusReportUpdateTool,+ update_status_report: updateStatusReportTool,+ resolve_status_report: resolveStatusReportTool,+ list_maintenances: listMaintenancesTool,+ create_maintenance: createMaintenanceTool,+} satisfies Record<string, AnyAgentTool>;++/**+ * Iteration view used by adapters that don't care about the literal key.+ * Equivalent to `Object.values(agentTools)`.+ */+export const agentToolList: AnyAgentTool[] = Object.values(agentTools);++/** Literal union of every registered tool's name. */+export type AgentToolName = keyof typeof agentTools;++/** Concrete input type for a given tool name. */+export type AgentToolInput<N extends AgentToolName> = z.infer<+ (typeof agentTools)[N]["inputSchema"]+>;++/** Concrete output type for a given tool name. */+export type AgentToolOutput<N extends AgentToolName> = z.infer<+ (typeof agentTools)[N]["outputSchema"]+>;diff --git a/packages/services/src/agent-tools/maintenance.ts b/packages/services/src/agent-tools/maintenance.tsnew file mode 100644index 000000000..1ebfa802d--- /dev/null+++ b/packages/services/src/agent-tools/maintenance.ts@@ -0,0 +1,182 @@+import { z } from "zod";++import {+ createMaintenance,+ listMaintenances,+ notifyMaintenance,+} from "../maintenance";+import type { AgentTool } from "./types";++const PER_PAGE_DEFAULT = 50;+const PER_PAGE_MAX = 200;++const ListMaintenancesInputShape = z.object({+ pageId: z+ .number()+ .int()+ .optional()+ .describe("If set, only maintenances attached to this page id."),+ page: z+ .number()+ .int()+ .min(1)+ .default(1)+ .describe("1-indexed page number (default 1)."),+ perPage: z+ .number()+ .int()+ .min(1)+ .max(PER_PAGE_MAX)+ .default(PER_PAGE_DEFAULT)+ .describe(+ `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,+ ),+});++const ListMaintenancesOutput = z.object({+ items: z.array(+ z.object({+ id: z.number().int(),+ title: z.string(),+ message: z.string(),+ from: z.string(),+ to: z.string(),+ pageId: z.number().int().nullable(),+ pageComponentIds: z.array(z.number().int()),+ }),+ ),+ pagination: z.object({+ page: z.number().int(),+ perPage: z.number().int(),+ totalSize: z.number().int(),+ totalPages: z.number().int(),+ }),+});++export const listMaintenancesTool: AgentTool<+ z.infer<typeof ListMaintenancesInputShape>,+ z.infer<typeof ListMaintenancesOutput>+> = {+ name: "list_maintenances",+ description:+ "List maintenance windows in this workspace, newest first. Paginated via `page` (1-indexed) and `perPage`.",+ scope: "read",+ destructive: false,+ inputSchema: ListMaintenancesInputShape,+ outputSchema: ListMaintenancesOutput,+ async run({ ctx, input }) {+ const { pageId, page, perPage } = input;+ const result = await listMaintenances({+ ctx,+ input: {+ limit: perPage,+ offset: (page - 1) * perPage,+ pageId,+ order: "desc",+ },+ });+ return {+ items: result.items.map((m) => ({+ id: m.id,+ title: m.title,+ message: m.message,+ from: m.from.toISOString(),+ to: m.to.toISOString(),+ pageId: m.pageId,+ pageComponentIds: m.pageComponentIds,+ })),+ pagination: {+ page,+ perPage,+ totalSize: result.totalSize,+ totalPages: Math.max(1, Math.ceil(result.totalSize / perPage)),+ },+ };+ },+};++const CreateMaintenanceInputShape = z.object({+ title: z.string().min(1).max(256).describe("Short, public-facing title."),+ message: z+ .string()+ .min(1)+ .describe("Public message describing the work, shown on the page."),+ from: z.iso+ .datetime()+ .describe("Start time, ISO 8601 (e.g. 2026-04-30T14:00:00Z)."),+ to: z.iso+ .datetime()+ .describe("End time, ISO 8601. Must be strictly after `from`."),+ pageId: z+ .number()+ .int()+ .describe(+ "Status page to attach to. Resolve via list_status_pages — never guess.",+ ),+ pageComponentIds: z+ .array(z.number().int())+ .default([])+ .describe(+ "Optional component ids affected by the maintenance. Must belong to pageId.",+ ),+ notify: z+ .boolean()+ .describe(+ "Whether to dispatch subscriber notifications. No retroactive notify — false means subscribers will never hear about this window.",+ ),+});++const CreateMaintenanceOutput = z.object({+ id: z.number().int(),+ title: z.string(),+ from: z.string(),+ to: z.string(),+ pageId: z.number().int().nullable(),+ notified: z.boolean(),+});++export const createMaintenanceTool: AgentTool<+ z.infer<typeof CreateMaintenanceInputShape>,+ z.infer<typeof CreateMaintenanceOutput>+> = {+ name: "create_maintenance",+ description:+ "Schedule a maintenance window on a status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects. Subscriber notifications dispatch as part of this call only — no retroactive notify. The maintenance row persists even if the notify dispatch fails; `notified` reports the actual outcome. pageId MUST come from list_status_pages — never guess.",+ scope: "write",+ destructive: true,+ inputSchema: CreateMaintenanceInputShape,+ outputSchema: CreateMaintenanceOutput,+ async run({ ctx, input }) {+ const record = await createMaintenance({+ ctx,+ input: {+ title: input.title,+ message: input.message,+ from: new Date(input.from),+ to: new Date(input.to),+ pageId: input.pageId,+ pageComponentIds: input.pageComponentIds ?? [],+ },+ });+ let notified = false;+ if (input.notify) {+ try {+ await notifyMaintenance({+ ctx,+ input: { maintenanceId: record.id },+ });+ notified = true;+ } catch (err) {+ console.warn("notifyMaintenance failed after create_maintenance", err);+ }+ }+ return {+ id: record.id,+ title: record.title,+ from: record.from.toISOString(),+ to: record.to.toISOString(),+ pageId: record.pageId,+ notified,+ };+ },+};diff --git a/packages/services/src/agent-tools/page.ts b/packages/services/src/agent-tools/page.tsnew file mode 100644index 000000000..17c86a03c--- /dev/null+++ b/packages/services/src/agent-tools/page.ts@@ -0,0 +1,34 @@+import { z } from "zod";++import { listPages } from "../page";+import type { AgentTool } from "./types";++const ListStatusPagesInput = z.object({}).strict();+const ListStatusPagesOutput = z.object({+ items: z.array(+ z.object({+ id: z.number().int(),+ title: z.string(),+ slug: z.string(),+ }),+ ),+});++export const listStatusPagesTool: AgentTool<+ z.infer<typeof ListStatusPagesInput>,+ z.infer<typeof ListStatusPagesOutput>+> = {+ name: "list_status_pages",+ description:+ "List status pages in this workspace with their slug and ids. Use to discover the pageId required by create_status_report and create_maintenance.",+ scope: "read",+ destructive: false,+ inputSchema: ListStatusPagesInput,+ outputSchema: ListStatusPagesOutput,+ async run({ ctx }) {+ const pages = await listPages({ ctx, input: { order: "desc" } });+ return {+ items: pages.map((p) => ({ id: p.id, title: p.title, slug: p.slug })),+ };+ },+};diff --git a/packages/services/src/agent-tools/prompt.ts b/packages/services/src/agent-tools/prompt.tsnew file mode 100644index 000000000..01abd6a0a--- /dev/null+++ b/packages/services/src/agent-tools/prompt.ts@@ -0,0 +1,89 @@+/**+ * Shared system-prompt core for every agent surface. Per-surface flavor+ * is layered on top via `preamble`; the "draft → ask → confirm" rubric+ * lives here so tool descriptions stay factual.+ */+export type AgentSystemPromptOptions = {+ workspaceName: string;+ /** ISO timestamp anchor — defaults to now. Override for tests. */+ now?: Date;+ /** Surface label so the model knows where it's running. */+ surface: "slack" | "dashboard";+ /** Optional preamble injected before the shared core. */+ preamble?: string;+ /**+ * Whether the workspace plan supports status-page subscribers. When+ * false the model passes `notify: false` and skips the yes/no prompt.+ */+ canNotifySubscribers: boolean;+};++export function buildAgentSystemPrompt(opts: AgentSystemPromptOptions): string {+ const now = (opts.now ?? new Date()).toISOString();+ const surfaceLine =+ opts.surface === "slack"+ ? "You are running inside Slack. Keep replies concise and use Slack mrkdwn (*bold*, _italic_)."+ : "You are running inside the openstatus dashboard. Keep replies concise; the surface renders Markdown.";++ // Dashboard renders structured cards after every tool call; tell the+ // model not to duplicate them. Slack has no card, so the rule is skipped.+ const dashboardPostToolRule =+ opts.surface === "dashboard"+ ? `\n\nAfter a tool returns, the dashboard already renders a structured view of the result:+- Write tools (create_*, update_*, resolve_*, add_*) render a diff card with every input/output field (id, status, message, dates, notify outcome).+- List tools (list_status_pages, list_status_reports, list_maintenances) render a table with one row per result, showing title, slug/status/window, page id, and id.+DO NOT restate that data in your reply — no markdown tables, no bullet recaps of the rows, no field-by-field summaries. A one-line acknowledgement ("You have 4 status reports — 3 active." / "Incident resolved." / "Maintenance window scheduled.") plus an optional next step is enough.`+ : "";++ const preamble = opts.preamble ? `${opts.preamble}\n\n` : "";++ // Workspaces without subscriber notify get a different rubric — asking+ // is wasted friction when the field is a server-side no-op anyway.+ const notifyStep = opts.canNotifySubscribers+ ? `3. For tools with a notify flag (create_status_report, add_status_report_update, resolve_status_report, create_maintenance) ALWAYS ask explicitly: "Should I notify subscribers? yes/no" — never infer the answer.+4. Only call the tool once the user has confirmed BOTH the content AND the notify decision.`+ : `3. This workspace plan does NOT support subscriber notifications. For any tool with a notify flag (create_status_report, add_status_report_update, resolve_status_report, create_maintenance) ALWAYS pass \`notify: false\`. Do NOT ask the user about notifications — they would be a no-op anyway. Do NOT mention notifications in your draft.+4. Only call the tool once the user has confirmed the content.`;++ return `${preamble}You are the openstatus assistant for workspace "${opts.workspaceName}".+The current date and time is ${now} (UTC). Default timezone for any date you produce is UTC unless the user specifies otherwise — mention that you defaulted to UTC when relevant.+${surfaceLine}${dashboardPostToolRule}++You help teams manage status pages, status reports, and maintenance windows.++Anti-guess rules — these are absolute:+- You have NO knowledge of this workspace's data. NEVER invent or guess IDs (page id, status report id, maintenance id, page component id).+- Before referencing a status page: call list_status_pages.+- Before referencing a status report: call list_status_reports.+- Before referencing a maintenance window: call list_maintenances.+- pageId on create_status_report and create_maintenance MUST come from list_status_pages. Guessing will cause a NOT_FOUND error.++Lifecycle:+- Status reports flow: create_status_report once → add_status_report_update repeatedly → resolve_status_report.+- "provide an update", "we found the cause", "still investigating" → add_status_report_update.+- "rename the report", "add a component" → update_status_report (metadata only — does not notify).+- "it's fixed", "incident is resolved" → resolve_status_report (publishes a final update).+- Status progression hint: investigating → identified → monitoring → resolved.++Inferring status from conversation:+- "we have an incident" → investigating+- "we found the root cause" → identified+- "we're watching it" → monitoring+- "it's fixed" → resolved++Draft → Ask → Confirm rubric (MANDATORY for every write tool):+1. Draft the proposed change (title, status, message, time window, affected components).+2. Show the draft to the user before calling the tool.+${notifyStep}+5. Subscriber notifications dispatch only on the call that creates the update — there is no retroactive notify path.++Other guidance:+- If multiple status pages exist, ask which one to use. If only one, use it automatically.+- Draft professional public-facing messages. Don't repeat the user verbatim.+- For maintenance windows, parse natural language dates into ISO 8601. The "from" must be strictly before "to".+- Be concise. Don't restate everything the user said.++Tool result handling:+- If a tool returns an error or denied result (e.g. the user denied a destructive call with "Cancelled by user."), acknowledge the outcome plainly. NEVER claim success when the tool didn't run. Example replies: "Cancelled — nothing was created. Let me know if you want to adjust and try again." or "The status report couldn't be created (<reason>). Want me to retry with different inputs?"+- After a denied/errored call, do not re-issue the same tool unless the user explicitly asks.`;+}diff --git a/packages/services/src/agent-tools/status-report.ts b/packages/services/src/agent-tools/status-report.tsnew file mode 100644index 000000000..fcd6408c0--- /dev/null+++ b/packages/services/src/agent-tools/status-report.ts@@ -0,0 +1,419 @@+import { statusReportStatusSchema } from "@openstatus/db/src/schema";+import { z } from "zod";++import {+ addStatusReportUpdate,+ listStatusReports,+ notifyStatusReport,+ resolveStatusReport,+ updateStatusReport,+} from "../status-report";+import { createStatusReport } from "../status-report/create";+import type { AgentTool } from "./types";++const PER_PAGE_DEFAULT = 50;+const PER_PAGE_MAX = 200;++/**+ * "Active" statuses are computed at module load — extending the+ * `statusReportStatusSchema` enum (e.g. adding `degraded`) automatically+ * widens the filter without touching this file.+ */+const ACTIVE_STATUSES = statusReportStatusSchema.options.filter(+ (s) => s !== "resolved",+);++const ListStatusReportsInputShape = z.object({+ filter: z+ .enum(["active", "all"])+ .default("active")+ .describe(+ "active = exclude resolved reports (default). all = every report regardless of status.",+ ),+ pageId: z+ .number()+ .int()+ .optional()+ .describe("If set, only reports attached to this page id."),+ page: z+ .number()+ .int()+ .min(1)+ .default(1)+ .describe("1-indexed page number (default 1)."),+ perPage: z+ .number()+ .int()+ .min(1)+ .max(PER_PAGE_MAX)+ .default(PER_PAGE_DEFAULT)+ .describe(+ `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,+ ),+});++const ListStatusReportsOutput = z.object({+ items: z.array(+ z.object({+ id: z.number().int(),+ title: z.string(),+ status: statusReportStatusSchema,+ pageId: z.number().int().nullable(),+ createdAt: z.string().nullable(),+ updatedAt: z.string().nullable(),+ latestUpdate: z+ .object({+ message: z.string(),+ status: statusReportStatusSchema,+ date: z.string().nullable(),+ })+ .nullable(),+ }),+ ),+ pagination: z.object({+ page: z.number().int(),+ perPage: z.number().int(),+ totalSize: z.number().int(),+ totalPages: z.number().int(),+ }),+});++export const listStatusReportsTool: AgentTool<+ z.infer<typeof ListStatusReportsInputShape>,+ z.infer<typeof ListStatusReportsOutput>+> = {+ name: "list_status_reports",+ description:+ "List status reports in this workspace, newest first. Filter by status (e.g. exclude 'resolved' to see active incidents). Returns the most recent update per report so the current public message is visible without a follow-up call. Paginated via `page` (1-indexed) and `perPage`.",+ scope: "read",+ destructive: false,+ inputSchema: ListStatusReportsInputShape,+ outputSchema: ListStatusReportsOutput,+ async run({ ctx, input }) {+ const { filter, pageId, page, perPage } = input;+ const result = await listStatusReports({+ ctx,+ input: {+ limit: perPage,+ offset: (page - 1) * perPage,+ statuses: filter === "active" ? ACTIVE_STATUSES : [],+ pageId,+ order: "desc",+ },+ });+ return {+ items: result.items.map((r) => {+ const latestUpdate = r.updates[0] ?? null;+ return {+ id: r.id,+ title: r.title,+ status: r.status,+ pageId: r.pageId,+ createdAt: r.createdAt?.toISOString() ?? null,+ updatedAt: r.updatedAt?.toISOString() ?? null,+ latestUpdate: latestUpdate+ ? {+ message: latestUpdate.message,+ status: latestUpdate.status,+ date: latestUpdate.date?.toISOString() ?? null,+ }+ : null,+ };+ }),+ pagination: {+ page,+ perPage,+ totalSize: result.totalSize,+ totalPages: Math.max(1, Math.ceil(result.totalSize / perPage)),+ },+ };+ },+};++const CreateStatusReportInputShape = z.object({+ title: z.string().min(1).max(256).describe("Short, public-facing title."),+ status: statusReportStatusSchema.describe("Initial status for the report."),+ message: z+ .string()+ .min(1)+ .describe("Initial public update message customers will see."),+ pageId: z+ .number()+ .int()+ .describe(+ "Status page to attach to. Resolve via list_status_pages — never guess.",+ ),+ pageComponentIds: z+ .array(z.number().int())+ .default([])+ .describe(+ "Optional component ids affected by the incident. Must belong to pageId.",+ ),+ date: z.iso+ .datetime()+ .optional()+ .describe("Override the initial update's date. Defaults to now."),+ notify: z+ .boolean()+ .describe(+ "Whether to dispatch subscriber notifications for the initial update. true = notify on creation. false = create silently; subscribers will NEVER hear about this update (no retroactive notify).",+ ),+});++const CreateStatusReportOutput = z.object({+ statusReport: z.object({+ id: z.number().int(),+ title: z.string(),+ status: statusReportStatusSchema,+ pageId: z.number().int().nullable(),+ createdAt: z.string().nullable(),+ }),+ initialUpdateId: z.number().int(),+ notified: z.boolean(),+});++export const createStatusReportTool: AgentTool<+ z.infer<typeof CreateStatusReportInputShape>,+ z.infer<typeof CreateStatusReportOutput>+> = {+ name: "create_status_report",+ description:+ "Create a new status report on a public status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects. Subscriber notifications dispatch as part of this call only — no retroactive notify. The report persists even if the notify dispatch fails; `notified` reports the actual outcome. pageId MUST come from list_status_pages — never guess. pageComponentIds (if supplied) MUST belong to the same page.",+ scope: "write",+ destructive: true,+ inputSchema: CreateStatusReportInputShape,+ outputSchema: CreateStatusReportOutput,+ async run({ ctx, input }) {+ const result = await createStatusReport({+ ctx,+ input: {+ title: input.title,+ status: input.status,+ message: input.message,+ pageId: input.pageId,+ pageComponentIds: input.pageComponentIds ?? [],+ date: input.date ? new Date(input.date) : new Date(),+ },+ });+ let notified = false;+ if (input.notify) {+ try {+ await notifyStatusReport({+ ctx,+ input: { statusReportUpdateId: result.initialUpdate.id },+ });+ notified = true;+ } catch (err) {+ console.warn(+ "notifyStatusReport failed after create_status_report",+ err,+ );+ }+ }+ return {+ statusReport: {+ id: result.statusReport.id,+ title: result.statusReport.title,+ status: result.statusReport.status,+ pageId: result.statusReport.pageId,+ createdAt: result.statusReport.createdAt?.toISOString() ?? null,+ },+ initialUpdateId: result.initialUpdate.id,+ notified,+ };+ },+};++const AddStatusReportUpdateInputShape = z.object({+ statusReportId: z+ .number()+ .int()+ .describe("Status report to update. Resolve via list_status_reports."),+ status: statusReportStatusSchema.describe(+ "New status to set on the report. The update entry inherits this status.",+ ),+ message: z+ .string()+ .min(1)+ .describe("Public update message customers will see."),+ date: z.iso+ .datetime()+ .optional()+ .describe("Override the update's date. Defaults to now."),+ notify: z+ .boolean()+ .describe(+ "Whether to dispatch subscriber notifications for this update. No retroactive notify — false means subscribers will never hear about this update.",+ ),+});++const AddStatusReportUpdateOutput = z.object({+ statusReportUpdateId: z.number().int(),+ notified: z.boolean(),+});++export const addStatusReportUpdateTool: AgentTool<+ z.infer<typeof AddStatusReportUpdateInputShape>,+ z.infer<typeof AddStatusReportUpdateOutput>+> = {+ name: "add_status_report_update",+ description:+ "Append a new public update to an existing status report. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects. Sets the report's status to the new value (use resolve_status_report instead if the new status would be 'resolved'). Subscriber notifications dispatch as part of this call only — no retroactive notify. The update persists even if the notify dispatch fails; `notified` reports the actual outcome.",+ scope: "write",+ destructive: true,+ inputSchema: AddStatusReportUpdateInputShape,+ outputSchema: AddStatusReportUpdateOutput,+ async run({ ctx, input }) {+ const result = await addStatusReportUpdate({+ ctx,+ input: {+ statusReportId: input.statusReportId,+ status: input.status,+ message: input.message,+ date: input.date ? new Date(input.date) : undefined,+ },+ });+ let notified = false;+ if (input.notify) {+ try {+ await notifyStatusReport({+ ctx,+ input: { statusReportUpdateId: result.statusReportUpdate.id },+ });+ notified = true;+ } catch (err) {+ console.warn(+ "notifyStatusReport failed after add_status_report_update",+ err,+ );+ }+ }+ return {+ statusReportUpdateId: result.statusReportUpdate.id,+ notified,+ };+ },+};++const UpdateStatusReportInputShape = z.object({+ statusReportId: z+ .number()+ .int()+ .describe("Report to edit. Resolve via list_status_reports."),+ title: z.string().min(1).max(256).optional().describe("New title."),+ status: statusReportStatusSchema+ .refine((s) => s !== "resolved", {+ error:+ "update_status_report cannot set status to 'resolved' — use resolve_status_report instead, which also publishes a final resolution update.",+ })+ .optional()+ .describe(+ "New status (without appending a public update entry). Cannot be 'resolved'.",+ ),+ pageComponentIds: z+ .array(z.number().int())+ .optional()+ .describe(+ "Replace the full set of associated component ids. Empty array clears the association.",+ ),+});++const UpdateStatusReportOutput = z.object({+ id: z.number().int(),+ title: z.string(),+ status: statusReportStatusSchema,+});++export const updateStatusReportTool: AgentTool<+ z.infer<typeof UpdateStatusReportInputShape>,+ z.infer<typeof UpdateStatusReportOutput>+> = {+ name: "update_status_report",+ description:+ "Edit metadata on an existing status report (title, status, affected components). Does NOT add a public update — use add_status_report_update for that. Does NOT and CANNOT notify subscribers — there is no notify path on this tool because metadata edits do not create a new update entry to dispatch. Audit-logged.",+ scope: "write",+ destructive: true,+ inputSchema: UpdateStatusReportInputShape,+ outputSchema: UpdateStatusReportOutput,+ async run({ ctx, input }) {+ const report = await updateStatusReport({+ ctx,+ input: {+ id: input.statusReportId,+ title: input.title,+ status: input.status,+ pageComponentIds: input.pageComponentIds,+ },+ });+ return { id: report.id, title: report.title, status: report.status };+ },+};++const ResolveStatusReportInputShape = z.object({+ statusReportId: z+ .number()+ .int()+ .describe("Report to resolve. Resolve via list_status_reports."),+ message: z+ .string()+ .min(1)+ .describe(+ "Resolution message customers will see explaining what was fixed.",+ ),+ date: z.iso+ .datetime()+ .optional()+ .describe("Override the resolution date. Defaults to now."),+ notify: z+ .boolean()+ .describe(+ "Whether to dispatch subscriber notifications for the resolution update. No retroactive notify — false means subscribers will never hear about this resolution.",+ ),+});++const ResolveStatusReportOutput = z.object({+ statusReportUpdateId: z.number().int(),+ notified: z.boolean(),+});++export const resolveStatusReportTool: AgentTool<+ z.infer<typeof ResolveStatusReportInputShape>,+ z.infer<typeof ResolveStatusReportOutput>+> = {+ name: "resolve_status_report",+ description:+ "Resolve an active status report. Appends a final public update with the supplied message and flips status to 'resolved'. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects. Subscriber notifications dispatch as part of this call only — no retroactive notify. The report flips to resolved even if the notify dispatch fails; `notified` reports the actual outcome.",+ scope: "write",+ destructive: true,+ inputSchema: ResolveStatusReportInputShape,+ outputSchema: ResolveStatusReportOutput,+ async run({ ctx, input }) {+ const result = await resolveStatusReport({+ ctx,+ input: {+ statusReportId: input.statusReportId,+ message: input.message,+ date: input.date ? new Date(input.date) : undefined,+ },+ });+ let notified = false;+ if (input.notify) {+ try {+ await notifyStatusReport({+ ctx,+ input: { statusReportUpdateId: result.statusReportUpdate.id },+ });+ notified = true;+ } catch (err) {+ console.warn(+ "notifyStatusReport failed after resolve_status_report",+ err,+ );+ }+ }+ return {+ statusReportUpdateId: result.statusReportUpdate.id,+ notified,+ };+ },+};diff --git a/packages/services/src/agent-tools/types.ts b/packages/services/src/agent-tools/types.tsnew file mode 100644index 000000000..cbc7c44e4--- /dev/null+++ b/packages/services/src/agent-tools/types.ts@@ -0,0 +1,38 @@+import type { Scope } from "@openstatus/db/src/schema";+import type { ZodType, z } from "zod";++import type { ServiceContext } from "../context";++/**+ * Framework-agnostic tool descriptor shared by every adapter (MCP, AI SDK).+ * `description` is factual; behavioral rubrics live in the system prompt+ * so per-surface prompts can vary the wording. `destructive` is mirrored+ * onto MCP `destructiveHint` and used by the AI SDK adapter to enable+ * HITL approval. `run` returns plain JS objects — the MCP adapter wraps+ * them into `CallToolResult`.+ */+export type AgentTool<TInput = unknown, TOutput = unknown> = {+ name: string;+ description: string;+ scope: Scope;+ destructive: boolean;+ inputSchema: ZodType<TInput>;+ outputSchema: ZodType<TOutput>;+ run(args: { ctx: ServiceContext; input: TInput }): Promise<TOutput>;+};++export type InferAgentToolInput<T> = T extends AgentTool<infer I, unknown>+ ? I+ : never;+export type InferAgentToolOutput<T> = T extends AgentTool<unknown, infer O>+ ? O+ : never;++// `any` is the variance escape hatch — `unknown` would block storing+// concrete tools because function inputs are contravariant.+// biome-ignore lint/suspicious/noExplicitAny: registry-level variance escape hatch+export type AnyAgentTool = AgentTool<any, any>;++export type AgentToolRegistry = Record<string, AnyAgentTool>;++export type { z };diff --git a/packages/services/src/chat-session/create.ts b/packages/services/src/chat-session/create.tsnew file mode 100644index 000000000..e941065a0--- /dev/null+++ b/packages/services/src/chat-session/create.ts@@ -0,0 +1,65 @@+import {+ CHAT_TITLE_MAX_LENGTH,+ type ChatSessionRow,+ MAX_CHAT_SESSIONS_PER_USER,+ chatSession,+} from "@openstatus/db/src/schema";++import {+ type ServiceContext,+ tryGetActorUserId,+ withTransaction,+} from "../context";+import { UnauthorizedError } from "../errors";+import { enforceSessionCap } from "./internal";+import { CreateChatSessionInput } from "./schemas";++export async function createChatSession(args: {+ ctx: ServiceContext;+ input: CreateChatSessionInput;+}): Promise<ChatSessionRow> {+ const { ctx } = args;+ const input = CreateChatSessionInput.parse(args.input);++ const userId = tryGetActorUserId(ctx.actor);+ if (userId == null) {+ throw new UnauthorizedError(+ "Chat sessions must be created by a known user actor.",+ );+ }++ return withTransaction(ctx, async (tx) => {+ await enforceSessionCap({+ tx,+ workspaceId: ctx.workspace.id,+ userId,+ capAfterInsert: MAX_CHAT_SESSIONS_PER_USER - 1,+ });++ const title = deriveTitle(input.firstMessage.parts);++ const row = await tx+ .insert(chatSession)+ .values({+ workspaceId: ctx.workspace.id,+ userId,+ title,+ messages: [input.firstMessage],+ })+ .returning()+ .get();++ return row;+ });+}++function deriveTitle(parts: CreateChatSessionInput["firstMessage"]["parts"]) {+ const textPart = parts.find(+ (p): p is { type: "text"; text: string } & Record<string, unknown> =>+ p.type === "text" && typeof (p as { text?: unknown }).text === "string",+ );+ const raw = textPart?.text ?? "New chat";+ const trimmed = raw.trim().replace(/\s+/g, " ");+ if (trimmed.length === 0) return "New chat";+ return trimmed.slice(0, CHAT_TITLE_MAX_LENGTH);+}diff --git a/packages/services/src/chat-session/get.ts b/packages/services/src/chat-session/get.tsnew file mode 100644index 000000000..0706d3225--- /dev/null+++ b/packages/services/src/chat-session/get.ts@@ -0,0 +1,28 @@+import type { ChatSessionRow } from "@openstatus/db/src/schema";++import { type ServiceContext, getReadDb, tryGetActorUserId } from "../context";+import { UnauthorizedError } from "../errors";+import { getChatSessionInWorkspace } from "./internal";+import { GetChatSessionInput } from "./schemas";++export async function getChatSession(args: {+ ctx: ServiceContext;+ input: GetChatSessionInput;+}): Promise<ChatSessionRow> {+ const { ctx } = args;+ const input = GetChatSessionInput.parse(args.input);++ const userId = tryGetActorUserId(ctx.actor);+ if (userId == null) {+ throw new UnauthorizedError(+ "Chat sessions can only be read by a known user actor.",+ );+ }++ return getChatSessionInWorkspace({+ tx: getReadDb(ctx),+ sessionId: input.sessionId,+ workspaceId: ctx.workspace.id,+ userId,+ });+}diff --git a/packages/services/src/chat-session/index.ts b/packages/services/src/chat-session/index.tsnew file mode 100644index 000000000..84020b94f--- /dev/null+++ b/packages/services/src/chat-session/index.ts@@ -0,0 +1,13 @@+export { createChatSession } from "./create";+export { getChatSession } from "./get";+export { type ChatSessionSummary, listChatSessions } from "./list";+export { deleteChatSession } from "./remove";+export { setChatSessionMessages } from "./set";++export {+ CreateChatSessionInput,+ DeleteChatSessionInput,+ GetChatSessionInput,+ ListChatSessionsInput,+ SetChatSessionMessagesInput,+} from "./schemas";diff --git a/packages/services/src/chat-session/internal.ts b/packages/services/src/chat-session/internal.tsnew file mode 100644index 000000000..c77c27b32--- /dev/null+++ b/packages/services/src/chat-session/internal.ts@@ -0,0 +1,77 @@+import { and, eq, inArray } from "@openstatus/db";+import {+ type ChatStoredMessage,+ MAX_CHAT_MESSAGES,+ chatSession,+} from "@openstatus/db/src/schema";++import type { DB } from "../context";+import { NotFoundError } from "../errors";++export async function getChatSessionInWorkspace(args: {+ tx: DB;+ sessionId: number;+ workspaceId: number;+ userId: number;+}) {+ const { tx, sessionId, workspaceId, userId } = args;+ // Single combined WHERE — collapses ownership checks into NotFoundError+ // so callers can't distinguish "exists but forbidden" from "missing".+ const row = await tx+ .select()+ .from(chatSession)+ .where(+ and(+ eq(chatSession.id, sessionId),+ eq(chatSession.workspaceId, workspaceId),+ eq(chatSession.userId, userId),+ ),+ )+ .get();+ if (!row) throw new NotFoundError("chat_session", sessionId);+ return row;+}++/**+ * Bound message storage by dropping oldest entries if the array is over+ * `MAX_CHAT_MESSAGES`. Pending HITL tool parts are left intact — the+ * route filters them at `convertToModelMessages` time before they reach+ * the provider.+ */+export function compactMessages(+ messages: ChatStoredMessage[],+): ChatStoredMessage[] {+ if (messages.length <= MAX_CHAT_MESSAGES) return messages.slice();+ return messages.slice(messages.length - MAX_CHAT_MESSAGES);+}++/**+ * Drop the oldest sessions for `(workspace, user)` so the row count+ * stays at `capAfterInsert` once the caller inserts a new one.+ */+export async function enforceSessionCap(args: {+ tx: DB;+ workspaceId: number;+ userId: number;+ capAfterInsert: number;+}): Promise<void> {+ const { tx, workspaceId, userId, capAfterInsert } = args;+ const rows = await tx+ .select({ id: chatSession.id, updatedAt: chatSession.updatedAt })+ .from(chatSession)+ .where(+ and(+ eq(chatSession.workspaceId, workspaceId),+ eq(chatSession.userId, userId),+ ),+ )+ .all();+ if (rows.length <= capAfterInsert) return;+ const sorted = rows.sort(+ (a, b) => a.updatedAt.getTime() - b.updatedAt.getTime(),+ );+ const idsToDelete = sorted+ .slice(0, rows.length - capAfterInsert)+ .map((r) => r.id);+ await tx.delete(chatSession).where(inArray(chatSession.id, idsToDelete));+}diff --git a/packages/services/src/chat-session/list.ts b/packages/services/src/chat-session/list.tsnew file mode 100644index 000000000..754ed74aa--- /dev/null+++ b/packages/services/src/chat-session/list.ts@@ -0,0 +1,47 @@+import { and, desc, eq } from "@openstatus/db";+import {+ MAX_CHAT_SESSIONS_PER_USER,+ chatSession,+} from "@openstatus/db/src/schema";++import { type ServiceContext, getReadDb, tryGetActorUserId } from "../context";+import { UnauthorizedError } from "../errors";++export type ChatSessionSummary = {+ id: number;+ title: string;+ updatedAt: Date;+ createdAt: Date;+};++export async function listChatSessions(args: {+ ctx: ServiceContext;+}): Promise<ChatSessionSummary[]> {+ const { ctx } = args;+ const userId = tryGetActorUserId(ctx.actor);+ if (userId == null) {+ throw new UnauthorizedError(+ "Chat sessions can only be listed for a known user actor.",+ );+ }++ const db = getReadDb(ctx);+ const rows = await db+ .select({+ id: chatSession.id,+ title: chatSession.title,+ updatedAt: chatSession.updatedAt,+ createdAt: chatSession.createdAt,+ })+ .from(chatSession)+ .where(+ and(+ eq(chatSession.workspaceId, ctx.workspace.id),+ eq(chatSession.userId, userId),+ ),+ )+ .orderBy(desc(chatSession.updatedAt))+ .limit(MAX_CHAT_SESSIONS_PER_USER)+ .all();+ return rows;+}diff --git a/packages/services/src/chat-session/remove.ts b/packages/services/src/chat-session/remove.tsnew file mode 100644index 000000000..d6e3ebe03--- /dev/null+++ b/packages/services/src/chat-session/remove.ts@@ -0,0 +1,36 @@+import { eq } from "@openstatus/db";+import { chatSession } from "@openstatus/db/src/schema";++import {+ type ServiceContext,+ tryGetActorUserId,+ withTransaction,+} from "../context";+import { UnauthorizedError } from "../errors";+import { getChatSessionInWorkspace } from "./internal";+import { DeleteChatSessionInput } from "./schemas";++export async function deleteChatSession(args: {+ ctx: ServiceContext;+ input: DeleteChatSessionInput;+}): Promise<void> {+ const { ctx } = args;+ const input = DeleteChatSessionInput.parse(args.input);++ const userId = tryGetActorUserId(ctx.actor);+ if (userId == null) {+ throw new UnauthorizedError(+ "Chat sessions can only be deleted by a known user actor.",+ );+ }++ await withTransaction(ctx, async (tx) => {+ const session = await getChatSessionInWorkspace({+ tx,+ sessionId: input.sessionId,+ workspaceId: ctx.workspace.id,+ userId,+ });+ await tx.delete(chatSession).where(eq(chatSession.id, session.id));+ });+}diff --git a/packages/services/src/chat-session/schemas.ts b/packages/services/src/chat-session/schemas.tsnew file mode 100644index 000000000..c561d6251--- /dev/null+++ b/packages/services/src/chat-session/schemas.ts@@ -0,0 +1,35 @@+import {+ CHAT_TITLE_MAX_LENGTH,+ storedMessageSchema,+} from "@openstatus/db/src/schema";+import { z } from "zod";++export const CreateChatSessionInput = z.object({+ firstMessage: storedMessageSchema,+});+export type CreateChatSessionInput = z.infer<typeof CreateChatSessionInput>;++export const SetChatSessionMessagesInput = z.object({+ sessionId: z.number().int(),+ // No `.min(1)` — replacing a session with an empty list is valid+ // (e.g. user wipes the conversation).+ messages: z.array(storedMessageSchema),+});+export type SetChatSessionMessagesInput = z.infer<+ typeof SetChatSessionMessagesInput+>;++export const GetChatSessionInput = z.object({+ sessionId: z.number().int(),+});+export type GetChatSessionInput = z.infer<typeof GetChatSessionInput>;++export const ListChatSessionsInput = z.object({}).strict();+export type ListChatSessionsInput = z.infer<typeof ListChatSessionsInput>;++export const DeleteChatSessionInput = z.object({+ sessionId: z.number().int(),+});+export type DeleteChatSessionInput = z.infer<typeof DeleteChatSessionInput>;++export { CHAT_TITLE_MAX_LENGTH };diff --git a/packages/services/src/chat-session/set.ts b/packages/services/src/chat-session/set.tsnew file mode 100644index 000000000..4c6a5d85b--- /dev/null+++ b/packages/services/src/chat-session/set.ts@@ -0,0 +1,69 @@+import { eq } from "@openstatus/db";+import {+ type ChatSessionRow,+ type ChatStoredMessage,+ chatSession,+} from "@openstatus/db/src/schema";++import {+ type ServiceContext,+ tryGetActorUserId,+ withTransaction,+} from "../context";+import { UnauthorizedError } from "../errors";+import { compactMessages, getChatSessionInWorkspace } from "./internal";+import { SetChatSessionMessagesInput } from "./schemas";++/**+ * Replace the chat session's full message list. Idempotent across+ * onFinish retries — HITL turns can fire onFinish multiple times, and+ * full-replace lets each fire be the canonical snapshot. Existing-row+ * `createdAt` wins on overlap so older messages don't drift forward.+ */+export async function setChatSessionMessages(args: {+ ctx: ServiceContext;+ input: SetChatSessionMessagesInput;+}): Promise<ChatSessionRow> {+ const { ctx } = args;+ const input = SetChatSessionMessagesInput.parse(args.input);++ const userId = tryGetActorUserId(ctx.actor);+ if (userId == null) {+ throw new UnauthorizedError(+ "Chat sessions must be updated by a known user actor.",+ );+ }++ return withTransaction(ctx, async (tx) => {+ const session = await getChatSessionInWorkspace({+ tx,+ sessionId: input.sessionId,+ workspaceId: ctx.workspace.id,+ userId,+ });++ const stamped = mergeTimestamps(session.messages, input.messages);+ const compacted = compactMessages(stamped);++ const updated = await tx+ .update(chatSession)+ .set({ messages: compacted, updatedAt: new Date() })+ .where(eq(chatSession.id, session.id))+ .returning()+ .get();++ return updated;+ });+}++function mergeTimestamps(+ existing: ChatStoredMessage[],+ incoming: ChatStoredMessage[],+): ChatStoredMessage[] {+ const existingStamps = new Map<string, number>();+ for (const m of existing) existingStamps.set(m.id, m.createdAt);+ return incoming.map((m) => {+ const prior = existingStamps.get(m.id);+ return prior !== undefined ? { ...m, createdAt: prior } : m;+ });+}diff --git a/packages/services/src/monitor/__tests__/stream-monitor-preview.test.ts b/packages/services/src/monitor/__tests__/stream-monitor-preview.test.tsindex 16a810c9d..431a9302c 100644--- a/packages/services/src/monitor/__tests__/stream-monitor-preview.test.ts+++ b/packages/services/src/monitor/__tests__/stream-monitor-preview.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeAll, describe, expect, test } from "bun:test";-import { SEEDED_WORKSPACE_FREE_ID } from "../../../test/fixtures";+import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {loadSeededWorkspace,makeUserCtx,@@ -57,7 +57,7 @@ describe("streamMonitorPreview", () => {test("throws NotFoundError when monitor belongs to a different workspace", async () => {await withTestTransaction(async (tx) => {- const ws = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const ws = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);const ctx = { ...makeUserCtx(ws), db: tx };// Use a monitor id that does not exist for this workspace.@@ -76,7 +76,7 @@ describe("streamMonitorPreview", () => {test("yields one result per region for an owned monitor", async () => {await withTestTransaction(async (tx) => {- const ws = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const ws = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);const ctx = { ...makeUserCtx(ws), db: tx };const created = await createMonitor({ctx,diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 51214b19c..08c0bd035 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -19,6 +19,10 @@"types": "./src/components/blocks/*.tsx","default": "./src/components/blocks/*.tsx"},+ "./components/custom/*": {+ "types": "./src/components/custom/*.tsx",+ "default": "./src/components/custom/*.tsx"+ },"./lib/*": {"types": "./src/lib/*.ts","default": "./src/lib/*.ts"@@ -68,6 +72,7 @@"@radix-ui/react-popover": "1.1.14","@radix-ui/react-progress": "1.1.7","@radix-ui/react-radio-group": "1.3.7",+ "@radix-ui/react-scroll-area": "1.2.10","@radix-ui/react-select": "2.2.5","@radix-ui/react-separator": "1.1.7","@radix-ui/react-slider": "1.3.5",diff --git a/packages/ui/src/components/custom/text-shimmer.tsx b/packages/ui/src/components/custom/text-shimmer.tsxnew file mode 100644index 000000000..7b8fa3cf8--- /dev/null+++ b/packages/ui/src/components/custom/text-shimmer.tsx@@ -0,0 +1,50 @@+"use client";++import type { ComponentProps, ElementType, ReactNode } from "react";++import { cn } from "@openstatus/ui/lib/utils";++/**+ * CSS-only animated text shimmer — a gradient slides under a `bg-clip:text`+ * mask. Pure CSS keeps the runtime cost trivial (no motion / framer-motion+ * payload) and avoids hydration of a client-only animation library.+ *+ * `spread` controls the width of the highlight band (clamped to 5–45%);+ * `duration` controls how long one sweep takes. The `shimmer` keyframe is+ * defined in `globals.css`.+ */+export type TextShimmerProps<E extends ElementType = "span"> = {+ as?: E;+ duration?: number;+ spread?: number;+ children: ReactNode;+} & Omit<ComponentProps<E>, "as" | "children">;++export function TextShimmer<E extends ElementType = "span">({+ as,+ className,+ duration = 3,+ spread = 20,+ children,+ ...props+}: TextShimmerProps<E>) {+ const Component = (as ?? "span") as ElementType;+ const dynamicSpread = Math.min(Math.max(spread, 5), 45);++ return (+ <Component+ className={cn(+ "bg-size-[200%_auto] bg-clip-text font-medium text-transparent",+ "animate-[shimmer_4s_infinite_linear]",+ className,+ )}+ style={{+ backgroundImage: `linear-gradient(to right, var(--muted-foreground) ${50 - dynamicSpread}%, var(--foreground) 50%, var(--muted-foreground) ${50 + dynamicSpread}%)`,+ animationDuration: `${duration}s`,+ }}+ {...props}+ >+ {children}+ </Component>+ );+}diff --git a/packages/ui/src/components/ui/scroll-area.tsx b/packages/ui/src/components/ui/scroll-area.tsxnew file mode 100644index 000000000..b069f4c65--- /dev/null+++ b/packages/ui/src/components/ui/scroll-area.tsx@@ -0,0 +1,58 @@+"use client";++import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";+import * as React from "react";++import { cn } from "@openstatus/ui/lib/utils";++function ScrollArea({+ className,+ children,+ ...props+}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {+ return (+ <ScrollAreaPrimitive.Root+ data-slot="scroll-area"+ className={cn("relative", className)}+ {...props}+ >+ <ScrollAreaPrimitive.Viewport+ data-slot="scroll-area-viewport"+ className="size-full rounded-[inherit] outline-none transition-[color,box-shadow] focus-visible:outline-1 focus-visible:ring-[3px] focus-visible:ring-ring/50"+ >+ {children}+ </ScrollAreaPrimitive.Viewport>+ <ScrollBar />+ <ScrollAreaPrimitive.Corner />+ </ScrollAreaPrimitive.Root>+ );+}++function ScrollBar({+ className,+ orientation = "vertical",+ ...props+}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {+ return (+ <ScrollAreaPrimitive.ScrollAreaScrollbar+ data-slot="scroll-area-scrollbar"+ orientation={orientation}+ className={cn(+ "flex touch-none select-none p-px transition-colors",+ orientation === "vertical" &&+ "h-full w-2.5 border-l border-l-transparent",+ orientation === "horizontal" &&+ "h-2.5 flex-col border-t border-t-transparent",+ className,+ )}+ {...props}+ >+ <ScrollAreaPrimitive.ScrollAreaThumb+ data-slot="scroll-area-thumb"+ className="relative flex-1 rounded-full bg-border"+ />+ </ScrollAreaPrimitive.ScrollAreaScrollbar>+ );+}++export { ScrollArea, ScrollBar };diff --git a/packages/ui/src/components/ui/spinner.tsx b/packages/ui/src/components/ui/spinner.tsxnew file mode 100644index 000000000..89bb20a6b--- /dev/null+++ b/packages/ui/src/components/ui/spinner.tsx@@ -0,0 +1,16 @@+import { Loader2Icon } from "lucide-react";++import { cn } from "@openstatus/ui/lib/utils";++function Spinner({ className, ...props }: React.ComponentProps<"svg">) {+ return (+ <Loader2Icon+ role="status"+ aria-label="Loading"+ className={cn("size-4 animate-spin", className)}+ {...props}+ />+ );+}++export { Spinner };diff --git a/packages/ui/src/globals.css b/packages/ui/src/globals.cssindex 0442a3824..a0a7fc491 100644--- a/packages/ui/src/globals.css+++ b/packages/ui/src/globals.css@@ -44,6 +44,15 @@--color-success: var(--success);--color-warning: var(--warning);--color-info: var(--info);++ @keyframes shimmer {+ 0% {+ background-position: 200% 50%;+ }+ 100% {+ background-position: -200% 50%;+ }+ }}:root {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3d3adbd3f..a2cb45a57 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -38,6 +38,9 @@ importers:apps/dashboard:dependencies:+ '@ai-sdk/react':+ specifier: 3.0.96+ version: 3.0.96([email protected])([email protected])'@auth/core':specifier: 0.40.0version: 0.40.0@@ -73,7 +76,7 @@ importers:version: 0.15.15'@openpanel/nextjs':specifier: 1.2.0- version: 1.2.0([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 1.2.0([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])'@openstatus/analytics':specifier: workspace:*version: link:../../packages/analytics@@ -190,7 +193,7 @@ importers:version: 1.2.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@sentry/nextjs':specifier: 10.31.0- version: 10.31.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))+ version: 10.31.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))'@stripe/stripe-js':specifier: 2.1.6version: 2.1.6@@ -205,7 +208,7 @@ importers:'@trpc/next':specifier: 11.4.4- version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])+ version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])'@trpc/react-query':specifier: 11.4.4version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -218,6 +221,9 @@ importers:'@unkey/api':specifier: 2.2.0version: 2.2.0+ ai:+ specifier: 6.0.94+ version: 6.0.94([email protected])class-variance-authority:specifier: 0.7.1version: 0.7.1@@ -238,13 +244,13 @@ importers:version: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: 5.0.0-beta.29- version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])next-themes:specifier: 0.4.6nuqs:specifier: 2.8.5- version: 2.8.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 2.8.5([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])random-word-slugs:specifier: 0.1.7version: 0.1.7@@ -641,7 +647,7 @@ importers:version: 0.15.15'@openpanel/nextjs':specifier: 1.2.0- version: 1.2.0([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 1.2.0([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])'@openstatus/analytics':specifier: workspace:*version: link:../../packages/analytics@@ -686,7 +692,7 @@ importers:version: 1.1.14(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@sentry/nextjs':specifier: 10.31.0- version: 10.31.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))+ version: 10.31.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))'@stripe/stripe-js':specifier: 2.1.6version: 2.1.6@@ -701,7 +707,7 @@ importers:'@trpc/next':specifier: 11.4.4- version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])+ version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])'@trpc/react-query':specifier: 11.4.4version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -737,19 +743,19 @@ importers:version: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: 5.0.0-beta.29- version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])next-intl:specifier: ^4.8.3version: 4.8.3(@swc/[email protected])([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])next-plausible:specifier: 3.12.5- version: 3.12.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 3.12.5([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])next-themes:specifier: 0.4.6nuqs:specifier: 2.8.5- version: 2.8.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 2.8.5([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])react:specifier: 19.2.3version: 19.2.3@@ -846,7 +852,7 @@ importers:version: 0.15.15'@openpanel/nextjs':specifier: 1.2.0- version: 1.2.0([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 1.2.0([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])'@openstatus/analytics':specifier: workspace:*version: link:../../packages/analytics@@ -918,7 +924,7 @@ importers:version: link:../../packages/utils'@sentry/nextjs':specifier: 10.31.0- version: 10.31.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))+ version: 10.31.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))'@stripe/stripe-js':specifier: 2.1.6version: 2.1.6@@ -945,7 +951,7 @@ importers:'@trpc/next':specifier: 11.4.4- version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])+ version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])'@trpc/react-query':specifier: 11.4.4version: 11.4.4(@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -996,19 +1002,19 @@ importers:version: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: 5.0.0-beta.29- version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])next-mdx-remote:specifier: 6.0.0version: 6.0.0(@types/[email protected])([email protected])next-plausible:specifier: 3.12.5- version: 3.12.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 3.12.5([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])next-themes:specifier: 0.4.6nuqs:specifier: 2.8.5- version: 2.8.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 2.8.5([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])random-word-slugs:specifier: 0.1.7version: 0.1.7@@ -1217,7 +1223,7 @@ importers:version: link:../../packages/tsconfig'@types/bun':specifier: latest- version: 1.3.12+ version: 1.3.13typescript:specifier: 5.9.3version: 5.9.3@@ -1443,7 +1449,7 @@ importers:version: 0.31.4next-auth:specifier: 5.0.0-beta.29- version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])typescript:specifier: 5.9.3version: 5.9.3@@ -2118,7 +2124,7 @@ importers:devDependencies:'@types/bun':specifier: latest- version: 1.3.12+ version: 1.3.13packages/subscriptions:dependencies:@@ -2143,7 +2149,7 @@ importers:version: link:../tsconfig'@types/bun':specifier: latest- version: 1.3.12+ version: 1.3.13typescript:specifier: 5.9.3version: 5.9.3@@ -2262,6 +2268,9 @@ importers:'@radix-ui/react-radio-group':specifier: 1.3.7version: 1.3.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-scroll-area':+ specifier: 1.2.10+ version: 1.2.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@radix-ui/react-select':specifier: 2.2.5version: 2.2.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -2447,6 +2456,12 @@ packages:resolution: {integrity: sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==}engines: {node: '>=18'}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-9nTW9tteFB7F6x2WzT4nK45atNphFDChlfMu9OJy0WAMzEAswwvE1dfWGqFH2bGs8Q+mdWBATMxqDvfvHcGnxQ==}+ engines: {node: '>=18'}+ peerDependencies:+ react: ^18 || ~19.0.1 || ~19.1.2 || ^19.2.1+'@alloc/[email protected]':resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}engines: {node: '>=10'}@@ -7367,9 +7382,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-SQFof9H+LXeWNz8wDe7oN5zu7ket0qwMu5vZubW4GCJ8Kkeh6nBWUz87+KTz/G3Kqsrp0j/W253XJb3KMEeg3w==}- '@types/[email protected]':- resolution: {integrity: sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A==}-'@types/[email protected]':resolution: {integrity: sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw==}@@ -7981,9 +7993,6 @@ packages:peerDependencies:'@types/react': ^19- resolution: {integrity: sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA==}-resolution: {integrity: sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA==}@@ -11819,6 +11828,10 @@ packages:resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}+ resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}@@ -12765,6 +12778,16 @@ snapshots:dependencies:json-schema: 0.4.0+ dependencies:+ '@ai-sdk/provider-utils': 4.0.15([email protected])+ ai: 6.0.94([email protected])+ react: 19.2.3+ swr: 2.3.6([email protected])+ throttleit: 2.1.0+ transitivePeerDependencies:+ - zod+'@alloc/[email protected]': {}'@ampproject/[email protected]':@@ -14983,7 +15006,7 @@ snapshots:'@openpanel/web': 1.0.1astro: 5.16.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@openpanel/[email protected]([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':+ '@openpanel/[email protected]([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@openpanel/web': 1.1.0next: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -17320,7 +17343,7 @@ snapshots:'@sentry/types': 8.9.2'@sentry/utils': 8.9.2- '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))':+ '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))':dependencies:'@opentelemetry/api': 1.9.0'@opentelemetry/semantic-conventions': 1.38.0@@ -18100,7 +18123,7 @@ snapshots:'@trpc/server': 11.4.4([email protected])typescript: 5.9.3- '@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])':+ '@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected](@tanstack/[email protected]([email protected]))(@trpc/[email protected](@trpc/[email protected]([email protected]))([email protected]))(@trpc/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@trpc/[email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])':dependencies:'@trpc/server': 11.4.4([email protected])@@ -18217,10 +18240,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]':- dependencies:- bun-types: 1.3.12-'@types/[email protected]':dependencies:bun-types: 1.3.13@@ -18999,10 +19018,6 @@ snapshots:'@types/node': 24.0.8'@types/react': 19.2.2- dependencies:- '@types/node': 24.0.8-dependencies:'@types/node': 24.0.8@@ -21777,7 +21792,7 @@ snapshots:- [email protected]([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]):+ [email protected]([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]):dependencies:'@auth/core': 0.40.0next: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -21816,7 +21831,7 @@ snapshots:- '@types/react'- supports-color- [email protected]([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):+ [email protected]([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:next: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])react: 19.2.3@@ -21938,7 +21953,7 @@ snapshots:dependencies:boolbase: 1.0.0- [email protected]([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]):+ [email protected]([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]):dependencies:'@standard-schema/spec': 1.0.0react: 19.2.3@@ -23767,6 +23782,8 @@ snapshots:dependencies:any-promise: 1.3.0+ [email protected]: {}+