A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
feat: add AI agent workspace (#3062)
Amruth Pillai6d8d8f6e559d
diff --git a/.env.example b/.env.exampleindex afc3508e6..397f821ae 100644--- a/.env.example+++ b/.env.example@@ -77,6 +77,15 @@ S3_ENDPOINT="http://localhost:8333"S3_BUCKET="reactive-resume"S3_FORCE_PATH_STYLE="true"+# --- AI Agent Workspace (optional) ---+# Required only for the authenticated /agent workspace and saved AI providers.+REDIS_URL="redis://localhost:6379"+ENCRYPTION_SECRET="change-me-to-a-secure-agent-secret-in-production"++# Optional Cloudflare Browser Run credentials used as a URL extraction fallback for agent web access.+CLOUDFLARE_ACCOUNT_ID=""+CLOUDFLARE_API_TOKEN=""+# --- Feature Flags ---# This flag disables new signups, both on the web app and the server.FLAG_DISABLE_SIGNUPS="false"diff --git a/DESIGN.md b/DESIGN.mdnew file mode 100644index 000000000..b68e244bd--- /dev/null+++ b/DESIGN.md@@ -0,0 +1,347 @@+---+version: alpha+name: Reactive Resume+description: A monochrome, content-first design system for a free and open-source resume builder. Dark-by-default with light mode support.+colors:+ primary: "#343434"+ primary-foreground: "#FBFBFB"+ secondary: "#F7F7F7"+ secondary-foreground: "#343434"+ background: "#FFFFFF"+ foreground: "#252525"+ muted: "#F7F7F7"+ muted-foreground: "#8E8E8E"+ card: "#FFFFFF"+ card-foreground: "#252525"+ border: "#EBEBEB"+ input: "#EBEBEB"+ ring: "#B5B5B5"+ destructive: "#DC2626"+ on-destructive: "#FFFFFF"+typography:+ heading:+ fontFamily: IBM Plex Sans Variable+ fontSize: 1rem+ fontWeight: 500+ body:+ fontFamily: IBM Plex Sans Variable+ fontSize: 0.875rem+ fontWeight: 400+ body-sm:+ fontFamily: IBM Plex Sans Variable+ fontSize: 0.75rem+ fontWeight: 400+ label:+ fontFamily: IBM Plex Sans Variable+ fontSize: 0.8rem+ fontWeight: 500+ hero-heading:+ fontFamily: IBM Plex Sans Variable+ fontSize: 3.75rem+ fontWeight: 700+ letterSpacing: -0.025em+rounded:+ sm: 0.18rem+ md: 0.24rem+ lg: 0.3rem+ xl: 0.42rem+ 2xl: 0.54rem+ 3xl: 0.66rem+ 4xl: 0.78rem+spacing:+ xs: 4px+ sm: 8px+ md: 16px+ lg: 24px+ xl: 32px+ 2xl: 48px+components:+ button-default:+ backgroundColor: "{colors.primary}"+ textColor: "{colors.primary-foreground}"+ rounded: "{rounded.lg}"+ padding: 10px+ height: 36px+ button-outline:+ backgroundColor: "{colors.background}"+ textColor: "{colors.foreground}"+ rounded: "{rounded.lg}"+ padding: 10px+ height: 36px+ button-secondary:+ backgroundColor: "{colors.secondary}"+ textColor: "{colors.secondary-foreground}"+ rounded: "{rounded.lg}"+ padding: 10px+ height: 36px+ button-ghost:+ backgroundColor: "{colors.background}"+ textColor: "{colors.foreground}"+ rounded: "{rounded.lg}"+ padding: 10px+ height: 36px+ button-destructive:+ backgroundColor: "{colors.destructive}"+ textColor: "{colors.on-destructive}"+ rounded: "{rounded.lg}"+ padding: 10px+ height: 36px+ card:+ backgroundColor: "{colors.card}"+ textColor: "{colors.card-foreground}"+ rounded: "{rounded.lg}"+ padding: 16px+ input:+ backgroundColor: "{colors.background}"+ textColor: "{colors.foreground}"+ rounded: "{rounded.lg}"+ height: 36px+ padding: 10px+ input-focus:+ backgroundColor: "{colors.background}"+ textColor: "{colors.foreground}"+ rounded: "{rounded.lg}"+ height: 36px+ padding: 10px+ badge:+ backgroundColor: "{colors.primary}"+ textColor: "{colors.primary-foreground}"+ rounded: "{rounded.md}"+ padding: 4px+ popover:+ backgroundColor: "{colors.card}"+ textColor: "{colors.card-foreground}"+ rounded: "{rounded.xl}"+ padding: 4px+ sidebar:+ backgroundColor: "{colors.muted}"+ textColor: "{colors.foreground}"+ padding: 8px+ sidebar-item:+ backgroundColor: "{colors.muted}"+ textColor: "{colors.muted-foreground}"+ rounded: "{rounded.lg}"+ padding: 8px+ sidebar-item-active:+ backgroundColor: "{colors.primary}"+ textColor: "{colors.primary-foreground}"+ rounded: "{rounded.lg}"+ padding: 8px+ tooltip:+ backgroundColor: "{colors.primary}"+ textColor: "{colors.primary-foreground}"+ rounded: "{rounded.md}"+ padding: 6px+ separator:+ backgroundColor: "{colors.border}"+ height: 1px+ dialog:+ backgroundColor: "{colors.card}"+ textColor: "{colors.card-foreground}"+ rounded: "{rounded.xl}"+ padding: 24px+ input-invalid:+ backgroundColor: "{colors.background}"+ textColor: "{colors.destructive}"+ rounded: "{rounded.lg}"+ height: 36px+ padding: 10px+---++## Overview++Reactive Resume is a monochrome, content-first design system built for a resume builder used by tens of thousands of people worldwide. The visual identity prioritizes readability and unobtrusiveness — the user's resume content is always the hero, never the chrome around it.++The system defaults to dark mode with a warm near-black backdrop that makes the resume preview "float" as the visual anchor. Light mode is supported as a full alternative. The authenticated app shell (dashboard, builder, settings) uses an entirely achromatic grayscale palette — the sole chromatic exception is destructive red for dangerous actions. The landing page introduces subtle chromatic accents: blue-tinted spotlight gradients on the hero, a multicolor text-mask animation on hover, and social auth provider brand colors (Google blue, LinkedIn blue) on the login page.++The overall aesthetic is a professional tool UI: clean grid lines, subtle borders, generous whitespace, and typography that steps back to let the content shine. Think "VS Code meets Figma" — a productivity workspace, not a marketing site.++One deliberate counterpoint to the serious UI: all resume templates are named after Pokemon (Azurill, Bronzor, Chikorita, Ditgar, Gengar, Pikachu, etc.). This is an intentional brand choice — playful naming for templates injects personality into an otherwise utilitarian interface, making templates feel collectible and memorable rather than generic ("Template 1", "Modern", "Classic").++## Colors++The palette is rooted in achromatic OKLch values (chroma = 0), producing a pure grayscale scale without warm or cool casts. Colors are defined as CSS custom properties using `oklch()` and consumed through Tailwind CSS 4 theme tokens. Always prefer CSS variables (e.g., `var(--primary)`) or Tailwind tokens (e.g., `bg-primary`) over raw color values. The hex values in this document's YAML front matter are agent-friendly approximations of the canonical OKLch definitions in `packages/ui/src/styles/globals.css` — use hex only where OKLch is unavailable.++- **Primary (#343434 light / #EBEBEB dark):** Used for high-emphasis interactive surfaces — default buttons, selected states, and text selection. In dark mode this inverts to near-white so buttons remain prominent.+- **Foreground (#252525 light / #FBFBFB dark):** Body text and headings. High contrast against the background in both themes.+- **Background (#FFFFFF light / #252525 dark):** The canvas. Pure white in light mode, warm near-black in dark mode.+- **Card (#FFFFFF light / #343434 dark):** Elevated surface for cards, panels, and the builder sidebar. In dark mode, one step lighter than the background to create subtle depth.+- **Muted (#F7F7F7 light / #454545 dark):** De-emphasized backgrounds for secondary UI regions, hover states, and inactive tabs.+- **Muted Foreground (#8E8E8E light / #B5B5B5 dark):** Captions, helper text, timestamps, and metadata. Deliberately low-contrast against the background to recede visually.+- **Border (#EBEBEB light / white at 10% opacity dark):** Thin separator lines. In dark mode, uses transparent white rather than a solid gray to blend naturally with any underlying surface color.+- **Input (#EBEBEB light / white at 15% opacity dark):** Form field borders, slightly more prominent than general borders to make input areas discoverable.+- **Destructive (#DC2626 light / #EF4444 dark):** The only chromatic color in the palette. Reserved exclusively for delete actions, error states, and danger-zone operations. Used at 10% opacity as a background tint with full saturation for text, creating a soft but unmistakable warning.+- **Ring (#B5B5B5 light / #8E8E8E dark):** Focus ring indicator at 50% opacity, surrounding focused interactive elements.+- **Sidebar Primary (dark only, #6366F1):** An indigo value inherited from the shadcn/ui defaults. Not actively used in the current UI — sidebar active states use the standard grayscale primary token instead. Retained in the CSS custom properties for potential future customization.++Resume templates have their own independent color system — users pick primary, text, and background colors per resume through a color picker in the builder's Design panel. These template colors are completely separate from the app shell palette.++## Typography++The entire application uses a single typeface: **IBM Plex Sans Variable**. This is a humanist sans-serif with an extensive weight range (100–900) and excellent readability at small sizes, both on screen and in PDFs.++- **Hero heading (responsive: 2.25rem mobile / 3rem tablet / 3.75rem desktop, weight 700, tracking-tight):** Landing page headline only. Large, bold, and commanding. Scales across three breakpoints.+- **Section heading (1rem / 16px, weight 500):** Used for section titles in the builder sidebar, settings panels, and dashboard cards. Medium weight provides hierarchy without shouting.+- **Body (0.875rem / 14px, weight 400):** The workhorse. All form labels, descriptions, card content, and general UI text.+- **Small body (0.75rem / 12px, weight 400):** Captions, helper text, timestamps, and metadata.+- **Label (0.8rem / ~13px, weight 500):** Button text, badge labels, and form field labels. Slightly heavier than body to denote interactivity.++The resume content itself uses a separate font system — users choose from 1,000+ Google Fonts for their resume headings and body text, with category-aware fallback stacks including CJK support (Noto Sans SC, PingFang SC, Hiragino Sans GB for sans-serif; Noto Serif SC, Songti SC for serif). Standard PDF fonts (Helvetica, Courier, Times-Roman) are available as offline fallbacks.++Font rendering uses `antialiased` (grayscale AA) and `proportional-nums` across the board for clean rendering and properly spaced numerals in dates and phone numbers.++## Layout++### Builder (Three-Panel Workspace)++The core builder uses a resizable three-panel layout powered by `react-resizable-panels`:++- **Left sidebar (default 22%):** Resume section forms — personal info, experience, education, skills, and custom sections. Scrollable with collapsible section groups.+- **Center artboard (default 56%):** Live resume preview rendered via PDF.js canvas. Supports zoom, pan, and pinch gestures via `react-zoom-pan-pinch`. The preview maintains A4 aspect ratio (210:297) with a subtle shadow to simulate a physical page.+- **Right sidebar (default 22%):** Design controls — template picker, font selection, color picker, layout manager (page assignments, section ordering via drag-and-drop).++Panel sizes persist in cookies. On mobile (< 768px), sidebars collapse to 0% width and become toggleable overlays (max 95% width when open). The desktop minimum collapsed width is 48px (icon rail).++### Dashboard++Standard sidebar navigation layout using the `Sidebar` component system. The sidebar contains: logo, resume list link, agent link, settings subnavigation (profile, preferences, authentication, API keys, integrations, danger zone), and a footer with user avatar. Content area shows a responsive grid of resume cards.++### Landing Page++Full-width single-column marketing layout:+1. **Floating builder preview** — A non-interactive screenshot of the builder as a hero visual, creating an immediate "this is what you get" impression.+2. **Hero** — Centered headline, subheadline, and two CTAs (primary "Get Started" with arrow, ghost "Learn More" with icon).+3. **Features grid** — 4-column responsive grid with icon + title + description cards, separated by thin border lines.+4. **Template carousel** — Horizontally scrolling row of template preview thumbnails with Pokemon-themed names.+5. **Testimonials** — Tiled user quotes in a masonry-style grid.+6. **Support / FAQ / Footer** — Accordion FAQ, community section, and a 4-column footer with logo, resource links, community links, and license info.++### Responsive Breakpoints++Mobile detection uses a 768px threshold via `MediaQueryList`. The layout is optimized for workspace productivity on larger screens, with responsive mobile support that adapts the multi-panel builder into a streamlined single-panel experience. Both desktop and mobile are supported experiences — the builder's three-panel layout leverages desktop space, while mobile surfaces the same editing capabilities through collapsible overlays.++### Page Aspect Ratio++A custom Tailwind token `--aspect-page: 210 / 297` enforces A4 paper proportions wherever resume pages are rendered (builder preview, public view, PDF export).++## Animation++Animations use the Motion library (formerly Framer Motion) and follow a consistent choreography pattern:++**Entrance animations** use a fade-up reveal: elements start at `opacity: 0, y: 20-100` and animate to `opacity: 1, y: 0`. The hero section uses a larger y-offset (100px) for dramatic effect; subsequent sections use 20px for subtlety.++**Timing principles:**+- **Base duration:** 0.35s–0.6s for standard section reveals, 0.45s for hero elements, up to 1.1s for the hero video entrance.+- **Stagger pattern:** Sequential delays within a group, typically 0.1s–0.15s apart (hero: 0.55s, 0.7s, 0.82s, 0.95s). For grids, use `index * 0.03`–`0.1` for per-item stagger.+- **Easing:** `easeOut` for entrances (elements decelerate into position). `easeInOut` for looping/ambient animations.+- **Performance:** Apply `will-change-[transform,opacity]` on animated elements and `will-change-transform` on continuously animated elements.++**Hover/interaction animations** are quick (0.2s) and subtle — small scale bumps (`scale: 1.01`), slight y-offsets (`y: -2`), and `active:translate-y-px` for button press.++**Ambient animations** loop infinitely with `easeInOut` — the scroll indicator bounces gently (`y: [0, 5, 0]` over 1.5s).++**Reduced motion:** All CSS transitions and animations collapse to `0.01ms` duration and single iteration when `prefers-reduced-motion: reduce` is active. Motion library animations should also respect this preference.++## Elevation & Depth++Elevation is handled through background color layering rather than drop shadows:++- **Level 0 — Background:** The base canvas (`--background`).+- **Level 1 — Card:** One step lighter in dark mode (`--card`), used for sidebars, panels, and cards.+- **Level 2 — Popover:** Same as card, but appears above the content layer in popovers, dropdowns, and command palette.+- **Level 3 — Overlay:** Backdrop blur (`backdrop-blur-xs` at 0.5px or `backdrop-blur-2xl` at 40px) with `backdrop-saturate-150` for modal overlays, creating a frosted-glass effect over the workspace.++The resume preview page uses a subtle drop shadow to simulate a physical sheet of paper floating above the dark artboard — one of the few places actual shadows appear.++## Shapes++Border radius follows a multiplicative scale from a single `--radius` base of `0.3rem`:++| Token | Value | Usage |+|:------|:------|:------|+| `sm` | 0.18rem (≈3px) | Small badges, inline chips |+| `md` | 0.24rem (≈4px) | XS/SM buttons, compact elements |+| `lg` | 0.3rem (≈5px) | Default buttons, cards, inputs |+| `xl` | 0.42rem (≈7px) | Larger cards, modal corners |+| `2xl` | 0.54rem (≈9px) | Dialog containers |+| `3xl` | 0.66rem (≈11px) | Large panels |+| `4xl` | 0.78rem (≈12px) | Full-page modals |++The radius scale is deliberately tight — the largest value (0.78rem) is still quite subtle. This avoids the "rounded everything" aesthetic and keeps the UI feeling precise and tool-like. Interactive elements consistently use `rounded-lg` as the default.++## Components++### Buttons++Six variants, all sharing `rounded-lg` corners, `font-medium`, `text-sm`, and a 1px `translate-y` on active press (except when the button opens a popup):++- **Default:** Solid primary background. The highest-emphasis action on any screen.+- **Outline:** Transparent with a border. For secondary actions that need clear boundaries.+- **Secondary:** Muted background. For paired actions alongside a primary button.+- **Ghost:** No background or border. For toolbar actions and inline controls where chrome would be noise.+- **Destructive:** Red at 10% opacity background with red text. Visually alarming without being garish.+- **Link:** Underline-on-hover text. For inline navigation within prose.++Size scale: `xs` (28px), `sm` (32px), `default` (36px), `lg` (40px), plus `icon` variants at each size for square icon-only buttons.++### Cards++White/dark surface with foreground text. Composed of `CardHeader`, `CardTitle`, `CardDescription`, `CardContent`, `CardFooter`, and `CardAction` slots. Default vertical padding is `py-4` (compact: `py-3`).++### Forms++Built on TanStack Form with Zod validation. Composed of `FormItem`, `FormLabel`, `FormControl`, `FormMessage`, and `FormDescription`. Validation errors only appear after field touch. Invalid fields get a red destructive border with a ring.++### Dialogs++Centralized dialog manager with 40+ dialog types, all rendered via pattern matching (`ts-pattern`). Dialogs support before-close validation, form blocking for unsaved changes, and confirmation prompts. Used for all CRUD operations on resume sections, settings changes, and import/export flows.++### Command Palette++Triggered by `Cmd+K` / `Ctrl+K`. Built on `cmdk` with fuzzy search via `Fuse.js`. Multi-page navigation (resumes, settings, preferences) with back navigation via Backspace. Screen-reader accessible with `sr-only` headings.++### Toast Notifications++Powered by Sonner, positioned bottom-right with rich colors. Used for auto-save feedback, form submission status, error reporting, and donation prompts. Loading toasts are used during async operations (PDF generation, resume creation) with dismiss-on-complete.++### Drag and Drop++Powered by `@dnd-kit` with `PointerSensor` and `KeyboardSensor`. Used in chip inputs (skill tags, URL lists) and page layout management (section ordering across resume pages). Smooth animations via Motion library.++## Internationalization++The app supports 40+ locales including RTL languages (Arabic, Hebrew, Persian, Urdu, Uyghur, Yiddish). i18n is not an afterthought — it shapes layout decisions:++**Direction:** The `<html>` element receives `dir="rtl"` or `dir="ltr"` based on the active locale, detected via `isRTL()` which checks the language prefix against a known RTL set. All layout mirroring flows from this single attribute.++**Logical properties:** Use CSS logical properties (`ps-`, `pe-`, `ms-`, `me-`, `inline-start`, `inline-end`, `inset-s-`, `inset-e-`) instead of physical (`pl-`, `pr-`, `ml-`, `mr-`, `left`, `right`). Button components already use `has-data-[icon=inline-start]:ps-2` and `has-data-[icon=inline-end]:pe-2` patterns. This ensures correct spacing in both LTR and RTL layouts without separate stylesheets.++**Variable-length text:** Translations can be 30–50% longer than English (German, Finnish) or significantly shorter (CJK). UI elements should accommodate variable text length — avoid fixed widths on buttons and labels. Use `whitespace-nowrap` only where truncation is acceptable, and prefer `min-w-0` with `truncate` over fixed-width containers.++**Icons:** Directional icons (arrows, chevrons, progress indicators) should mirror in RTL contexts. Phosphor Icons provides mirrored variants for directional icons. Non-directional icons (settings gear, checkmark, delete) do not mirror.++**Strings:** All user-facing strings use Lingui macros (`t`, `msg`, `<Trans>`) — never hardcode English text in components. Translation files are `.po` format under `/locale/`.++## Do's and Don'ts++### Do++- **Use the grayscale palette for all app chrome.** The absence of color is the brand. The resume content is the only thing that should be colorful.+- **Default to dark mode.** The dark workspace makes resume previews pop and reduces eye strain during extended editing sessions.+- **Use `text-sm` (14px) as the base text size.** The UI is information-dense — form fields, section labels, metadata — and needs to be scannable without feeling cramped.+- **Keep border radius tight.** Use `rounded-lg` (0.3rem) as the default. The tool should feel precise, not playful.+- **Respect reduced motion preferences.** All animations collapse to 0.01ms when `prefers-reduced-motion: reduce` is active.+- **Use Phosphor Icons consistently.** Regular weight, `size-4` (16px) default. Icons should be functional labels, not decorative.+- **Maintain the three-panel builder proportions.** The center artboard should always dominate. Sidebars are support panels, not equal peers.+- **Use transparent-white borders in dark mode.** `oklch(1 0 0 / 10%)` blends naturally with any surface rather than introducing a distinct gray band.++### Don't++- **Don't introduce accent colors into the app shell.** No blues, greens, or purples for primary actions. The only chromatic color is destructive red. The inherited indigo sidebar-primary token exists in CSS custom properties but is not actively used.+- **Don't use drop shadows for elevation.** Rely on background color layering and border separation. The one exception is the resume page preview shadow.+- **Don't make the UI compete with the resume content.** If a new feature draws more visual attention than the resume preview, it needs to be toned down.+- **Don't use large border radii.** Nothing above `rounded-xl` on standard components. Large pills and full-round shapes conflict with the precision-tool aesthetic.+- **Don't hardcode colors outside the token system.** All colors flow through CSS custom properties so that dark/light mode switching works automatically.+- **Don't use multiple typefaces in the app shell.** IBM Plex Sans Variable is the only UI font. Resume templates have their own font system, but the chrome stays single-family.+- **Don't skip the `data-slot` attribute on components.** It's used for styling hooks and accessibility selectors throughout the component library.+- **Don't forget RTL.** The app supports 40+ locales including Arabic, Hebrew, Persian, and Urdu. Use logical properties (`ps`, `pe`, `ms`, `me`) instead of physical (`pl`, `pr`, `ml`, `mr`).diff --git a/Dockerfile.dev b/Dockerfile.devindex 43bcc8241..d9b3e696e 100644--- a/Dockerfile.dev+++ b/Dockerfile.dev@@ -39,4 +39,4 @@ COPY . .EXPOSE 3000/tcp-CMD ["pnpm", "dev"]+CMD ["pnpm", "run", "dev:web"]diff --git a/apps/web/package.json b/apps/web/package.jsonindex fc2f8ae5d..b5411c868 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -16,7 +16,7 @@"lingui:extract": "lingui extract --clean --overwrite"},"dependencies": {- "@ai-sdk/react": "^3.0.182",+ "@ai-sdk/react": "^3.0.184","@base-ui/react": "^1.4.1","@better-auth/api-key": "^1.6.11","@better-auth/infra": "^0.2.8",@@ -54,17 +54,18 @@"@tanstack/react-router": "^1.169.2","@tanstack/react-router-ssr-query": "^1.166.12","@tanstack/react-start": "^1.167.65",- "@tiptap/extension-color": "^3.23.2",- "@tiptap/extension-highlight": "^3.23.2",- "@tiptap/extension-table": "^3.23.2",- "@tiptap/extension-text-align": "^3.23.2",- "@tiptap/extension-text-style": "^3.23.2",- "@tiptap/pm": "^3.23.2",- "@tiptap/react": "^3.23.2",- "@tiptap/starter-kit": "^3.23.2",+ "@tiptap/extension-color": "^3.23.4",+ "@tiptap/extension-highlight": "^3.23.4",+ "@tiptap/extension-table": "^3.23.4",+ "@tiptap/extension-text-align": "^3.23.4",+ "@tiptap/extension-text-style": "^3.23.4",+ "@tiptap/pm": "^3.23.4",+ "@tiptap/react": "^3.23.4",+ "@tiptap/starter-kit": "^3.23.4","@types/js-cookie": "^3.0.6","@uiw/color-convert": "^2.10.1","@uiw/react-color-colorful": "^2.10.1",+ "ai": "^6.0.182","better-auth": "1.6.11","cmdk": "^1.1.1","drizzle-orm": "1.0.0-rc.2",@@ -78,6 +79,7 @@"qrcode.react": "^4.2.0","react": "^19.2.6","react-dom": "^19.2.6",+ "react-markdown": "^10.1.0","react-resizable-panels": "^4.11.1","react-window": "^2.2.7","react-zoom-pan-pinch": "^4.0.3",diff --git a/apps/web/src/components/command-palette/pages/navigation.tsx b/apps/web/src/components/command-palette/pages/navigation.tsxindex f775f13dc..c31b3b04b 100644--- a/apps/web/src/components/command-palette/pages/navigation.tsx+++ b/apps/web/src/components/command-palette/pages/navigation.tsx@@ -1,6 +1,7 @@import { t } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";import {+ ChatCircleDotsIcon,GearIcon,HouseSimpleIcon,KeyIcon,@@ -44,6 +45,16 @@ export function NavigationCommandGroup() {<Trans>Resumes</Trans></CommandItem>+ <CommandItem+ disabled={!session}+ keywords={[t`Agent`, t`Artificial Intelligence`]}+ value="navigation.agent"+ onSelect={() => onNavigate("/agent")}+ >+ <ChatCircleDotsIcon />+ <Trans>Agent</Trans>+ </CommandItem>+<CommandItemdisabled={!session}keywords={[t`Settings`]}diff --git a/apps/web/src/components/resume/builder-resume-draft.ts b/apps/web/src/components/resume/builder-resume-draft.tsindex 77f4569b0..b580994b1 100644--- a/apps/web/src/components/resume/builder-resume-draft.ts+++ b/apps/web/src/components/resume/builder-resume-draft.ts@@ -280,20 +280,6 @@ export function usePatchResume() {return useResumeStore((state) => state.patchResume);}-export function useReplaceResumeFromServer() {- const queryClient = useQueryClient();- const replaceResumeFromServer = useResumeStore((state) => state.replaceResumeFromServer);-- return useCallback(- (resume: Resume) => {- bindRuntimeQueryClient(resume.id, queryClient);- queryClient.setQueryData(getResumeQueryKey(resume.id), resume);- replaceResumeFromServer(resume);- },- [queryClient, replaceResumeFromServer],- );-}-function useBuilderResumeSelector<T>(selector: (resume: Resume) => T): T | undefined {const params = useParams({ strict: false }) as { resumeId?: string };const resumeId = params.resumeId;diff --git a/apps/web/src/components/resume/preview.browser.test.tsx b/apps/web/src/components/resume/preview.browser.test.tsxindex d2d87eed5..05c433b7b 100644--- a/apps/web/src/components/resume/preview.browser.test.tsx+++ b/apps/web/src/components/resume/preview.browser.test.tsx@@ -93,20 +93,14 @@ describe("ResumePreviewClient", () => {previewMock.builderResumeData = resumeDataWithPageCount(3);previewMock.toBlob.mockImplementation(() => new Promise<Blob>(() => {}));- render(<ResumePreviewClient pageGap="1rem" pageLayout="vertical" pageScale={1.25} showPageNumbers={false} />);+ render(<ResumePreviewClient pageGap={16} pageLayout="vertical" pageScale={1.25} showPageNumbers={false} />);expect(screen.getAllByRole("img", { name: /Loading resume page/ })).toHaveLength(3);});it("renders from explicit resume data when no builder resume is active", async () => {render(- <ResumePreviewClient- data={sampleResumeData}- pageGap="1rem"- pageLayout="vertical"- pageScale={1.25}- showPageNumbers={false}- />,+ <ResumePreviewClient data={sampleResumeData} pageLayout="vertical" pageScale={1.25} showPageNumbers={false} />,);expect(await screen.findByRole("img", { name: "Resume page 1 of 1" })).toBeTruthy();diff --git a/apps/web/src/components/resume/preview.browser.tsx b/apps/web/src/components/resume/preview.browser.tsxindex 64261d7dc..ec4a3cfa1 100644--- a/apps/web/src/components/resume/preview.browser.tsx+++ b/apps/web/src/components/resume/preview.browser.tsx@@ -1,3 +1,4 @@+import type { CSSProperties } from "react";import type { PreviewPageSize, ResolvedResumePreviewProps } from "./preview.shared";import { pdf } from "@react-pdf/renderer";import { AnimatePresence, motion } from "motion/react";@@ -6,7 +7,7 @@ import { cn } from "@reactive-resume/utils/style";import { useLocalizedResumeDocument } from "@/libs/resume/pdf-document";import { useResumeData } from "./builder-resume-draft";import { PdfCanvasDocument, PdfCanvasPage } from "./pdf-canvas";-import { getResumePreviewPageCount, ResumePreviewLoader } from "./preview.shared";+import { getResumePreviewGapValue, getResumePreviewPageCount, ResumePreviewLoader } from "./preview.shared";type PreviewPdf = {file: Blob;@@ -84,7 +85,7 @@ const removePreviewLayer = (layers: PreviewPdf[], layerId: number) => layers.filexport function ResumePreviewClient({className,data,- pageGap,+ pageGap = 16,pageLayout,pageScale,pageClassName,@@ -133,6 +134,7 @@ export function ResumePreviewClient({if (!resumeData) return null;const visiblePdf = getActivePreviewLayer(previewLayers);+ const resolvedPageGap = getResumePreviewGapValue(pageGap);if (!visiblePdf) {return (@@ -154,8 +156,8 @@ export function ResumePreviewClient({<motion.divkey={visiblePdf.id}aria-hidden={visiblePdf.phase !== "active"}+ style={{ "--resume-preview-page-gap": resolvedPageGap } as CSSProperties}className={cn("col-start-1 row-start-1", visiblePdf.phase !== "active" && "pointer-events-none")}- style={{ "--resume-preview-page-gap": pageGap } as React.CSSProperties}initial={{ opacity: visiblePdf.phase === "active" ? 1 : 0 }}animate={{ opacity: visiblePdf.phase === "active" ? 1 : 0 }}exit={{ opacity: 0 }}diff --git a/apps/web/src/components/resume/preview.shared.helpers.test.ts b/apps/web/src/components/resume/preview.shared.helpers.test.tsindex 78c62b681..ec57e9f0d 100644--- a/apps/web/src/components/resume/preview.shared.helpers.test.ts+++ b/apps/web/src/components/resume/preview.shared.helpers.test.ts@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";import {DEFAULT_PDF_PAGE_SIZE,getPreviewCanvasScale,+ getResumePreviewGapValue,getScaledPreviewPageSize,normalizeResumePreviewProps,} from "./preview.shared";@@ -12,7 +13,7 @@ describe("normalizeResumePreviewProps", () => {it("applies the documented defaults when fields are omitted", () => {const result = normalizeResumePreviewProps({});expect(result).toMatchObject({- pageGap: 40,+ pageGap: 16,pageLayout: "horizontal",pageScale: 1,showPageNumbers: false,@@ -52,6 +53,20 @@ describe("getScaledPreviewPageSize", () => {});});+describe("getResumePreviewGapValue", () => {+ it("adds px units for numeric custom-property gap values", () => {+ expect(getResumePreviewGapValue(96)).toBe("96px");+ });++ it("preserves explicit zero gap", () => {+ expect(getResumePreviewGapValue(0)).toBe(0);+ });++ it("preserves string gap values", () => {+ expect(getResumePreviewGapValue("1rem")).toBe("1rem");+ });+});+const setDevicePixelRatio = (value: number) => {Object.defineProperty(window, "devicePixelRatio", {writable: true,diff --git a/apps/web/src/components/resume/preview.shared.test.tsx b/apps/web/src/components/resume/preview.shared.test.tsxindex c59ac1909..00c18bf3a 100644--- a/apps/web/src/components/resume/preview.shared.test.tsx+++ b/apps/web/src/components/resume/preview.shared.test.tsx@@ -29,6 +29,14 @@ describe("ResumePreviewLoader", () => {expect(screen.getAllByRole("img", { name: /Loading resume page/ })).toHaveLength(pageCount);});++ it("writes numeric page gaps as valid CSS custom-property lengths", () => {+ const { container } = render(<ResumePreviewLoader pageGap={96} />);++ expect((container.firstElementChild as HTMLElement).style.getPropertyValue("--resume-preview-page-gap")).toBe(+ "96px",+ );+ });});describe("getResumePreviewPageCount", () => {diff --git a/apps/web/src/components/resume/preview.shared.tsx b/apps/web/src/components/resume/preview.shared.tsxindex 892b3f187..680037633 100644--- a/apps/web/src/components/resume/preview.shared.tsx+++ b/apps/web/src/components/resume/preview.shared.tsx@@ -1,11 +1,12 @@import type { ResumeData } from "@reactive-resume/schema/resume/data";+import type { CSSProperties } from "react";import { Spinner } from "@reactive-resume/ui/components/spinner";import { cn } from "@reactive-resume/utils/style";export type ResumePreviewProps = {className?: string;data?: ResumeData;- pageGap?: React.CSSProperties["gap"];+ pageGap?: CSSProperties["gap"];pageLayout?: "horizontal" | "vertical";pageScale?: number;pageClassName?: string;@@ -13,7 +14,6 @@ export type ResumePreviewProps = {};export type ResolvedResumePreviewProps = ResumePreviewProps & {- pageGap: React.CSSProperties["gap"];pageLayout: "horizontal" | "vertical";pageScale: number;showPageNumbers: boolean;@@ -26,7 +26,7 @@ export type PreviewPageSize = {type ResumePreviewLoaderProps = Pick<ResumePreviewProps, "pageClassName" | "showPageNumbers"> & {pageCount?: number;- pageGap?: React.CSSProperties["gap"];+ pageGap?: CSSProperties["gap"];pageLayout?: "horizontal" | "vertical";pageScale?: number;};@@ -39,7 +39,7 @@ export const DEFAULT_PDF_PAGE_SIZE: PreviewPageSize = {};export const normalizeResumePreviewProps = ({- pageGap = 40,+ pageGap = 16,pageLayout = "horizontal",pageScale = 1,showPageNumbers = false,@@ -67,25 +67,29 @@ export const getScaledPreviewPageSize = (pageSize: PreviewPageSize, pageScale: nwidth: pageSize.width * pageScale,});+export const getResumePreviewGapValue = (pageGap: CSSProperties["gap"]) =>+ typeof pageGap === "number" && pageGap !== 0 ? `${pageGap}px` : pageGap;+export const getResumePreviewPageCount = (data?: ResumeData) => Math.max(1, data?.metadata.layout.pages.length ?? 1);export function ResumePreviewLoader({pageCount = 1,pageClassName,- pageGap = 40,+ pageGap = 16,pageLayout = "horizontal",pageScale = 1,showPageNumbers = false,}: ResumePreviewLoaderProps) {const pageSize = getScaledPreviewPageSize(DEFAULT_PDF_PAGE_SIZE, pageScale);+ const resolvedPageGap = getResumePreviewGapValue(pageGap);return (<div+ style={{ "--resume-preview-page-gap": resolvedPageGap } as CSSProperties}className={cn("flex justify-start gap-(--resume-preview-page-gap)",pageLayout === "horizontal" ? "flex-row items-start" : "flex-col items-center",)}- style={{ "--resume-preview-page-gap": pageGap } as React.CSSProperties}>{Array.from({ length: pageCount }, (_, index) => {const pageNumber = index + 1;diff --git a/apps/web/src/dialogs/resume/import.tsx b/apps/web/src/dialogs/resume/import.tsxindex 640dc99f5..c39f28d92 100644--- a/apps/web/src/dialogs/resume/import.tsx+++ b/apps/web/src/dialogs/resume/import.tsx@@ -4,12 +4,11 @@ import { t } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";import { DownloadSimpleIcon, FileIcon, UploadSimpleIcon } from "@phosphor-icons/react";import { useStore } from "@tanstack/react-form";-import { useMutation } from "@tanstack/react-query";+import { useMutation, useQuery } from "@tanstack/react-query";import { useNavigate } from "@tanstack/react-router";import { useEffect, useRef, useState } from "react";import { toast } from "sonner";import z from "zod";-import { useAIStore } from "@reactive-resume/ai/store";import { JSONResumeImporter } from "@reactive-resume/import/json-resume";import { ReactiveResumeJSONImporter } from "@reactive-resume/import/reactive-resume-json";import { ReactiveResumeV4JSONImporter } from "@reactive-resume/import/reactive-resume-v4-json";@@ -91,7 +90,6 @@ function fileToBase64(file: File): Promise<string> {export function ImportResumeDialog(_: DialogProps<"resume.import">) {const navigate = useNavigate();- const { enabled: isAIEnabled, provider, model, apiKey, baseURL } = useAIStore();const closeDialog = useDialogStore((state) => state.closeDialog);const prevTypeRef = useRef<string>("");@@ -99,6 +97,8 @@ export function ImportResumeDialog(_: DialogProps<"resume.import">) {const [isLoading, setIsLoading] = useState<boolean>(false);const { mutateAsync: importResume } = useMutation(orpc.resume.import.mutationOptions());+ const { data: aiProviders, isLoading: isLoadingAiProviders } = useQuery(orpc.aiProviders.list.queryOptions());+ const hasAIProvider = aiProviders?.some((provider) => provider.enabled && provider.testStatus === "success") ?? false;const form = useAppForm({defaultValues: {@@ -137,23 +137,21 @@ export function ImportResumeDialog(_: DialogProps<"resume.import">) {}if (value.type === "pdf") {- if (!isAIEnabled)- throw new Error(t`This feature requires AI Integration to be enabled. Please enable it in the settings.`);+ if (isLoadingAiProviders) throw new Error(t`Loading AI providers. Please try again in a moment.`);+ if (!hasAIProvider)+ throw new Error(t`This feature requires a tested AI provider. Please add one in the settings.`);const base64 = await fileToBase64(value.file);data = await client.ai.parsePdf({- provider,- model,- apiKey,- baseURL,file: { name: value.file.name, data: base64 },});}if (value.type === "docx") {- if (!isAIEnabled)- throw new Error(t`This feature requires AI Integration to be enabled. Please enable it in the settings.`);+ if (isLoadingAiProviders) throw new Error(t`Loading AI providers. Please try again in a moment.`);+ if (!hasAIProvider)+ throw new Error(t`This feature requires a tested AI provider. Please add one in the settings.`);const base64 = await fileToBase64(value.file);@@ -163,10 +161,6 @@ export function ImportResumeDialog(_: DialogProps<"resume.import">) {: ("application/vnd.openxmlformats-officedocument.wordprocessingml.document" as const);data = await client.ai.parseDocx({- provider,- model,- apiKey,- baseURL,mediaType,file: { name: value.file.name, data: base64 },});diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 63d4e3725..af78714e1 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -12,10 +12,12 @@ import { Route as rootRouteImport } from './routes/__root'import { Route as SchemaDotjsonRouteImport } from './routes/schema[.]json'import { Route as DashboardRouteRouteImport } from './routes/dashboard/route'import { Route as AuthRouteRouteImport } from './routes/auth/route'+import { Route as AgentRouteRouteImport } from './routes/agent/route'import { Route as HomeRouteRouteImport } from './routes/_home/route'import { Route as McpIndexRouteImport } from './routes/mcp/index'import { Route as DashboardIndexRouteImport } from './routes/dashboard/index'import { Route as AuthIndexRouteImport } from './routes/auth/index'+import { Route as AgentIndexRouteImport } from './routes/agent/index'import { Route as HomeIndexRouteImport } from './routes/_home/index'import { Route as TemplatesSplatRouteImport } from './routes/templates/$'import { Route as AuthVerify2faBackupRouteImport } from './routes/auth/verify-2fa-backup'@@ -27,6 +29,8 @@ import { Route as AuthOauthRouteImport } from './routes/auth/oauth'import { Route as AuthLoginRouteImport } from './routes/auth/login'import { Route as AuthForgotPasswordRouteImport } from './routes/auth/forgot-password'import { Route as ApiHealthRouteImport } from './routes/api/health'+import { Route as AgentNewRouteImport } from './routes/agent/new'+import { Route as AgentThreadIdRouteImport } from './routes/agent/$threadId'import { Route as DotwellKnownOpenidConfigurationRouteImport } from './routes/[.]well-known/openid-configuration'import { Route as DotwellKnownOauthProtectedResourceRouteImport } from './routes/[.]well-known/oauth-protected-resource'import { Route as DotwellKnownOauthAuthorizationServerRouteImport } from './routes/[.]well-known/oauth-authorization-server'@@ -66,6 +70,11 @@ const AuthRouteRoute = AuthRouteRouteImport.update({path: '/auth',getParentRoute: () => rootRouteImport,} as any)+const AgentRouteRoute = AgentRouteRouteImport.update({+ id: '/agent',+ path: '/agent',+ getParentRoute: () => rootRouteImport,+} as any)const HomeRouteRoute = HomeRouteRouteImport.update({id: '/_home',getParentRoute: () => rootRouteImport,@@ -85,6 +94,11 @@ const AuthIndexRoute = AuthIndexRouteImport.update({path: '/',getParentRoute: () => AuthRouteRoute,} as any)+const AgentIndexRoute = AgentIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => AgentRouteRoute,+} as any)const HomeIndexRoute = HomeIndexRouteImport.update({id: '/',path: '/',@@ -140,6 +154,16 @@ const ApiHealthRoute = ApiHealthRouteImport.update({path: '/api/health',getParentRoute: () => rootRouteImport,} as any)+const AgentNewRoute = AgentNewRouteImport.update({+ id: '/new',+ path: '/new',+ getParentRoute: () => AgentRouteRoute,+} as any)+const AgentThreadIdRoute = AgentThreadIdRouteImport.update({+ id: '/$threadId',+ path: '/$threadId',+ getParentRoute: () => AgentRouteRoute,+} as any)const DotwellKnownOpenidConfigurationRoute =DotwellKnownOpenidConfigurationRouteImport.update({id: '/.well-known/openid-configuration',@@ -271,6 +295,7 @@ const ApiUploadsUserIdSplatRoute = ApiUploadsUserIdSplatRouteImport.update({export interface FileRoutesByFullPath {'/': typeof HomeIndexRoute+ '/agent': typeof AgentRouteRouteWithChildren'/auth': typeof AuthRouteRouteWithChildren'/dashboard': typeof DashboardRouteRouteWithChildren'/schema.json': typeof SchemaDotjsonRoute@@ -280,6 +305,8 @@ export interface FileRoutesByFullPath {'/.well-known/oauth-authorization-server': typeof DotwellKnownOauthAuthorizationServerRouteWithChildren'/.well-known/oauth-protected-resource': typeof DotwellKnownOauthProtectedResourceRouteWithChildren'/.well-known/openid-configuration': typeof DotwellKnownOpenidConfigurationRoute+ '/agent/$threadId': typeof AgentThreadIdRoute+ '/agent/new': typeof AgentNewRoute'/api/health': typeof ApiHealthRoute'/auth/forgot-password': typeof AuthForgotPasswordRoute'/auth/login': typeof AuthLoginRoute@@ -290,6 +317,7 @@ export interface FileRoutesByFullPath {'/auth/verify-2fa': typeof AuthVerify2faRoute'/auth/verify-2fa-backup': typeof AuthVerify2faBackupRoute'/templates/$': typeof TemplatesSplatRoute+ '/agent/': typeof AgentIndexRoute'/auth/': typeof AuthIndexRoute'/dashboard/': typeof DashboardIndexRoute'/mcp/': typeof McpIndexRoute@@ -318,6 +346,8 @@ export interface FileRoutesByTo {'/.well-known/oauth-authorization-server': typeof DotwellKnownOauthAuthorizationServerRouteWithChildren'/.well-known/oauth-protected-resource': typeof DotwellKnownOauthProtectedResourceRouteWithChildren'/.well-known/openid-configuration': typeof DotwellKnownOpenidConfigurationRoute+ '/agent/$threadId': typeof AgentThreadIdRoute+ '/agent/new': typeof AgentNewRoute'/api/health': typeof ApiHealthRoute'/auth/forgot-password': typeof AuthForgotPasswordRoute'/auth/login': typeof AuthLoginRoute@@ -329,6 +359,7 @@ export interface FileRoutesByTo {'/auth/verify-2fa-backup': typeof AuthVerify2faBackupRoute'/templates/$': typeof TemplatesSplatRoute'/': typeof HomeIndexRoute+ '/agent': typeof AgentIndexRoute'/auth': typeof AuthIndexRoute'/dashboard': typeof DashboardIndexRoute'/mcp': typeof McpIndexRoute@@ -353,6 +384,7 @@ export interface FileRoutesByTo {export interface FileRoutesById {__root__: typeof rootRouteImport'/_home': typeof HomeRouteRouteWithChildren+ '/agent': typeof AgentRouteRouteWithChildren'/auth': typeof AuthRouteRouteWithChildren'/dashboard': typeof DashboardRouteRouteWithChildren'/schema.json': typeof SchemaDotjsonRoute@@ -362,6 +394,8 @@ export interface FileRoutesById {'/.well-known/oauth-authorization-server': typeof DotwellKnownOauthAuthorizationServerRouteWithChildren'/.well-known/oauth-protected-resource': typeof DotwellKnownOauthProtectedResourceRouteWithChildren'/.well-known/openid-configuration': typeof DotwellKnownOpenidConfigurationRoute+ '/agent/$threadId': typeof AgentThreadIdRoute+ '/agent/new': typeof AgentNewRoute'/api/health': typeof ApiHealthRoute'/auth/forgot-password': typeof AuthForgotPasswordRoute'/auth/login': typeof AuthLoginRoute@@ -373,6 +407,7 @@ export interface FileRoutesById {'/auth/verify-2fa-backup': typeof AuthVerify2faBackupRoute'/templates/$': typeof TemplatesSplatRoute'/_home/': typeof HomeIndexRoute+ '/agent/': typeof AgentIndexRoute'/auth/': typeof AuthIndexRoute'/dashboard/': typeof DashboardIndexRoute'/mcp/': typeof McpIndexRoute@@ -398,6 +433,7 @@ export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPathfullPaths:| '/'+ | '/agent'| '/auth'| '/dashboard'| '/schema.json'@@ -407,6 +443,8 @@ export interface FileRouteTypes {| '/.well-known/oauth-authorization-server'| '/.well-known/oauth-protected-resource'| '/.well-known/openid-configuration'+ | '/agent/$threadId'+ | '/agent/new'| '/api/health'| '/auth/forgot-password'| '/auth/login'@@ -417,6 +455,7 @@ export interface FileRouteTypes {| '/auth/verify-2fa'| '/auth/verify-2fa-backup'| '/templates/$'+ | '/agent/'| '/auth/'| '/dashboard/'| '/mcp/'@@ -445,6 +484,8 @@ export interface FileRouteTypes {| '/.well-known/oauth-authorization-server'| '/.well-known/oauth-protected-resource'| '/.well-known/openid-configuration'+ | '/agent/$threadId'+ | '/agent/new'| '/api/health'| '/auth/forgot-password'| '/auth/login'@@ -456,6 +497,7 @@ export interface FileRouteTypes {| '/auth/verify-2fa-backup'| '/templates/$'| '/'+ | '/agent'| '/auth'| '/dashboard'| '/mcp'@@ -479,6 +521,7 @@ export interface FileRouteTypes {id:| '__root__'| '/_home'+ | '/agent'| '/auth'| '/dashboard'| '/schema.json'@@ -488,6 +531,8 @@ export interface FileRouteTypes {| '/.well-known/oauth-authorization-server'| '/.well-known/oauth-protected-resource'| '/.well-known/openid-configuration'+ | '/agent/$threadId'+ | '/agent/new'| '/api/health'| '/auth/forgot-password'| '/auth/login'@@ -499,6 +544,7 @@ export interface FileRouteTypes {| '/auth/verify-2fa-backup'| '/templates/$'| '/_home/'+ | '/agent/'| '/auth/'| '/dashboard/'| '/mcp/'@@ -523,6 +569,7 @@ export interface FileRouteTypes {}export interface RootRouteChildren {HomeRouteRoute: typeof HomeRouteRouteWithChildren+ AgentRouteRoute: typeof AgentRouteRouteWithChildrenAuthRouteRoute: typeof AuthRouteRouteWithChildrenDashboardRouteRoute: typeof DashboardRouteRouteWithChildrenSchemaDotjsonRoute: typeof SchemaDotjsonRoute@@ -566,6 +613,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthRouteRouteImportparentRoute: typeof rootRouteImport}+ '/agent': {+ id: '/agent'+ path: '/agent'+ fullPath: '/agent'+ preLoaderRoute: typeof AgentRouteRouteImport+ parentRoute: typeof rootRouteImport+ }'/_home': {id: '/_home'path: ''@@ -594,6 +648,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthIndexRouteImportparentRoute: typeof AuthRouteRoute}+ '/agent/': {+ id: '/agent/'+ path: '/'+ fullPath: '/agent/'+ preLoaderRoute: typeof AgentIndexRouteImport+ parentRoute: typeof AgentRouteRoute+ }'/_home/': {id: '/_home/'path: '/'@@ -671,6 +732,20 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ApiHealthRouteImportparentRoute: typeof rootRouteImport}+ '/agent/new': {+ id: '/agent/new'+ path: '/new'+ fullPath: '/agent/new'+ preLoaderRoute: typeof AgentNewRouteImport+ parentRoute: typeof AgentRouteRoute+ }+ '/agent/$threadId': {+ id: '/agent/$threadId'+ path: '/$threadId'+ fullPath: '/agent/$threadId'+ preLoaderRoute: typeof AgentThreadIdRouteImport+ parentRoute: typeof AgentRouteRoute+ }'/.well-known/openid-configuration': {id: '/.well-known/openid-configuration'path: '/.well-known/openid-configuration'@@ -847,6 +922,22 @@ const HomeRouteRouteWithChildren = HomeRouteRoute._addFileChildren(HomeRouteRouteChildren,)+interface AgentRouteRouteChildren {+ AgentThreadIdRoute: typeof AgentThreadIdRoute+ AgentNewRoute: typeof AgentNewRoute+ AgentIndexRoute: typeof AgentIndexRoute+}++const AgentRouteRouteChildren: AgentRouteRouteChildren = {+ AgentThreadIdRoute: AgentThreadIdRoute,+ AgentNewRoute: AgentNewRoute,+ AgentIndexRoute: AgentIndexRoute,+}++const AgentRouteRouteWithChildren = AgentRouteRoute._addFileChildren(+ AgentRouteRouteChildren,+)+interface AuthRouteRouteChildren {AuthForgotPasswordRoute: typeof AuthForgotPasswordRouteAuthLoginRoute: typeof AuthLoginRoute@@ -948,6 +1039,7 @@ const DotwellKnownOauthProtectedResourceRouteWithChildren =const rootRouteChildren: RootRouteChildren = {HomeRouteRoute: HomeRouteRouteWithChildren,+ AgentRouteRoute: AgentRouteRouteWithChildren,AuthRouteRoute: AuthRouteRouteWithChildren,DashboardRouteRoute: DashboardRouteRouteWithChildren,SchemaDotjsonRoute: SchemaDotjsonRoute,diff --git a/apps/web/src/routes/agent/$threadId.tsx b/apps/web/src/routes/agent/$threadId.tsxnew file mode 100644index 000000000..e25612829--- /dev/null+++ b/apps/web/src/routes/agent/$threadId.tsx@@ -0,0 +1,1243 @@+import type { UIMessage, UIMessageChunk } from "ai";+import type * as React from "react";+import type { PanelImperativeHandle } from "react-resizable-panels";+import type { RouterOutput } from "@/libs/orpc/client";+import { useChat } from "@ai-sdk/react";+import { t } from "@lingui/core/macro";+import { Trans } from "@lingui/react/macro";+import { eventIteratorToUnproxiedDataStream } from "@orpc/client";+import {+ ArchiveIcon,+ ArrowClockwiseIcon,+ ArrowSquareOutIcon,+ ChatCircleDotsIcon,+ CircleNotchIcon,+ ClockCounterClockwiseIcon,+ CopyIcon,+ DotsThreeVerticalIcon,+ FileIcon,+ FilePdfIcon,+ MinusIcon,+ PaperclipIcon,+ PaperPlaneRightIcon,+ PlusIcon,+ SidebarSimpleIcon,+ SparkleIcon,+ SquaresFourIcon,+ StopIcon,+ TrashIcon,+} from "@phosphor-icons/react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";+import { lastAssistantMessageIsCompleteWithToolCalls } from "ai";+import { motion } from "motion/react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import ReactMarkdown from "react-markdown";+import { toast } from "sonner";+import { Badge } from "@reactive-resume/ui/components/badge";+import { Button } from "@reactive-resume/ui/components/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@reactive-resume/ui/components/dropdown-menu";+import { ResizableGroup, ResizablePanel, ResizableSeparator } from "@reactive-resume/ui/components/resizable";+import { ScrollArea } from "@reactive-resume/ui/components/scroll-area";+import { Tabs, TabsList, TabsTrigger } from "@reactive-resume/ui/components/tabs";+import { Textarea } from "@reactive-resume/ui/components/textarea";+import { Tooltip, TooltipContent, TooltipTrigger } from "@reactive-resume/ui/components/tooltip";+import { downloadWithAnchor, generateFilename } from "@reactive-resume/utils/file";+import { cn } from "@reactive-resume/utils/style";+import { ResumePreview } from "@/components/resume/preview";+import { useConfirm } from "@/hooks/use-confirm";+import { getOrpcErrorMessage } from "@/libs/error-message";+import { client, orpc, streamClient } from "@/libs/orpc/client";+import { createResumePdfBlob } from "@/libs/resume/pdf-document";+import { AgentThreadSidebar } from "./-components/thread-sidebar";+import { attachmentIdsFromTransportBody, buildAgentChatSubmission } from "./-helpers/chat-attachments";++type AgentThreadDetail = RouterOutput["agent"]["threads"]["get"];+type AgentAction = AgentThreadDetail["actions"][number];+type AgentAttachment = AgentThreadDetail["attachments"][number];+type PatchOperation = AgentAction["operations"][number];++function toRecord(value: unknown) {+ return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : null;+}++function PatchToolCard({+ part,+ action,+ onRevert,+ isReverting,+}: {+ part: UIMessage["parts"][number];+ action: AgentAction | undefined;+ onRevert: (actionId: string) => void;+ isReverting: boolean;+}) {+ const partRecord = part as Record<string, unknown>;+ const state = typeof partRecord.state === "string" ? partRecord.state : null;+ const input = toRecord(partRecord.input);+ const output = toRecord(partRecord.output);+ const actionId =+ state === "output-available"+ ? (action?.id ?? (typeof output?.actionId === "string" ? output.actionId : null))+ : null;++ const title =+ action?.title ??+ (typeof output?.title === "string" ? output.title : null) ??+ (typeof input?.title === "string" ? input.title : t`Resume patch`);+ const operations: PatchOperation[] =+ action?.operations ??+ (Array.isArray(output?.operations)+ ? (output.operations as PatchOperation[])+ : Array.isArray(input?.operations)+ ? (input.operations as PatchOperation[])+ : []);+ const status = action?.status ?? "applied";+ const revertMessage = action?.revertMessage ?? null;+ const label =+ state === "output-error"+ ? t`Patch failed`+ : state !== "output-available"+ ? t`Patch pending`+ : status === "reverted"+ ? t`Patch reverted`+ : status === "conflicted"+ ? t`Patch conflicted`+ : t`Patch applied`;+ const revertDisabled = isReverting || status === "reverted" || status === "conflicted";+ const errorText = typeof partRecord.errorText === "string" ? partRecord.errorText : null;+ const rawPayload = JSON.stringify(+ {+ state,+ input,+ ...(partRecord.rawInput !== undefined ? { rawInput: partRecord.rawInput } : {}),+ output,+ ...(errorText ? { errorText } : {}),+ ...(action ? { action } : {}),+ operations,+ },+ null,+ 2,+ );++ return (+ <details className="group text-muted-foreground text-xs">+ <summary className="inline-flex cursor-pointer list-none items-center gap-2 rounded-md py-1 font-medium text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden">+ <span>{label}</span>+ <span className="text-muted-foreground/70 group-open:hidden">{title}</span>+ </summary>++ <div className="mt-2 space-y-2 rounded-md border bg-muted/20 p-3">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <p className="truncate font-medium text-foreground">{title}</p>+ {status === "conflicted" && revertMessage ? (+ <p className="mt-1 text-amber-600 dark:text-amber-300">{revertMessage}</p>+ ) : null}+ {errorText ? <p className="mt-1 text-rose-500">{errorText}</p> : null}+ </div>+ {actionId ? (+ <Button size="xs" variant="ghost" disabled={revertDisabled} onClick={() => onRevert(actionId)}>+ <ClockCounterClockwiseIcon />+ <Trans>Revert</Trans>+ </Button>+ ) : null}+ </div>+ <pre className="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded border bg-background p-3 font-mono text-[0.7rem] leading-relaxed">+ {rawPayload}+ </pre>+ </div>+ </details>+ );+}++export const Route = createFileRoute("/agent/$threadId")({+ component: RouteComponent,+ ssr: false,+});++function fileToBase64(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(String(reader.result).split(",")[1] ?? "");+ reader.onerror = reject;+ reader.readAsDataURL(file);+ });+}++function textFromMessage(message: UIMessage) {+ return message.parts+ .filter((part) => part.type === "text")+ .map((part) => part.text)+ .join("\n");+}++function parseAgentSseStream(stream: ReadableStream<string>) {+ let buffer = "";+ const eventBoundary = /\r?\n\r?\n/;++ return stream.pipeThrough(+ new TransformStream<string, UIMessageChunk>({+ transform(chunk, controller) {+ buffer += chunk;++ let boundary = eventBoundary.exec(buffer);+ while (boundary) {+ const event = buffer.slice(0, boundary.index);+ buffer = buffer.slice(boundary.index + boundary[0].length);++ for (const line of event.split(/\r?\n/)) {+ if (!line.startsWith("data:")) continue;++ const data = line.slice("data:".length).trimStart();+ if (!data || data === "[DONE]") continue;++ try {+ controller.enqueue(JSON.parse(data) as UIMessageChunk);+ } catch (error) {+ console.warn("[agent] dropping malformed SSE frame", error);+ }+ }++ boundary = eventBoundary.exec(buffer);+ }+ },+ }),+ );+}++function promptPreview(prompt: string) {+ const words = prompt.split(/\s+/).filter(Boolean);+ return `${words.slice(0, 7).join(" ")}${words.length > 7 ? "..." : ""}`;+}++function chunkPrompts(prompts: string[], columns: number) {+ return prompts.reduce<string[][]>(+ (rows, prompt, index) => {+ rows[index % columns]?.push(prompt);+ return rows;+ },+ Array.from({ length: columns }, () => []),+ );+}++function StarterPromptMarquee({ onSelect }: { onSelect: (prompt: string) => void }) {+ const prompts = [+ t`Tailor this resume to a product manager job description and emphasize roadmap ownership, stakeholder communication, and measurable launch outcomes.`,+ t`Compare this resume against this role URL and update keywords while keeping the voice concise and credible.`,+ t`Find weak bullets and rewrite them with stronger outcomes, numbers, scope, and sharper verbs.`,+ t`Rework the summary so it targets a senior engineering manager role without sounding generic.`,+ t`Identify gaps for an applicant tracking system and apply only high-confidence keyword improvements.`,+ t`Rewrite this resume for a startup founder-to-product-lead transition with clear business impact.`,+ t`Make the experience section more results-oriented and remove vague responsibilities.`,+ t`Adjust the resume for a remote-first role that values async communication and ownership.`,+ t`Review the resume against a job description and ask me questions before changing uncertain sections.`,+ t`Tighten the skills section so it supports the target role instead of reading like a keyword dump.`,+ t`Update project bullets to show leadership, constraints, tradeoffs, and measurable outcomes.`,+ t`Prepare a conservative patch that improves clarity without changing my career narrative.`,+ ];++ const promptRows = chunkPrompts(prompts, 3);++ return (+ <div className="relative mx-auto grid w-full max-w-4xl gap-3 overflow-hidden py-1 [mask-image:linear-gradient(to_right,transparent,black_10%,black_90%,transparent)]">+ {promptRows.map((row, rowIndex) => {+ const marqueePrompts = [...row, ...row, ...row];+ const duration = 135 + rowIndex * 22;+ const animate = rowIndex % 2 === 0 ? { x: ["0%", "-33.333%"] } : { x: ["-33.333%", "0%"] };++ return (+ <motion.div+ key={`prompt-row-${rowIndex}`}+ className="flex w-max gap-3"+ animate={animate}+ transition={{ duration, ease: "linear", repeat: Number.POSITIVE_INFINITY }}+ >+ {marqueePrompts.map((prompt, index) => (+ <Button+ key={`${prompt}-${index}`}+ type="button"+ variant="outline"+ className="h-8 shrink-0 rounded-full bg-background/70 px-3 font-normal text-muted-foreground hover:text-foreground"+ onClick={() => onSelect(prompt)}+ >+ {promptPreview(prompt)}+ </Button>+ ))}+ </motion.div>+ );+ })}+ </div>+ );+}++function AssistantMarkdown({ text }: { text: string }) {+ return (+ <ReactMarkdown+ skipHtml+ components={{+ p: ({ children }) => <p className="my-2 leading-relaxed first:mt-0 last:mb-0">{children}</p>,+ ul: ({ children }) => <ul className="my-2 ms-5 list-disc space-y-1">{children}</ul>,+ ol: ({ children }) => <ol className="my-2 ms-5 list-decimal space-y-1">{children}</ol>,+ li: ({ children }) => <li className="ps-1">{children}</li>,+ a: ({ children, href }) => (+ <a className="text-primary underline underline-offset-4" href={href} target="_blank" rel="noreferrer">+ {children}+ </a>+ ),+ code: ({ children, className }) => (+ <code className={cn("rounded border bg-muted px-1 py-0.5 font-mono text-[0.85em]", className)}>+ {children}+ </code>+ ),+ pre: ({ children }) => (+ <pre className="my-3 max-w-full overflow-auto rounded-md border bg-muted/30 p-3 text-xs leading-relaxed">+ {children}+ </pre>+ ),+ blockquote: ({ children }) => (+ <blockquote className="my-3 border-l-2 ps-3 text-muted-foreground">{children}</blockquote>+ ),+ }}+ >+ {text}+ </ReactMarkdown>+ );+}++function MessagePart({+ part,+ isUser,+ onAnswer,+ onRevert,+ isReverting,+ actionsById,+}: {+ part: UIMessage["parts"][number];+ isUser: boolean;+ onAnswer: (toolCallId: string, answer: string) => void;+ onRevert: (actionId: string) => void;+ isReverting: boolean;+ actionsById: Map<string, AgentAction>;+}) {+ if (part.type === "text") {+ return isUser ? (+ <div className="whitespace-pre-wrap leading-relaxed">{part.text}</div>+ ) : (+ <AssistantMarkdown text={part.text} />+ );+ }++ if (part.type === "reasoning") {+ return (+ <details className="rounded-md border bg-muted/40 px-3 py-2 text-sm">+ <summary className="cursor-pointer text-muted-foreground">+ <Trans>Thinking</Trans>+ </summary>+ <div className="mt-2 whitespace-pre-wrap">{part.text}</div>+ </details>+ );+ }++ if (part.type === "tool-ask_user_question") {+ const input =+ "input" in part && typeof part.input === "object" && part.input ? (part.input as Record<string, unknown>) : {};+ const choices = Array.isArray(input.choices)+ ? input.choices.filter((choice): choice is string => typeof choice === "string")+ : [];+ const question = typeof input.question === "string" ? input.question : t`The agent needs your input.`;++ return (+ <div className="space-y-3 rounded-md border bg-card p-3">+ <div className="font-medium">{question}</div>+ <div className="flex flex-wrap gap-2">+ {choices.map((choice) => (+ <Button key={choice} size="sm" variant="outline" onClick={() => onAnswer(part.toolCallId, choice)}>+ {choice}+ </Button>+ ))}+ </div>+ </div>+ );+ }++ if (part.type === "tool-fetch_url") {+ const output =+ "output" in part && typeof part.output === "object" && part.output+ ? (part.output as Record<string, unknown>)+ : null;+ return (+ <details className="rounded-md border bg-card p-3 text-sm">+ <summary className="cursor-pointer font-medium">+ <Trans>Fetched URL</Trans>+ </summary>+ <div className="mt-2 space-y-1 text-muted-foreground">+ <p>{typeof output?.url === "string" ? output.url : t`Waiting for fetch result...`}</p>+ {typeof output?.title === "string" ? <p>{output.title}</p> : null}+ </div>+ </details>+ );+ }++ if (part.type === "tool-apply_resume_patch") {+ const output =+ "output" in part && typeof part.output === "object" && part.output+ ? (part.output as Record<string, unknown>)+ : null;+ const actionId = typeof output?.actionId === "string" ? output.actionId : null;+ const action = actionId ? actionsById.get(actionId) : undefined;++ return <PatchToolCard part={part} action={action} onRevert={onRevert} isReverting={isReverting} />;+ }++ if (part.type === "source-url") {+ const title = part.title?.trim() || null;++ return (+ <a className="block text-primary text-sm underline" href={part.url} target="_blank" rel="noreferrer">+ {title ? (+ <>+ <span className="block truncate">{title}</span>+ <span className="block truncate text-muted-foreground">{part.url}</span>+ </>+ ) : (+ <span className="block truncate">{part.url}</span>+ )}+ </a>+ );+ }++ if (part.type === "file") {+ return (+ <div className="flex max-w-full items-center gap-2 rounded-md border bg-background/20 px-2 py-1 text-sm">+ <FileIcon className="shrink-0" />+ <span className="truncate">{part.filename ?? part.url}</span>+ </div>+ );+ }++ return null;+}++function ChatMessage({+ message,+ onAnswer,+ onRevert,+ isReverting,+ actionsById,+}: {+ message: UIMessage;+ onAnswer: (toolCallId: string, answer: string) => void;+ onRevert: (actionId: string) => void;+ isReverting: boolean;+ actionsById: Map<string, AgentAction>;+}) {+ const isUser = message.role === "user";++ return (+ <div className={cn("flex", isUser ? "justify-end" : "justify-start")}>+ <div+ className={cn(+ "space-y-3 text-sm",+ isUser+ ? "max-w-[86%] rounded-md bg-primary px-4 py-3 text-primary-foreground"+ : "w-full max-w-full py-1 text-foreground",+ )}+ >+ {message.parts.map((part, index) => (+ <MessagePart+ key={`${message.id}-${index}`}+ part={part}+ isUser={isUser}+ onAnswer={onAnswer}+ onRevert={onRevert}+ isReverting={isReverting}+ actionsById={actionsById}+ />+ ))}+ </div>+ </div>+ );+}++function AgentChat({+ threadId,+ initialMessages,+ isReadOnly,+ readOnlyReason,+ threadStatus,+ activeRunId,+ actions,+ onToggleThreads,+ onToggleResume,+}: {+ threadId: string;+ initialMessages: UIMessage[];+ isReadOnly: boolean;+ readOnlyReason: "archived" | "missing" | null;+ threadStatus: string;+ activeRunId: string | null;+ actions: AgentAction[];+ onToggleThreads?: () => void;+ onToggleResume?: () => void;+}) {+ const queryClient = useQueryClient();+ const navigate = useNavigate();+ const confirm = useConfirm();+ const fileInputRef = useRef<HTMLInputElement>(null);+ const refreshedPatchOutputsRef = useRef(new Set<string>());+ const lastSyncedThreadIdRef = useRef<string | null>(null);+ const [input, setInput] = useState("");+ const [pendingAttachments, setPendingAttachments] = useState<+ Array<Pick<AgentAttachment, "id" | "filename" | "mediaType">>+ >([]);+ const [isUploading, setIsUploading] = useState(false);+ const revertMutation = useMutation(orpc.agent.actions.revert.mutationOptions());+ const archiveMutation = useMutation(orpc.agent.threads.archive.mutationOptions());+ const deleteMutation = useMutation(orpc.agent.threads.delete.mutationOptions());+ const isArchived = threadStatus === "archived";++ const refreshThread = useCallback(async () => {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: orpc.agent.threads.list.queryKey() }),+ queryClient.invalidateQueries({ queryKey: orpc.agent.threads.get.queryKey({ input: { id: threadId } }) }),+ ]);+ }, [queryClient, threadId]);++ const actionsById = useMemo(() => {+ const map = new Map<string, AgentAction>();+ for (const action of actions) map.set(action.id, action);+ return map;+ }, [actions]);++ const handleArchive = () => {+ archiveMutation.mutate(+ { id: threadId },+ {+ onSuccess: async () => {+ toast.success(t`Thread archived.`);+ await refreshThread();+ },+ onError: (error) => {+ toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to archive thread.` }));+ },+ },+ );+ };++ const handleDelete = async () => {+ const confirmation = await confirm(t`Delete this agent thread?`, {+ description: t`This action cannot be undone. Conversation messages and uploaded attachments will be removed. The working resume draft remains in your dashboard and can be deleted separately.`,+ });++ if (!confirmation) return;++ deleteMutation.mutate(+ { id: threadId },+ {+ onSuccess: async () => {+ toast.success(t`Thread deleted.`);+ await queryClient.invalidateQueries({ queryKey: orpc.agent.threads.list.queryKey() });+ void navigate({ to: "/agent" });+ },+ onError: (error) => {+ toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to delete thread.` }));+ },+ },+ );+ };++ const transport = useMemo(+ () => ({+ async sendMessages(options: { messages: UIMessage[]; abortSignal?: AbortSignal; body?: object }) {+ const message = options.messages.at(-1);+ if (!message) throw new Error("No message to send.");+ const attachmentIds = attachmentIdsFromTransportBody(options.body);++ return parseAgentSseStream(+ eventIteratorToUnproxiedDataStream(+ await streamClient.agent.messages.send(+ { threadId, message, attachmentIds },+ { signal: options.abortSignal },+ ),+ ),+ );+ },+ async reconnectToStream() {+ return parseAgentSseStream(+ eventIteratorToUnproxiedDataStream(await streamClient.agent.messages.resume({ threadId })),+ );+ },+ }),+ [threadId],+ );++ const { messages, sendMessage, regenerate, setMessages, status, error, clearError, addToolOutput } = useChat({+ id: threadId,+ messages: initialMessages,+ resume: !!activeRunId,+ transport,+ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,+ onFinish: () => {+ void refreshThread();+ },+ });++ useEffect(() => {+ let shouldRefresh = false;++ for (const message of messages) {+ for (const part of message.parts) {+ if (part.type !== "tool-apply_resume_patch" || !("output" in part) || !part.output) continue;++ const output = typeof part.output === "object" ? (part.output as Record<string, unknown>) : null;+ const actionId = typeof output?.actionId === "string" ? output.actionId : null;+ const toolCallId = "toolCallId" in part && typeof part.toolCallId === "string" ? part.toolCallId : null;+ const patchOutputKey = actionId ?? toolCallId;++ if (!patchOutputKey || refreshedPatchOutputsRef.current.has(patchOutputKey)) continue;++ refreshedPatchOutputsRef.current.add(patchOutputKey);+ shouldRefresh = true;+ }+ }++ if (shouldRefresh) void refreshThread();+ }, [messages, refreshThread]);++ useEffect(() => {+ if (lastSyncedThreadIdRef.current === threadId) return;+ lastSyncedThreadIdRef.current = threadId;+ setMessages(initialMessages);+ }, [threadId, initialMessages, setMessages]);++ const isStreaming = status === "submitted" || status === "streaming";++ const send = () => {+ const text = input.trim();+ if ((!text && pendingAttachments.length === 0) || isReadOnly || isStreaming || isUploading) return;++ clearError();+ const submission = buildAgentChatSubmission(text, pendingAttachments);+ sendMessage(submission.message, submission.options);+ setInput("");+ setPendingAttachments([]);+ };++ const uploadFiles = async (files: FileList | null) => {+ if (!files?.length) return;++ setIsUploading(true);+ try {+ for (const file of Array.from(files)) {+ const attachment = await client.agent.attachments.create({+ threadId,+ filename: file.name,+ mediaType: file.type || "application/octet-stream",+ data: await fileToBase64(file),+ });+ setPendingAttachments((current) => [+ ...current,+ { id: attachment.id, filename: attachment.filename, mediaType: attachment.mediaType },+ ]);+ }+ toast.success(t`Attachment uploaded.`);+ } catch (error) {+ toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to upload attachment.` }));+ } finally {+ setIsUploading(false);+ if (fileInputRef.current) fileInputRef.current.value = "";+ }+ };++ const stopRun = async () => {+ const last = messages.at(-1);+ await client.agent.messages.stop({+ threadId,+ ...(last?.role === "assistant" ? { partialMessage: last } : {}),+ });+ };++ const copyConversationJson = () => {+ void navigator.clipboard.writeText(+ JSON.stringify(+ {+ threadId,+ threadStatus,+ chatStatus: status,+ isReadOnly,+ readOnlyReason,+ messages,+ actions,+ },+ null,+ 2,+ ),+ );+ toast.success(t`Conversation JSON copied.`);+ };++ return (+ <section className="flex h-full min-h-0 flex-col bg-background">+ <div className="flex h-14 shrink-0 items-center justify-between border-b px-4">+ <div className="flex min-w-0 items-center gap-2">+ {onToggleThreads ? (+ <Button size="icon-sm" variant="ghost" onClick={onToggleThreads}>+ <SidebarSimpleIcon />+ <span className="sr-only">+ <Trans>Toggle threads</Trans>+ </span>+ </Button>+ ) : null}++ <div className="min-w-0 truncate font-semibold">+ <Trans>Chat</Trans>+ </div>+ </div>+ <div className="flex items-center gap-1">+ {onToggleResume ? (+ <Button size="icon-sm" variant="ghost" onClick={onToggleResume}>+ <SquaresFourIcon />+ <span className="sr-only">+ <Trans>Toggle resume preview</Trans>+ </span>+ </Button>+ ) : null}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button size="icon-sm" variant="ghost">+ <DotsThreeVerticalIcon />+ <span className="sr-only">+ <Trans>Thread actions</Trans>+ </span>+ </Button>+ }+ />++ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onClick={() => {+ void navigator.clipboard.writeText(messages.map(textFromMessage).join("\n\n"));+ toast.success(t`Conversation copied.`);+ }}+ >+ <CopyIcon />+ <Trans>Copy</Trans>+ </DropdownMenuItem>+ <DropdownMenuItem onClick={copyConversationJson}>+ <CopyIcon />+ <Trans>Copy JSON</Trans>+ </DropdownMenuItem>++ <DropdownMenuSeparator />++ {!isArchived ? (+ <DropdownMenuItem disabled={archiveMutation.isPending} onClick={handleArchive}>+ <ArchiveIcon />+ <Trans>Archive</Trans>+ </DropdownMenuItem>+ ) : null}++ <DropdownMenuItem+ variant="destructive"+ disabled={deleteMutation.isPending}+ onClick={() => void handleDelete()}+ >+ <TrashIcon />+ <Trans>Delete</Trans>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>++ {isReadOnly ? (+ <div className="border-amber-300 border-b bg-amber-50 px-4 py-2 text-amber-950 text-sm dark:bg-amber-950/20 dark:text-amber-200">+ {readOnlyReason === "archived" ? (+ <Trans>This thread is archived. New messages cannot be sent.</Trans>+ ) : (+ <Trans>This thread is read-only because the working resume or AI provider is unavailable.</Trans>+ )}+ </div>+ ) : null}++ <ScrollArea className="min-h-0 flex-1">+ <div className="mx-auto flex max-w-3xl flex-col gap-4 p-4">+ {messages.length === 0 ? (+ <div className="grid gap-6 py-12 text-center">+ <SparkleIcon className="mx-auto size-8 text-muted-foreground" />+ <h2 className="font-semibold text-2xl">+ <Trans>What do you want to do?</Trans>+ </h2>+ <StarterPromptMarquee onSelect={setInput} />+ </div>+ ) : null}++ {messages.map((message) => (+ <ChatMessage+ key={message.id}+ message={message}+ isReverting={revertMutation.isPending}+ actionsById={actionsById}+ onAnswer={(toolCallId, answer) => {+ addToolOutput({ tool: "ask_user_question", toolCallId, output: answer });+ }}+ onRevert={(actionId) =>+ revertMutation.mutate(+ { id: actionId },+ {+ onSuccess: (action) => {+ if (action.status === "conflicted") {+ toast.error(+ action.revertMessage ?? t`Cannot revert; the resume has changed since this edit was applied.`,+ );+ } else if (action.status === "reverted") {+ toast.success(t`Patch reverted.`);+ }+ void refreshThread();+ },+ onError: (error) =>+ toast.error(getOrpcErrorMessage(error, { fallback: t`Could not revert this patch.` })),+ },+ )+ }+ />+ ))}++ {isStreaming ? (+ <div className="flex justify-start">+ <div className="rounded-md bg-muted px-4 py-3 text-muted-foreground text-sm">+ <Trans>Working...</Trans>+ </div>+ </div>+ ) : null}++ {error ? (+ <div className="flex items-center justify-between gap-3 rounded-md border border-rose-300 bg-rose-50 p-3 text-rose-950 text-sm dark:bg-rose-950/20 dark:text-rose-200">+ <span>{error.message}</span>+ {!isReadOnly ? (+ <Button+ size="sm"+ variant="outline"+ type="button"+ onClick={() => {+ clearError();+ void regenerate();+ }}+ >+ <ArrowClockwiseIcon />+ <Trans>Retry</Trans>+ </Button>+ ) : null}+ </div>+ ) : null}+ </div>+ </ScrollArea>++ <form+ className="border-t p-3"+ onSubmit={(event) => {+ event.preventDefault();+ send();+ }}+ >+ <div className="mx-auto max-w-3xl space-y-2">+ {pendingAttachments.length > 0 ? (+ <div className="flex flex-wrap gap-2">+ {pendingAttachments.map((attachment) => (+ <Badge key={attachment.id} variant="secondary">+ <FileIcon />+ {attachment.filename}+ </Badge>+ ))}+ </div>+ ) : null}++ <div className="flex items-end gap-1 rounded-md border bg-card p-1.5">+ <input+ ref={fileInputRef}+ type="file"+ multiple+ className="hidden"+ onChange={(event) => void uploadFiles(event.target.files)}+ />+ <Button+ type="button"+ size="icon"+ variant="ghost"+ aria-label={t`Attach files`}+ disabled={isReadOnly || isUploading}+ onClick={() => fileInputRef.current?.click()}+ >+ {isUploading ? <ArrowClockwiseIcon className="animate-spin" /> : <PaperclipIcon />}+ </Button>+ <Textarea+ value={input}+ rows={1}+ disabled={isReadOnly || isStreaming}+ onChange={(event) => setInput(event.target.value)}+ onKeyDown={(event) => {+ if (event.nativeEvent.isComposing) return;+ if (event.key !== "Enter" || event.shiftKey) return;+ event.preventDefault();+ send();+ }}+ placeholder={isReadOnly ? t`This thread is read-only` : t`Ask anything about this resume`}+ className="max-h-40 min-h-9 resize-none border-0 bg-transparent px-2 py-2 leading-5 shadow-none focus-visible:ring-0"+ />+ {isStreaming && !isReadOnly ? (+ <Button+ type="button"+ size="icon"+ variant="outline"+ aria-label={t`Stop generation`}+ onClick={() => void stopRun()}+ >+ <StopIcon />+ </Button>+ ) : (+ <Button+ type="submit"+ size="icon"+ aria-label={t`Send message`}+ disabled={isReadOnly || isUploading || (!input.trim() && pendingAttachments.length === 0)}+ >+ <PaperPlaneRightIcon />+ </Button>+ )}+ </div>+ </div>+ </form>+ </section>+ );+}++const AGENT_PREVIEW_ZOOM_STORAGE_KEY = "reactive-resume:agent-preview-zoom:v3";+const AGENT_PREVIEW_ZOOM_MIGRATION_KEY = `${AGENT_PREVIEW_ZOOM_STORAGE_KEY}:initialized`;+const MIN_PREVIEW_ZOOM = 0.4;+const MAX_PREVIEW_ZOOM = 1.5;+const PREVIEW_ZOOM_STEP = 0.05;+const DEFAULT_PREVIEW_ZOOM = 1;++function clampPreviewZoom(value: number) {+ return Math.min(MAX_PREVIEW_ZOOM, Math.max(MIN_PREVIEW_ZOOM, value));+}++function getInitialPreviewZoom() {+ if (typeof window === "undefined") return DEFAULT_PREVIEW_ZOOM;++ if (!window.localStorage.getItem(AGENT_PREVIEW_ZOOM_MIGRATION_KEY)) {+ window.localStorage.setItem(AGENT_PREVIEW_ZOOM_STORAGE_KEY, String(DEFAULT_PREVIEW_ZOOM));+ window.localStorage.setItem(AGENT_PREVIEW_ZOOM_MIGRATION_KEY, "true");+ return DEFAULT_PREVIEW_ZOOM;+ }++ const stored = Number(window.localStorage.getItem(AGENT_PREVIEW_ZOOM_STORAGE_KEY));+ return Number.isFinite(stored) ? clampPreviewZoom(stored) : DEFAULT_PREVIEW_ZOOM;+}++function ToolbarButton({+ label,+ children,+ ...props+}: React.ComponentProps<typeof Button> & {+ label: string;+}) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button size="icon-sm" variant="ghost" aria-label={label} {...props}>+ {children}+ </Button>+ }+ />+ <TooltipContent side="bottom" align="center">+ {label}+ </TooltipContent>+ </Tooltip>+ );+}++function ResumePane({ resume }: { resume: AgentThreadDetail["resume"] }) {+ const [zoom, setZoom] = useState(getInitialPreviewZoom);+ const [isPrinting, setIsPrinting] = useState(false);++ useEffect(() => {+ window.localStorage.setItem(AGENT_PREVIEW_ZOOM_STORAGE_KEY, String(zoom));+ }, [zoom]);++ const setClampedZoom = useCallback((value: number) => {+ setZoom(clampPreviewZoom(Number(value.toFixed(2))));+ }, []);++ const onDownloadPDF = useCallback(async () => {+ if (!resume) return;++ const filename = generateFilename(resume.name || resume.data.basics.name || resume.id, "pdf");+ const toastId = toast.loading(t`Please wait while your PDF is being generated...`);++ setIsPrinting(true);++ try {+ const blob = await createResumePdfBlob(resume.data);+ downloadWithAnchor(blob, filename);+ } catch {+ toast.error(t`There was a problem while generating the PDF, please try again.`);+ } finally {+ setIsPrinting(false);+ toast.dismiss(toastId);+ }+ }, [resume]);++ const zoomPercent = Math.round(zoom * 100);++ return (+ <section className="flex h-full min-h-0 flex-col bg-muted/30">+ <div className="flex h-14 shrink-0 items-center justify-between border-b px-4">+ <div>+ <div className="font-semibold">+ <Trans>Resume</Trans>+ </div>+ <div className="text-muted-foreground text-xs">{resume?.name ?? t`Missing working resume`}</div>+ </div>+ </div>++ <div className="min-h-0 flex-1 overflow-auto">+ <div className="sticky top-0 z-10 flex h-10 items-center justify-between border-b bg-background/90 px-2 backdrop-blur">+ <div className="flex items-center gap-1">+ <ToolbarButton+ label={t`Decrease zoom`}+ disabled={!resume}+ onClick={() => setClampedZoom(zoom - PREVIEW_ZOOM_STEP)}+ >+ <MinusIcon />+ </ToolbarButton>+ <Tooltip>+ <TooltipTrigger+ render={+ <input+ type="text"+ inputMode="numeric"+ value={`${zoomPercent}%`}+ disabled={!resume}+ aria-label={t`Zoom level`}+ className="h-8 w-14 rounded-md border bg-background px-1 text-center text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50"+ onChange={(event) => {+ const nextValue = Number(event.target.value.replace(/[^0-9.]/g, ""));+ if (Number.isFinite(nextValue)) setClampedZoom(nextValue / 100);+ }}+ />+ }+ />+ <TooltipContent side="bottom" align="center">+ <Trans>Zoom level</Trans>+ </TooltipContent>+ </Tooltip>+ <ToolbarButton+ label={t`Increase zoom`}+ disabled={!resume}+ onClick={() => setClampedZoom(zoom + PREVIEW_ZOOM_STEP)}+ >+ <PlusIcon />+ </ToolbarButton>+ </div>+ <div className="flex items-center gap-1">+ <ToolbarButton+ label={t`Open in builder`}+ disabled={!resume}+ nativeButton={false}+ render={resume ? <Link to="/builder/$resumeId" params={{ resumeId: resume.id }} /> : undefined}+ >+ <ArrowSquareOutIcon />+ </ToolbarButton>+ <ToolbarButton+ label={t`Download PDF`}+ disabled={!resume || isPrinting}+ onClick={() => void onDownloadPDF()}+ >+ {isPrinting ? <CircleNotchIcon className="animate-spin" /> : <FilePdfIcon />}+ </ToolbarButton>+ </div>+ </div>+ <div className="p-4">+ {resume ? (+ <ResumePreview+ data={resume.data}+ pageLayout="vertical"+ pageScale={zoom}+ showPageNumbers+ className="mx-auto"+ pageClassName="shadow-lg"+ />+ ) : (+ <div className="rounded-md border border-dashed p-6 text-center text-muted-foreground">+ <Trans>The working resume was deleted. This thread is read-only.</Trans>+ </div>+ )}+ </div>+ </div>+ </section>+ );+}++function RouteComponent() {+ const { threadId } = Route.useParams();+ const navigate = useNavigate();+ const [mobileTab, setMobileTab] = useState("chat");+ const threadsPanelRef = useRef<PanelImperativeHandle | null>(null);+ const resumePanelRef = useRef<PanelImperativeHandle | null>(null);+ const [isThreadsCollapsed, setIsThreadsCollapsed] = useState(false);+ const [isResumeCollapsed, setIsResumeCollapsed] = useState(false);+ const { data, isLoading, error } = useQuery(orpc.agent.threads.get.queryOptions({ input: { id: threadId } }));++ const toggleThreadsPanel = useCallback(() => {+ const panel = threadsPanelRef.current;+ if (!panel) return;+ if (panel.isCollapsed()) {+ panel.expand();+ setIsThreadsCollapsed(false);+ } else {+ panel.collapse();+ setIsThreadsCollapsed(true);+ }+ }, []);++ const toggleResumePanel = useCallback(() => {+ const panel = resumePanelRef.current;+ if (!panel) return;+ if (panel.isCollapsed()) {+ panel.expand();+ setIsResumeCollapsed(false);+ } else {+ panel.collapse();+ setIsResumeCollapsed(true);+ }+ }, []);++ if (isLoading) {+ return (+ <div className="grid h-svh place-items-center bg-background text-muted-foreground">+ <Trans>Loading agent workspace...</Trans>+ </div>+ );+ }++ if (error || !data) {+ return (+ <div className="grid h-svh place-items-center bg-background p-6 text-center">+ <div className="space-y-4">+ <p className="text-muted-foreground">+ <Trans>This agent thread could not be opened.</Trans>+ </p>+ <Button onClick={() => void navigate({ to: "/agent/new" })}>+ <Trans>Start a new thread</Trans>+ </Button>+ </div>+ </div>+ );+ }++ const readOnlyReason: "archived" | "missing" | null = data.isReadOnly+ ? data.thread.status === "archived"+ ? "archived"+ : "missing"+ : null;++ return (+ <div className="h-svh bg-background">+ <div className="hidden h-full lg:block">+ <ResizableGroup orientation="horizontal" className="h-full">+ <ResizablePanel+ id="threads"+ panelRef={threadsPanelRef}+ defaultSize="18%"+ minSize="240px"+ maxSize="360px"+ collapsible+ collapsedSize="0px"+ onResize={(size) => setIsThreadsCollapsed(size.inPixels < 24)}+ >+ <AgentThreadSidebar activeThreadId={threadId} className={cn(isThreadsCollapsed && "invisible")} />+ </ResizablePanel>+ <ResizableSeparator withHandle />+ <ResizablePanel id="chat" defaultSize="52%" minSize="280px">+ <AgentChat+ threadId={threadId}+ initialMessages={data.messages}+ isReadOnly={data.isReadOnly}+ readOnlyReason={readOnlyReason}+ threadStatus={data.thread.status}+ activeRunId={data.thread.activeRunId}+ actions={data.actions}+ onToggleThreads={toggleThreadsPanel}+ onToggleResume={toggleResumePanel}+ />+ </ResizablePanel>+ <ResizableSeparator withHandle />+ <ResizablePanel+ id="resume"+ panelRef={resumePanelRef}+ defaultSize="30%"+ minSize="340px"+ maxSize="70%"+ collapsible+ collapsedSize="0px"+ onResize={(size) => setIsResumeCollapsed(size.inPixels < 24)}+ >+ <div className={cn("h-full", isResumeCollapsed && "invisible")}>+ <ResumePane resume={data.resume} />+ </div>+ </ResizablePanel>+ </ResizableGroup>+ </div>++ <div className="flex h-full flex-col lg:hidden">+ <div className="border-b p-2">+ <Tabs value={mobileTab} onValueChange={setMobileTab}>+ <TabsList className="grid w-full grid-cols-3">+ <TabsTrigger value="threads">+ <SidebarSimpleIcon />+ <Trans>Threads</Trans>+ </TabsTrigger>+ <TabsTrigger value="chat">+ <ChatCircleDotsIcon />+ <Trans>Chat</Trans>+ </TabsTrigger>+ <TabsTrigger value="resume">+ <SquaresFourIcon />+ <Trans>Resume</Trans>+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </div>+ <div className="min-h-0 flex-1">+ <div className={cn("h-full", mobileTab !== "threads" && "hidden")}>+ <AgentThreadSidebar activeThreadId={threadId} />+ </div>+ <div className={cn("h-full", mobileTab !== "chat" && "hidden")}>+ <AgentChat+ threadId={threadId}+ initialMessages={data.messages}+ isReadOnly={data.isReadOnly}+ readOnlyReason={readOnlyReason}+ threadStatus={data.thread.status}+ activeRunId={data.thread.activeRunId}+ actions={data.actions}+ />+ </div>+ <div className={cn("h-full", mobileTab !== "resume" && "hidden")}>+ <ResumePane resume={data.resume} />+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/src/routes/agent/-$threadId.test.ts b/apps/web/src/routes/agent/-$threadId.test.tsnew file mode 100644index 000000000..18a3a53dc--- /dev/null+++ b/apps/web/src/routes/agent/-$threadId.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import {+ attachmentIdsFromTransportBody,+ attachmentToFilePart,+ buildAgentChatSubmission,+} from "./-helpers/chat-attachments";++describe("agent chat attachment helpers", () => {+ it("builds safe UI file parts without embedding file bytes", () => {+ expect(attachmentToFilePart({ id: "attachment-1", filename: "resume.pdf", mediaType: "application/pdf" })).toEqual({+ type: "file",+ url: "agent-attachment:attachment-1",+ mediaType: "application/pdf",+ filename: "resume.pdf",+ });+ });++ it("extracts only string attachment IDs from transport body metadata", () => {+ expect(attachmentIdsFromTransportBody({ attachmentIds: ["a", 1, "b", null] })).toEqual(["a", "b"]);+ expect(attachmentIdsFromTransportBody({ attachmentIds: "a" })).toBeUndefined();+ expect(attachmentIdsFromTransportBody(undefined)).toBeUndefined();+ });++ it("keeps attachment IDs in transport metadata while sending file parts in the UI message", () => {+ const submission = buildAgentChatSubmission(" Tailor this ", [+ { id: "attachment-1", filename: "job.txt", mediaType: "text/plain" },+ { id: "attachment-2", filename: "portfolio.png", mediaType: "image/png" },+ ]);++ expect(submission).toEqual({+ message: {+ text: "Tailor this",+ files: [+ {+ type: "file",+ url: "agent-attachment:attachment-1",+ mediaType: "text/plain",+ filename: "job.txt",+ },+ {+ type: "file",+ url: "agent-attachment:attachment-2",+ mediaType: "image/png",+ filename: "portfolio.png",+ },+ ],+ },+ options: { body: { attachmentIds: ["attachment-1", "attachment-2"] } },+ });+ });++ it("supports attachment-only submissions", () => {+ const submission = buildAgentChatSubmission(" ", [+ { id: "attachment-1", filename: "job.txt", mediaType: "text/plain" },+ ]);++ expect(submission.message).toEqual({+ files: [+ {+ type: "file",+ url: "agent-attachment:attachment-1",+ mediaType: "text/plain",+ filename: "job.txt",+ },+ ],+ });+ expect(submission.options).toEqual({ body: { attachmentIds: ["attachment-1"] } });+ });+});diff --git a/apps/web/src/routes/agent/-components/new-thread-setup.tsx b/apps/web/src/routes/agent/-components/new-thread-setup.tsxnew file mode 100644index 000000000..04cbf3e80--- /dev/null+++ b/apps/web/src/routes/agent/-components/new-thread-setup.tsx@@ -0,0 +1,209 @@+import type { AIProvider } from "@reactive-resume/ai/types";+import { t } from "@lingui/core/macro";+import { Trans } from "@lingui/react/macro";+import { ArrowRightIcon, ChatCircleDotsIcon, FilePlusIcon, GearSixIcon } from "@phosphor-icons/react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Link, useNavigate } from "@tanstack/react-router";+import { useEffect, useMemo, useState } from "react";+import { toast } from "sonner";+import { useIsClient } from "usehooks-ts";+import { Badge } from "@reactive-resume/ui/components/badge";+import { Button } from "@reactive-resume/ui/components/button";+import { Label } from "@reactive-resume/ui/components/label";+import { Spinner } from "@reactive-resume/ui/components/spinner";+import { Combobox } from "@/components/ui/combobox";+import { getOrpcErrorMessage } from "@/libs/error-message";+import { orpc } from "@/libs/orpc/client";++function providerLabel(provider: { label: string; provider: AIProvider; model: string }) {+ return `${provider.label} · ${provider.provider} · ${provider.model}`;+}++function isAgentConfigError(error: unknown) {+ if (!error || typeof error !== "object") return false;+ const message = (error as { message?: unknown }).message;+ const status = (error as { status?: unknown; code?: unknown }).status ?? (error as { code?: unknown }).code;+ if (status === "PRECONDITION_FAILED" || status === 412) return true;+ return typeof message === "string" && /REDIS_URL|ENCRYPTION_SECRET/.test(message);+}++export function NewThreadSetup({ resumeId }: { resumeId?: string }) {+ const isClient = useIsClient();+ const navigate = useNavigate();+ const {+ data: providers,+ isLoading: isLoadingProviders,+ error: providersError,+ } = useQuery(orpc.aiProviders.list.queryOptions());+ const { data: resumes, isLoading: isLoadingResumes } = useQuery(+ orpc.resume.list.queryOptions({ input: { sort: "lastUpdatedAt", tags: [] } }),+ );+ const { mutate: createThread, isPending } = useMutation(orpc.agent.threads.create.mutationOptions());++ const usableProviders = useMemo(+ () => providers?.filter((provider) => provider.enabled && provider.testStatus === "success") ?? [],+ [providers],+ );+ const [aiProviderId, setAiProviderId] = useState<string | null>(null);+ const [sourceResumeId, setSourceResumeId] = useState<string | null>(resumeId ?? null);++ useEffect(() => {+ if (aiProviderId || usableProviders.length === 0) return;+ setAiProviderId(usableProviders[0]?.id ?? null);+ }, [aiProviderId, usableProviders]);++ useEffect(() => {+ setSourceResumeId(resumeId ?? null);+ }, [resumeId]);++ const providerOptions = usableProviders.map((provider) => ({+ value: provider.id,+ label: providerLabel(provider),+ keywords: [provider.label, provider.provider, provider.model],+ }));++ const resumeOptions = [+ { value: "__scratch__", label: t`Create from scratch` },+ ...(resumes?.map((resume) => ({+ value: resume.id,+ label: resume.name,+ keywords: [resume.name, resume.slug, ...resume.tags],+ })) ?? []),+ ];++ const selectedResumeValue = sourceResumeId ?? "__scratch__";+ const canCreate = !!aiProviderId && usableProviders.length > 0;++ if (!isClient) return null;++ return (+ <div className="mx-auto grid w-full max-w-4xl gap-6 self-center p-4 lg:p-6">+ <div className="flex items-start gap-4">+ <div className="grid size-12 shrink-0 place-items-center rounded-md border bg-card shadow-sm lg:size-14">+ <ChatCircleDotsIcon className="size-6 text-foreground" weight="fill" />+ </div>+ <div className="min-w-0">+ <h1 className="font-semibold text-3xl tracking-tight lg:text-4xl">+ <Trans>Start a thread</Trans>+ </h1>+ <p className="mt-1 text-muted-foreground">+ <Trans>Choose a model and resume draft.</Trans>+ </p>+ </div>+ </div>++ {providersError ? (+ <div className="rounded-md border border-amber-300 bg-amber-50 p-4 text-amber-950 text-sm dark:bg-amber-950/20 dark:text-amber-200">+ {isAgentConfigError(providersError) ? (+ <Trans>AI agent setup is unavailable until REDIS_URL and ENCRYPTION_SECRET are configured.</Trans>+ ) : (+ <Trans>AI agent setup is unavailable right now. Please try again in a moment.</Trans>+ )}+ </div>+ ) : null}++ <div className="rounded-md border bg-card p-4 shadow-sm lg:p-6">+ <div className="grid gap-x-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">+ <div className="relative isolate min-h-32 overflow-hidden rounded-md p-1 lg:p-2">+ <span+ aria-hidden="true"+ className="pointer-events-none absolute -top-7 right-1 -z-10 select-none font-black text-8xl text-foreground/[0.045] leading-none lg:-top-10 lg:right-3 lg:text-[8rem]"+ >+ 1+ </span>+ <div className="space-y-3">+ <Label>+ <Trans>Select an agent model</Trans>+ </Label>+ <Combobox+ value={aiProviderId}+ options={providerOptions}+ disabled={isLoadingProviders || providerOptions.length === 0}+ placeholder={isLoadingProviders ? t`Loading providers...` : t`Select a tested provider`}+ onValueChange={setAiProviderId}+ />+ {providerOptions.length === 0 && !isLoadingProviders ? (+ <div className="flex flex-col gap-3 rounded-md border border-dashed p-3 text-sm lg:flex-row lg:items-center lg:justify-between">+ <span className="text-muted-foreground">+ <Trans>Add and test a provider before starting a thread.</Trans>+ </span>+ <Button+ size="sm"+ variant="outline"+ nativeButton={false}+ render={<Link to="/dashboard/settings/integrations" />}+ >+ <GearSixIcon />+ <Trans>Settings</Trans>+ </Button>+ </div>+ ) : null}+ </div>+ </div>++ <div className="relative isolate min-h-32 overflow-hidden rounded-md p-1 lg:p-2">+ <span+ aria-hidden="true"+ className="pointer-events-none absolute -top-7 right-1 -z-10 select-none font-black text-8xl text-foreground/[0.045] leading-none lg:-top-10 lg:right-3 lg:text-[8rem]"+ >+ 2+ </span>+ <div className="space-y-3">+ <Label>+ <Trans>Select a resume</Trans>+ </Label>+ <Combobox+ value={selectedResumeValue}+ showClear={false}+ options={resumeOptions}+ disabled={isLoadingResumes}+ placeholder={isLoadingResumes ? t`Loading resumes...` : t`Choose a resume`}+ onValueChange={(value) => setSourceResumeId(value && value !== "__scratch__" ? value : null)}+ />+ <div className="flex flex-wrap items-center gap-2 text-muted-foreground text-sm">+ <Badge variant="secondary" className="h-7 gap-1.5 rounded-md px-2">+ <FilePlusIcon />+ {sourceResumeId ? <Trans>Duplicate as AI Draft</Trans> : <Trans>Blank draft</Trans>}+ </Badge>+ </div>+ </div>+ </div>+ </div>++ <div className="mt-2 flex border-t pt-5 lg:justify-end">+ <Button+ size="lg"+ className="h-11 w-full gap-2 px-5 lg:w-auto"+ disabled={!canCreate || isPending}+ onClick={() =>+ createThread(+ {+ ...(aiProviderId ? { aiProviderId } : {}),+ ...(sourceResumeId ? { sourceResumeId } : {}),+ },+ {+ onSuccess: (thread) => {+ void navigate({ to: "/agent/$threadId", params: { threadId: thread.id } });+ },+ onError: (error) =>+ toast.error(+ getOrpcErrorMessage(error, {+ byCode: {+ PRECONDITION_FAILED: t`AI agent setup is unavailable until REDIS_URL and ENCRYPTION_SECRET are configured.`,+ BAD_REQUEST: t`Select a tested provider before starting a thread.`,+ },+ fallback: t`Failed to start agent thread.`,+ }),+ ),+ },+ )+ }+ >+ <Trans>Start Thread</Trans>+ {isPending ? <Spinner /> : <ArrowRightIcon />}+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/src/routes/agent/-components/thread-sidebar.tsx b/apps/web/src/routes/agent/-components/thread-sidebar.tsxnew file mode 100644index 000000000..2b1637854--- /dev/null+++ b/apps/web/src/routes/agent/-components/thread-sidebar.tsx@@ -0,0 +1,217 @@+import type { RouterOutput } from "@/libs/orpc/client";+import { t } from "@lingui/core/macro";+import { useLingui } from "@lingui/react";+import { Trans } from "@lingui/react/macro";+import {+ ArchiveIcon,+ ArrowLeftIcon,+ ChatCircleDotsIcon,+ DotsThreeVerticalIcon,+ PlusIcon,+ TrashIcon,+} from "@phosphor-icons/react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Link, useNavigate } from "@tanstack/react-router";+import { toast } from "sonner";+import { Button } from "@reactive-resume/ui/components/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@reactive-resume/ui/components/dropdown-menu";+import { ScrollArea } from "@reactive-resume/ui/components/scroll-area";+import { cn } from "@reactive-resume/utils/style";+import { useConfirm } from "@/hooks/use-confirm";+import { getOrpcErrorMessage } from "@/libs/error-message";+import { orpc } from "@/libs/orpc/client";++type AgentThreadSummary = RouterOutput["agent"]["threads"]["list"][number];++function formatRelativeTime(value: Date | string, locale: string) {+ const date = value instanceof Date ? value : new Date(value);+ const diffMs = date.getTime() - Date.now();+ const absMs = Math.abs(diffMs);+ const divisions: Array<{ amount: number; unit: Intl.RelativeTimeFormatUnit }> = [+ { amount: 31_536_000_000, unit: "year" },+ { amount: 2_592_000_000, unit: "month" },+ { amount: 604_800_000, unit: "week" },+ { amount: 86_400_000, unit: "day" },+ { amount: 3_600_000, unit: "hour" },+ { amount: 60_000, unit: "minute" },+ ];++ if (absMs < 60_000) return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(0, "second");++ const division = divisions.find((candidate) => absMs >= candidate.amount);+ if (!division) return "";++ return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(+ Math.round(diffMs / division.amount),+ division.unit,+ );+}++function ThreadActions({ thread, activeThreadId }: { thread: AgentThreadSummary; activeThreadId: string | null }) {+ const navigate = useNavigate();+ const confirm = useConfirm();+ const queryClient = useQueryClient();+ const archiveMutation = useMutation(orpc.agent.threads.archive.mutationOptions());+ const deleteMutation = useMutation(orpc.agent.threads.delete.mutationOptions());+ const isArchived = thread.status === "archived";++ const handleArchive = () => {+ archiveMutation.mutate(+ { id: thread.id },+ {+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey: orpc.agent.threads.list.queryKey() });+ if (activeThreadId === thread.id) {+ await queryClient.invalidateQueries({+ queryKey: orpc.agent.threads.get.queryKey({ input: { id: thread.id } }),+ });+ }+ },+ onError: (error) => toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to archive thread.` })),+ },+ );+ };++ const handleDelete = async () => {+ const confirmed = await confirm(t`Delete this agent thread?`, {+ description: t`This action cannot be undone. Messages and thread attachments will be removed.`,+ });++ if (!confirmed) return;++ deleteMutation.mutate(+ { id: thread.id },+ {+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey: orpc.agent.threads.list.queryKey() });+ if (activeThreadId === thread.id) void navigate({ to: "/agent" });+ },+ onError: (error) => toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to delete thread.` })),+ },+ );+ };++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ size="icon-sm"+ variant="ghost"+ className="absolute end-1.5 top-2 opacity-60 transition-opacity hover:opacity-100 focus-visible:opacity-100 group-hover/thread:opacity-100 aria-expanded:opacity-100"+ >+ <DotsThreeVerticalIcon />+ <span className="sr-only">+ <Trans>Thread actions</Trans>+ </span>+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ {!isArchived ? (+ <DropdownMenuItem disabled={archiveMutation.isPending} onClick={handleArchive}>+ <ArchiveIcon />+ <Trans>Archive</Trans>+ </DropdownMenuItem>+ ) : null}+ <DropdownMenuItem variant="destructive" disabled={deleteMutation.isPending} onClick={() => void handleDelete()}>+ <TrashIcon />+ <Trans>Delete</Trans>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function ThreadRow({ thread, activeThreadId }: { thread: AgentThreadSummary; activeThreadId: string | null }) {+ const { i18n } = useLingui();+ const isActive = thread.id === activeThreadId;+ const isArchived = thread.status === "archived";+ const title = thread.title === thread.resumeName ? t`New thread` : thread.title;++ return (+ <div+ className={cn(+ "group/thread relative rounded-md transition-colors hover:bg-accent",+ isActive && "bg-accent",+ isArchived && "opacity-60",+ )}+ >+ <Link+ to="/agent/$threadId"+ params={{ threadId: thread.id }}+ className="block min-w-0 rounded-md px-3 py-2 pe-10 text-sm outline-hidden ring-ring focus-visible:ring-2"+ >+ <div className="truncate font-medium">{title}</div>+ <div className="truncate text-muted-foreground text-xs">+ {formatRelativeTime(thread.lastMessageAt, i18n.locale)}+ </div>+ </Link>+ <ThreadActions thread={thread} activeThreadId={activeThreadId} />+ </div>+ );+}++export function AgentThreadSidebar({+ activeThreadId = null,+ className,+}: {+ activeThreadId?: string | null;+ className?: string;+}) {+ const { data: threads, isLoading } = useQuery(orpc.agent.threads.list.queryOptions());++ return (+ <aside className={cn("flex h-full min-h-0 flex-col border-e bg-muted/30", className)}>+ <div className="flex h-14 shrink-0 items-center justify-between gap-3 border-b px-3">+ <div className="flex min-w-0 items-center gap-2">+ <ChatCircleDotsIcon className="shrink-0" />+ <div className="min-w-0 truncate font-semibold">+ <Trans>Threads</Trans>+ </div>+ </div>+ <Button size="icon-sm" variant="ghost" nativeButton={false} render={<Link to="/dashboard/resumes" />}>+ <ArrowLeftIcon />+ <span className="sr-only">+ <Trans>Back to resumes</Trans>+ </span>+ </Button>+ </div>++ <ScrollArea className="min-h-0 flex-1">+ <div className="space-y-1 p-2">+ <Button+ variant="ghost"+ className="mb-2 w-full justify-start border border-dashed bg-background/40 text-muted-foreground hover:text-foreground"+ nativeButton={false}+ render={<Link to="/agent/new" />}+ >+ <PlusIcon />+ <Trans>New thread</Trans>+ </Button>++ {isLoading ? (+ <div className="px-3 py-2 text-muted-foreground text-sm">+ <Trans>Loading threads...</Trans>+ </div>+ ) : null}++ {threads?.length === 0 ? (+ <div className="rounded-md border border-dashed p-3 text-muted-foreground text-sm">+ <Trans>No threads yet.</Trans>+ </div>+ ) : null}++ {threads?.map((thread) => (+ <ThreadRow key={thread.id} thread={thread} activeThreadId={activeThreadId} />+ ))}+ </div>+ </ScrollArea>+ </aside>+ );+}diff --git a/apps/web/src/routes/agent/-helpers/chat-attachments.ts b/apps/web/src/routes/agent/-helpers/chat-attachments.tsnew file mode 100644index 000000000..0ce1e3b1c--- /dev/null+++ b/apps/web/src/routes/agent/-helpers/chat-attachments.ts@@ -0,0 +1,38 @@+import type { FileUIPart } from "ai";++export type ChatAttachment = {+ id: string;+ filename: string;+ mediaType: string;+};++export function attachmentToFilePart(attachment: ChatAttachment): FileUIPart {+ return {+ type: "file",+ url: `agent-attachment:${attachment.id}`,+ mediaType: attachment.mediaType,+ filename: attachment.filename,+ };+}++export function attachmentIdsFromTransportBody(body: object | undefined) {+ return body && "attachmentIds" in body && Array.isArray(body.attachmentIds)+ ? body.attachmentIds.filter((id): id is string => typeof id === "string")+ : undefined;+}++export function buildAgentChatSubmission(text: string, pendingAttachments: ChatAttachment[]) {+ const trimmedText = text.trim();+ const files = pendingAttachments.map(attachmentToFilePart);+ const attachmentIds = pendingAttachments.map((attachment) => attachment.id);+ const options = { body: { attachmentIds } };++ if (trimmedText) {+ return {+ message: files.length > 0 ? { text: trimmedText, files } : { text: trimmedText },+ options,+ };+ }++ return { message: { files }, options };+}diff --git a/apps/web/src/routes/agent/index.tsx b/apps/web/src/routes/agent/index.tsxnew file mode 100644index 000000000..9767f1c5d--- /dev/null+++ b/apps/web/src/routes/agent/index.tsx@@ -0,0 +1,44 @@+import { Trans } from "@lingui/react/macro";+import { ArrowRightIcon, ChatCircleDotsIcon } from "@phosphor-icons/react";+import { createFileRoute, Link } from "@tanstack/react-router";+import { Button } from "@reactive-resume/ui/components/button";+import { AgentThreadSidebar } from "./-components/thread-sidebar";++export const Route = createFileRoute("/agent/")({+ component: RouteComponent,+});++function RouteComponent() {+ return (+ <div className="flex h-svh bg-background">+ <div className="w-72 shrink-0">+ <AgentThreadSidebar />+ </div>++ <main className="grid min-w-0 flex-1 place-items-center p-6">+ <div className="w-full max-w-xl rounded-md border bg-card p-6 shadow-sm">+ <div className="flex items-start gap-4">+ <div className="grid size-11 shrink-0 place-items-center rounded-md border bg-background">+ <ChatCircleDotsIcon className="size-5" weight="fill" />+ </div>+ <div className="min-w-0 space-y-2">+ <h1 className="font-semibold text-2xl tracking-tight">+ <Trans>Select a thread</Trans>+ </h1>+ <p className="text-muted-foreground text-sm">+ <Trans>Choose an existing conversation from the sidebar, or start a new draft-focused thread.</Trans>+ </p>+ </div>+ </div>++ <div className="mt-6 flex justify-end border-t pt-4">+ <Button nativeButton={false} render={<Link to="/agent/new" />}>+ <ArrowRightIcon />+ <Trans>Start new thread</Trans>+ </Button>+ </div>+ </div>+ </main>+ </div>+ );+}diff --git a/apps/web/src/routes/agent/new.tsx b/apps/web/src/routes/agent/new.tsxnew file mode 100644index 000000000..cfe420837--- /dev/null+++ b/apps/web/src/routes/agent/new.tsx@@ -0,0 +1,27 @@+import { createFileRoute } from "@tanstack/react-router";+import z from "zod";+import { NewThreadSetup } from "./-components/new-thread-setup";+import { AgentThreadSidebar } from "./-components/thread-sidebar";++const searchSchema = z.object({ resumeId: z.string().optional() });++export const Route = createFileRoute("/agent/new")({+ component: RouteComponent,+ validateSearch: searchSchema,+});++function RouteComponent() {+ const { resumeId } = Route.useSearch();++ return (+ <div className="flex h-svh bg-background">+ <div className="w-72 shrink-0">+ <AgentThreadSidebar />+ </div>++ <main className="grid min-w-0 flex-1 overflow-auto">+ <NewThreadSetup resumeId={resumeId} />+ </main>+ </div>+ );+}diff --git a/apps/web/src/routes/agent/route.tsx b/apps/web/src/routes/agent/route.tsxnew file mode 100644index 000000000..0fa33e68d--- /dev/null+++ b/apps/web/src/routes/agent/route.tsx@@ -0,0 +1,13 @@+import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";++export const Route = createFileRoute("/agent")({+ component: RouteComponent,+ beforeLoad: async ({ context }) => {+ if (!context.session) throw redirect({ to: "/auth/login", replace: true });+ return { session: context.session };+ },+});++function RouteComponent() {+ return <Outlet />;+}diff --git a/apps/web/src/routes/builder/$resumeId/-components/assistant-store.test.ts b/apps/web/src/routes/builder/$resumeId/-components/assistant-store.test.tsdeleted file mode 100644index 4f60dfab8..000000000--- a/apps/web/src/routes/builder/$resumeId/-components/assistant-store.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { useBuilderAssistantStore } from "./assistant-store";--afterEach(() => useBuilderAssistantStore.setState({ isOpen: false }));--describe("useBuilderAssistantStore", () => {- it("starts closed", () => {- expect(useBuilderAssistantStore.getState().isOpen).toBe(false);- });-- it("setOpen overrides the open state directly", () => {- useBuilderAssistantStore.getState().setOpen(true);- expect(useBuilderAssistantStore.getState().isOpen).toBe(true);-- useBuilderAssistantStore.getState().setOpen(false);- expect(useBuilderAssistantStore.getState().isOpen).toBe(false);- });-- it("toggleOpen flips the state", () => {- const { toggleOpen } = useBuilderAssistantStore.getState();-- toggleOpen();- expect(useBuilderAssistantStore.getState().isOpen).toBe(true);-- toggleOpen();- expect(useBuilderAssistantStore.getState().isOpen).toBe(false);- });-});diff --git a/apps/web/src/routes/builder/$resumeId/-components/assistant-store.ts b/apps/web/src/routes/builder/$resumeId/-components/assistant-store.tsdeleted file mode 100644index c782961e0..000000000--- a/apps/web/src/routes/builder/$resumeId/-components/assistant-store.ts+++ /dev/null@@ -1,13 +0,0 @@-import { create } from "zustand/react";--type BuilderAssistantStore = {- isOpen: boolean;- setOpen: (isOpen: boolean) => void;- toggleOpen: () => void;-};--export const useBuilderAssistantStore = create<BuilderAssistantStore>((set) => ({- isOpen: false,- setOpen: (isOpen) => set({ isOpen }),- toggleOpen: () => set((state) => ({ isOpen: !state.isOpen })),-}));diff --git a/apps/web/src/routes/builder/$resumeId/-components/assistant.tsx b/apps/web/src/routes/builder/$resumeId/-components/assistant.tsxdeleted file mode 100644index 33de7b472..000000000--- a/apps/web/src/routes/builder/$resumeId/-components/assistant.tsx+++ /dev/null@@ -1,1088 +0,0 @@-import type { UIMessage } from "@ai-sdk/react";-import type { ResumePatchProposal, ResumePatchProposalPreview } from "@reactive-resume/ai/tools/patch-proposal";-import type React from "react";-import type { Resume } from "@/components/resume/builder-resume-draft";-import { useChat } from "@ai-sdk/react";-import { t } from "@lingui/core/macro";-import { Trans } from "@lingui/react/macro";-import { eventIteratorToUnproxiedDataStream } from "@orpc/client";-import {- ArrowClockwiseIcon,- CaretDownIcon,- ChatCircleDotsIcon,- CheckIcon,- MagicWandIcon,- NotchesIcon,- PaperPlaneRightIcon,- SparkleIcon,- WarningCircleIcon,- XIcon,-} from "@phosphor-icons/react";-import { useMutation } from "@tanstack/react-query";-import { Link } from "@tanstack/react-router";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { toast } from "sonner";-import { useAIStore } from "@reactive-resume/ai/store";-import {- buildResumePatchProposalPreview,- resumePatchProposalToolOutputSchema,-} from "@reactive-resume/ai/tools/patch-proposal";-import { Badge } from "@reactive-resume/ui/components/badge";-import { Button } from "@reactive-resume/ui/components/button";-import { ButtonGroup } from "@reactive-resume/ui/components/button-group";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@reactive-resume/ui/components/dropdown-menu";-import { ScrollArea } from "@reactive-resume/ui/components/scroll-area";-import { Sheet, SheetContent } from "@reactive-resume/ui/components/sheet";-import { Textarea } from "@reactive-resume/ui/components/textarea";-import { cn } from "@reactive-resume/utils/style";-import { useCurrentResume, useReplaceResumeFromServer } from "@/components/resume/builder-resume-draft";-import { useIsMobile } from "@/hooks/use-mobile";-import { getOrpcErrorMessage } from "@/libs/error-message";-import { orpc, streamClient } from "@/libs/orpc/client";-import { useBuilderAssistantStore } from "./assistant-store";--type AssistantLayout = {- window: { x: number; y: number; width: number; height: number };-};--type QueuedProposal = {- key: string;- sourceMessageId: string;- toolCallId: string;- proposal: ResumePatchProposal;- preview: ResumePatchProposalPreview;- stalePreview?: boolean;-};--type ProposalResolution = {- key: string;- sourceMessageId: string;- title: string;- status: "accepted" | "rejected";-};--const MIN_WINDOW_WIDTH = 360;-const MIN_WINDOW_HEIGHT = 440;-const DEFAULT_WINDOW_WIDTH = 460;-const DEFAULT_WINDOW_HEIGHT = 650;-const LAYOUT_STORAGE_VERSION = 2;--function clamp(value: number, min: number, max: number): number {- return Math.min(Math.max(value, min), max);-}--function createDefaultLayout(): AssistantLayout {- if (typeof window === "undefined") {- return {- window: { x: 24, y: 88, width: DEFAULT_WINDOW_WIDTH, height: DEFAULT_WINDOW_HEIGHT },- };- }-- const width = Math.min(DEFAULT_WINDOW_WIDTH, window.innerWidth - 32);- const height = Math.min(DEFAULT_WINDOW_HEIGHT, window.innerHeight - 112);-- return {- window: {- x: Math.max(16, Math.round((window.innerWidth - width) / 2)),- y: Math.max(68, Math.round((window.innerHeight - height) / 2)),- width,- height,- },- };-}--function constrainLayout(layout: AssistantLayout): AssistantLayout {- if (typeof window === "undefined") return layout;-- const maxWindowWidth = Math.max(MIN_WINDOW_WIDTH, window.innerWidth - 32);- const maxWindowHeight = Math.max(MIN_WINDOW_HEIGHT, window.innerHeight - 88);- const width = clamp(layout.window.width, MIN_WINDOW_WIDTH, maxWindowWidth);- const height = clamp(layout.window.height, MIN_WINDOW_HEIGHT, maxWindowHeight);-- return {- window: {- x: clamp(layout.window.x, 12, window.innerWidth - width - 12),- y: clamp(layout.window.y, 68, window.innerHeight - height - 12),- width,- height,- },- };-}--function getLayoutStorageKey(resumeId: string) {- return `resume-builder-ai-assistant:${resumeId}:layout:v${LAYOUT_STORAGE_VERSION}`;-}--function usePersistentAssistantLayout(resumeId: string) {- const [layout, setLayout] = useState<AssistantLayout>(() => createDefaultLayout());- const hydratedRef = useRef(false);-- useEffect(() => {- const key = getLayoutStorageKey(resumeId);-- try {- const stored = window.localStorage.getItem(key);- const parsed = stored ? (JSON.parse(stored) as AssistantLayout) : createDefaultLayout();- setLayout(constrainLayout(parsed));- } catch {- setLayout(constrainLayout(createDefaultLayout()));- } finally {- hydratedRef.current = true;- }- }, [resumeId]);-- useEffect(() => {- if (!hydratedRef.current) return;-- try {- window.localStorage.setItem(getLayoutStorageKey(resumeId), JSON.stringify(layout));- } catch {- // Layout persistence is best effort only.- }- }, [layout, resumeId]);-- useEffect(() => {- const onResize = () => setLayout((current) => constrainLayout(current));- window.addEventListener("resize", onResize);- return () => window.removeEventListener("resize", onResize);- }, []);-- return { layout, setLayout };-}--function formatPreviewValue(value: unknown): string {- if (value === undefined || value === null || value === "") return "Empty";- if (typeof value === "string") {- const text = value- .replace(/<[^>]*>/g, " ")- .replace(/\s+/g, " ")- .trim();-- return text || value;- }-- return JSON.stringify(value, null, 2);-}--function refreshQueuedProposal(item: QueuedProposal, resume: Resume): QueuedProposal {- const proposal = { ...item.proposal, baseUpdatedAt: resume.updatedAt.toISOString() };-- try {- return {- ...item,- proposal,- preview: buildResumePatchProposalPreview(resume.data, proposal),- stalePreview: false,- };- } catch {- return { ...item, proposal, stalePreview: true };- }-}--function getPatchErrorMessage(error: unknown): string {- return getOrpcErrorMessage(error, {- allowServerMessage: true,- byCode: {- INVALID_PATCH_OPERATIONS: t`The AI proposed a change that no longer applies to this resume.`,- RESUME_LOCKED: t`This resume is locked and cannot be updated.`,- RESUME_VERSION_CONFLICT: t`This proposal is stale. Ask the assistant to regenerate it from the latest resume.`,- },- fallback: t`Could not apply the AI proposal.`,- });-}--function beginElementDrag(- event: React.PointerEvent<HTMLElement>,- onMove: (deltaX: number, deltaY: number) => void,- onEnd?: () => void,-) {- if (event.button !== 0) return;-- const target = event.currentTarget;- const startX = event.clientX;- const startY = event.clientY;-- target.setPointerCapture(event.pointerId);-- const handlePointerMove = (moveEvent: PointerEvent) => {- onMove(moveEvent.clientX - startX, moveEvent.clientY - startY);- };-- const handlePointerUp = () => {- target.removeEventListener("pointermove", handlePointerMove);- target.removeEventListener("pointerup", handlePointerUp);- target.removeEventListener("pointercancel", handlePointerUp);- onEnd?.();- };-- target.addEventListener("pointermove", handlePointerMove);- target.addEventListener("pointerup", handlePointerUp);- target.addEventListener("pointercancel", handlePointerUp);-}--export function BuilderAssistant() {- const resume = useCurrentResume();- const isMobile = useIsMobile();- const { layout, setLayout } = usePersistentAssistantLayout(resume.id);- const isOpen = useBuilderAssistantStore((state) => state.isOpen);- const setIsOpen = useBuilderAssistantStore((state) => state.setOpen);-- const beginWindowDrag = (event: React.PointerEvent<HTMLElement>) => {- const start = layout.window;-- beginElementDrag(event, (deltaX, deltaY) => {- setLayout((current) =>- constrainLayout({- ...current,- window: { ...current.window, x: start.x + deltaX, y: start.y + deltaY },- }),- );- });- };-- const beginWindowResize = (event: React.PointerEvent<HTMLElement>) => {- event.stopPropagation();- const start = layout.window;-- beginElementDrag(event, (deltaX, deltaY) => {- setLayout((current) =>- constrainLayout({- ...current,- window: {- ...current.window,- width: start.width + deltaX,- height: start.height + deltaY,- },- }),- );- });- };-- if (isMobile) {- return (- <Sheet open={isOpen} onOpenChange={setIsOpen}>- <SheetContent side="right" showCloseButton={false} className="h-svh w-svw max-w-none! gap-0 p-0">- <AssistantPanel resume={resume} isMobile onClose={() => setIsOpen(false)} />- </SheetContent>- </Sheet>- );- }-- return isOpen ? (- <div- className="fixed top-0 left-0 z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-2xl ring-1 ring-foreground/10"- style={{- width: layout.window.width,- height: layout.window.height,- transform: `translate3d(${layout.window.x}px, ${layout.window.y}px, 0)`,- }}- >- <AssistantPanel- resume={resume}- onClose={() => setIsOpen(false)}- onDragHeaderPointerDown={beginWindowDrag}- onResizePointerDown={beginWindowResize}- />- </div>- ) : null;-}--type AssistantPanelProps = {- resume: Resume;- isMobile?: boolean;- onClose: () => void;- onDragHeaderPointerDown?: (event: React.PointerEvent<HTMLElement>) => void;- onResizePointerDown?: (event: React.PointerEvent<HTMLElement>) => void;-};--function AssistantPanel({- resume,- isMobile = false,- onClose,- onDragHeaderPointerDown,- onResizePointerDown,-}: AssistantPanelProps) {- const replaceResumeFromServer = useReplaceResumeFromServer();- const aiEnabled = useAIStore((state) => state.enabled);- const provider = useAIStore((state) => state.provider);- const model = useAIStore((state) => state.model);- const apiKey = useAIStore((state) => state.apiKey);- const baseURL = useAIStore((state) => state.baseURL);- const [input, setInput] = useState("");- const [queue, setQueue] = useState<QueuedProposal[]>([]);- const [activeIndex, setActiveIndex] = useState(0);- const [resolutions, setResolutions] = useState<Record<string, ProposalResolution>>({});- const seenProposalKeysRef = useRef(new Set<string>());- const requestContextRef = useRef({- provider,- model,- apiKey,- baseURL,- resumeData: resume.data,- resumeUpdatedAt: resume.updatedAt,- });-- requestContextRef.current = {- provider,- model,- apiKey,- baseURL,- resumeData: resume.data,- resumeUpdatedAt: resume.updatedAt,- };-- const transport = useMemo(- () => ({- async sendMessages(options: { messages: UIMessage[]; abortSignal?: AbortSignal }) {- const requestContext = requestContextRef.current;-- return eventIteratorToUnproxiedDataStream(- await streamClient.ai.chat(- {- provider: requestContext.provider,- model: requestContext.model,- apiKey: requestContext.apiKey,- baseURL: requestContext.baseURL,- messages: options.messages,- resumeData: requestContext.resumeData,- resumeUpdatedAt: requestContext.resumeUpdatedAt,- },- { signal: options.abortSignal },- ),- );- },- reconnectToStream() {- throw new Error("AI assistant stream reconnection is not supported.");- },- }),- [],- );-- const { messages, sendMessage, status, error, stop, setMessages, clearError } = useChat({ transport });- const patchMutation = useMutation(orpc.resume.patch.mutationOptions({ meta: { noInvalidate: true } }));- const hasChatError = status === "error" || Boolean(error);- const isStreaming = !hasChatError && (status === "submitted" || status === "streaming");- const isApplying = patchMutation.isPending;- const activeProposal = queue[activeIndex];- const activeProposalSourceVisible = activeProposal- ? messages.some((message) => message.id === activeProposal.sourceMessageId)- : false;-- const resolveProposal = useCallback((item: QueuedProposal, status: ProposalResolution["status"]) => {- setResolutions((current) => ({- ...current,- [item.key]: {- key: item.key,- sourceMessageId: item.sourceMessageId,- title: item.preview.title,- status,- },- }));- }, []);-- useEffect(() => {- if (activeIndex < queue.length) return;- setActiveIndex(Math.max(0, queue.length - 1));- }, [activeIndex, queue.length]);-- useEffect(() => {- if (!error || (status !== "submitted" && status !== "streaming")) return;- stop();- }, [error, status, stop]);-- useEffect(() => {- const incoming: QueuedProposal[] = [];-- for (const message of messages) {- for (const part of message.parts ?? []) {- if (part.type !== "tool-propose_resume_patches" || part.state !== "output-available") continue;-- const parsed = resumePatchProposalToolOutputSchema.safeParse(part.output);- if (!parsed.success) continue;-- for (const proposal of parsed.data.proposals) {- const key = `${part.toolCallId}:${proposal.id}`;- if (seenProposalKeysRef.current.has(key)) continue;-- try {- incoming.push({- key,- sourceMessageId: message.id,- toolCallId: part.toolCallId,- proposal,- preview: buildResumePatchProposalPreview(resume.data, proposal),- });- seenProposalKeysRef.current.add(key);- } catch {- toast.error(t`The AI returned a proposal that could not be previewed.`);- }- }- }- }-- if (incoming.length === 0) return;-- setQueue((current) => [...current, ...incoming]);- setActiveIndex((index) => (queue.length === 0 ? 0 : index));- }, [messages, queue.length, resume.data]);-- const removeActiveProposal = useCallback(() => {- setQueue((current) => {- const next = current.filter((_, index) => index !== activeIndex);- setActiveIndex((index) => Math.min(index, Math.max(0, next.length - 1)));- return next;- });- }, [activeIndex]);-- const handleAcceptCurrent = async () => {- if (!activeProposal) return;-- try {- const updated = (await patchMutation.mutateAsync({- id: resume.id,- operations: activeProposal.proposal.operations,- expectedUpdatedAt: activeProposal.proposal.baseUpdatedAt- ? new Date(activeProposal.proposal.baseUpdatedAt)- : resume.updatedAt,- })) as Resume;-- requestContextRef.current = {- ...requestContextRef.current,- resumeData: updated.data,- resumeUpdatedAt: updated.updatedAt,- };- replaceResumeFromServer(updated);- toast.success(t`AI proposal applied.`);- resolveProposal(activeProposal, "accepted");-- setQueue((current) => {- const next = current- .filter((_, index) => index !== activeIndex)- .map((item) => refreshQueuedProposal(item, updated));- setActiveIndex((index) => Math.min(index, Math.max(0, next.length - 1)));- return next;- });- } catch (error) {- toast.error(getPatchErrorMessage(error));- }- };-- const handleRejectCurrent = () => {- if (!activeProposal) return;-- resolveProposal(activeProposal, "rejected");- removeActiveProposal();- toast.message(t`AI proposal rejected.`);- };-- const handleAcceptAll = async () => {- if (queue.length === 0) return;-- try {- const operations = queue.flatMap((item) => item.proposal.operations);- const updated = (await patchMutation.mutateAsync({- id: resume.id,- operations,- expectedUpdatedAt: queue[0]?.proposal.baseUpdatedAt- ? new Date(queue[0].proposal.baseUpdatedAt)- : resume.updatedAt,- })) as Resume;-- requestContextRef.current = {- ...requestContextRef.current,- resumeData: updated.data,- resumeUpdatedAt: updated.updatedAt,- };- replaceResumeFromServer(updated);- setResolutions((current) => ({- ...current,- ...Object.fromEntries(- queue.map((item) => [- item.key,- {- key: item.key,- sourceMessageId: item.sourceMessageId,- title: item.preview.title,- status: "accepted" as const,- },- ]),- ),- }));- setQueue([]);- setActiveIndex(0);- toast.success(t`AI proposals applied.`);- } catch (error) {- toast.error(getPatchErrorMessage(error));- }- };-- const handleRejectAll = () => {- setResolutions((current) => ({- ...current,- ...Object.fromEntries(- queue.map((item) => [- item.key,- {- key: item.key,- sourceMessageId: item.sourceMessageId,- title: item.preview.title,- status: "rejected" as const,- },- ]),- ),- }));- setQueue([]);- setActiveIndex(0);- toast.message(t`AI proposals rejected.`);- };-- const resetChat = () => {- stop();- clearError();- setMessages([]);- setQueue([]);- setActiveIndex(0);- setResolutions({});- setInput("");- seenProposalKeysRef.current.clear();- };-- const submitMessage = () => {- const text = input.trim();- if (!text || !aiEnabled || isStreaming) return;-- clearError();- sendMessage({ text });- setInput("");- };-- return (- <div className="flex size-full flex-col bg-popover">- <header className="flex h-13 shrink-0 select-none items-center gap-3 border-b px-3">- <div- className={cn(- "flex min-w-0 flex-1 items-center gap-3 self-stretch py-2",- onDragHeaderPointerDown && "cursor-grab active:cursor-grabbing",- )}- onPointerDown={onDragHeaderPointerDown}- >- <div className="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">- <ChatCircleDotsIcon className="size-4" weight="fill" />- </div>-- <div className="min-w-0 flex-1">- <div className="font-semibold text-sm leading-tight">- <Trans>AI Resume Assistant</Trans>- </div>- <div className="truncate text-muted-foreground text-xs">- {aiEnabled ? `${provider} · ${model}` : t`AI integration disabled`}- </div>- </div>- </div>-- <Button size="icon-sm" variant="ghost" title={t`Reset chat`} aria-label={t`Reset chat`} onClick={resetChat}>- <ArrowClockwiseIcon />- </Button>- <Button size="icon-sm" variant="ghost" title={t`Close`} onClick={onClose}>- <XIcon />- </Button>- </header>-- {!aiEnabled ? (- <DisabledAssistantState />- ) : (- <>- <div className="min-h-0 flex-1">- <ScrollArea className="h-full">- <div className="space-y-3 p-3">- {messages.length === 0 && !activeProposal ? <EmptyProposalState /> : null}-- <div className="space-y-2">- {messages.map((message) => {- const proposalForMessage =- activeProposal?.sourceMessageId === message.id ? activeProposal : undefined;- const resolutionsForMessage = Object.values(resolutions).filter(- (resolution) => resolution.sourceMessageId === message.id,- );-- return (- <AssistantTimelineItem- key={message.id}- message={message}- proposal={proposalForMessage}- resolutions={resolutionsForMessage}- proposalIndex={activeIndex}- proposalTotal={queue.length}- isApplying={isApplying}- onAcceptProposal={handleAcceptCurrent}- onRejectProposal={handleRejectCurrent}- onAcceptAllProposals={handleAcceptAll}- onRejectAllProposals={handleRejectAll}- onPreviousProposal={() => setActiveIndex((index) => Math.max(0, index - 1))}- onNextProposal={() => setActiveIndex((index) => Math.min(queue.length - 1, index + 1))}- />- );- })}-- {activeProposal && !activeProposalSourceVisible ? (- <ProposalApprovalCard- item={activeProposal}- index={activeIndex}- total={queue.length}- isApplying={isApplying}- onAccept={handleAcceptCurrent}- onReject={handleRejectCurrent}- onAcceptAll={handleAcceptAll}- onRejectAll={handleRejectAll}- onPrevious={() => setActiveIndex((index) => Math.max(0, index - 1))}- onNext={() => setActiveIndex((index) => Math.min(queue.length - 1, index + 1))}- />- ) : null}-- {isStreaming ? <AssistantThinkingBubble status={status} /> : null}- {hasChatError ? <AssistantErrorBubble error={error} /> : null}- </div>- </div>- </ScrollArea>- </div>-- <form- className="border-t p-3"- onSubmit={(event) => {- event.preventDefault();- submitMessage();- }}- >- <div className="flex items-end gap-2">- <Textarea- value={input}- onChange={(event) => setInput(event.target.value)}- placeholder={t`Ask for a targeted resume change...`}- className="max-h-28 min-h-12 resize-none"- disabled={isStreaming}- onKeyDown={(event) => {- if (event.key !== "Enter" || event.shiftKey) return;- event.preventDefault();- submitMessage();- }}- />- <Button size="icon" type="submit" disabled={!input.trim() || isStreaming}>- {isStreaming ? <MagicWandIcon className="animate-pulse" /> : <PaperPlaneRightIcon />}- <span className="sr-only">- <Trans>Send</Trans>- </span>- </Button>- {isStreaming ? (- <Button size="icon" variant="outline" onClick={stop}>- <XIcon />- <span className="sr-only">- <Trans>Stop</Trans>- </span>- </Button>- ) : null}- </div>- </form>- </>- )}-- {!isMobile && onResizePointerDown ? (- <button- type="button"- onPointerDown={onResizePointerDown}- aria-label={t`Resize AI assistant`}- className="absolute right-0 bottom-0 cursor-nwse-resize"- >- <NotchesIcon className="size-3" />- </button>- ) : null}- </div>- );-}--function DisabledAssistantState() {- return (- <div className="flex flex-1 flex-col items-center justify-center gap-4 p-6 text-center">- <div className="flex size-12 items-center justify-center rounded-lg bg-muted text-muted-foreground">- <SparkleIcon className="size-6" />- </div>- <div className="space-y-1">- <div className="font-semibold text-base">- <Trans>Enable AI integration</Trans>- </div>- <p className="max-w-[32ch] text-muted-foreground text-sm">- <Trans>Connect and verify an AI provider before using resume editing proposals.</Trans>- </p>- </div>- <Button nativeButton={false} render={<Link to="/dashboard/settings/integrations" />}>- <Trans>Open Integrations</Trans>- </Button>- </div>- );-}--function EmptyProposalState() {- return (- <div className="rounded-lg border border-dashed bg-muted/20 p-4">- <div className="mb-2 flex items-center gap-2 font-medium text-sm">- <SparkleIcon className="size-4 text-primary" />- <Trans>Ask for an incremental change</Trans>- </div>- <p className="text-muted-foreground text-xs leading-relaxed">- <Trans>- Examples: rewrite the summary, tighten one experience bullet, add metrics, or adapt the resume for a job- description.- </Trans>- </p>- </div>- );-}--type ProposalApprovalCardProps = {- item: QueuedProposal;- index: number;- total: number;- isApplying: boolean;- onAccept: () => void;- onReject: () => void;- onAcceptAll: () => void;- onRejectAll: () => void;- onPrevious: () => void;- onNext: () => void;-};--function ProposalApprovalCard({- item,- index,- total,- isApplying,- onAccept,- onReject,- onAcceptAll,- onRejectAll,- onPrevious,- onNext,-}: ProposalApprovalCardProps) {- return (- <section className="rounded-lg border bg-background shadow-sm ring-1 ring-primary/10">- <div className="space-y-2 border-b bg-muted/20 p-3">- <div className="flex items-start justify-between gap-3">- <div className="flex min-w-0 gap-2.5">- <div className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">- <MagicWandIcon className="size-4" />- </div>- <div className="min-w-0">- <div className="flex flex-wrap items-center gap-1.5">- <code className="rounded bg-background px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">- propose_resume_patches- </code>- {total > 1 ? (- <span className="text-muted-foreground text-xs">- <Trans>- Proposal {index + 1} of {total}- </Trans>- </span>- ) : null}- </div>- <h3 className="mt-1 font-semibold text-sm leading-snug">{item.preview.title}</h3>- {item.preview.summary ? (- <p className="mt-1 text-muted-foreground text-xs leading-relaxed">{item.preview.summary}</p>- ) : null}- </div>- </div>- <Badge variant={item.stalePreview ? "destructive" : "secondary"}>- {item.stalePreview ? <Trans>Needs review</Trans> : <Trans>Review required</Trans>}- </Badge>- </div>-- <div className="flex flex-wrap gap-1.5">- {item.preview.entries.map((entry, entryIndex) => (- <Badge key={`${entry.path}-${entryIndex}`} variant="outline">- {entry.operationLabel}- </Badge>- ))}- </div>- </div>-- <div className="max-h-[310px] space-y-3 overflow-y-auto p-3">- {item.preview.entries.map((entry, entryIndex) => (- <div key={`${entry.path}-${entryIndex}`} className="space-y-2 rounded-md border bg-muted/20 p-2.5">- <div className="flex items-center justify-between gap-2">- <div className="font-medium text-xs">{entry.label}</div>- <code className="max-w-[55%] truncate rounded bg-background px-1.5 py-0.5 text-[10px] text-muted-foreground">- {entry.path}- </code>- </div>- <div className="grid gap-2 sm:grid-cols-2">- <div>- <div className="mb-1 text-[11px] text-muted-foreground uppercase tracking-normal">- <Trans>Before</Trans>- </div>- <pre className="max-h-28 overflow-auto whitespace-pre-wrap rounded-md bg-background p-2 text-xs leading-relaxed">- {formatPreviewValue(entry.before)}- </pre>- </div>- <div>- <div className="mb-1 text-[11px] text-muted-foreground uppercase tracking-normal">- <Trans>After</Trans>- </div>- <pre className="max-h-28 overflow-auto whitespace-pre-wrap rounded-md bg-background p-2 text-xs leading-relaxed">- {formatPreviewValue(entry.after)}- </pre>- </div>- </div>- </div>- ))}-- <details className="rounded-md border bg-muted/20 p-2">- <summary className="cursor-pointer font-medium text-xs">- <Trans>Raw JSON Patch</Trans>- </summary>- <pre className="mt-2 max-h-44 overflow-auto rounded bg-background p-2 text-[11px]">- {JSON.stringify(item.proposal.operations, null, 2)}- </pre>- </details>- </div>-- <div className={cn("flex items-center gap-2 border-t p-3", total > 1 ? "justify-between" : "justify-end")}>- {total > 1 ? (- <div className="flex gap-1">- <Button size="xs" variant="outline" disabled={index === 0 || isApplying} onClick={onPrevious}>- <Trans>Prev</Trans>- </Button>- <Button size="xs" variant="outline" disabled={index >= total - 1 || isApplying} onClick={onNext}>- <Trans>Next</Trans>- </Button>- </div>- ) : null}-- <div className="flex gap-2">- <SplitDecisionButton- variant="outline"- disabled={isApplying}- label={<Trans>Reject</Trans>}- icon={<XIcon />}- menuLabel={<Trans>Reject all</Trans>}- onClick={onReject}- onMenuClick={onRejectAll}- />- <SplitDecisionButton- disabled={isApplying}- label={<Trans>Accept</Trans>}- icon={<CheckIcon />}- menuLabel={<Trans>Accept all</Trans>}- onClick={onAccept}- onMenuClick={onAcceptAll}- />- </div>- </div>- </section>- );-}--type SplitDecisionButtonProps = {- label: React.ReactNode;- menuLabel: React.ReactNode;- icon: React.ReactNode;- disabled?: boolean;- variant?: React.ComponentProps<typeof Button>["variant"];- onClick: () => void;- onMenuClick: () => void;-};--function SplitDecisionButton({- label,- menuLabel,- icon,- disabled,- variant = "default",- onClick,- onMenuClick,-}: SplitDecisionButtonProps) {- return (- <ButtonGroup>- <Button size="sm" variant={variant} disabled={disabled} onClick={onClick}>- {icon}- {label}- </Button>- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button size="icon-sm" variant={variant} disabled={disabled} aria-label={t`More proposal actions`}>- <CaretDownIcon />- </Button>- }- />- <DropdownMenuContent align="end" side="top" sideOffset={8} positionerClassName="z-[80]" className="min-w-32">- <DropdownMenuItem onClick={onMenuClick}>{menuLabel}</DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </ButtonGroup>- );-}--function AssistantThinkingBubble({ status }: { status: string }) {- return (- <div className="flex justify-start">- <div- className="flex max-w-[86%] items-center gap-2 rounded-lg bg-muted px-3 py-2 text-muted-foreground text-sm"- role="status"- aria-live="polite"- >- <span>{status === "submitted" ? <Trans>Sending request</Trans> : <Trans>Preparing changes</Trans>}</span>- <span className="inline-flex items-center gap-1" aria-hidden="true">- <span className="size-1.5 animate-bounce rounded-full bg-current [animation-delay:0ms]" />- <span className="size-1.5 animate-bounce rounded-full bg-current [animation-delay:120ms]" />- <span className="size-1.5 animate-bounce rounded-full bg-current [animation-delay:240ms]" />- </span>- </div>- </div>- );-}--function AssistantErrorBubble({ error }: { error?: Error }) {- return (- <div className="flex justify-start">- <div- className="max-w-[86%] rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-destructive text-sm"- role="alert"- >- <div className="flex items-center gap-2 font-medium">- <WarningCircleIcon className="size-4" />- <Trans>Assistant request failed</Trans>- </div>- <p className="mt-1 text-destructive/80 text-xs leading-relaxed">- {error?.message?.trim() || <Trans>The assistant stopped before returning a proposal.</Trans>}- </p>- </div>- </div>- );-}--type AssistantTimelineItemProps = {- message: UIMessage;- proposal?: QueuedProposal;- resolutions: ProposalResolution[];- proposalIndex: number;- proposalTotal: number;- isApplying: boolean;- onAcceptProposal: () => void;- onRejectProposal: () => void;- onAcceptAllProposals: () => void;- onRejectAllProposals: () => void;- onPreviousProposal: () => void;- onNextProposal: () => void;-};--function AssistantTimelineItem({- message,- proposal,- resolutions,- proposalIndex,- proposalTotal,- isApplying,- onAcceptProposal,- onRejectProposal,- onAcceptAllProposals,- onRejectAllProposals,- onPreviousProposal,- onNextProposal,-}: AssistantTimelineItemProps) {- const hasVisibleText = message.parts.some((part) => part.type === "text" && part.text.trim());-- if (!hasVisibleText && !proposal && resolutions.length === 0) return null;-- return (- <div className="space-y-2">- {hasVisibleText ? <AssistantMessage message={message} /> : null}-- {proposal ? (- <ProposalApprovalCard- item={proposal}- index={proposalIndex}- total={proposalTotal}- isApplying={isApplying}- onAccept={onAcceptProposal}- onReject={onRejectProposal}- onAcceptAll={onAcceptAllProposals}- onRejectAll={onRejectAllProposals}- onPrevious={onPreviousProposal}- onNext={onNextProposal}- />- ) : resolutions.length > 0 ? (- <ProposalResolutionBubble resolutions={resolutions} />- ) : null}- </div>- );-}--function ProposalResolutionBubble({ resolutions }: { resolutions: ProposalResolution[] }) {- const acceptedCount = resolutions.filter((resolution) => resolution.status === "accepted").length;- const rejectedCount = resolutions.length - acceptedCount;- const label =- acceptedCount > 0 && rejectedCount > 0- ? t`Reviewed proposals`- : acceptedCount > 0- ? t`Accepted proposal`- : t`Rejected proposal`;-- return (- <div className="flex justify-start">- <div className="flex max-w-[86%] items-start gap-2 rounded-lg border bg-muted/35 px-3 py-2 text-sm">- <div- className={cn(- "mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full",- acceptedCount > 0 && rejectedCount === 0 ? "bg-primary/15 text-primary" : "bg-muted text-muted-foreground",- )}- >- {acceptedCount > 0 && rejectedCount === 0 ? (- <CheckIcon className="size-3.5" />- ) : (- <XIcon className="size-3.5" />- )}- </div>- <div className="min-w-0">- <div className="flex flex-wrap items-center gap-1.5">- <code className="rounded bg-background px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">- propose_resume_patches- </code>- <span className="font-medium">{label}</span>- </div>- <div className="truncate text-muted-foreground text-xs">- {resolutions.length === 1 ? resolutions[0]?.title : t`${resolutions.length} proposals reviewed`}- </div>- </div>- </div>- </div>- );-}--function AssistantMessage({ message }: { message: UIMessage }) {- const isUser = message.role === "user";- const textParts = message.parts.filter((part) => part.type === "text");-- if (textParts.length === 0) return null;-- return (- <div className={cn("flex", isUser ? "justify-end" : "justify-start")}>- <div- className={cn(- "max-w-[86%] space-y-2 rounded-lg px-3 py-2 text-sm",- isUser- ? "bg-primary text-primary-foreground selection:bg-background/80 selection:text-foreground"- : "bg-muted text-foreground",- )}- >- {textParts.map((part, index) => (- <p key={index} className="whitespace-pre-wrap leading-relaxed">- {part.text}- </p>- ))}- </div>- </div>- );-}diff --git a/apps/web/src/routes/builder/$resumeId/-components/dock.tsx b/apps/web/src/routes/builder/$resumeId/-components/dock.tsxindex 23dce6356..284d69243 100644--- a/apps/web/src/routes/builder/$resumeId/-components/dock.tsx+++ b/apps/web/src/routes/builder/$resumeId/-components/dock.tsx@@ -14,6 +14,7 @@ import {MagnifyingGlassMinusIcon,MagnifyingGlassPlusIcon,} from "@phosphor-icons/react";+import { useNavigate } from "@tanstack/react-router";import { motion } from "motion/react";import { useCallback, useMemo, useState } from "react";import { useControls } from "react-zoom-pan-pinch";@@ -27,7 +28,6 @@ import { cn } from "@reactive-resume/utils/style";import { useCurrentResume } from "@/components/resume/builder-resume-draft";import { authClient } from "@/libs/auth/client";import { createResumePdfBlob } from "@/libs/resume/pdf-document";-import { useBuilderAssistantStore } from "./assistant-store";type BuilderDockProps = {pageLayout: BuilderPreviewPageLayout;@@ -37,13 +37,12 @@ type BuilderDockProps = {export function BuilderDock({ pageLayout, onTogglePageLayout }: BuilderDockProps) {const { data: session } = authClient.useSession();const resume = useCurrentResume();+ const navigate = useNavigate();const [_, copyToClipboard] = useCopyToClipboard();const { zoomIn, zoomOut, centerView } = useControls();const [isPrinting, setIsPrinting] = useState(false);- const isAssistantOpen = useBuilderAssistantStore((state) => state.isOpen);- const toggleAssistant = useBuilderAssistantStore((state) => state.toggleOpen);const publicUrl = useMemo(() => {if (!session?.user.username || !resume?.slug) return "";@@ -114,9 +113,11 @@ export function BuilderDock({ pageLayout, onTogglePageLayout }: BuilderDockProps/><DockIconicon={ChatCircleDotsIcon}- title={isAssistantOpen ? t`Close AI assistant` : t`Open AI assistant`}- onClick={toggleAssistant}- active={isAssistantOpen}+ title={t`Open AI agent`}+ onClick={() => {+ if (!resume) return;+ void navigate({ to: "/agent/new", search: { resumeId: resume.id } });+ }}/><div className="mx-1 h-8 w-px bg-border" /><DockIcon icon={LinkSimpleIcon} title={t`Copy URL`} onClick={() => onCopyUrl()} />diff --git a/apps/web/src/routes/builder/$resumeId/-components/preview-page.tsx b/apps/web/src/routes/builder/$resumeId/-components/preview-page.tsxindex 2d42c6226..d01413a6e 100644--- a/apps/web/src/routes/builder/$resumeId/-components/preview-page.tsx+++ b/apps/web/src/routes/builder/$resumeId/-components/preview-page.tsx@@ -28,7 +28,7 @@ export function PreviewPage() {wheel={{ step: 0.001 }}><TransformComponent wrapperClass="h-full! w-full!">- <ResumePreview pageGap="2rem" pageLayout={pageLayout} showPageNumbers />+ <ResumePreview showPageNumbers pageLayout={pageLayout} /></TransformComponent><BuilderDockdiff --git a/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/resume-analysis.tsx b/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/resume-analysis.tsxindex 23fb647f1..d64651218 100644--- a/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/resume-analysis.tsx+++ b/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/resume-analysis.tsx@@ -6,7 +6,6 @@ import { Link } from "@tanstack/react-router";import { useMemo } from "react";import { toast } from "sonner";import { match } from "ts-pattern";-import { useAIStore } from "@reactive-resume/ai/store";import { Alert, AlertDescription } from "@reactive-resume/ui/components/alert";import { Badge } from "@reactive-resume/ui/components/badge";import { Button } from "@reactive-resume/ui/components/button";@@ -50,13 +49,11 @@ export function ResumeAnalysisSectionBuilder() {const queryClient = useQueryClient();const resume = useResume();- const aiEnabled = useAIStore((state) => state.enabled);- const aiProvider = useAIStore((state) => state.provider);- const aiModel = useAIStore((state) => state.model);- const aiApiKey = useAIStore((state) => state.apiKey);- const aiBaseURL = useAIStore((state) => state.baseURL);const resumeId = resume?.id ?? "";+ const providersQuery = useQuery(orpc.aiProviders.list.queryOptions());+ const aiEnabled =+ providersQuery.data?.some((provider) => provider.enabled && provider.testStatus === "success") ?? false;const analysisQuery = useQuery({...orpc.resume.analysis.getById.queryOptions({ input: { id: resumeId } }),@@ -106,12 +103,7 @@ export function ResumeAnalysisSectionBuilder() {if (!resume) return;analyzeResume({- provider: aiProvider,- model: aiModel,- apiKey: aiApiKey,- baseURL: aiBaseURL,resumeId: resume.id,- resumeData: resume.data,});};diff --git a/apps/web/src/routes/builder/$resumeId/route.tsx b/apps/web/src/routes/builder/$resumeId/route.tsxindex 0a2f2f7fa..6a40e9d23 100644--- a/apps/web/src/routes/builder/$resumeId/route.tsx+++ b/apps/web/src/routes/builder/$resumeId/route.tsx@@ -17,7 +17,6 @@ import {} from "@/components/resume/builder-resume-draft";import { useIsMobile } from "@/hooks/use-mobile";import { orpc } from "@/libs/orpc/client";-import { BuilderAssistant } from "./-components/assistant";import { BuilderHeader } from "./-components/header";import { BuilderSidebarLeft } from "./-sidebar/left";import { BuilderSidebarRight } from "./-sidebar/right";@@ -168,8 +167,6 @@ function BuilderLayoutShell({ initialLayout }: BuilderLayoutShellProps) {<BuilderSidebarRight /></ResizablePanel></ResizableGroup>-- <BuilderAssistant /></div>);}diff --git a/apps/web/src/routes/dashboard/-components/sidebar.tsx b/apps/web/src/routes/dashboard/-components/sidebar.tsxindex 84f0ffc97..e5e8930ac 100644--- a/apps/web/src/routes/dashboard/-components/sidebar.tsx+++ b/apps/web/src/routes/dashboard/-components/sidebar.tsx@@ -4,6 +4,7 @@ import { useLingui } from "@lingui/react";import { Trans } from "@lingui/react/macro";import {BrainIcon,+ ChatCircleDotsIcon,GearSixIcon,KeyIcon,ReadCvLogoIcon,@@ -46,6 +47,11 @@ const appSidebarItems = [label: msg`Resumes`,href: "/dashboard/resumes",},+ {+ icon: <ChatCircleDotsIcon />,+ label: msg`Agents`,+ href: "/agent",+ },] as const satisfies SidebarItem[];const settingsSidebarItems = [diff --git a/apps/web/src/routes/dashboard/settings/integrations/-components/ai-section.tsx b/apps/web/src/routes/dashboard/settings/integrations/-components/ai-section.tsxindex e70d981c4..d9404c771 100644--- a/apps/web/src/routes/dashboard/settings/integrations/-components/ai-section.tsx+++ b/apps/web/src/routes/dashboard/settings/integrations/-components/ai-section.tsx@@ -1,238 +1,355 @@import type { AIProvider } from "@reactive-resume/ai/types";import type { ComboboxOption } from "@/components/ui/combobox";+import type { RouterOutput } from "@/libs/orpc/client";import { t } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";-import { CheckCircleIcon, InfoIcon, XCircleIcon } from "@phosphor-icons/react";-import { useMutation } from "@tanstack/react-query";-import { useMemo } from "react";+import { ORPCError } from "@orpc/client";+import { CheckCircleIcon, KeyIcon, PlusIcon, TrashIcon, WarningCircleIcon, XCircleIcon } from "@phosphor-icons/react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useMemo, useState } from "react";import { toast } from "sonner";-import { useAIStore } from "@reactive-resume/ai/store";import { AI_PROVIDER_DEFAULT_BASE_URLS } from "@reactive-resume/ai/types";+import { Badge } from "@reactive-resume/ui/components/badge";import { Button } from "@reactive-resume/ui/components/button";import { Input } from "@reactive-resume/ui/components/input";import { Label } from "@reactive-resume/ui/components/label";import { Spinner } from "@reactive-resume/ui/components/spinner";import { Switch } from "@reactive-resume/ui/components/switch";+import { cn } from "@reactive-resume/utils/style";import { Combobox } from "@/components/ui/combobox";import { getOrpcErrorMessage } from "@/libs/error-message";import { orpc } from "@/libs/orpc/client";+type SavedProvider = RouterOutput["aiProviders"]["list"][number];type AIProviderOption = ComboboxOption<AIProvider> & { defaultBaseURL: string };const providerOptions: AIProviderOption[] = [{value: "openai",- label: t({- comment: "AI provider option label in dashboard AI settings",- message: "OpenAI",- }),+ label: t`OpenAI`,keywords: ["openai", "gpt", "chatgpt"],defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.openai,},{value: "anthropic",- label: t({- comment: "AI provider option label in dashboard AI settings",- message: "Anthropic Claude",- }),+ label: t`Anthropic Claude`,keywords: ["anthropic", "claude", "ai"],defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.anthropic,},{value: "gemini",- label: t({- comment: "AI provider option label in dashboard AI settings",- message: "Google Gemini",- }),- keywords: ["gemini", "google", "bard"],+ label: t`Google Gemini`,+ keywords: ["gemini", "google"],defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.gemini,},{value: "vercel-ai-gateway",- label: t({- comment: "AI provider option label in dashboard AI settings",- message: "Vercel AI Gateway",- }),+ label: t`Vercel AI Gateway`,keywords: ["vercel", "gateway", "ai"],defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS["vercel-ai-gateway"],},{value: "openrouter",- label: t({- comment: "AI provider option label in dashboard AI settings",- message: "OpenRouter",- }),- keywords: ["openrouter", "router", "multi", "proxy"],+ label: t`OpenRouter`,+ keywords: ["openrouter", "router"],defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.openrouter,},{value: "ollama",- label: t({- comment: "AI provider option label in dashboard AI settings",- message: "Ollama",- }),- keywords: ["ollama", "ai", "local"],+ label: t`Ollama`,+ keywords: ["ollama", "local"],defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.ollama,},+ {+ value: "openai-compatible",+ label: t`OpenAI-compatible`,+ keywords: ["compatible", "custom", "gateway"],+ defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS["openai-compatible"],+ },];-function AIForm() {- const { set, model, apiKey, baseURL, provider, enabled, testStatus } = useAIStore();+const emptyForm = {+ label: "",+ provider: "openai" as AIProvider,+ model: "",+ baseURL: "",+ apiKey: "",+};- const selectedOption = useMemo(() => {- return providerOptions.find((option) => option.value === provider);- }, [provider]);+function statusBadge(provider: SavedProvider) {+ if (provider.testStatus === "success") {+ return (+ <Badge className="bg-emerald-600 text-white">+ <Trans>Tested</Trans>+ </Badge>+ );+ }+ if (provider.testStatus === "failure") {+ return (+ <Badge variant="destructive">+ <Trans>Failed</Trans>+ </Badge>+ );+ }+ return (+ <Badge variant="secondary">+ <Trans>Untested</Trans>+ </Badge>+ );+}- const canTestConnection = model.trim().length > 0 && apiKey.trim().length > 0;+function providerLabel(provider: AIProvider) {+ return providerOptions.find((option) => option.value === provider)?.label ?? provider;+}- const { mutate: testConnection, isPending: isTesting } = useMutation(orpc.ai.testConnection.mutationOptions());+function isAiProviderConfigError(error: unknown) {+ if (error instanceof ORPCError && error.code === "PRECONDITION_FAILED") return true;- const handleProviderChange = (value: AIProvider | null) => {- if (!value) return;+ if (!error || typeof error !== "object") return false;+ const status = (error as { status?: unknown; code?: unknown }).status ?? (error as { code?: unknown }).code;+ return status === "PRECONDITION_FAILED" || status === 412;+}- set((draft) => {- draft.provider = value;- });- };+function ProviderRow({ provider }: { provider: SavedProvider }) {+ const queryClient = useQueryClient();+ const invalidate = () => queryClient.invalidateQueries({ queryKey: orpc.aiProviders.list.queryKey() });+ const { mutate: testProvider, isPending: isTesting } = useMutation(orpc.aiProviders.test.mutationOptions());+ const { mutate: updateProvider, isPending: isUpdating } = useMutation(orpc.aiProviders.update.mutationOptions());+ const { mutate: deleteProvider, isPending: isDeleting } = useMutation(orpc.aiProviders.delete.mutationOptions());+ const isMutating = isTesting || isUpdating || isDeleting;- const handleTestConnection = () => {- if (!canTestConnection) return;+ return (+ <div className="grid gap-4 rounded-md border bg-card p-4 md:grid-cols-[1fr_auto]">+ <div className="min-w-0 space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="truncate font-semibold">{provider.label}</h3>+ {statusBadge(provider)}+ {provider.enabled ? (+ <Badge variant="outline">+ <Trans>Enabled</Trans>+ </Badge>+ ) : null}+ </div>- testConnection(- { provider, model: model.trim(), apiKey: apiKey.trim(), baseURL: baseURL.trim() },- {- onSuccess: (data) => {- set((draft) => {- draft.testStatus = data ? "success" : "failure";- });- },- onError: (error) => {- set((draft) => {- draft.testStatus = "failure";- });+ <div className="grid gap-1 text-muted-foreground text-sm">+ <p>+ {providerLabel(provider.provider)} · {provider.model}+ </p>+ <p className="truncate">{provider.baseURL ?? AI_PROVIDER_DEFAULT_BASE_URLS[provider.provider]}</p>+ <p>+ <Trans>Key</Trans>: {provider.apiKeyPreview}+ </p>+ {provider.testError ? <p className="text-rose-600">{provider.testError}</p> : null}+ </div>+ </div>- toast.error(- getOrpcErrorMessage(error, {- byCode: {- BAD_REQUEST: t({- comment: "Error shown when AI provider credentials or base URL are invalid in AI settings",- message: "Invalid AI provider configuration. Please check your settings.",- }),- BAD_GATEWAY: t({- comment: "Error shown when the configured AI provider cannot be reached during connection test",- message: "Could not reach the AI provider. Please try again.",- }),- },- fallback: t({- comment: "Fallback toast when testing AI provider connection fails",- message: "Failed to test AI provider connection. Please try again.",- }),- }),- );- },- },- );- };+ <div className="flex items-center gap-2 md:justify-end">+ <div className="flex items-center gap-2 pe-2">+ <Switch+ checked={provider.enabled}+ disabled={provider.testStatus !== "success" || isMutating}+ onCheckedChange={(enabled) =>+ updateProvider(+ { id: provider.id, enabled },+ {+ onSuccess: () => void invalidate(),+ onError: (error) =>+ toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to update provider.` })),+ },+ )+ }+ />+ <span className="text-muted-foreground text-sm">+ <Trans>Use</Trans>+ </span>+ </div>- return (- <div className="grid gap-6 sm:grid-cols-2">- <div className="flex flex-col gap-y-2">- <Label htmlFor="ai-provider">- <Trans>Provider</Trans>- </Label>- <Combobox- id="ai-provider"- value={provider}- disabled={enabled}- options={providerOptions}- onValueChange={handleProviderChange}- />- </div>+ <Button+ variant="outline"+ disabled={isMutating}+ onClick={() =>+ testProvider(+ { id: provider.id },+ {+ onSuccess: (response) => {+ if (response.testStatus === "success") {+ toast.success(t`Provider connection verified.`);+ } else {+ toast.error(response.testError ?? t`Could not verify provider connection.`);+ }+ void invalidate();+ },+ onError: (error) => {+ toast.error(getOrpcErrorMessage(error, { fallback: t`Could not verify provider connection.` }));+ void invalidate();+ },+ },+ )+ }+ >+ {isTesting ? <Spinner /> : provider.testStatus === "success" ? <CheckCircleIcon /> : <WarningCircleIcon />}+ <Trans>Test</Trans>+ </Button>- <div className="flex flex-col gap-y-2">- <Label htmlFor="ai-model">- <Trans>Model</Trans>- </Label>- <Input- id="ai-model"- name="ai-model"- type="text"- value={model}- disabled={enabled}- onChange={(e) =>- set((draft) => {- draft.model = e.target.value;- })+ <Button+ size="icon"+ variant="ghost"+ disabled={isMutating}+ onClick={() =>+ deleteProvider(+ { id: provider.id },+ {+ onSuccess: () => void invalidate(),+ onError: (error) =>+ toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to delete provider.` })),+ },+ )}- placeholder={t({- comment: "Example model-name placeholder in AI settings",- message: "e.g., gpt-4, claude-3-opus, gemini-pro",- })}- autoCorrect="off"- autoComplete="off"- spellCheck="false"- autoCapitalize="off"- />+ >+ <TrashIcon />+ <span className="sr-only">+ <Trans>Delete provider</Trans>+ </span>+ </Button></div>+ </div>+ );+}- <div className="flex flex-col gap-y-2 sm:col-span-2">- <Label htmlFor="ai-api-key">- <Trans>API Key</Trans>- </Label>- <Input- id="ai-api-key"- name="ai-api-key"- type="password"- value={apiKey}- disabled={enabled}- onChange={(e) =>- set((draft) => {- draft.apiKey = e.target.value;- })- }- autoCorrect="off"- autoComplete="off"- spellCheck="false"- autoCapitalize="off"- data-lpignore="true"- data-bwignore="true"- data-1p-ignore="true"- />+function CreateProviderForm() {+ const queryClient = useQueryClient();+ const [form, setForm] = useState(emptyForm);+ const selectedOption = useMemo(+ () => providerOptions.find((option) => option.value === form.provider),+ [form.provider],+ );+ const canCreate = form.label.trim() && form.model.trim() && form.apiKey.trim();+ const { mutate: createProvider, isPending } = useMutation(orpc.aiProviders.create.mutationOptions());++ return (+ <div className="rounded-md border bg-card p-4">+ <div className="mb-4 flex items-center gap-2">+ <div className="grid size-8 place-items-center rounded-md bg-primary/10 text-primary">+ <PlusIcon />+ </div>+ <h3 className="font-semibold">+ <Trans>Add Provider</Trans>+ </h3></div>- <div className="flex flex-col gap-y-2 sm:col-span-2">- <Label htmlFor="ai-base-url">- <Trans>Base URL (Optional)</Trans>- </Label>- <Input- id="ai-base-url"- name="ai-base-url"- type="url"- value={baseURL}- disabled={enabled}- placeholder={selectedOption?.defaultBaseURL}- onChange={(e) =>- set((draft) => {- draft.baseURL = e.target.value;- })- }- autoCorrect="off"- autoComplete="off"- spellCheck="false"- autoCapitalize="off"- />+ <div className="grid gap-4 md:grid-cols-2">+ <div className="space-y-2">+ <Label htmlFor="ai-label">+ <Trans>Label</Trans>+ </Label>+ <Input+ id="ai-label"+ value={form.label}+ onChange={(event) => setForm((current) => ({ ...current, label: event.target.value }))}+ placeholder={t`Work OpenAI`}+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="ai-provider">+ <Trans>Provider</Trans>+ </Label>+ <Combobox+ id="ai-provider"+ value={form.provider}+ showClear={false}+ options={providerOptions}+ onValueChange={(provider) => {+ if (!provider) return;+ setForm((current) => ({ ...current, provider }));+ }}+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="ai-model">+ <Trans>Model</Trans>+ </Label>+ <Input+ id="ai-model"+ value={form.model}+ onChange={(event) => setForm((current) => ({ ...current, model: event.target.value }))}+ placeholder={t`gpt-4.1`}+ autoCorrect="off"+ autoCapitalize="off"+ spellCheck="false"+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="ai-base-url">+ <Trans>Base URL</Trans>+ </Label>+ <Input+ id="ai-base-url"+ type="url"+ value={form.baseURL}+ onChange={(event) => setForm((current) => ({ ...current, baseURL: event.target.value }))}+ placeholder={selectedOption?.defaultBaseURL || t`https://gateway.example.com/v1`}+ autoCorrect="off"+ autoCapitalize="off"+ spellCheck="false"+ />+ </div>++ <div className="space-y-2 md:col-span-2">+ <Label htmlFor="ai-api-key">+ <Trans>API Key</Trans>+ </Label>+ <Input+ id="ai-api-key"+ type="password"+ value={form.apiKey}+ onChange={(event) => setForm((current) => ({ ...current, apiKey: event.target.value }))}+ autoCorrect="off"+ autoCapitalize="off"+ spellCheck="false"+ data-lpignore="true"+ data-bwignore="true"+ data-1p-ignore="true"+ />+ </div></div>- <div>- <Button variant="outline" disabled={isTesting || enabled || !canTestConnection} onClick={handleTestConnection}>- {isTesting ? (- <Spinner />- ) : testStatus === "success" ? (- <CheckCircleIcon className="text-emerald-500" />- ) : testStatus === "failure" ? (- <XCircleIcon className="text-rose-500" />- ) : null}- <Trans>Test Connection</Trans>+ <div className="mt-4 flex justify-end">+ <Button+ disabled={!canCreate || isPending}+ onClick={() =>+ createProvider(+ {+ label: form.label.trim(),+ provider: form.provider,+ model: form.model.trim(),+ baseURL: form.baseURL.trim(),+ apiKey: form.apiKey.trim(),+ },+ {+ onSuccess: () => {+ setForm(emptyForm);+ toast.success(t`AI provider saved. Test it before use.`);+ void queryClient.invalidateQueries({ queryKey: orpc.aiProviders.list.queryKey() });+ },+ onError: (error) =>+ toast.error(+ getOrpcErrorMessage(error, {+ byCode: {+ PRECONDITION_FAILED: t`AI providers require REDIS_URL and ENCRYPTION_SECRET to be configured.`,+ BAD_REQUEST: t`Invalid AI provider configuration.`,+ },+ fallback: t`Failed to save AI provider.`,+ }),+ ),+ },+ )+ }+ >+ {isPending ? <Spinner /> : <KeyIcon />}+ <Trans>Save Provider</Trans></Button></div></div>@@ -240,48 +357,71 @@ function AIForm() {}export function AISettingsSection() {- const aiEnabled = useAIStore((state) => state.enabled);- const canEnableAI = useAIStore((state) => state.canEnable());- const setAIEnabled = useAIStore((state) => state.setEnabled);+ const { data: providers, isLoading, error } = useQuery(orpc.aiProviders.list.queryOptions());+ const hasUsableProvider = providers?.some((provider) => provider.enabled && provider.testStatus === "success");+ const isConfigError = isAiProviderConfigError(error);return (<section className="grid gap-6">- <h2 className="font-semibold text-lg">- <Trans>Artificial Intelligence</Trans>- </h2>-- <div className="flex items-start gap-4 rounded-md border bg-popover p-6">- <div className="rounded-md bg-primary/10 p-2.5">- <InfoIcon className="text-primary" size={24} />+ <div className="flex items-center justify-between gap-4">+ <div>+ <h2 className="font-semibold text-lg">+ <Trans>AI Providers</Trans>+ </h2>+ <p className="text-muted-foreground text-sm">+ <Trans>API keys are encrypted on the server and never shown again after saving.</Trans>+ </p></div>- <div className="flex-1 space-y-2">- <h3 className="font-semibold">- <Trans>Your data is stored locally</Trans>- </h3>+ <p className="flex items-center gap-2 text-sm">+ {hasUsableProvider ? (+ <CheckCircleIcon className="text-emerald-600" />+ ) : (+ <XCircleIcon className="text-rose-600" />+ )}+ <span className={cn(hasUsableProvider ? "text-emerald-700" : "text-muted-foreground")}>+ {hasUsableProvider ? <Trans>Agent ready</Trans> : <Trans>No tested provider</Trans>}+ </span>+ </p>+ </div>- <p className="text-muted-foreground leading-relaxed">- <Trans>- Everything entered here is stored locally on your browser. Your data is only sent to the server when- making a request to the AI provider, and is never stored or logged on our servers.- </Trans>- </p>+ {error ? (+ <div+ className={cn(+ "rounded-md border p-4 text-sm",+ isConfigError+ ? "border-amber-300 bg-amber-50 text-amber-950 dark:bg-amber-950/20 dark:text-amber-200"+ : "border-rose-300 bg-rose-50 text-rose-950 dark:bg-rose-950/20 dark:text-rose-200",+ )}+ >+ {isConfigError ? (+ <Trans>AI provider management is unavailable until REDIS_URL and ENCRYPTION_SECRET are configured.</Trans>+ ) : (+ <Trans>AI provider management is unavailable. Please try again.</Trans>+ )}</div>- </div>+ ) : null}- <div className="flex items-center justify-between">- <Label htmlFor="enable-ai">- <Trans>Enable AI Features</Trans>- </Label>- <Switch id="enable-ai" checked={aiEnabled} disabled={!canEnableAI} onCheckedChange={setAIEnabled} />- </div>+ {error ? null : <CreateProviderForm />}- <p className="flex items-center gap-x-2">- {aiEnabled ? <CheckCircleIcon className="text-emerald-500" /> : <XCircleIcon className="text-rose-500" />}- {aiEnabled ? <Trans>Enabled</Trans> : <Trans>Disabled</Trans>}- </p>+ <div className="grid gap-3">+ {isLoading ? (+ <div className="flex items-center gap-2 text-muted-foreground text-sm">+ <Spinner />+ <Trans>Loading providers...</Trans>+ </div>+ ) : null}++ {providers?.length === 0 ? (+ <div className="rounded-md border border-dashed p-6 text-center text-muted-foreground text-sm">+ <Trans>Add and test a provider before starting an agent thread.</Trans>+ </div>+ ) : null}- <AIForm />+ {providers?.map((provider) => (+ <ProviderRow key={provider.id} provider={provider} />+ ))}+ </div></section>);}diff --git a/apps/web/src/routes/dashboard/settings/integrations/route.tsx b/apps/web/src/routes/dashboard/settings/integrations/route.tsxindex 26ac57788..8a5b10b3f 100644--- a/apps/web/src/routes/dashboard/settings/integrations/route.tsx+++ b/apps/web/src/routes/dashboard/settings/integrations/route.tsx@@ -26,7 +26,7 @@ function RouteComponent() {initial={{ opacity: 0, y: -20 }}animate={{ opacity: 1, y: 0 }}transition={{ duration: 0.25, ease: "easeOut" }}- className="grid max-w-xl gap-8 will-change-[transform,opacity]"+ className="grid max-w-4xl gap-8 will-change-[transform,opacity]"><AISettingsSection /></motion.div>diff --git a/compose.dev.yml b/compose.dev.ymlindex 71e0f6f1e..39ca8f022 100644--- a/compose.dev.yml+++ b/compose.dev.yml@@ -5,18 +5,15 @@ services:build:context: .dockerfile: Dockerfile.dev- init: truerestart: unless-stopped+ env_file:+ - path: .env.local+ required: falseenvironment:- PORT: "3000"APP_URL: http://localhost:3000DATABASE_URL: postgresql://postgres:postgres@postgres:5432/postgres- AUTH_SECRET: change-me-to-a-secure-secret-key-in-production- S3_ACCESS_KEY_ID: seaweedfs- S3_SECRET_ACCESS_KEY: seaweedfsS3_ENDPOINT: http://seaweedfs:8333- S3_BUCKET: reactive-resume- S3_FORCE_PATH_STYLE: "true"+ REDIS_URL: redis://redis:6379CHOKIDAR_USEPOLLING: "true"ports:- "127.0.0.1:3000:3000"@@ -49,6 +46,8 @@ services:depends_on:postgres:condition: service_healthy+ redis:+ condition: service_healthyseaweedfs:condition: service_healthyseaweedfs_create_bucket:@@ -69,8 +68,8 @@ services:POSTGRES_PASSWORD: postgresvolumes:- postgres_data:/var/lib/postgresql- expose:- - "5432"+ ports:+ - "127.0.0.1:5432:5432"healthcheck:test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"]start_period: 10s@@ -78,6 +77,21 @@ services:timeout: 10sretries: 3+ redis:+ image: redis:7-alpine+ restart: unless-stopped+ command: redis-server --appendonly yes+ volumes:+ - redis_data:/data+ ports:+ - "127.0.0.1:6379:6379"+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]+ start_period: 5s+ interval: 30s+ timeout: 10s+ retries: 3+seaweedfs:image: chrislusf/seaweedfs:latestrestart: unless-stopped@@ -87,8 +101,8 @@ services:AWS_SECRET_ACCESS_KEY: seaweedfsvolumes:- seaweedfs_data:/data- expose:- - "8333"+ ports:+ - "127.0.0.1:8333:8333"healthcheck:test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://localhost:8888"]start_period: 10s@@ -113,4 +127,5 @@ services:volumes:postgres_data:+ redis_data:seaweedfs_data:diff --git a/compose.yml b/compose.ymlindex 5d012de1c..d112bcc63 100644--- a/compose.yml+++ b/compose.yml@@ -21,6 +21,26 @@ services:timeout: 10sretries: 3+ redis:+ image: redis:7-alpine+ restart: unless-stopped+ command: redis-server --appendonly yes+ networks:+ - data_network+ # Not exposed on the host by default. Redis can contain agent stream data+ # including user chat content; keep it internal to the Docker network.+ # Uncomment the ports block below if you need host access for tooling.+ # ports:+ # - "127.0.0.1:6379:6379"+ volumes:+ - redis_data:/data+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]+ start_period: 5s+ interval: 30s+ timeout: 10s+ retries: 3+seaweedfs:image: chrislusf/seaweedfs:latestrestart: unless-stopped@@ -71,6 +91,8 @@ services:- APP_URL=http://localhost:3000- DATABASE_URL=postgresql://postgres:postgres@postgres:5432/postgres- AUTH_SECRET=change-me-to-a-secure-secret-key-in-production+ - REDIS_URL=redis://redis:6379+ - ENCRYPTION_SECRET=change-me-to-a-secure-agent-secret-in-production- S3_ACCESS_KEY_ID=seaweedfs- S3_SECRET_ACCESS_KEY=seaweedfs- S3_ENDPOINT=http://seaweedfs:8333@@ -81,6 +103,8 @@ services:depends_on:postgres:condition: service_healthy+ redis:+ condition: service_healthyseaweedfs:condition: service_healthyseaweedfs_create_bucket:@@ -94,6 +118,7 @@ services:volumes:postgres_data:+ redis_data:seaweedfs_data:networks:diff --git a/docs/docs.json b/docs/docs.jsonindex fdcd65757..20a3b1b17 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -61,6 +61,7 @@"guides/adding-a-cover-letter","guides/using-the-builder-dock","guides/using-ai-in-the-builder",+ "guides/using-ai-agent","guides/exporting-your-resume","guides/sharing-your-resume-publicly","guides/using-private-notes"@@ -77,6 +78,7 @@"guides/using-the-patch-api","guides/using-the-mcp-server","guides/using-ai",+ "guides/ai-agent-tools","guides/json-resume-schema"]},diff --git a/docs/getting-started/quickstart.mdx b/docs/getting-started/quickstart.mdxindex 22b3241d5..51ce005a7 100644--- a/docs/getting-started/quickstart.mdx+++ b/docs/getting-started/quickstart.mdx@@ -96,10 +96,15 @@ S3_SECRET_ACCESS_KEY=seaweedfsS3_ENDPOINT=http://seaweedfs:8333S3_BUCKET=reactive-resumeS3_FORCE_PATH_STYLE=true++# AI features (optional; ENCRYPTION_SECRET for saved providers, plus REDIS_URL for the agent)+REDIS_URL=redis://redis:6379+ENCRYPTION_SECRET=your-secure-encryption-secret-here```<Warning>- For production deployments, always use strong, unique values for `AUTH_SECRET` and database credentials.+ For production deployments, always use strong, unique values for `AUTH_SECRET`, `ENCRYPTION_SECRET`, and+ database credentials.</Warning></Step>@@ -110,6 +115,7 @@ S3_FORCE_PATH_STYLE=trueThis starts:- **PostgreSQL** — Database for storing user data and resumes+ - **Redis** — Required for the AI Agent workspace- **SeaweedFS** — S3-compatible storage for file uploads- **Reactive Resume** — The main application</Step>@@ -131,9 +137,16 @@ Here's what each service in the stack does:| Service | Port | Description || ----------------- | ---- | ---------------------------------------------------- || `postgres` | 5432 | PostgreSQL database for storing all application data |+| `redis` | 6379 | Redis instance required by the AI Agent workspace || `seaweedfs` | 8333 | S3-compatible object storage for file uploads || `reactive_resume` | 3000 | The main Reactive Resume application |+<Note>+ Saved AI provider management requires `ENCRYPTION_SECRET`, and the AI Agent workspace requires both `REDIS_URL` and+ `ENCRYPTION_SECRET`. Other Reactive Resume features can run without them. Agent attachments and other private objects+ require S3-compatible storage; local storage rejects private objects.+</Note>+### Health ChecksAll services include built-in health checks. You can verify everything is running correctly:@@ -192,13 +205,19 @@ Here's a complete list of environment variables you can configure:| `S3_ENDPOINT` | S3-compatible Endpoint URL | — || `S3_BUCKET` | S3 Bucket Name | — || `S3_FORCE_PATH_STYLE` | Use path-style URLs for S3 (set `true` for MinIO/SeaweedFS) | `false` |+| `REDIS_URL` | Redis connection string for the AI Agent workspace | — |+| `ENCRYPTION_SECRET` | Encryption secret for saved AI provider credentials | — |+| `CLOUDFLARE_ACCOUNT_ID` | Optional Cloudflare URL extraction fallback account ID | — |+| `CLOUDFLARE_API_TOKEN` | Optional Cloudflare URL extraction fallback API token | — || `FLAG_DISABLE_SIGNUPS` | Disables new user signups | `false` || `FLAG_DISABLE_EMAIL_AUTH` | Disables email/password login (SSO only) | `false` || `FLAG_DISABLE_IMAGE_PROCESSING` | Disables image processing | `false` |-| `FLAG_ALLOW_UNSAFE_AI_BASE_URL` | Enables local-network AI providers (e.g. Ollama) | `false` |+| `FLAG_ALLOW_UNSAFE_AI_BASE_URL` | Allows unsafe/private/non-public AI provider base URLs | `false` |> **Note:** Some variables are only required for using related features (OAuth, SMTP, S3, etc.) and can be left unset if unused.+> **AI features:** Saved AI provider management requires `ENCRYPTION_SECRET`, and the AI Agent workspace requires both `REDIS_URL` and `ENCRYPTION_SECRET`. Cloudflare variables only enable the optional URL extraction fallback and are not required for normal agent operation. Keep `FLAG_ALLOW_UNSAFE_AI_BASE_URL` disabled unless this is a trusted self-hosted deployment; public HTTPS provider URLs are the safe default.+> **Health check behavior:** `/api/health` reports status for database and storage. A failure in either dependency returns HTTP `503`.---diff --git a/docs/guides/ai-agent-tools.mdx b/docs/guides/ai-agent-tools.mdxnew file mode 100644index 000000000..dadf536ae--- /dev/null+++ b/docs/guides/ai-agent-tools.mdx@@ -0,0 +1,83 @@+---+title: "AI Agent Tools"+description: "Understand the tools available to the AI Agent workspace and how they affect resume drafts."+---++The AI Agent workspace can use a curated set of tools while it chats with you. You do not call these tools directly; the agent chooses them when your request needs resume data, web context, attachments, questions, or a resume patch.++## Tool activity in chat++Tool activity appears inside the conversation. Some activity is collapsed by default so the chat stays readable.++Applied resume patches are shown as a small inline **Patch applied** item. Open it to inspect the raw JSON payload.++<Frame caption="Patch details and tool activity in the AI Agent chat">+ <img+ src="/images/guides/ai-agent-tools/screenshot-1.webp"+ alt="AI Agent chat showing an applied patch with raw JSON details"+ />+</Frame>++## Available tools++| Tool | What it does | Example request |+| --- | --- | --- |+| `read_resume` | Reads the current AI draft and gives the agent the resume data it can safely edit. | "What are the weakest parts of this resume?" |+| `fetch_url` | Fetches public HTTPS pages, extracts readable content, and returns it as agent input. | "Tailor this resume to this job description: `https://example.com/job`" |+| Provider-native search | Uses the selected provider's native web search when that provider/model supports it. | "Research this company and adjust the summary for its product area." |+| `read_attachment` | Reads extracted text from attached plain text, Markdown, or JSON files. Other supported attachments, such as images or PDFs, are passed to the model when the selected provider can use them. | "Use the attached notes to update the keywords." |+| `ask_user_question` | Shows a question card with answer choices when the agent needs your decision. | "Ask me before changing the career narrative." |+| `apply_resume_patch` | Applies a JSON Patch to the AI draft and stores enough history to revert it later. | "Change the visible name to Amruth Pillai." |++## Resume patches++Resume patches are rooted at the resume data object. For example, the visible resume name is patched at `/basics/name`.++When a patch is applied:++- the AI draft updates immediately;+- the raw JSON Patch is available from the **Patch applied** details;+- an inverse patch is stored for revert;+- the resume preview refreshes to show the updated draft.++If the resume changed after the patch was generated, revert or apply can fail with a version conflict. In that case, ask the agent to retry from the latest draft.++## Web access++The agent can fetch public HTTPS URLs so it can read job descriptions, company pages, or other public context you provide.++For self-hosted deployments:++- private, loopback, and non-HTTPS URLs are blocked by default;+- Cloudflare URL extraction is optional and is used only as a fallback when local readability extraction fails;+- unsafe/private AI provider base URLs require `FLAG_ALLOW_UNSAFE_AI_BASE_URL=true`, which should only be used on trusted self-hosted deployments.++## Attachments++Attach files from the chat composer when the agent needs extra context, such as:++- a job description PDF;+- a portfolio brief;+- a screenshot;+- a plain text note with constraints.++Self-hosted deployments need S3-compatible storage for private agent attachments. Local filesystem storage rejects private objects.++## Good prompts for tool use++Use direct prompts that tell the agent what context to use and how cautious to be:++- "Fetch this role URL, identify the most important keywords, and apply a conservative patch."+- "Read the attached job description and ask me before changing anything outside the summary."+- "Compare my current projects against this company page and suggest only truthful wording."+- "Apply a patch for the visible resume name, then show me what changed."++## When tools are unavailable++Tool use can be limited by the selected provider, deployment configuration, or thread state.++- A deleted provider makes the thread read-only; a disabled or untested provider blocks new agent runs until it is enabled and tested again.+- A deleted working resume makes the thread read-only.+- Archived threads cannot receive new messages.+- URL fetching may fail for private URLs, blocked hosts, non-HTML pages, or pages that cannot be extracted.+- Attachments may fail if private object storage is not configured.diff --git a/docs/guides/creating-your-first-resume.mdx b/docs/guides/creating-your-first-resume.mdxindex fa4fa1890..38ddce432 100644--- a/docs/guides/creating-your-first-resume.mdx+++ b/docs/guides/creating-your-first-resume.mdx@@ -27,7 +27,7 @@ description: "Learn how to create your first resume in Reactive Resume, set a na<Frame caption="Create a new resume dialog"><img- src="/images/guides/creating-your-first-resume/screenshot-1.png"+ src="/images/guides/creating-your-first-resume/screenshot-1.webp"alt="Create a new resume dialog with name, slug, and tags fields"/></Frame>diff --git a/docs/guides/exporting-your-resume.mdx b/docs/guides/exporting-your-resume.mdxindex 71ff6ebd2..c2ab28500 100644--- a/docs/guides/exporting-your-resume.mdx+++ b/docs/guides/exporting-your-resume.mdx@@ -23,7 +23,7 @@ Reactive Resume can export your resume in three formats:<Frame caption="Export section in the resume builder"><img- src="/images/guides/exporting-your-resume/screenshot-1.png"+ src="/images/guides/exporting-your-resume/screenshot-1.webp"alt="Export section showing JSON, DOCX, and PDF download buttons"/></Frame>diff --git a/docs/guides/importing-resumes.mdx b/docs/guides/importing-resumes.mdxindex 14036c2c5..5e58f25d7 100644--- a/docs/guides/importing-resumes.mdx+++ b/docs/guides/importing-resumes.mdx@@ -32,7 +32,7 @@ Reactive Resume can create a new resume from several existing file formats. Use<Frame caption="Import an existing resume dialog"><img- src="/images/guides/importing-resumes/screenshot-1.png"+ src="/images/guides/importing-resumes/screenshot-1.webp"alt="Import dialog showing supported resume import types"/></Frame>diff --git a/docs/guides/managing-resumes-from-the-dashboard.mdx b/docs/guides/managing-resumes-from-the-dashboard.mdxindex 0b3777388..e393c23dd 100644--- a/docs/guides/managing-resumes-from-the-dashboard.mdx+++ b/docs/guides/managing-resumes-from-the-dashboard.mdx@@ -7,7 +7,7 @@ The **Resumes** dashboard is where you manage every resume in your account. Use<Frame caption="Resumes dashboard in grid view"><img- src="/images/guides/managing-resumes-from-the-dashboard/screenshot-1.png"+ src="/images/guides/managing-resumes-from-the-dashboard/screenshot-1.webp"alt="Resumes dashboard showing sort controls, grid view, create and import cards, and a sample resume"/></Frame>@@ -23,7 +23,7 @@ Use the **Grid** and **List** tabs in the top-right of the dashboard to switch b<Frame caption="Resumes dashboard in list view"><img- src="/images/guides/managing-resumes-from-the-dashboard/screenshot-2.png"+ src="/images/guides/managing-resumes-from-the-dashboard/screenshot-2.webp"alt="Resumes dashboard showing the same resume in list view"/></Frame>diff --git a/docs/guides/sharing-your-resume-publicly.mdx b/docs/guides/sharing-your-resume-publicly.mdxindex bfc0736c1..b51e57fda 100644--- a/docs/guides/sharing-your-resume-publicly.mdx+++ b/docs/guides/sharing-your-resume-publicly.mdx@@ -36,7 +36,7 @@ Reactive Resume lets you share your resume via a **public URL** that anyone can<Frame caption="Sharing section in the resume builder"><img- src="/images/guides/sharing-your-resume-publicly/screenshot-1.png"+ src="/images/guides/sharing-your-resume-publicly/screenshot-1.webp"alt="Sharing section showing the public access control"/></Frame>diff --git a/docs/guides/using-ai-agent.mdx b/docs/guides/using-ai-agent.mdxnew file mode 100644index 000000000..294f57cd8--- /dev/null+++ b/docs/guides/using-ai-agent.mdx@@ -0,0 +1,115 @@+---+title: "Using the AI Agent Workspace"+description: "Learn how to start an isolated AI draft, chat with an agent, review resume patches, and continue existing agent threads."+---++The AI Agent workspace is a dedicated place to work with an AI assistant on a resume draft. It keeps the conversation, tool activity, and read-only resume preview in one full-screen view.++<Info>+ Agent threads edit an AI draft copy of your resume. Your original resume is not changed when you start from an existing resume.+</Info>++## Before you start++You need at least one AI provider that is tested and enabled in **Dashboard -> Settings -> Integrations**. For setup, see [Using Artificial Intelligence](/guides/using-ai).++If you self-host Reactive Resume, the agent workspace also requires the server-side agent configuration described in [Self-hosting with Docker](/self-hosting/docker).++## Open the agent workspace++From the dashboard sidebar, click **Agents**.++The agent page always shows your thread sidebar. Use it to continue an existing thread, or click **New thread** to start another one.++You can also open the agent from the builder dock. When you do this, the current resume is preselected in the new thread setup screen.++## Start a new thread++<Steps>+ <Step title="Choose an agent model">+ Pick the provider/model combo the agent should use. This choice is locked once the thread starts.+ </Step>++ <Step title="Choose a resume draft">+ Select an existing resume to duplicate as an AI draft, or choose **Create from scratch** for a blank draft.+ </Step>++ <Step title="Start the thread">+ Click **Start Thread** to create the draft and open the workspace.++ <Frame caption="Starting an AI Agent thread">+ <img+ src="/images/guides/using-ai-agent/screenshot-1.webp"+ alt="AI Agent new thread setup with model and resume selectors"+ />+ </Frame>+ </Step>+</Steps>++## Use the three-pane workspace++The desktop workspace is split into three panes:++- **Threads** on the left: continue, archive, delete, or start agent threads.+- **Chat** in the center: send prompts, upload files, answer agent questions, and review tool activity.+- **Resume** on the right: read the current AI draft, adjust zoom, open it in the builder, or download a PDF.++<Frame caption="AI Agent workspace with chat and resume preview">+ <img+ src="/images/guides/using-ai-agent/screenshot-2.webp"+ alt="AI Agent workspace showing thread sidebar, chat, and resume preview"+ />+</Frame>++On smaller screens, the workspace uses tabs/sheets so you can switch between threads, chat, and preview without losing the active conversation.++## Ask for resume changes++The agent works best with concrete instructions:++- "Tailor this resume to this job description: `https://example.com/job`"+- "Find weak bullets and rewrite them with stronger outcomes."+- "Compare this draft against a product manager role and update the keywords."+- "Ask me before changing anything that looks uncertain."++You can attach files or images from the composer. The agent can read uploaded attachments when they are relevant to your request.++<Note>+ Text input is supported. Voice input is not supported in the agent workspace yet.+</Note>++## Review patches++When the agent edits the resume, the patch is applied immediately to the AI draft. The chat shows a small **Patch applied** line.++Open the line to inspect the raw JSON Patch and use **Revert** if you want to undo that patch.++<Warning>+ AI-generated changes can still be inaccurate. Review the draft in the preview or builder before exporting or sharing it.+</Warning>++## Answer agent questions++If the agent needs a decision, it may show a question card with recommended answers. Click the answer you want to send it back to the agent.++This is useful when the agent finds ambiguous instructions, missing job context, or a change that depends on your preference.++## Use the resume preview++The resume pane is read-only. Use the toolbar to:++- decrease or increase zoom;+- set an exact zoom percentage;+- open the AI draft in the builder;+- download the draft as a PDF.++Zoom settings are remembered across refreshes.++## Manage threads++Threads are ordered by the newest message. Use the thread menu to archive or delete a thread.++- **Archive** keeps the conversation but makes the thread read-only.+- **Delete** removes the thread conversation and its attachments. The generated resume draft remains in your dashboard.++Threads can also become read-only if the working resume is deleted, the selected provider is deleted, or the thread is archived. If a provider is disabled or no longer tested, re-enable and test it before sending new messages.diff --git a/docs/guides/using-ai-in-the-builder.mdx b/docs/guides/using-ai-in-the-builder.mdxindex afb018d0a..2320a3309 100644--- a/docs/guides/using-ai-in-the-builder.mdx+++ b/docs/guides/using-ai-in-the-builder.mdx@@ -27,7 +27,7 @@ Use resume analysis when you want a broad review before making changes.<Frame caption="Resume Analysis section in the builder"><img- src="/images/guides/using-ai-in-the-builder/screenshot-1.png"+ src="/images/guides/using-ai-in-the-builder/screenshot-1.webp"alt="Resume Analysis section showing the AI setup prompt in the builder sidebar"/></Frame>diff --git a/docs/guides/using-ai.mdx b/docs/guides/using-ai.mdxindex 0074d7a07..fd02ad3d7 100644--- a/docs/guides/using-ai.mdx+++ b/docs/guides/using-ai.mdx@@ -17,7 +17,7 @@ Reactive Resume uses AI providers for features such as resume analysis, AI-assis<Frame caption="AI provider settings in Integrations"><img- src="/images/guides/using-ai/screenshot-1.png"+ src="/images/guides/using-ai/screenshot-1.webp"alt="Integrations settings showing AI provider configuration"/></Frame>@@ -38,6 +38,13 @@ In the **AI Providers** section, fill out the **Add Provider** form.Click **Save Provider** when the form is complete.+<Frame caption="Saved AI provider in Integrations">+ <img+ src="/images/guides/using-ai/screenshot-2.webp"+ alt="Integrations settings showing a saved and tested AI provider"+ />+</Frame>+<Warning>Treat API keys like passwords. Anyone with a key can use the connected provider account and may incur costs.</Warning>@@ -71,8 +78,8 @@ AI provider credentials are encrypted on the server and are never shown again afIf provider management is unavailable, your self-hosted deployment may be missing required server configuration.<Warning>- AI provider management requires the server-side services used to encrypt credentials and run AI work. If the page says- provider management is unavailable, check your deployment configuration before using AI features.+ AI provider management requires the server-side services used to encrypt credentials. If the page says provider+ management is unavailable, check your deployment configuration before using AI features.</Warning>## Where AI is used@@ -84,4 +91,4 @@ After a provider is tested and enabled, you can use AI in:- **Agent** workflows that create isolated AI drafts;- **PDF and Microsoft Word imports** from the dashboard import dialog.-For the builder workflow, see [Using AI in the builder](/guides/using-ai-in-the-builder). For AI-assisted imports, see [Importing resumes](/guides/importing-resumes).+For the builder workflow, see [Using AI in the builder](/guides/using-ai-in-the-builder). For the dedicated agent workspace, see [Using the AI Agent Workspace](/guides/using-ai-agent) and [AI Agent Tools](/guides/ai-agent-tools). For AI-assisted imports, see [Importing resumes](/guides/importing-resumes).diff --git a/docs/guides/using-the-builder-dock.mdx b/docs/guides/using-the-builder-dock.mdxindex 333417b0c..9fe9d9923 100644--- a/docs/guides/using-the-builder-dock.mdx+++ b/docs/guides/using-the-builder-dock.mdx@@ -7,7 +7,7 @@ The builder dock is the floating toolbar at the bottom of the resume builder. It<Frame caption="Resume builder with the floating dock"><img- src="/images/guides/using-the-builder-dock/screenshot-1.png"+ src="/images/guides/using-the-builder-dock/screenshot-1.webp"alt="Resume builder showing the floating dock with preview controls and download shortcuts"/></Frame>diff --git a/docs/images/guides/ai-agent-tools/screenshot-1.webp b/docs/images/guides/ai-agent-tools/screenshot-1.webpnew file mode 100644index 000000000..2eee14176Binary files /dev/null and b/docs/images/guides/ai-agent-tools/screenshot-1.webp differdiff --git a/docs/images/guides/creating-your-first-resume/screenshot-1.png b/docs/images/guides/creating-your-first-resume/screenshot-1.pngdeleted file mode 100644index 9513e5c2a..000000000Binary files a/docs/images/guides/creating-your-first-resume/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/creating-your-first-resume/screenshot-1.webp b/docs/images/guides/creating-your-first-resume/screenshot-1.webpnew file mode 100644index 000000000..b3f70966bBinary files /dev/null and b/docs/images/guides/creating-your-first-resume/screenshot-1.webp differdiff --git a/docs/images/guides/exporting-your-resume/screenshot-1.png b/docs/images/guides/exporting-your-resume/screenshot-1.pngdeleted file mode 100644index 48afb15ce..000000000Binary files a/docs/images/guides/exporting-your-resume/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/exporting-your-resume/screenshot-1.webp b/docs/images/guides/exporting-your-resume/screenshot-1.webpnew file mode 100644index 000000000..a5f2a62d8Binary files /dev/null and b/docs/images/guides/exporting-your-resume/screenshot-1.webp differdiff --git a/docs/images/guides/importing-resumes/screenshot-1.png b/docs/images/guides/importing-resumes/screenshot-1.pngdeleted file mode 100644index e4a3d6e46..000000000Binary files a/docs/images/guides/importing-resumes/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/importing-resumes/screenshot-1.webp b/docs/images/guides/importing-resumes/screenshot-1.webpnew file mode 100644index 000000000..d0d07119eBinary files /dev/null and b/docs/images/guides/importing-resumes/screenshot-1.webp differdiff --git a/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-1.png b/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-1.pngdeleted file mode 100644index 323cab97d..000000000Binary files a/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-1.webp b/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-1.webpnew file mode 100644index 000000000..4794cbe8eBinary files /dev/null and b/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-1.webp differdiff --git a/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-2.png b/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-2.pngdeleted file mode 100644index d5405fec8..000000000Binary files a/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-2.png and /dev/null differdiff --git a/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-2.webp b/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-2.webpnew file mode 100644index 000000000..4edb11708Binary files /dev/null and b/docs/images/guides/managing-resumes-from-the-dashboard/screenshot-2.webp differdiff --git a/docs/images/guides/sharing-your-resume-publicly/screenshot-1.png b/docs/images/guides/sharing-your-resume-publicly/screenshot-1.pngdeleted file mode 100644index 9577fc720..000000000Binary files a/docs/images/guides/sharing-your-resume-publicly/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/sharing-your-resume-publicly/screenshot-1.webp b/docs/images/guides/sharing-your-resume-publicly/screenshot-1.webpnew file mode 100644index 000000000..eb29eaab0Binary files /dev/null and b/docs/images/guides/sharing-your-resume-publicly/screenshot-1.webp differdiff --git a/docs/images/guides/using-ai-agent/screenshot-1.webp b/docs/images/guides/using-ai-agent/screenshot-1.webpnew file mode 100644index 000000000..eeedc6e40Binary files /dev/null and b/docs/images/guides/using-ai-agent/screenshot-1.webp differdiff --git a/docs/images/guides/using-ai-agent/screenshot-2.webp b/docs/images/guides/using-ai-agent/screenshot-2.webpnew file mode 100644index 000000000..d189374e4Binary files /dev/null and b/docs/images/guides/using-ai-agent/screenshot-2.webp differdiff --git a/docs/images/guides/using-ai-in-the-builder/screenshot-1.png b/docs/images/guides/using-ai-in-the-builder/screenshot-1.pngdeleted file mode 100644index 30de90726..000000000Binary files a/docs/images/guides/using-ai-in-the-builder/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/using-ai-in-the-builder/screenshot-1.webp b/docs/images/guides/using-ai-in-the-builder/screenshot-1.webpnew file mode 100644index 000000000..8a4555ee3Binary files /dev/null and b/docs/images/guides/using-ai-in-the-builder/screenshot-1.webp differdiff --git a/docs/images/guides/using-ai/screenshot-1.png b/docs/images/guides/using-ai/screenshot-1.pngdeleted file mode 100644index 0bd843de3..000000000Binary files a/docs/images/guides/using-ai/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/using-ai/screenshot-1.webp b/docs/images/guides/using-ai/screenshot-1.webpnew file mode 100644index 000000000..9d9f9e52dBinary files /dev/null and b/docs/images/guides/using-ai/screenshot-1.webp differdiff --git a/docs/images/guides/using-ai/screenshot-2.webp b/docs/images/guides/using-ai/screenshot-2.webpnew file mode 100644index 000000000..6ff89f0deBinary files /dev/null and b/docs/images/guides/using-ai/screenshot-2.webp differdiff --git a/docs/images/guides/using-the-builder-dock/screenshot-1.png b/docs/images/guides/using-the-builder-dock/screenshot-1.pngdeleted file mode 100644index eb6a909f2..000000000Binary files a/docs/images/guides/using-the-builder-dock/screenshot-1.png and /dev/null differdiff --git a/docs/images/guides/using-the-builder-dock/screenshot-1.webp b/docs/images/guides/using-the-builder-dock/screenshot-1.webpnew file mode 100644index 000000000..ede330ba4Binary files /dev/null and b/docs/images/guides/using-the-builder-dock/screenshot-1.webp differdiff --git a/docs/self-hosting/docker.mdx b/docs/self-hosting/docker.mdxindex 887edd47e..088afe146 100644--- a/docs/self-hosting/docker.mdx+++ b/docs/self-hosting/docker.mdx@@ -90,7 +90,6 @@ OAUTH_SCOPES=""# BETTER_AUTH_URL="https://auth.example.com"# BETTER_AUTH_SECRET=""-# --- Email (optional) ---# If all keys are disabled, the app logs the email to be sent to the console instead.SMTP_HOST=""@@ -112,10 +111,21 @@ S3_BUCKET=""# Set to "false" for virtual-hosted-style URLs (https://bucket.endpoint), common with AWS S3, Cloudflare R2, etc.S3_FORCE_PATH_STYLE="false"+# --- AI features (optional) ---+# ENCRYPTION_SECRET is required for saved AI providers. REDIS_URL is also required for the AI Agent workspace.+# The rest of Reactive Resume can run without these.+REDIS_URL=""+# Generated using `openssl rand -hex 32`+ENCRYPTION_SECRET=""+# Optional fallback for URL extraction. Not required for normal agent operation.+CLOUDFLARE_ACCOUNT_ID=""+CLOUDFLARE_API_TOKEN=""+# --- Feature Flags ---FLAG_DISABLE_SIGNUPS="false"FLAG_DISABLE_EMAIL_AUTH="false"FLAG_DISABLE_IMAGE_PROCESSING="false"+# Allows unsafe/private/non-public AI provider base URLs. Keep false unless this is a trusted self-hosted deployment.FLAG_ALLOW_UNSAFE_AI_BASE_URL="false"```@@ -251,6 +261,9 @@ docker compose logs -f reactive-resume<li>S3 storage (<code>S3_*</code>)</li>+ <li>+ AI providers and AI Agent workspace (<code>ENCRYPTION_SECRET</code>, <code>REDIS_URL</code>)+ </li><li>Feature flags (<code>FLAG_*</code>)</li>@@ -326,17 +339,28 @@ openssl rand -hex 32- **`LOCAL_STORAGE_PATH`** (optional): Overrides the local data directory. Defaults to `/app/data` in the official Docker image and `<workspace>/data` in development. The container validates this path is writable at startup and refuses to start otherwise.- **Rootless Docker**: `/app/data` remains the container path. Prefer the named volume from the example Compose file, or make sure a bind-mounted host directory is writable by the container's `node` user mapping.- **S3/S3-compatible**: Configure `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_REGION`, `S3_ENDPOINT`, and `S3_BUCKET`.+ - **Agent attachments/private objects**: The AI Agent workspace requires S3-compatible storage for private objects. Local storage rejects private objects.- **`S3_FORCE_PATH_STYLE`** controls bucket addressing (defaults to `"false"`):- `"true"` for path-style URLs (`https://endpoint/bucket`) common with MinIO/SeaweedFS.- `"false"` for virtual-hosted-style URLs (`https://bucket.endpoint`) common with AWS S3 / Cloudflare R2.</Accordion>+<Accordion title="AI features (optional)">+ Saved AI provider management is usable only when **`ENCRYPTION_SECRET`** is configured. The AI Agent workspace also requires **`REDIS_URL`**. The rest of Reactive Resume can run without them.++ - **`REDIS_URL`**: Redis connection string used by the AI Agent workspace.+ - **`ENCRYPTION_SECRET`**: Secret used to encrypt saved AI provider credentials. Generate with `openssl rand -hex 32`.+ - **`CLOUDFLARE_ACCOUNT_ID`** / **`CLOUDFLARE_API_TOKEN`** (optional): Enables the Cloudflare URL extraction fallback. Cloudflare is not required for normal agent operation.++ If you use the Postgres-only Compose example above and want the AI Agent workspace, add a Redis service or use managed Redis, then set `REDIS_URL`.+</Accordion>+<Accordion title="Feature Flags">- - **`FLAG_DISABLE_SIGNUPS`**: Disables new signups (web app and server). Useful for private instances.- - **`FLAG_DISABLE_EMAIL_AUTH`**: Disables email/password login entirely. Also disables email verification, forgot password, and reset password flows. Users can still sign up via social auth (Google/GitHub/LinkedIn/Custom OAuth), unless FLAG_DISABLE_SIGNUPS is also set to true. Useful when only SSO is required.- - **`FLAG_DISABLE_IMAGE_PROCESSING`**: Disables image processing. This is useful if you are using a machine with limited resources, like a Raspberry Pi.- - **`FLAG_ALLOW_UNSAFE_AI_BASE_URL`**: Allows AI providers to be configured with `http://` URLs and private/loopback addresses (e.g. a local Ollama instance at `http://192.168.1.10:11434`). **Warning: enabling this on a multi-tenant deployment is an SSRF risk.** Only enable on a trusted, single-tenant self-hosted instance.- </Accordion>+ - **`FLAG_DISABLE_SIGNUPS`**: Disables new signups (web app and server). Useful for private instances.+ - **`FLAG_DISABLE_EMAIL_AUTH`**: Disables email/password login entirely. Also disables email verification, forgot password, and reset password flows. Users can still sign up via social auth (Google/GitHub/LinkedIn/Custom OAuth), unless FLAG_DISABLE_SIGNUPS is also set to true. Useful when only SSO is required.+ - **`FLAG_DISABLE_IMAGE_PROCESSING`**: Disables image processing. This is useful if you are using a machine with limited resources, like a Raspberry Pi.+ - **`FLAG_ALLOW_UNSAFE_AI_BASE_URL`**: Allows AI providers to be configured with unsafe, private, or non-public base URLs, including `http://` and private/loopback addresses (for example, a local Ollama instance at `http://192.168.1.10:11434`). Public HTTPS provider URLs remain the safe default. **Warning: enabling this on a multi-tenant deployment is an SSRF risk.** Only enable on trusted, self-hosted deployments.+</Accordion></AccordionGroup>## Updating your installationdiff --git a/knip.json b/knip.jsonindex 7e25bb186..61a707198 100644--- a/knip.json+++ b/knip.json@@ -14,6 +14,9 @@"config": []}},+ "packages/api": {+ "ignoreDependencies": ["ioredis"]+ },"packages/runtime-externals": {"ignoreDependencies": ["@aws-sdk/client-s3", "bcrypt", "sharp"]}diff --git a/migrations/20260513181752_bent_human_cannonball/migration.sql b/migrations/20260513181752_bent_human_cannonball/migration.sqlnew file mode 100644index 000000000..ed28b69ff--- /dev/null+++ b/migrations/20260513181752_bent_human_cannonball/migration.sql@@ -0,0 +1,111 @@+CREATE TABLE "agent_actions" (+ "id" text PRIMARY KEY,+ "user_id" text NOT NULL,+ "thread_id" text NOT NULL,+ "message_id" text,+ "resume_id" text,+ "kind" text NOT NULL,+ "status" text DEFAULT 'applied' NOT NULL,+ "title" text NOT NULL,+ "summary" text,+ "operations" jsonb NOT NULL,+ "inverse_operations" jsonb NOT NULL,+ "base_updated_at" timestamp with time zone NOT NULL,+ "applied_updated_at" timestamp with time zone NOT NULL,+ "reverted_at" timestamp with time zone,+ "revert_message" text,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE TABLE "agent_attachments" (+ "id" text PRIMARY KEY,+ "user_id" text NOT NULL,+ "thread_id" text NOT NULL,+ "message_id" text,+ "storage_key" text NOT NULL,+ "filename" text NOT NULL,+ "media_type" text NOT NULL,+ "size" integer NOT NULL,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE TABLE "agent_messages" (+ "id" text PRIMARY KEY,+ "user_id" text NOT NULL,+ "thread_id" text NOT NULL,+ "role" text NOT NULL,+ "status" text DEFAULT 'completed' NOT NULL,+ "sequence" integer NOT NULL,+ "ui_message" jsonb NOT NULL,+ "error" text,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE TABLE "agent_threads" (+ "id" text PRIMARY KEY,+ "user_id" text NOT NULL,+ "ai_provider_id" text,+ "source_resume_id" text,+ "working_resume_id" text,+ "title" text NOT NULL,+ "status" text DEFAULT 'active' NOT NULL,+ "active_run_id" text,+ "active_stream_id" text,+ "active_run_started_at" timestamp with time zone,+ "last_message_at" timestamp with time zone DEFAULT now() NOT NULL,+ "archived_at" timestamp with time zone,+ "deleted_at" timestamp with time zone,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE TABLE "ai_providers" (+ "id" text PRIMARY KEY,+ "user_id" text NOT NULL,+ "label" text NOT NULL,+ "provider" text NOT NULL,+ "model" text NOT NULL,+ "base_url" text,+ "encrypted_api_key" text NOT NULL,+ "api_key_salt" text NOT NULL,+ "api_key_hash" text NOT NULL,+ "api_key_preview" text NOT NULL,+ "test_status" text DEFAULT 'untested' NOT NULL,+ "test_error" text,+ "last_tested_at" timestamp with time zone,+ "last_used_at" timestamp with time zone,+ "enabled" boolean DEFAULT false NOT NULL,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE INDEX "agent_actions_thread_id_created_at_index" ON "agent_actions" ("thread_id","created_at" DESC NULLS LAST);--> statement-breakpoint+CREATE INDEX "agent_actions_resume_id_index" ON "agent_actions" ("resume_id");--> statement-breakpoint+CREATE INDEX "agent_actions_message_id_index" ON "agent_actions" ("message_id");--> statement-breakpoint+CREATE INDEX "agent_attachments_thread_id_index" ON "agent_attachments" ("thread_id");--> statement-breakpoint+CREATE INDEX "agent_attachments_message_id_index" ON "agent_attachments" ("message_id");--> statement-breakpoint+CREATE INDEX "agent_attachments_user_id_index" ON "agent_attachments" ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "agent_messages_thread_id_sequence_index" ON "agent_messages" ("thread_id","sequence");--> statement-breakpoint+CREATE INDEX "agent_messages_user_id_created_at_index" ON "agent_messages" ("user_id","created_at" DESC NULLS LAST);--> statement-breakpoint+CREATE INDEX "agent_threads_user_id_status_last_message_at_index" ON "agent_threads" ("user_id","status","last_message_at" DESC NULLS LAST);--> statement-breakpoint+CREATE INDEX "agent_threads_working_resume_id_index" ON "agent_threads" ("working_resume_id");--> statement-breakpoint+CREATE INDEX "agent_threads_ai_provider_id_index" ON "agent_threads" ("ai_provider_id");--> statement-breakpoint+CREATE INDEX "ai_providers_user_id_enabled_index" ON "ai_providers" ("user_id","enabled");--> statement-breakpoint+CREATE INDEX "ai_providers_user_id_last_used_at_index" ON "ai_providers" ("user_id","last_used_at" DESC NULLS LAST);--> statement-breakpoint+CREATE INDEX "ai_providers_user_id_created_at_index" ON "ai_providers" ("user_id","created_at");--> statement-breakpoint+ALTER TABLE "agent_actions" ADD CONSTRAINT "agent_actions_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint+ALTER TABLE "agent_actions" ADD CONSTRAINT "agent_actions_thread_id_agent_threads_id_fkey" FOREIGN KEY ("thread_id") REFERENCES "agent_threads"("id") ON DELETE CASCADE;--> statement-breakpoint+ALTER TABLE "agent_actions" ADD CONSTRAINT "agent_actions_message_id_agent_messages_id_fkey" FOREIGN KEY ("message_id") REFERENCES "agent_messages"("id") ON DELETE SET NULL;--> statement-breakpoint+ALTER TABLE "agent_actions" ADD CONSTRAINT "agent_actions_resume_id_resume_id_fkey" FOREIGN KEY ("resume_id") REFERENCES "resume"("id") ON DELETE SET NULL;--> statement-breakpoint+ALTER TABLE "agent_attachments" ADD CONSTRAINT "agent_attachments_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint+ALTER TABLE "agent_attachments" ADD CONSTRAINT "agent_attachments_thread_id_agent_threads_id_fkey" FOREIGN KEY ("thread_id") REFERENCES "agent_threads"("id") ON DELETE CASCADE;--> statement-breakpoint+ALTER TABLE "agent_attachments" ADD CONSTRAINT "agent_attachments_message_id_agent_messages_id_fkey" FOREIGN KEY ("message_id") REFERENCES "agent_messages"("id") ON DELETE SET NULL;--> statement-breakpoint+ALTER TABLE "agent_messages" ADD CONSTRAINT "agent_messages_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint+ALTER TABLE "agent_messages" ADD CONSTRAINT "agent_messages_thread_id_agent_threads_id_fkey" FOREIGN KEY ("thread_id") REFERENCES "agent_threads"("id") ON DELETE CASCADE;--> statement-breakpoint+ALTER TABLE "agent_threads" ADD CONSTRAINT "agent_threads_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint+ALTER TABLE "agent_threads" ADD CONSTRAINT "agent_threads_ai_provider_id_ai_providers_id_fkey" FOREIGN KEY ("ai_provider_id") REFERENCES "ai_providers"("id") ON DELETE SET NULL;--> statement-breakpoint+ALTER TABLE "agent_threads" ADD CONSTRAINT "agent_threads_source_resume_id_resume_id_fkey" FOREIGN KEY ("source_resume_id") REFERENCES "resume"("id") ON DELETE SET NULL;--> statement-breakpoint+ALTER TABLE "agent_threads" ADD CONSTRAINT "agent_threads_working_resume_id_resume_id_fkey" FOREIGN KEY ("working_resume_id") REFERENCES "resume"("id") ON DELETE SET NULL;--> statement-breakpoint+ALTER TABLE "ai_providers" ADD CONSTRAINT "ai_providers_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;\ No newline at end of filediff --git a/migrations/20260513181752_bent_human_cannonball/snapshot.json b/migrations/20260513181752_bent_human_cannonball/snapshot.jsonnew file mode 100644index 000000000..a48c60025--- /dev/null+++ b/migrations/20260513181752_bent_human_cannonball/snapshot.json@@ -0,0 +1,4756 @@+{+ "version": "8",+ "dialect": "postgres",+ "id": "4910390e-c52a-4576-8189-168cc1ead68a",+ "prevIds": ["c889ff94-4bfe-4291-be04-02bc9eb7b94e"],+ "ddl": [+ {+ "isRlsEnabled": false,+ "name": "account",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "apikey",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "jwks",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "oauth_access_token",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "oauth_client",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "oauth_consent",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "oauth_refresh_token",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "passkey",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "session",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "two_factor",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "user",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "verification",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "resume",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "resume_analysis",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "resume_statistics",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "agent_actions",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "agent_attachments",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "agent_messages",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "agent_threads",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "isRlsEnabled": false,+ "name": "ai_providers",+ "entityType": "tables",+ "schema": "public"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "account_id",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "'credential'",+ "generated": null,+ "identity": null,+ "name": "provider_id",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "scope",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id_token",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "password",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "access_token",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "refresh_token",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "access_token_expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "refresh_token_expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "account"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "name",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "start",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "prefix",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "key",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "'default'",+ "generated": null,+ "identity": null,+ "name": "config_id",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "reference_id",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "refill_interval",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "refill_amount",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "last_refill_at",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "true",+ "generated": null,+ "identity": null,+ "name": "enabled",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "rate_limit_enabled",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "86400000",+ "generated": null,+ "identity": null,+ "name": "rate_limit_time_window",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "10",+ "generated": null,+ "identity": null,+ "name": "rate_limit_max",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "0",+ "generated": null,+ "identity": null,+ "name": "request_count",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "remaining",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "last_request",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "permissions",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "jsonb",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "metadata",+ "entityType": "columns",+ "schema": "public",+ "table": "apikey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "jwks"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "public_key",+ "entityType": "columns",+ "schema": "public",+ "table": "jwks"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "private_key",+ "entityType": "columns",+ "schema": "public",+ "table": "jwks"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "jwks"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "jwks"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "token",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "client_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "session_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "reference_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "refresh_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "scopes",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "client_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "client_secret",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "disabled",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "skip_consent",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "enable_end_session",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "subject_type",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "scopes",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "name",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "uri",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "icon",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "contacts",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "tos",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "policy",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "software_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "software_version",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "software_statement",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "redirect_uris",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "post_logout_redirect_uris",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "token_endpoint_auth_method",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "grant_types",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "response_types",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "public",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "type",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "require_pkce",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "reference_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "jsonb",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "metadata",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "client_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "reference_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "scopes",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "token",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "client_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "session_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "reference_id",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "revoked",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "auth_time",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 1,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "scopes",+ "entityType": "columns",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "name",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "aaguid",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "public_key",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "credential_id",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "counter",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "device_type",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "backed_up",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "transports",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "passkey"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "token",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "ip_address",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_agent",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "impersonated_by",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "session"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "secret",+ "entityType": "columns",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "backup_codes",+ "entityType": "columns",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "true",+ "generated": null,+ "identity": null,+ "name": "verified",+ "entityType": "columns",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "image",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "name",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "email",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "email_verified",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "username",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "display_username",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "two_factor_enabled",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "last_active_at",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "'user'",+ "generated": null,+ "identity": null,+ "name": "role",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "banned",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "ban_reason",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "timestamp(6) with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "ban_expires",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "user"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "verification"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "identifier",+ "entityType": "columns",+ "schema": "public",+ "table": "verification"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "value",+ "entityType": "columns",+ "schema": "public",+ "table": "verification"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "expires_at",+ "entityType": "columns",+ "schema": "public",+ "table": "verification"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "verification"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "verification"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "name",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "slug",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 1,+ "default": "'{}'",+ "generated": null,+ "identity": null,+ "name": "tags",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "is_public",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "is_locked",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "password",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "jsonb",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "data",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_analysis"+ },+ {+ "type": "jsonb",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "analysis",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_analysis"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "resume_id",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_analysis"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_analysis"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_analysis"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "0",+ "generated": null,+ "identity": null,+ "name": "views",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "0",+ "generated": null,+ "identity": null,+ "name": "downloads",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "last_viewed_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "last_downloaded_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "resume_id",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "thread_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "message_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "resume_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "kind",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "'applied'",+ "generated": null,+ "identity": null,+ "name": "status",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "title",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "summary",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "jsonb",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "operations",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "jsonb",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "inverse_operations",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "base_updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "applied_updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "reverted_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "revert_message",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "thread_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "message_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "storage_key",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "filename",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "media_type",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "size",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "thread_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "role",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "'completed'",+ "generated": null,+ "identity": null,+ "name": "status",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "integer",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "sequence",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "jsonb",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "ui_message",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "error",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "ai_provider_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "source_resume_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "working_resume_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "title",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "'active'",+ "generated": null,+ "identity": null,+ "name": "status",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "active_run_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "active_stream_id",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "active_run_started_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "last_message_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "archived_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "deleted_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "id",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "user_id",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "label",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "provider",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "model",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "base_url",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "encrypted_api_key",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "api_key_salt",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "api_key_hash",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "api_key_preview",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "'untested'",+ "generated": null,+ "identity": null,+ "name": "test_status",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "text",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "test_error",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "last_tested_at",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": false,+ "dimensions": 0,+ "default": null,+ "generated": null,+ "identity": null,+ "name": "last_used_at",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "boolean",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "false",+ "generated": null,+ "identity": null,+ "name": "enabled",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "created_at",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "type": "timestamp with time zone",+ "typeSchema": null,+ "notNull": true,+ "dimensions": 0,+ "default": "now()",+ "generated": null,+ "identity": null,+ "name": "updated_at",+ "entityType": "columns",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "account_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "account"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "reference_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "apikey_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "apikey"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "key",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "apikey_key_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "apikey"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "config_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "apikey_config_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "apikey"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "enabled",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "reference_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "apikey_enabled_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "apikey"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "token",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "oauth_access_token_token_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "client_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "oauth_client_client_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "client_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "oauth_consent_user_id_client_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "token",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "oauth_refresh_token_token_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "passkey_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "passkey"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "token",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "session_token_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "session"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "expires_at",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "session_expires_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "session"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "two_factor_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "secret",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "two_factor_secret_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "created_at",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "user_created_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "user"+ },+ {+ "nameExplicit": true,+ "columns": [+ {+ "value": "lower(\"email\")",+ "isExpression": true,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": true,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "user_email_lower_unique_idx",+ "entityType": "indexes",+ "schema": "public",+ "table": "user"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "identifier",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "verification_identifier_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "verification"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "resume_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "resume"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "created_at",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "resume_created_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "resume"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "updated_at",+ "isExpression": false,+ "asc": false,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "resume_user_id_updated_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "resume"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "is_public",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "slug",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "resume_is_public_slug_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "resume"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "resume_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "resume_analysis_resume_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "resume_analysis"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "thread_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "created_at",+ "isExpression": false,+ "asc": false,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_actions_thread_id_created_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "resume_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_actions_resume_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "message_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_actions_message_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "thread_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_attachments_thread_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "message_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_attachments_message_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_attachments_user_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "thread_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "sequence",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": true,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_messages_thread_id_sequence_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "created_at",+ "isExpression": false,+ "asc": false,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_messages_user_id_created_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "status",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "last_message_at",+ "isExpression": false,+ "asc": false,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_threads_user_id_status_last_message_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "working_resume_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_threads_working_resume_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "ai_provider_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "agent_threads_ai_provider_id_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "enabled",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "ai_providers_user_id_enabled_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "last_used_at",+ "isExpression": false,+ "asc": false,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "ai_providers_user_id_last_used_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "nameExplicit": false,+ "columns": [+ {+ "value": "user_id",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ },+ {+ "value": "created_at",+ "isExpression": false,+ "asc": true,+ "nullsFirst": false,+ "opclass": null+ }+ ],+ "isUnique": false,+ "where": null,+ "with": "",+ "method": "btree",+ "concurrently": false,+ "name": "ai_providers_user_id_created_at_index",+ "entityType": "indexes",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "account_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "account"+ },+ {+ "nameExplicit": false,+ "columns": ["reference_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "apikey_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "apikey"+ },+ {+ "nameExplicit": false,+ "columns": ["client_id"],+ "schemaTo": "public",+ "tableTo": "oauth_client",+ "columnsTo": ["client_id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_access_token_client_id_oauth_client_client_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "nameExplicit": false,+ "columns": ["session_id"],+ "schemaTo": "public",+ "tableTo": "session",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "oauth_access_token_session_id_session_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_access_token_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "nameExplicit": false,+ "columns": ["refresh_id"],+ "schemaTo": "public",+ "tableTo": "oauth_refresh_token",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_access_token_refresh_id_oauth_refresh_token_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_access_token"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_client_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_client"+ },+ {+ "nameExplicit": false,+ "columns": ["client_id"],+ "schemaTo": "public",+ "tableTo": "oauth_client",+ "columnsTo": ["client_id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_consent_client_id_oauth_client_client_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_consent_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_consent"+ },+ {+ "nameExplicit": false,+ "columns": ["client_id"],+ "schemaTo": "public",+ "tableTo": "oauth_client",+ "columnsTo": ["client_id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_refresh_token_client_id_oauth_client_client_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "nameExplicit": false,+ "columns": ["session_id"],+ "schemaTo": "public",+ "tableTo": "session",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "oauth_refresh_token_session_id_session_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "oauth_refresh_token_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "oauth_refresh_token"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "passkey_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "passkey"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "session_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "session"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "two_factor_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "two_factor"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "resume_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "resume"+ },+ {+ "nameExplicit": false,+ "columns": ["resume_id"],+ "schemaTo": "public",+ "tableTo": "resume",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "resume_analysis_resume_id_resume_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "resume_analysis"+ },+ {+ "nameExplicit": false,+ "columns": ["resume_id"],+ "schemaTo": "public",+ "tableTo": "resume",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "resume_statistics_resume_id_resume_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "resume_statistics"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "agent_actions_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "nameExplicit": false,+ "columns": ["thread_id"],+ "schemaTo": "public",+ "tableTo": "agent_threads",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "agent_actions_thread_id_agent_threads_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "nameExplicit": false,+ "columns": ["message_id"],+ "schemaTo": "public",+ "tableTo": "agent_messages",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "agent_actions_message_id_agent_messages_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "nameExplicit": false,+ "columns": ["resume_id"],+ "schemaTo": "public",+ "tableTo": "resume",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "agent_actions_resume_id_resume_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_actions"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "agent_attachments_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "nameExplicit": false,+ "columns": ["thread_id"],+ "schemaTo": "public",+ "tableTo": "agent_threads",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "agent_attachments_thread_id_agent_threads_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "nameExplicit": false,+ "columns": ["message_id"],+ "schemaTo": "public",+ "tableTo": "agent_messages",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "agent_attachments_message_id_agent_messages_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_attachments"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "agent_messages_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "nameExplicit": false,+ "columns": ["thread_id"],+ "schemaTo": "public",+ "tableTo": "agent_threads",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "agent_messages_thread_id_agent_threads_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_messages"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "agent_threads_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "nameExplicit": false,+ "columns": ["ai_provider_id"],+ "schemaTo": "public",+ "tableTo": "ai_providers",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "agent_threads_ai_provider_id_ai_providers_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "nameExplicit": false,+ "columns": ["source_resume_id"],+ "schemaTo": "public",+ "tableTo": "resume",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "agent_threads_source_resume_id_resume_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "nameExplicit": false,+ "columns": ["working_resume_id"],+ "schemaTo": "public",+ "tableTo": "resume",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "SET NULL",+ "name": "agent_threads_working_resume_id_resume_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "agent_threads"+ },+ {+ "nameExplicit": false,+ "columns": ["user_id"],+ "schemaTo": "public",+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "NO ACTION",+ "onDelete": "CASCADE",+ "name": "ai_providers_user_id_user_id_fkey",+ "entityType": "fks",+ "schema": "public",+ "table": "ai_providers"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "account_pkey",+ "schema": "public",+ "table": "account",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "apikey_pkey",+ "schema": "public",+ "table": "apikey",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "jwks_pkey",+ "schema": "public",+ "table": "jwks",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "oauth_access_token_pkey",+ "schema": "public",+ "table": "oauth_access_token",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "oauth_client_pkey",+ "schema": "public",+ "table": "oauth_client",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "oauth_consent_pkey",+ "schema": "public",+ "table": "oauth_consent",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "oauth_refresh_token_pkey",+ "schema": "public",+ "table": "oauth_refresh_token",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "passkey_pkey",+ "schema": "public",+ "table": "passkey",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "session_pkey",+ "schema": "public",+ "table": "session",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "two_factor_pkey",+ "schema": "public",+ "table": "two_factor",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "user_pkey",+ "schema": "public",+ "table": "user",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "verification_pkey",+ "schema": "public",+ "table": "verification",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "resume_pkey",+ "schema": "public",+ "table": "resume",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "resume_analysis_pkey",+ "schema": "public",+ "table": "resume_analysis",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "resume_statistics_pkey",+ "schema": "public",+ "table": "resume_statistics",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "agent_actions_pkey",+ "schema": "public",+ "table": "agent_actions",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "agent_attachments_pkey",+ "schema": "public",+ "table": "agent_attachments",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "agent_messages_pkey",+ "schema": "public",+ "table": "agent_messages",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "agent_threads_pkey",+ "schema": "public",+ "table": "agent_threads",+ "entityType": "pks"+ },+ {+ "columns": ["id"],+ "nameExplicit": false,+ "name": "ai_providers_pkey",+ "schema": "public",+ "table": "ai_providers",+ "entityType": "pks"+ },+ {+ "nameExplicit": false,+ "columns": ["slug", "user_id"],+ "nullsNotDistinct": false,+ "name": "resume_slug_user_id_unique",+ "entityType": "uniques",+ "schema": "public",+ "table": "resume"+ },+ {+ "nameExplicit": false,+ "columns": ["token"],+ "nullsNotDistinct": false,+ "name": "oauth_access_token_token_key",+ "schema": "public",+ "table": "oauth_access_token",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["client_id"],+ "nullsNotDistinct": false,+ "name": "oauth_client_client_id_key",+ "schema": "public",+ "table": "oauth_client",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["token"],+ "nullsNotDistinct": false,+ "name": "session_token_key",+ "schema": "public",+ "table": "session",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["email"],+ "nullsNotDistinct": false,+ "name": "user_email_key",+ "schema": "public",+ "table": "user",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["username"],+ "nullsNotDistinct": false,+ "name": "user_username_key",+ "schema": "public",+ "table": "user",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["display_username"],+ "nullsNotDistinct": false,+ "name": "user_display_username_key",+ "schema": "public",+ "table": "user",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["identifier"],+ "nullsNotDistinct": false,+ "name": "verification_identifier_key",+ "schema": "public",+ "table": "verification",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["resume_id"],+ "nullsNotDistinct": false,+ "name": "resume_analysis_resume_id_key",+ "schema": "public",+ "table": "resume_analysis",+ "entityType": "uniques"+ },+ {+ "nameExplicit": false,+ "columns": ["resume_id"],+ "nullsNotDistinct": false,+ "name": "resume_statistics_resume_id_key",+ "schema": "public",+ "table": "resume_statistics",+ "entityType": "uniques"+ }+ ],+ "renames": []+}diff --git a/packages/ai/package.json b/packages/ai/package.jsonindex 635b03af4..9247aa7be 100644--- a/packages/ai/package.json+++ b/packages/ai/package.json@@ -4,7 +4,6 @@"type": "module","private": true,"exports": {- "./store": "./src/store.ts","./types": "./src/types.ts","./prompts": "./src/prompts.ts","./tools/patch-resume": "./src/tools/patch-resume.ts",@@ -24,10 +23,8 @@"@reactive-resume/utils": "workspace:*","deepmerge-ts": "^7.1.5","fast-json-patch": "^3.1.1",- "immer": "^11.1.8","jsonrepair": "^3.14.0",- "zod": "^4.4.3",- "zustand": "^5.0.13"+ "zod": "^4.4.3"},"devDependencies": {"@reactive-resume/config": "workspace:*",diff --git a/packages/ai/src/store.test.ts b/packages/ai/src/store.test.tsdeleted file mode 100644index 3155e96ce..000000000--- a/packages/ai/src/store.test.ts+++ /dev/null@@ -1,123 +0,0 @@-// @vitest-environment happy-dom--import { afterEach, describe, expect, it } from "vitest";-import { useAIStore } from "./store";--const reset = () => {- useAIStore.setState({- enabled: false,- provider: "openai",- model: "",- apiKey: "",- baseURL: "",- testStatus: "unverified",- });-};--afterEach(reset);--describe("useAIStore", () => {- it("starts with provider=openai and disabled state", () => {- const state = useAIStore.getState();- expect(state.enabled).toBe(false);- expect(state.provider).toBe("openai");- expect(state.testStatus).toBe("unverified");- });-- it("set() updates fields and resets verification when credential fields change", () => {- useAIStore.setState({ testStatus: "success", enabled: true });-- useAIStore.getState().set((draft) => {- draft.apiKey = "new-key";- });-- const state = useAIStore.getState();- expect(state.apiKey).toBe("new-key");- expect(state.testStatus).toBe("unverified");- expect(state.enabled).toBe(false);- });-- it("set() does NOT reset testStatus when changing non-credential fields", () => {- useAIStore.setState({ testStatus: "success", enabled: true });-- useAIStore.getState().set((draft) => {- draft.testStatus = "success"; // explicit no-op- });-- const state = useAIStore.getState();- expect(state.testStatus).toBe("success");- expect(state.enabled).toBe(true);- });-- it("canEnable() is true only when testStatus is success", () => {- expect(useAIStore.getState().canEnable()).toBe(false);-- useAIStore.setState({ testStatus: "success" });- expect(useAIStore.getState().canEnable()).toBe(true);-- useAIStore.setState({ testStatus: "failure" });- expect(useAIStore.getState().canEnable()).toBe(false);- });-- it("setEnabled(true) refuses to enable when testStatus is not success", () => {- useAIStore.getState().setEnabled(true);- expect(useAIStore.getState().enabled).toBe(false);- });-- it("setEnabled(true) succeeds when testStatus is success", () => {- useAIStore.setState({ testStatus: "success" });- useAIStore.getState().setEnabled(true);- expect(useAIStore.getState().enabled).toBe(true);- });-- it("setEnabled(false) always succeeds (regardless of testStatus)", () => {- useAIStore.setState({ testStatus: "success", enabled: true });- useAIStore.getState().setEnabled(false);- expect(useAIStore.getState().enabled).toBe(false);- });-- it("reset() clears every field back to initial state", () => {- useAIStore.setState({- enabled: true,- provider: "anthropic",- model: "claude-3",- apiKey: "key",- baseURL: "https://api.anthropic.com",- testStatus: "success",- });-- useAIStore.getState().reset();-- const state = useAIStore.getState();- expect(state).toMatchObject({- enabled: false,- provider: "openai",- model: "",- apiKey: "",- baseURL: "",- testStatus: "unverified",- });- });-- it("resets when only the provider changes", () => {- useAIStore.setState({ testStatus: "success", enabled: true });-- useAIStore.getState().set((draft) => {- draft.provider = "gemini";- });-- expect(useAIStore.getState().testStatus).toBe("unverified");- expect(useAIStore.getState().enabled).toBe(false);- });-- it("resets when only the baseURL changes", () => {- useAIStore.setState({ testStatus: "success", enabled: true });-- useAIStore.getState().set((draft) => {- draft.baseURL = "https://custom.example";- });-- expect(useAIStore.getState().testStatus).toBe("unverified");- expect(useAIStore.getState().enabled).toBe(false);- });-});diff --git a/packages/ai/src/store.ts b/packages/ai/src/store.tsdeleted file mode 100644index 0171ab82f..000000000--- a/packages/ai/src/store.ts+++ /dev/null@@ -1,88 +0,0 @@-import type { WritableDraft } from "immer";-import type { AIProvider } from "./types";-import { createJSONStorage, persist } from "zustand/middleware";-import { immer } from "zustand/middleware/immer";-import { create } from "zustand/react";--type TestStatus = "unverified" | "success" | "failure";--type AIStoreState = {- enabled: boolean;- provider: AIProvider;- model: string;- apiKey: string;- baseURL: string;- testStatus: TestStatus;-};--type AIStoreActions = {- canEnable: () => boolean;- setEnabled: (value: boolean) => void;- set: (fn: (draft: WritableDraft<AIStoreState>) => void) => void;- reset: () => void;-};--type AIStore = AIStoreState & AIStoreActions;--const initialState: AIStoreState = {- enabled: false,- provider: "openai",- model: "",- apiKey: "",- baseURL: "",- testStatus: "unverified",-};--export const useAIStore = create<AIStore>()(- persist(- immer((set, get) => ({- ...initialState,- set: (fn) => {- set((draft) => {- const prev = {- provider: draft.provider,- model: draft.model,- apiKey: draft.apiKey,- baseURL: draft.baseURL,- };-- fn(draft);-- if (- draft.provider !== prev.provider ||- draft.model !== prev.model ||- draft.apiKey !== prev.apiKey ||- draft.baseURL !== prev.baseURL- ) {- draft.testStatus = "unverified";- draft.enabled = false;- }- });- },- reset: () => set(() => initialState),- canEnable: () => {- const { testStatus } = get();- return testStatus === "success";- },- setEnabled: (value: boolean) => {- const canEnable = get().canEnable();- if (value && !canEnable) return;- set((draft) => {- draft.enabled = value;- });- },- })),- {- name: "ai-store",- storage: createJSONStorage(() => localStorage),- partialize: (state) => ({- enabled: state.enabled,- provider: state.provider,- model: state.model,- apiKey: state.apiKey,- baseURL: state.baseURL,- testStatus: state.testStatus,- }),- },- ),-);diff --git a/packages/ai/src/types.ts b/packages/ai/src/types.tsindex 86fb20a14..a10be8d48 100644--- a/packages/ai/src/types.ts+++ b/packages/ai/src/types.ts@@ -1,6 +1,14 @@import { z } from "zod";-const AI_PROVIDERS = ["openai", "anthropic", "gemini", "vercel-ai-gateway", "openrouter", "ollama"] as const;+const AI_PROVIDERS = [+ "openai",+ "anthropic",+ "gemini",+ "vercel-ai-gateway",+ "openrouter",+ "ollama",+ "openai-compatible",+] as const;export type AIProvider = (typeof AI_PROVIDERS)[number];@@ -13,4 +21,5 @@ export const AI_PROVIDER_DEFAULT_BASE_URLS: Record<AIProvider, string> = {"vercel-ai-gateway": "https://ai-gateway.vercel.sh/v3/ai",openrouter: "https://openrouter.ai/api/v1",ollama: "https://ollama.com/api",+ "openai-compatible": "",};diff --git a/packages/api/package.json b/packages/api/package.jsonindex 2feaa74bd..23ecdba51 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -23,6 +23,7 @@"@ai-sdk/openai": "^3.0.63","@ai-sdk/openai-compatible": "^2.0.47","@aws-sdk/client-s3": "^3.1045.0",+ "@mozilla/readability": "^0.6.0","@orpc/client": "^1.14.3","@orpc/experimental-ratelimit": "^1.14.3","@orpc/server": "^1.14.3",@@ -33,21 +34,26 @@"@reactive-resume/schema": "workspace:*","@reactive-resume/utils": "workspace:*","@tanstack/react-start": "^1.167.65",- "ai": "^6.0.180",+ "ai": "^6.0.182","bcrypt": "^6.0.0","better-auth": "1.6.11","drizzle-orm": "1.0.0-rc.2","drizzle-zod": "1.0.0-beta.14-a36c63d","es-toolkit": "^1.46.1",+ "ioredis": "^5.10.1",+ "jsdom": "^29.1.1","ollama-ai-provider-v2": "^3.5.1","react": "^19.2.6",+ "resumable-stream": "^2.2.12","sharp": "^0.34.5","ts-pattern": "^5.9.0",+ "undici": "^8.2.0","zod": "^4.4.3"},"devDependencies": {"@reactive-resume/config": "workspace:*","@types/bcrypt": "^6.0.0",+ "@types/jsdom": "^28.0.3","@typescript/native-preview": "7.0.0-dev.20260513.1","typescript": "^6.0.3"}diff --git a/packages/api/src/middleware/rate-limit/index.ts b/packages/api/src/middleware/rate-limit/index.tsindex f52aab037..49d1f0ddb 100644--- a/packages/api/src/middleware/rate-limit/index.ts+++ b/packages/api/src/middleware/rate-limit/index.ts@@ -44,9 +44,15 @@ function getInputKeyPart(input: unknown): string {if (!input || typeof input !== "object") return "no-input";const inputRecord = input as Record<string, unknown>;- const id = inputRecord.id;- if (typeof id === "string" && id.trim()) return id;+ const fields = ["resumeId", "threadId", "conversationId", "messageId", "fileId", "id"] as const;+ for (const field of fields) {+ const value = inputRecord[field];+ if (typeof value !== "string") continue;++ const trimmedValue = value.trim();+ if (trimmedValue) return `${field}:${trimmedValue}`;+ }const username = inputRecord.username;const slug = inputRecord.slug;@@ -87,9 +93,9 @@ export const pdfExportRateLimit = createRatelimitMiddleware<ContextWithHeaders,key: ({ context }, input) => `pdf-export:${getUserKey(context)}:${input.id}`,});-export const aiRequestRateLimit = createRatelimitMiddleware<ContextWithHeaders, { provider: string }>({+export const aiRequestRateLimit = createRatelimitMiddleware<ContextWithHeaders, unknown>({limiter: productionLimiter(aiLimiter),- key: ({ context }, input) => `ai-request:${getUserKey(context)}:${input.provider}`,+ key: ({ context }, input) => `ai-request:${getUserKey(context)}:${getInputKeyPart(input)}`,});export const jobsSearchRateLimit = createRatelimitMiddleware<ContextWithHeaders, { params: { query: string } }>({diff --git a/packages/api/src/routers/agent.ts b/packages/api/src/routers/agent.tsnew file mode 100644index 000000000..ce65839e1--- /dev/null+++ b/packages/api/src/routers/agent.ts@@ -0,0 +1,287 @@+import type { UIMessage } from "ai";+import { ORPCError } from "@orpc/client";+import z from "zod";+import { protectedProcedure } from "../context";+import { aiRequestRateLimit, storageUploadRateLimit } from "../middleware/rate-limit";+import { agentService } from "../services/agent";++function isAgentEnvironmentUnavailable(error: unknown) {+ return error instanceof Error && error.message === "AGENT_ENVIRONMENT_UNAVAILABLE";+}++function throwUnavailable(): never {+ throw new ORPCError("PRECONDITION_FAILED", {+ message: "AI agent workspace is unavailable because REDIS_URL or ENCRYPTION_SECRET is not configured.",+ });+}++function base64ToUint8Array(value: string) {+ return Uint8Array.from(Buffer.from(value, "base64"));+}++function isUiMessage(value: unknown): value is UIMessage {+ if (!value || typeof value !== "object") return false;++ const message = value as Partial<UIMessage>;+ return (+ typeof message.id === "string" &&+ (message.role === "system" || message.role === "user" || message.role === "assistant") &&+ Array.isArray(message.parts)+ );+}++const threadsRouter = {+ list: protectedProcedure+ .route({+ method: "GET",+ path: "/agent/threads",+ tags: ["Agent"],+ operationId: "listAgentThreads",+ summary: "List agent threads",+ })+ .handler(async ({ context }) => {+ try {+ return await agentService.threads.list({ userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ create: protectedProcedure+ .route({+ method: "POST",+ path: "/agent/threads",+ tags: ["Agent"],+ operationId: "createAgentThread",+ summary: "Create agent thread",+ })+ .input(z.object({ aiProviderId: z.string().optional(), sourceResumeId: z.string().optional() }))+ .handler(async ({ context, input }) => {+ try {+ return await agentService.threads.create({+ userId: context.user.id,+ locale: context.locale,+ ...(input.aiProviderId ? { aiProviderId: input.aiProviderId } : {}),+ ...(input.sourceResumeId ? { sourceResumeId: input.sourceResumeId } : {}),+ });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ get: protectedProcedure+ .route({+ method: "GET",+ path: "/agent/threads/{id}",+ tags: ["Agent"],+ operationId: "getAgentThread",+ summary: "Get agent thread",+ })+ .input(z.object({ id: z.string() }))+ .handler(async ({ context, input }) => {+ try {+ return await agentService.threads.get({ id: input.id, userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ archive: protectedProcedure+ .route({+ method: "POST",+ path: "/agent/threads/{id}/archive",+ tags: ["Agent"],+ operationId: "archiveAgentThread",+ summary: "Archive agent thread",+ })+ .input(z.object({ id: z.string() }))+ .output(z.void())+ .handler(async ({ context, input }) => {+ try {+ await agentService.threads.archive({ id: input.id, userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ delete: protectedProcedure+ .route({+ method: "DELETE",+ path: "/agent/threads/{id}",+ tags: ["Agent"],+ operationId: "deleteAgentThread",+ summary: "Delete agent thread",+ })+ .input(z.object({ id: z.string() }))+ .output(z.void())+ .handler(async ({ context, input }) => {+ try {+ await agentService.threads.delete({ id: input.id, userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),+};++const messagesRouter = {+ send: protectedProcedure+ .route({+ method: "POST",+ path: "/agent/messages/send",+ tags: ["Agent"],+ operationId: "sendAgentMessage",+ summary: "Send agent message",+ })+ .input(+ z.object({+ threadId: z.string(),+ message: z.custom<UIMessage>(isUiMessage, { message: "Invalid UI message." }),+ attachmentIds: z.array(z.string().trim().min(1)).max(10).optional(),+ }),+ )+ .use(aiRequestRateLimit)+ .handler(async ({ context, input }) => {+ try {+ return await agentService.messages.send({+ userId: context.user.id,+ threadId: input.threadId,+ message: input.message,+ ...(input.attachmentIds ? { attachmentIds: input.attachmentIds } : {}),+ });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ stop: protectedProcedure+ .route({+ method: "POST",+ path: "/agent/messages/stop",+ tags: ["Agent"],+ operationId: "stopAgentMessage",+ summary: "Stop active agent run",+ })+ .input(+ z.object({+ threadId: z.string(),+ partialMessage: z.custom<UIMessage>(isUiMessage, { message: "Invalid UI message." }).optional(),+ }),+ )+ .output(z.void())+ .handler(async ({ context, input }) => {+ try {+ await agentService.messages.stop({+ userId: context.user.id,+ threadId: input.threadId,+ ...(input.partialMessage ? { partialMessage: input.partialMessage } : {}),+ });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ resume: protectedProcedure+ .route({+ method: "GET",+ path: "/agent/messages/resume",+ tags: ["Agent"],+ operationId: "resumeAgentMessages",+ summary: "Resume agent message stream",+ })+ .input(z.object({ threadId: z.string() }))+ .handler(async ({ context, input }) => {+ try {+ return await agentService.messages.resume({ userId: context.user.id, threadId: input.threadId });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),+};++const attachmentsRouter = {+ create: protectedProcedure+ .route({+ method: "POST",+ path: "/agent/attachments",+ tags: ["Agent"],+ operationId: "createAgentAttachment",+ summary: "Create agent attachment",+ })+ .input(+ z.object({+ threadId: z.string(),+ filename: z.string().trim().min(1),+ mediaType: z.string().trim().min(1),+ data: z.string().min(1),+ }),+ )+ .use(storageUploadRateLimit)+ .handler(async ({ context, input }) => {+ try {+ return await agentService.attachments.create({+ userId: context.user.id,+ threadId: input.threadId,+ filename: input.filename,+ mediaType: input.mediaType,+ data: base64ToUint8Array(input.data),+ });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ delete: protectedProcedure+ .route({+ method: "DELETE",+ path: "/agent/attachments/{id}",+ tags: ["Agent"],+ operationId: "deleteAgentAttachment",+ summary: "Delete agent attachment",+ })+ .input(z.object({ id: z.string() }))+ .output(z.void())+ .handler(async ({ context, input }) => {+ try {+ await agentService.attachments.delete({ id: input.id, userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),+};++const actionsRouter = {+ revert: protectedProcedure+ .route({+ method: "POST",+ path: "/agent/actions/{id}/revert",+ tags: ["Agent"],+ operationId: "revertAgentAction",+ summary: "Revert agent action",+ })+ .input(z.object({ id: z.string() }))+ .handler(async ({ context, input }) => {+ try {+ return await agentService.actions.revert({ id: input.id, userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),+};++export const agentRouter = {+ threads: threadsRouter,+ messages: messagesRouter,+ attachments: attachmentsRouter,+ actions: actionsRouter,+};diff --git a/packages/api/src/routers/ai-providers.ts b/packages/api/src/routers/ai-providers.tsnew file mode 100644index 000000000..87cb9a5f8--- /dev/null+++ b/packages/api/src/routers/ai-providers.ts@@ -0,0 +1,185 @@+import type { AiProviderResponse } from "../services/ai-providers";+import { ORPCError } from "@orpc/client";+import { type } from "@orpc/server";+import z from "zod";+import { aiProviderSchema } from "@reactive-resume/ai/types";+import { protectedProcedure } from "../context";+import { aiRequestRateLimit } from "../middleware/rate-limit";+import { aiProvidersService } from "../services/ai-providers";++const providerInput = z.object({+ label: z.string().trim().min(1),+ provider: aiProviderSchema,+ model: z.string().trim().min(1),+ baseURL: z.string().trim().optional().default(""),+ apiKey: z.string().trim().min(1),+});++const updateProviderInput = providerInput+ .partial()+ .extend({ id: z.string(), enabled: z.boolean().optional() })+ .refine((input) => Object.keys(input).some((key) => key !== "id"), {+ message: "At least one field must be provided.",+ });++function isAgentEnvironmentUnavailable(error: unknown) {+ return error instanceof Error && error.message === "AGENT_ENVIRONMENT_UNAVAILABLE";+}++function throwUnavailable(): never {+ throw new ORPCError("PRECONDITION_FAILED", {+ message: "AI agent workspace is unavailable because REDIS_URL or ENCRYPTION_SECRET is not configured.",+ });+}++function isInvalidAiBaseUrl(error: unknown) {+ return error instanceof Error && error.message === "INVALID_AI_BASE_URL";+}++function throwInvalidProviderConfig(): never {+ throw new ORPCError("BAD_REQUEST", { message: "Invalid AI provider configuration." });+}++export const aiProvidersRouter = {+ list: protectedProcedure+ .route({+ method: "GET",+ path: "/ai-providers",+ tags: ["AI Providers"],+ operationId: "listAiProviders",+ summary: "List saved AI providers",+ description: "Lists saved provider/model/API key combinations for the authenticated user. API keys are redacted.",+ })+ .output(type<AiProviderResponse[]>())+ .errors({+ PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },+ })+ .handler(async ({ context }) => {+ try {+ return await aiProvidersService.list({ userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ create: protectedProcedure+ .route({+ method: "POST",+ path: "/ai-providers",+ tags: ["AI Providers"],+ operationId: "createAiProvider",+ summary: "Create saved AI provider",+ description: "Stores an encrypted provider/model/API key combination. The key is never returned.",+ })+ .input(providerInput)+ .output(type<AiProviderResponse>())+ .errors({+ BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },+ PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },+ })+ .handler(async ({ context, input }) => {+ try {+ return await aiProvidersService.create({+ userId: context.user.id,+ label: input.label,+ provider: input.provider,+ model: input.model,+ baseURL: input.baseURL,+ apiKey: input.apiKey,+ });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ if (isInvalidAiBaseUrl(error)) throwInvalidProviderConfig();+ throw error;+ }+ }),++ update: protectedProcedure+ .route({+ method: "PATCH",+ path: "/ai-providers/{id}",+ tags: ["AI Providers"],+ operationId: "updateAiProvider",+ summary: "Update saved AI provider",+ description:+ "Updates a saved provider/model/API key combination. Updating the key requires retesting before use.",+ })+ .input(updateProviderInput)+ .output(type<AiProviderResponse>())+ .errors({+ BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },+ NOT_FOUND: { message: "AI provider was not found.", status: 404 },+ PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },+ })+ .handler(async ({ context, input }) => {+ try {+ return await aiProvidersService.update({+ id: input.id,+ userId: context.user.id,+ ...(input.label !== undefined ? { label: input.label } : {}),+ ...(input.provider !== undefined ? { provider: input.provider } : {}),+ ...(input.model !== undefined ? { model: input.model } : {}),+ ...(input.baseURL !== undefined ? { baseURL: input.baseURL } : {}),+ ...(input.apiKey !== undefined ? { apiKey: input.apiKey } : {}),+ ...(input.enabled !== undefined ? { enabled: input.enabled } : {}),+ });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ if (isInvalidAiBaseUrl(error)) throwInvalidProviderConfig();+ throw error;+ }+ }),++ delete: protectedProcedure+ .route({+ method: "DELETE",+ path: "/ai-providers/{id}",+ tags: ["AI Providers"],+ operationId: "deleteAiProvider",+ summary: "Delete saved AI provider",+ description: "Deletes a saved provider/model/API key combination.",+ })+ .input(z.object({ id: z.string() }))+ .output(z.void())+ .errors({+ PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },+ })+ .handler(async ({ context, input }) => {+ try {+ await aiProvidersService.delete({ id: input.id, userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ throw error;+ }+ }),++ test: protectedProcedure+ .route({+ method: "POST",+ path: "/ai-providers/{id}/test",+ tags: ["AI Providers"],+ operationId: "testAiProvider",+ summary: "Test saved AI provider",+ description: "Decrypts the saved API key server-side and validates the provider/model connection.",+ })+ .input(z.object({ id: z.string() }))+ .output(type<AiProviderResponse>())+ .use(aiRequestRateLimit)+ .errors({+ BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },+ BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },+ NOT_FOUND: { message: "AI provider was not found.", status: 404 },+ PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },+ })+ .handler(async ({ context, input }) => {+ try {+ return await aiProvidersService.test({ id: input.id, userId: context.user.id });+ } catch (error) {+ if (isAgentEnvironmentUnavailable(error)) throwUnavailable();+ if (isInvalidAiBaseUrl(error)) throwInvalidProviderConfig();+ if (error instanceof ORPCError) throw error;+ throw new ORPCError("BAD_GATEWAY", { message: "Could not reach the AI provider." });+ }+ }),+};diff --git a/packages/api/src/routers/ai.ts b/packages/api/src/routers/ai.tsindex 29ad764ed..cca06224d 100644--- a/packages/api/src/routers/ai.ts+++ b/packages/api/src/routers/ai.ts@@ -5,14 +5,12 @@ import { type } from "@orpc/server";import { AISDKError } from "ai";import { flattenError, ZodError, z } from "zod";import { storedResumeAnalysisSchema } from "@reactive-resume/schema/resume/analysis";-import { resumeDataSchema } from "@reactive-resume/schema/resume/data";import { protectedProcedure } from "../context";import { aiRequestRateLimit } from "../middleware/rate-limit";-import { aiCredentialsSchema, aiService, fileInputSchema } from "../services/ai";+import { aiService, fileInputSchema } from "../services/ai";+import { aiProvidersService } from "../services/ai-providers";import { resumeService } from "../services/resume";-type AIProvider = z.infer<typeof aiCredentialsSchema.shape.provider>;-function isInvalidAiBaseUrlError(error: unknown): boolean {return error instanceof Error && error.message === "INVALID_AI_BASE_URL";}@@ -21,6 +19,10 @@ function isAiProviderGatewayError(error: unknown): boolean {return error instanceof AISDKError;}+function isCredentialEncryptionUnavailable(error: unknown): boolean {+ return error instanceof Error && error.message === "AI_CREDENTIAL_ENCRYPTION_UNAVAILABLE";+}+function throwAiProviderGatewayError(): never {throw new ORPCError("BAD_GATEWAY", { message: "Could not reach the AI provider." });}@@ -29,6 +31,12 @@ function throwAiProviderConfigError(): never {throw new ORPCError("BAD_REQUEST", { message: "Invalid AI provider configuration." });}+function throwCredentialEncryptionUnavailable(): never {+ throw new ORPCError("PRECONDITION_FAILED", {+ message: "AI providers are unavailable because ENCRYPTION_SECRET is not configured.",+ });+}+function throwResumeStructureError(error: ZodError): never {throw new ORPCError("BAD_REQUEST", {message: "Invalid resume data structure",@@ -36,35 +44,17 @@ function throwResumeStructureError(error: ZodError): never {});}-export const aiRouter = {- testConnection: protectedProcedure- .route({- method: "POST",- path: "/ai/test-connection",- tags: ["AI"],- operationId: "testAiConnection",- summary: "Test AI provider connection",- description:- "Validates the connection to an AI provider by sending a simple test prompt. Requires the provider type, model name, API key, and an optional base URL. Supported providers: OpenAI, Anthropic, Google Gemini, Ollama, OpenRouter, and Vercel AI Gateway. Requires authentication.",- successDescription: "The AI provider connection was successful.",- })- .input(z.object({ ...aiCredentialsSchema.shape }))- .use(aiRequestRateLimit)- .errors({- BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },- BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },- })- .handler(async ({ input }) => {- try {- return await aiService.testConnection(input);- } catch (error) {- console.error(error);- if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();- if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();- throw error;- }- }),+async function getRunnableProvider(userId: string, aiProviderId?: string) {+ const provider = aiProviderId+ ? await aiProvidersService.getRunnableById({ id: aiProviderId, userId })+ : await aiProvidersService.getDefaultRunnable({ userId });++ if (!provider) throw new ORPCError("BAD_REQUEST", { message: "No tested AI provider is available." });++ return provider;+}+export const aiRouter = {parsePdf: protectedProcedure.route({method: "POST",@@ -76,16 +66,24 @@ export const aiRouter = {"Extracts structured resume data from a PDF file using the specified AI provider. The file should be sent as a base64-encoded string along with AI provider credentials. Returns a complete ResumeData object. Requires authentication.",successDescription: "The PDF was successfully parsed into structured resume data.",})- .input(z.object({ ...aiCredentialsSchema.shape, file: fileInputSchema }))+ .input(z.object({ aiProviderId: z.string().optional(), file: fileInputSchema })).use(aiRequestRateLimit).errors({BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },BAD_REQUEST: { message: "The AI returned an improperly formatted structure.", status: 400 },})- .handler(async ({ input }): Promise<ResumeData> => {+ .handler(async ({ context, input }): Promise<ResumeData> => {try {- return await aiService.parsePdf(input);+ const provider = await getRunnableProvider(context.user.id, input.aiProviderId);+ return await aiService.parsePdf({+ provider: provider.provider,+ model: provider.model,+ apiKey: provider.apiKey,+ baseURL: provider.baseURL ?? "",+ file: input.file,+ });} catch (error) {+ if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();if (error instanceof ZodError) throwResumeStructureError(error);@@ -106,7 +104,7 @@ export const aiRouter = {}).input(z.object({- ...aiCredentialsSchema.shape,+ aiProviderId: z.string().optional(),file: fileInputSchema,mediaType: z.enum(["application/msword",@@ -119,10 +117,19 @@ export const aiRouter = {BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },BAD_REQUEST: { message: "The AI returned an improperly formatted structure.", status: 400 },})- .handler(async ({ input }) => {+ .handler(async ({ context, input }) => {try {- return await aiService.parseDocx(input);+ const provider = await getRunnableProvider(context.user.id, input.aiProviderId);+ return await aiService.parseDocx({+ provider: provider.provider,+ model: provider.model,+ apiKey: provider.apiKey,+ baseURL: provider.baseURL ?? "",+ mediaType: input.mediaType,+ file: input.file,+ });} catch (error) {+ if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();if (error instanceof ZodError) throwResumeStructureError(error);@@ -142,20 +149,30 @@ export const aiRouter = {}).input(type<{- provider: AIProvider;- model: string;- apiKey: string;- baseURL: string;+ aiProviderId?: string;messages: UIMessage[];- resumeData: ResumeData;- resumeUpdatedAt: Date;+ resumeId: string;}>(),).use(aiRequestRateLimit)- .handler(async ({ input }) => {+ .handler(async ({ context, input }) => {try {- return await aiService.chat(input);+ const [provider, resume] = await Promise.all([+ getRunnableProvider(context.user.id, input.aiProviderId),+ resumeService.getById({ id: input.resumeId, userId: context.user.id }),+ ]);++ return await aiService.chat({+ provider: provider.provider,+ model: provider.model,+ apiKey: provider.apiKey,+ baseURL: provider.baseURL ?? "",+ messages: input.messages,+ resumeData: resume.data,+ resumeUpdatedAt: resume.updatedAt,+ });} catch (error) {+ if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();throw error;@@ -175,9 +192,8 @@ export const aiRouter = {}).input(z.object({- ...aiCredentialsSchema.shape,+ aiProviderId: z.string().optional(),resumeId: z.string(),- resumeData: resumeDataSchema,}),).use(aiRequestRateLimit)@@ -188,12 +204,16 @@ export const aiRouter = {}).handler(async ({ context, input }) => {try {+ const [provider, resume] = await Promise.all([+ getRunnableProvider(context.user.id, input.aiProviderId),+ resumeService.getById({ id: input.resumeId, userId: context.user.id }),+ ]);const analysis = await aiService.analyzeResume({- provider: input.provider,- model: input.model,- apiKey: input.apiKey,- baseURL: input.baseURL,- resumeData: input.resumeData,+ provider: provider.provider,+ model: provider.model,+ apiKey: provider.apiKey,+ baseURL: provider.baseURL ?? "",+ resumeData: resume.data,});return await resumeService.analysis.upsert({@@ -202,10 +222,11 @@ export const aiRouter = {analysis: {...analysis,updatedAt: new Date(),- modelMeta: { provider: input.provider, model: input.model },+ modelMeta: { provider: provider.provider, model: provider.model },},});} catch (error) {+ if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();if (error instanceof ZodError) {diff --git a/packages/api/src/routers/index.ts b/packages/api/src/routers/index.tsindex cecddd7b1..384708843 100644--- a/packages/api/src/routers/index.ts+++ b/packages/api/src/routers/index.ts@@ -1,4 +1,6 @@+import { agentRouter } from "./agent";import { aiRouter } from "./ai";+import { aiProvidersRouter } from "./ai-providers";import { authRouter } from "./auth";import { flagsRouter } from "./flags";import { resumeRouter } from "./resume";@@ -7,6 +9,8 @@ import { storageRouter } from "./storage";export default {ai: aiRouter,+ aiProviders: aiProvidersRouter,+ agent: agentRouter,auth: authRouter,flags: flagsRouter,resume: resumeRouter,diff --git a/packages/api/src/services/agent-patches.test.ts b/packages/api/src/services/agent-patches.test.tsnew file mode 100644index 000000000..01a50403b--- /dev/null+++ b/packages/api/src/services/agent-patches.test.ts@@ -0,0 +1,155 @@+import type { ResumeData } from "@reactive-resume/schema/resume/data";+import type { JsonPatchOperation } from "@reactive-resume/utils/resume/patch";+import { describe, expect, it } from "vitest";+import { defaultResumeData } from "@reactive-resume/schema/resume/default";+import { createInverseResumePatches } from "./agent-patches";++function buildFixture(): ResumeData {+ const clone = JSON.parse(JSON.stringify(defaultResumeData)) as ResumeData;+ clone.basics.name = "Alice";+ clone.basics.email = "[email protected]";+ clone.basics.customFields = [+ { id: "field-1", icon: "phosphor", text: "first", link: "" },+ { id: "field-2", icon: "phosphor", text: "second", link: "" },+ ];+ return clone;+}++describe("createInverseResumePatches", () => {+ it("inverts a single replace into a replace back to the original value", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [{ op: "replace", path: "/basics/name", value: "Bob" }];++ const inverse = createInverseResumePatches(data, operations);++ expect(inverse).toEqual([{ op: "replace", path: "/basics/name", value: "Alice" }]);+ });++ it("inverts a single remove into an add carrying the original value", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [{ op: "remove", path: "/basics/customFields/0" }];++ const inverse = createInverseResumePatches(data, operations);++ expect(inverse).toEqual([+ {+ op: "add",+ path: "/basics/customFields/0",+ value: { id: "field-1", icon: "phosphor", text: "first", link: "" },+ },+ ]);+ });++ it("inverts a single add into a remove at the same path", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [+ {+ op: "add",+ path: "/basics/customFields/2",+ value: { id: "field-3", icon: "phosphor", text: "third", link: "" },+ },+ ];++ const inverse = createInverseResumePatches(data, operations);++ expect(inverse).toEqual([{ op: "remove", path: "/basics/customFields/2" }]);+ });++ it("inverts an array insert at an existing index into a remove at the same path", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [+ {+ op: "add",+ path: "/basics/customFields/1",+ value: { id: "field-inserted", icon: "phosphor", text: "inserted", link: "" },+ },+ ];++ const inverse = createInverseResumePatches(data, operations);++ expect(inverse).toEqual([{ op: "remove", path: "/basics/customFields/1" }]);+ });++ it("composes inverses in reverse order with each original value", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [+ { op: "replace", path: "/basics/name", value: "Bob" },+ { op: "replace", path: "/basics/email", value: "[email protected]" },+ ];++ const inverse = createInverseResumePatches(data, operations);++ expect(inverse).toEqual([+ { op: "replace", path: "/basics/email", value: "[email protected]" },+ { op: "replace", path: "/basics/name", value: "Alice" },+ ]);+ });++ it("reads downstream pointers against the working copy after upstream removals", () => {+ // Removing /basics/customFields/1 does not affect /basics/name.+ // The inverse builder reads /basics/name from the working copy after the+ // removal has been applied; that value must still be the original "Alice".+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [+ { op: "remove", path: "/basics/customFields/1" },+ { op: "replace", path: "/basics/name", value: "Bob" },+ ];++ const inverse = createInverseResumePatches(data, operations);++ expect(inverse).toEqual([+ { op: "replace", path: "/basics/name", value: "Alice" },+ {+ op: "add",+ path: "/basics/customFields/1",+ value: { id: "field-2", icon: "phosphor", text: "second", link: "" },+ },+ ]);+ });++ it("throws INVERTIBLE_PATCH_REQUIRED when a path ends with /- (array append)", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [+ { op: "add", path: "/basics/customFields/-", value: { id: "x", icon: "phosphor", text: "x", link: "" } },+ ];++ expect(() => createInverseResumePatches(data, operations)).toThrow("INVERTIBLE_PATCH_REQUIRED");+ });++ it("throws INVERTIBLE_PATCH_REQUIRED for move operations", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [{ op: "move", path: "/basics/email", from: "/basics/name" }];++ expect(() => createInverseResumePatches(data, operations)).toThrow("INVERTIBLE_PATCH_REQUIRED");+ });++ it("throws INVERTIBLE_PATCH_REQUIRED for copy operations", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [{ op: "copy", path: "/basics/email", from: "/basics/name" }];++ expect(() => createInverseResumePatches(data, operations)).toThrow("INVERTIBLE_PATCH_REQUIRED");+ });++ it("throws INVERTIBLE_PATCH_REQUIRED for test operations", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [{ op: "test", path: "/basics/name", value: "Alice" }];++ expect(() => createInverseResumePatches(data, operations)).toThrow("INVERTIBLE_PATCH_REQUIRED");+ });++ it("throws INVALID_PATCH_OPERATIONS when reading a non-existent path", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [{ op: "replace", path: "/does/not/exist", value: "x" }];++ expect(() => createInverseResumePatches(data, operations)).toThrow("INVALID_PATCH_OPERATIONS");+ });++ it("inverts an add at an existing object member into a replace with the prior value", () => {+ const data = buildFixture();+ const operations: JsonPatchOperation[] = [{ op: "add", path: "/basics/name", value: "Bob" }];++ const inverse = createInverseResumePatches(data, operations);++ expect(inverse).toEqual([{ op: "replace", path: "/basics/name", value: "Alice" }]);+ });+});diff --git a/packages/api/src/services/agent-patches.ts b/packages/api/src/services/agent-patches.tsnew file mode 100644index 000000000..5d1e64b05--- /dev/null+++ b/packages/api/src/services/agent-patches.ts@@ -0,0 +1,83 @@+import type { ResumeData } from "@reactive-resume/schema/resume/data";+import type { JsonPatchOperation } from "@reactive-resume/utils/resume/patch";+import { applyResumePatches } from "@reactive-resume/utils/resume/patch";++function decodePointerSegment(segment: string) {+ return segment.replaceAll("~1", "/").replaceAll("~0", "~");+}++function readPointer(document: unknown, pointer: string): unknown {+ if (pointer === "") return document;+ if (!pointer.startsWith("/")) throw new Error("INVALID_PATCH_OPERATIONS");++ return pointer+ .slice(1)+ .split("/")+ .map(decodePointerSegment)+ .reduce<unknown>((current, segment) => {+ if (current == null || typeof current !== "object") throw new Error("INVALID_PATCH_OPERATIONS");++ return (current as Record<string, unknown>)[segment];+ }, document);+}++function pointerExists(document: unknown, pointer: string): boolean {+ if (pointer === "") return true;+ if (!pointer.startsWith("/")) return false;++ const segments = pointer.slice(1).split("/").map(decodePointerSegment);+ let current: unknown = document;+ for (const segment of segments) {+ if (current == null || typeof current !== "object") return false;+ const record = current as Record<string, unknown>;+ if (!Object.hasOwn(record, segment)) return false;+ current = record[segment];+ }+ return true;+}++function getParentPointer(pointer: string) {+ const lastSlashIndex = pointer.lastIndexOf("/");+ return lastSlashIndex <= 0 ? "" : pointer.slice(0, lastSlashIndex);+}++function cloneJson<T>(value: T): T {+ return JSON.parse(JSON.stringify(value)) as T;+}++export function createInverseResumePatches(data: ResumeData, operations: JsonPatchOperation[]): JsonPatchOperation[] {+ const working = cloneJson(data);+ const inverse: JsonPatchOperation[] = [];++ for (const operation of operations) {+ if (operation.path.endsWith("/-")) throw new Error("INVERTIBLE_PATCH_REQUIRED");++ if (operation.op === "replace") {+ inverse.unshift({ op: "replace", path: operation.path, value: cloneJson(readPointer(working, operation.path)) });+ } else if (operation.op === "remove") {+ inverse.unshift({ op: "add", path: operation.path, value: cloneJson(readPointer(working, operation.path)) });+ } else if (operation.op === "add") {+ const parent = readPointer(working, getParentPointer(operation.path));++ // JSON Patch "add" inserts into arrays, but overwrites existing object members.+ // Array inserts must be reverted with remove; object overwrites need replace.+ if (Array.isArray(parent)) {+ inverse.unshift({ op: "remove", path: operation.path });+ } else if (pointerExists(working, operation.path)) {+ inverse.unshift({+ op: "replace",+ path: operation.path,+ value: cloneJson(readPointer(working, operation.path)),+ });+ } else {+ inverse.unshift({ op: "remove", path: operation.path });+ }+ } else {+ throw new Error("INVERTIBLE_PATCH_REQUIRED");+ }++ applyResumePatches(working, [operation]);+ }++ return inverse;+}diff --git a/packages/api/src/services/agent-resume.test.ts b/packages/api/src/services/agent-resume.test.tsnew file mode 100644index 000000000..0b36386b9--- /dev/null+++ b/packages/api/src/services/agent-resume.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from "vitest";+import { buildAgentDraftResumeName, buildUniqueAgentDraftSlug } from "./agent-resume";++describe("agent resume setup helpers", () => {+ it("names duplicated resumes as AI drafts", () => {+ expect(buildAgentDraftResumeName("Senior Product Designer")).toBe("Senior Product Designer - AI Draft");+ expect(buildAgentDraftResumeName("Senior Product Designer - AI Draft")).toBe("Senior Product Designer - AI Draft");+ });++ it("generates unique AI draft slugs", () => {+ expect(buildUniqueAgentDraftSlug("Senior Product Designer", new Set())).toBe("senior-product-designer-ai-draft");+ expect(buildUniqueAgentDraftSlug("Senior Product Designer", new Set(["senior-product-designer-ai-draft"]))).toBe(+ "senior-product-designer-ai-draft-2",+ );+ });+});diff --git a/packages/api/src/services/agent-resume.ts b/packages/api/src/services/agent-resume.tsnew file mode 100644index 000000000..4a5385849--- /dev/null+++ b/packages/api/src/services/agent-resume.ts@@ -0,0 +1,25 @@+import { slugify } from "@reactive-resume/utils/string";++const AI_DRAFT_SUFFIX = " - AI Draft";++export function buildAgentDraftResumeName(sourceName: string) {+ const normalized = sourceName.trim() || "Resume";+ if (normalized.endsWith(AI_DRAFT_SUFFIX)) return normalized;++ return `${normalized}${AI_DRAFT_SUFFIX}`;+}++export function buildUniqueAgentDraftSlug(sourceName: string, existingSlugs: Set<string>) {+ const base = slugify(buildAgentDraftResumeName(sourceName));+ if (!existingSlugs.has(base)) return base;++ let index = 2;+ let candidate = `${base}-${index}`;++ while (existingSlugs.has(candidate)) {+ index += 1;+ candidate = `${base}-${index}`;+ }++ return candidate;+}diff --git a/packages/api/src/services/agent-run-state.ts b/packages/api/src/services/agent-run-state.tsnew file mode 100644index 000000000..417d607e0--- /dev/null+++ b/packages/api/src/services/agent-run-state.ts@@ -0,0 +1,43 @@+import { and, eq, isNull } from "drizzle-orm";+import { db } from "@reactive-resume/db/client";+import * as schema from "@reactive-resume/db/schema";++type AgentRunStateDb = Pick<typeof db, "update">;++export async function claimActiveAgentRun(+ input: { threadId: string; userId: string; runId: string; streamId: string },+ database: AgentRunStateDb = db,+) {+ const claimed = await database+ .update(schema.agentThread)+ .set({ activeRunId: input.runId, activeStreamId: input.streamId, activeRunStartedAt: new Date() })+ .where(+ and(+ eq(schema.agentThread.id, input.threadId),+ eq(schema.agentThread.userId, input.userId),+ isNull(schema.agentThread.activeRunId),+ ),+ )+ .returning({ id: schema.agentThread.id });++ return claimed.length === 1;+}++export async function clearActiveAgentRunIfCurrent(+ input: { threadId: string; userId: string; runId: string; streamId: string | null },+ database: AgentRunStateDb = db,+) {+ await database+ .update(schema.agentThread)+ .set({ activeRunId: null, activeStreamId: null, activeRunStartedAt: null })+ .where(+ and(+ eq(schema.agentThread.id, input.threadId),+ eq(schema.agentThread.userId, input.userId),+ eq(schema.agentThread.activeRunId, input.runId),+ input.streamId === null+ ? isNull(schema.agentThread.activeStreamId)+ : eq(schema.agentThread.activeStreamId, input.streamId),+ ),+ );+}diff --git a/packages/api/src/services/agent-streams.test.ts b/packages/api/src/services/agent-streams.test.tsnew file mode 100644index 000000000..573db2e7b--- /dev/null+++ b/packages/api/src/services/agent-streams.test.ts@@ -0,0 +1,179 @@+import { describe, expect, it, vi } from "vitest";+import { claimActiveAgentRun, clearActiveAgentRunIfCurrent } from "./agent-run-state";+import { createAgentStreamLifecycle, emptyAgentStream } from "./agent-streams";++vi.mock("@reactive-resume/db/client", () => ({ db: { update: vi.fn() } }));+vi.mock("@reactive-resume/db/schema", () => ({+ agentThread: {+ id: "agent_threads.id",+ userId: "agent_threads.user_id",+ activeRunId: "agent_threads.active_run_id",+ activeStreamId: "agent_threads.active_stream_id",+ },+}));+vi.mock("drizzle-orm", () => ({+ and: (...conditions: unknown[]) => ({ type: "and", conditions }),+ eq: (left: unknown, right: unknown) => ({ type: "eq", left, right }),+ isNull: (value: unknown) => ({ type: "isNull", value }),+}));++async function readStream(stream: ReadableStream<string>) {+ const reader = stream.getReader();+ const chunks: string[] = [];++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ chunks.push(value);+ }++ return chunks;+}++function createRunStateDb(returningRows: unknown[] = []) {+ const returning = vi.fn(async () => returningRows);+ const where = vi.fn(() => ({ returning }));+ const set = vi.fn(() => ({ where }));+ const update = vi.fn(() => ({ set }));++ return {+ database: { update },+ returning,+ set,+ update,+ where,+ };+}++describe("agent run state", () => {+ it("claims an active run only when the thread still has no active run", async () => {+ const db = createRunStateDb([{ id: "thread-1" }]);++ await expect(+ claimActiveAgentRun(+ { threadId: "thread-1", userId: "user-1", runId: "run-1", streamId: "stream-1" },+ db.database as never,+ ),+ ).resolves.toBe(true);++ expect(db.update).toHaveBeenCalledWith(expect.objectContaining({ id: "agent_threads.id" }));+ expect(db.set).toHaveBeenCalledWith({+ activeRunId: "run-1",+ activeStreamId: "stream-1",+ activeRunStartedAt: expect.any(Date),+ });+ expect(db.where).toHaveBeenCalledWith({+ type: "and",+ conditions: [+ { type: "eq", left: "agent_threads.id", right: "thread-1" },+ { type: "eq", left: "agent_threads.user_id", right: "user-1" },+ { type: "isNull", value: "agent_threads.active_run_id" },+ ],+ });+ });++ it("reports a failed claim when the guarded update claims no rows", async () => {+ const db = createRunStateDb([]);++ await expect(+ claimActiveAgentRun(+ { threadId: "thread-1", userId: "user-1", runId: "run-1", streamId: "stream-1" },+ db.database as never,+ ),+ ).resolves.toBe(false);+ });++ it("clears active run state only for the matching run and stream", async () => {+ const db = createRunStateDb();++ await clearActiveAgentRunIfCurrent(+ { threadId: "thread-1", userId: "user-1", runId: "run-1", streamId: "stream-1" },+ db.database as never,+ );++ expect(db.set).toHaveBeenCalledWith({ activeRunId: null, activeStreamId: null, activeRunStartedAt: null });+ expect(db.where).toHaveBeenCalledWith({+ type: "and",+ conditions: [+ { type: "eq", left: "agent_threads.id", right: "thread-1" },+ { type: "eq", left: "agent_threads.user_id", right: "user-1" },+ { type: "eq", left: "agent_threads.active_run_id", right: "run-1" },+ { type: "eq", left: "agent_threads.active_stream_id", right: "stream-1" },+ ],+ });+ });++ it("clears active run state with a null stream guard when no stream id was recorded", async () => {+ const db = createRunStateDb();++ await clearActiveAgentRunIfCurrent(+ { threadId: "thread-1", userId: "user-1", runId: "run-1", streamId: null },+ db.database as never,+ );++ expect(db.where).toHaveBeenCalledWith({+ type: "and",+ conditions: [+ { type: "eq", left: "agent_threads.id", right: "thread-1" },+ { type: "eq", left: "agent_threads.user_id", right: "user-1" },+ { type: "eq", left: "agent_threads.active_run_id", right: "run-1" },+ { type: "isNull", value: "agent_threads.active_stream_id" },+ ],+ });+ });+});++describe("agent stream lifecycle", () => {+ it("returns a closed stream when no active stream id exists", async () => {+ const lifecycle = createAgentStreamLifecycle({+ getContext: () => {+ throw new Error("context should not be used");+ },+ });++ await expect(readStream(await lifecycle.resume(null))).resolves.toEqual([]);+ });++ it("creates a resumable stream from UI message SSE chunks", async () => {+ const createNewResumableStream = vi.fn(async (_streamId: string, makeStream: () => ReadableStream<string>) =>+ makeStream(),+ );+ const lifecycle = createAgentStreamLifecycle({+ getContext: () => ({+ createNewResumableStream,+ resumeExistingStream: vi.fn(),+ }),+ });++ const stream = await lifecycle.create(+ "stream-1",+ () =>+ new ReadableStream({+ start(controller) {+ controller.enqueue({ type: "text-start", id: "text-1" });+ controller.enqueue({ type: "text-delta", id: "text-1", delta: "Hello" });+ controller.close();+ },+ }),+ );++ await expect(readStream(stream)).resolves.toEqual([+ 'data: {"type":"text-start","id":"text-1"}\n\n',+ 'data: {"type":"text-delta","id":"text-1","delta":"Hello"}\n\n',+ "data: [DONE]\n\n",+ ]);+ expect(createNewResumableStream).toHaveBeenCalledWith("stream-1", expect.any(Function));+ });++ it("returns a closed stream when the active stream is missing or already done", async () => {+ const lifecycle = createAgentStreamLifecycle({+ getContext: () => ({+ createNewResumableStream: vi.fn(),+ resumeExistingStream: vi.fn(async () => null),+ }),+ });++ await expect(readStream(await lifecycle.resume("stream-1"))).resolves.toEqual([]);+ await expect(readStream(emptyAgentStream())).resolves.toEqual([]);+ });+});diff --git a/packages/api/src/services/agent-streams.ts b/packages/api/src/services/agent-streams.tsnew file mode 100644index 000000000..e420e61f4--- /dev/null+++ b/packages/api/src/services/agent-streams.ts@@ -0,0 +1,50 @@+import type { UIMessageChunk } from "ai";+import type { ResumableStreamContext } from "resumable-stream/ioredis";+import { JsonToSseTransformStream } from "ai";+import { createResumableStreamContext } from "resumable-stream/ioredis";++type AgentStreamContext = Pick<ResumableStreamContext, "createNewResumableStream" | "resumeExistingStream">;++type AgentStreamLifecycleOptions = {+ getContext: () => AgentStreamContext;+};++let streamContext: AgentStreamContext | null = null;++export function emptyAgentStream() {+ return new ReadableStream<string>({+ start(controller) {+ controller.close();+ },+ });+}++function getAgentStreamContext() {+ streamContext ??= createResumableStreamContext({+ keyPrefix: "reactive-resume:agent-stream",+ waitUntil: null,+ });++ return streamContext;+}++export function createAgentStreamLifecycle(options: AgentStreamLifecycleOptions) {+ return {+ async create(streamId: string, makeStream: () => ReadableStream<UIMessageChunk>) {+ const stream = await options+ .getContext()+ .createNewResumableStream(streamId, () => makeStream().pipeThrough(new JsonToSseTransformStream()));++ return stream ?? emptyAgentStream();+ },++ async resume(streamId: string | null | undefined) {+ if (!streamId) return emptyAgentStream();++ const stream = await options.getContext().resumeExistingStream(streamId);+ return stream ?? emptyAgentStream();+ },+ };+}++export const agentStreamLifecycle = createAgentStreamLifecycle({ getContext: getAgentStreamContext });diff --git a/packages/api/src/services/agent-tools.test.ts b/packages/api/src/services/agent-tools.test.tsnew file mode 100644index 000000000..ba8f18df9--- /dev/null+++ b/packages/api/src/services/agent-tools.test.ts@@ -0,0 +1,100 @@+import type { AIProvider } from "@reactive-resume/ai/types";+import { describe, expect, it } from "vitest";+import { buildAgentInstructions, buildAgentTools } from "./agent-tools";++const handlers = {+ fetchUrl: async (url: string) => ({ url, title: null, content: "Fetched content" }),+ readResume: async () => ({+ id: "resume-1",+ name: "Resume",+ updatedAt: "2026-05-13T00:00:00.000Z",+ data: {},+ }),+ readAttachment: async () => ({+ id: "attachment-1",+ filename: "job.md",+ mediaType: "text/markdown",+ size: 128,+ content: "Job description",+ }),+ applyResumePatch: async () => ({+ actionId: "action-1",+ resumeId: "resume-1",+ title: "Update resume",+ summary: null,+ operations: [],+ appliedUpdatedAt: "2026-05-13T00:00:00.000Z",+ }),+};++function buildTools(provider: AIProvider, options?: { model?: string; baseURL?: string }) {+ return buildAgentTools({+ provider: { provider, model: options?.model ?? "gpt-5-mini", apiKey: "test-key", baseURL: options?.baseURL ?? "" },+ handlers,+ });+}++describe("agent tools", () => {+ it("adds provider-native web search for direct OpenAI providers", () => {+ const tools = buildTools("openai");++ expect(tools).toHaveProperty("web_search");+ expect(tools).toHaveProperty("fetch_url");+ });++ it("adds provider-native web search for OpenAI providers using the explicit default base URL", () => {+ const tools = buildTools("openai", { baseURL: "https://api.openai.com/v1" });++ expect(tools).toHaveProperty("web_search");+ expect(tools).toHaveProperty("fetch_url");+ });++ it("does not add provider-native web search for OpenAI providers with a custom base URL", () => {+ const tools = buildTools("openai", { baseURL: "https://openai-compatible.example.com/v1" });++ expect(tools).not.toHaveProperty("web_search");+ expect(tools).toHaveProperty("fetch_url");+ });++ it.each([+ "https://api.openai.com/v1?proxy=1",+ "https://api.openai.com/v1#fragment",+ ])("does not add provider-native web search for OpenAI providers with non-exact base URL %s", (baseURL) => {+ const tools = buildTools("openai", { baseURL });++ expect(tools).not.toHaveProperty("web_search");+ expect(tools).toHaveProperty("fetch_url");+ });++ it("does not add provider-native web search for unsupported OpenAI models", () => {+ const tools = buildTools("openai", { model: "custom-model" });++ expect(tools).not.toHaveProperty("web_search");+ expect(tools).toHaveProperty("fetch_url");+ });++ it.each<AIProvider>([+ "anthropic",+ "gemini",+ "vercel-ai-gateway",+ "openrouter",+ "ollama",+ "openai-compatible",+ ])("does not add provider-native web search for %s", (provider) => {+ const tools = buildTools(provider);++ expect(tools).not.toHaveProperty("web_search");+ expect(tools).toHaveProperty("fetch_url");+ });++ it("keeps instructions explicit about native search versus exact URL fetching", () => {+ expect(buildAgentInstructions({ hasProviderNativeSearch: true })).toContain("Use web_search");+ expect(buildAgentInstructions({ hasProviderNativeSearch: true })).toContain("Use fetch_url");+ expect(buildAgentInstructions({ hasProviderNativeSearch: false })).not.toContain("Use web_search");+ expect(buildAgentInstructions({ hasProviderNativeSearch: false })).toContain("Use fetch_url");+ expect(buildAgentInstructions({ hasProviderNativeSearch: false })).toContain("Batch related JSON Patch operations");+ expect(buildAgentInstructions({ hasProviderNativeSearch: false })).toContain("/basics/name");+ expect(buildAgentInstructions({ hasProviderNativeSearch: false })).toContain("never /data/basics/name or /name");+ expect(buildAgentInstructions({ hasProviderNativeSearch: false })).toContain("clean Markdown");+ });+});diff --git a/packages/api/src/services/agent-tools.ts b/packages/api/src/services/agent-tools.tsnew file mode 100644index 000000000..48a183560--- /dev/null+++ b/packages/api/src/services/agent-tools.ts@@ -0,0 +1,101 @@+import type { AIProvider } from "@reactive-resume/ai/types";+import type { ToolSet } from "ai";+import { createOpenAI } from "@ai-sdk/openai";+import { tool } from "ai";+import z from "zod";+import { jsonPatchOperationSchema } from "@reactive-resume/utils/resume/patch";+import { supportsProviderNativeWebSearch } from "./ai-capabilities";++type AgentProviderConfig = {+ provider: AIProvider;+ model: string;+ apiKey: string;+ baseURL?: string | null;+};++export const applyResumePatchToolInputSchema = z.object({+ title: z.string().trim().min(1),+ summary: z.string().trim().optional(),+ operations: z.array(jsonPatchOperationSchema).min(1),+});++type ApplyResumePatchToolInput = z.infer<typeof applyResumePatchToolInputSchema>;++type BuildAgentToolsInput = {+ provider: AgentProviderConfig;+ handlers: {+ fetchUrl: (url: string) => Promise<unknown>;+ readResume: () => Promise<unknown>;+ readAttachment: (attachmentId: string) => Promise<unknown>;+ applyResumePatch: (input: ApplyResumePatchToolInput) => Promise<unknown>;+ };+};++export function buildProviderNativeAgentTools(provider: AgentProviderConfig): ToolSet {+ if (!supportsProviderNativeWebSearch(provider)) return {};++ const openai = createOpenAI({+ apiKey: provider.apiKey,+ ...(provider.baseURL ? { baseURL: provider.baseURL } : {}),+ });++ // Defensive runtime check: older `@ai-sdk/openai` versions and some OpenAI-compatible+ // gateways don't expose tools.webSearch. supportsProviderNativeWebSearch() filters out+ // non-OpenAI providers, but this guards against SDK-shape drift on the OpenAI path.+ if (typeof openai.tools.webSearch !== "function") return {};++ return {+ web_search: openai.tools.webSearch({+ searchContextSize: "low",+ }),+ };+}++export function buildAgentInstructions({ hasProviderNativeSearch }: { hasProviderNativeSearch: boolean }) {+ const baseInstructions =+ "You are an expert resume-writing agent inside Reactive Resume. Help the user improve the working resume for a target role. Read the resume before editing. Respond to the user in clean Markdown with concise paragraphs, bullets, and bold text when it improves scanability. Apply concise, valid JSON Patch operations when changes are useful. Patch paths are evaluated against the resume data object returned by read_resume, so use paths like /basics/name for the visible name and never /data/basics/name or /name. apply_resume_patch cannot rename the resume file/title metadata. Batch related JSON Patch operations into one apply_resume_patch call for each coherent edit instead of making repeated patch calls for the same request. Ask the user a question when a missing preference blocks a high-confidence edit.";++ if (!hasProviderNativeSearch) {+ return `${baseInstructions} Use fetch_url for user-provided public HTTPS URLs, exact pages, public job descriptions, or company pages.`;+ }++ return `${baseInstructions} Use web_search for open-ended or current web research, such as finding recent company, industry, or role context. Use fetch_url for user-provided public HTTPS URLs, exact pages, public job descriptions, or company pages.`;+}++export function buildAgentTools(input: BuildAgentToolsInput): ToolSet {+ return {+ ...buildProviderNativeAgentTools(input.provider),+ ask_user_question: tool({+ description:+ "Ask the user a short question when you need a preference, missing fact, or choice before continuing. Provide 2-4 recommended answer choices when possible.",+ inputSchema: z.object({+ question: z.string().trim().min(1),+ choices: z.array(z.string().trim().min(1)).min(1).max(4).optional(),+ recommendedChoice: z.string().trim().optional(),+ }),+ }),+ fetch_url: tool({+ description:+ "Fetch readable text from a public HTTPS URL, such as a job description. Private, local, and non-HTTPS URLs are blocked.",+ inputSchema: z.object({ url: z.string().url() }),+ execute: ({ url }) => input.handlers.fetchUrl(url),+ }),+ read_resume: tool({+ description: "Read the current working resume JSON and metadata.",+ inputSchema: z.object({}),+ execute: input.handlers.readResume,+ }),+ read_attachment: tool({+ description:+ "Read a message attachment by id. Text, Markdown, and JSON attachments include content; images and supported files may already be provided directly to the model.",+ inputSchema: z.object({ attachmentId: z.string().trim().min(1) }),+ execute: ({ attachmentId }) => input.handlers.readAttachment(attachmentId),+ }),+ apply_resume_patch: tool({+ description:+ "Apply one cohesive batch of JSON Patch operations to the working resume data immediately. Paths are rooted at resume data; use /basics/name for the visible resume name, not /data/basics/name or /name. This tool cannot rename the resume file/title metadata. The user can revert the action later.",+ inputSchema: applyResumePatchToolInputSchema,+ execute: (toolInput) => input.handlers.applyResumePatch(toolInput),+ }),+ };+}diff --git a/packages/api/src/services/agent-url.test.ts b/packages/api/src/services/agent-url.test.tsnew file mode 100644index 000000000..dc4d5c50f--- /dev/null+++ b/packages/api/src/services/agent-url.test.ts@@ -0,0 +1,725 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const envMock = vi.hoisted(() => ({+ CLOUDFLARE_ACCOUNT_ID: "",+ CLOUDFLARE_API_TOKEN: "",+ FLAG_ALLOW_UNSAFE_AI_BASE_URL: false,+}));++const dnsMock = vi.hoisted(() => ({+ lookup: vi.fn(),+}));++const undiciMock = vi.hoisted(() => {+ class MockAgent {+ static instances: MockAgent[] = [];++ close = vi.fn().mockResolvedValue(undefined);++ constructor(readonly options: Record<string, unknown>) {+ MockAgent.instances.push(this);+ }+ }++ return {+ Agent: MockAgent,+ fetch: vi.fn((input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init)),+ };+});++vi.mock("@reactive-resume/env/server", () => ({ env: envMock }));+vi.mock("node:dns/promises", () => dnsMock);+vi.mock("undici", () => ({+ Agent: undiciMock.Agent,+ fetch: undiciMock.fetch,+}));++const { fetchUrlForAgent } = await import("./agent-url");++function textResponse(body: string, options: { contentType: string; url?: string; status?: number }) {+ return new Response(body, {+ status: options.status ?? 200,+ headers: { "content-type": options.contentType },+ }) as Response & { url: string };+}++function responseWithUrl(body: string, options: { contentType: string; url?: string; status?: number }) {+ const response = textResponse(body, options);+ Object.defineProperty(response, "url", { value: options.url ?? "https://example.com/article" });+ return response;+}++describe("fetchUrlForAgent", () => {+ beforeEach(() => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "";+ envMock.CLOUDFLARE_API_TOKEN = "";+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = false;+ vi.restoreAllMocks();+ dnsMock.lookup.mockReset();+ dnsMock.lookup.mockResolvedValue([{ address: "93.184.216.34", family: 4 }]);+ undiciMock.Agent.instances.length = 0;+ undiciMock.fetch.mockReset();+ undiciMock.fetch.mockImplementation((input: RequestInfo | URL, init?: RequestInit) =>+ globalThis.fetch(input, init),+ );+ vi.useRealTimers();+ });++ it("extracts local HTML article text with Readability and strips navigation/script/style noise", async () => {+ const articleText =+ "This is the actual article body with enough useful detail for the AI agent to summarize accurately. ".repeat(4);+ const fetchMock = vi.fn().mockResolvedValue(+ responseWithUrl(+ `+ <!doctype html>+ <html>+ <head>+ <title>Head title should lose to article title</title>+ <style>.secret { color: red; }</style>+ </head>+ <body>+ <nav>Home Pricing Login</nav>+ <script>window.__tracking = "do not include";</script>+ <article>+ <h1>Readable Article Title</h1>+ <p>${articleText}</p>+ </article>+ <footer>Privacy Terms</footer>+ </body>+ </html>+ `,+ { contentType: "text/html; charset=utf-8", url: "https://example.com/final/article" },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const result = await fetchUrlForAgent("https://example.com/article");++ expect(result).toEqual({+ url: "https://example.com/article",+ title: "Head title should lose to article title",+ content: expect.stringContaining("actual article body"),+ source: "local",+ });+ expect(result.content).toContain("Readable Article Title");+ expect(result.content).not.toContain("Home Pricing Login");+ expect(result.content).not.toContain("window.__tracking");+ expect(result.content).not.toContain("color: red");+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledWith(+ "https://example.com/article",+ expect.objectContaining({+ redirect: "manual",+ signal: expect.any(AbortSignal),+ }),+ );+ });++ it("compacts local plain text and JSON responses", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(responseWithUrl("one\n\n two\tthree", { contentType: "text/plain" }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ name: "Ada", role: "Engineer" }, null, 2), {+ contentType: "application/json",+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/plain.txt")).resolves.toMatchObject({+ content: "one two three",+ source: "local",+ title: null,+ });+ await expect(fetchUrlForAgent("https://example.com/data.json")).resolves.toMatchObject({+ content: '{ "name": "Ada", "role": "Engineer" }',+ source: "local",+ title: null,+ });+ });++ it("falls back to Cloudflare when local content type is unsupported and credentials exist", async () => {+ vi.useFakeTimers();+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(responseWithUrl("binary", { contentType: "application/pdf" }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "crawl-job-id" }), {+ contentType: "application/json",+ url: "https://api.cloudflare.com/client/v4/accounts/account-id/browser-rendering/crawl",+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ result: { status: "running", records: [] } }), {+ contentType: "application/json",+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({+ result: { status: "completed", records: [{ markdown: "# Rendered\n\nCloudflare markdown" }] },+ }),+ { contentType: "application/json" },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const result = fetchUrlForAgent("https://example.com/file.pdf");+ await vi.advanceTimersByTimeAsync(0);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(500);++ await expect(result).resolves.toMatchObject({+ url: "https://example.com/file.pdf",+ content: "# Rendered Cloudflare markdown",+ source: "cloudflare",+ });+ expect(fetchMock).toHaveBeenNthCalledWith(+ 2,+ "https://api.cloudflare.com/client/v4/accounts/account-id/browser-rendering/crawl",+ expect.objectContaining({+ method: "POST",+ signal: expect.any(AbortSignal),+ body: JSON.stringify({+ url: "https://example.com/file.pdf",+ crawlPurposes: ["ai-input"],+ formats: ["markdown"],+ render: true,+ limit: 1,+ depth: 0,+ }),+ }),+ );+ expect(fetchMock).toHaveBeenNthCalledWith(+ 3,+ "https://api.cloudflare.com/client/v4/accounts/account-id/browser-rendering/crawl/crawl-job-id?limit=1",+ expect.objectContaining({+ signal: expect.any(AbortSignal),+ headers: expect.objectContaining({+ authorization: "Bearer api-token",+ }),+ }),+ );+ expect(fetchMock).toHaveBeenNthCalledWith(+ 4,+ "https://api.cloudflare.com/client/v4/accounts/account-id/browser-rendering/crawl/crawl-job-id?limit=1",+ expect.any(Object),+ );+ });++ it("submits the final validated redirect URL to Cloudflare when local extraction fails after redirects", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "/file.pdf" } }))+ .mockResolvedValueOnce(+ responseWithUrl("binary", { contentType: "application/pdf", url: "https://example.com/file.pdf" }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "redirect-job-id" }), {+ contentType: "application/json",+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({ result: { status: "completed", records: [{ markdown: "redirect fallback" }] } }),+ {+ contentType: "application/json",+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/start")).resolves.toMatchObject({+ url: "https://example.com/file.pdf",+ content: "redirect fallback",+ source: "cloudflare",+ });+ expect(fetchMock).toHaveBeenNthCalledWith(+ 3,+ "https://api.cloudflare.com/client/v4/accounts/account-id/browser-rendering/crawl",+ expect.objectContaining({+ body: expect.stringContaining('"url":"https://example.com/file.pdf"'),+ }),+ );+ });++ it("blocks DNS resolutions to private addresses before local fetch or Cloudflare fallback", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ dnsMock.lookup.mockResolvedValueOnce([{ address: "10.0.0.8", family: 4 }]);+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://public.example.com/article")).rejects.toThrow("URL_NOT_FETCHABLE");+ expect(dnsMock.lookup).toHaveBeenCalledWith("public.example.com", { all: true });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("blocks DNS resolutions to special-use addresses before local fetch or Cloudflare fallback", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ for (const address of [+ "100.64.0.1",+ "192.0.2.1",+ "192.88.99.1",+ "198.18.0.1",+ "198.51.100.1",+ "203.0.113.1",+ "224.0.0.1",+ "255.255.255.255",+ "::",+ "::ffff:8.8.8.8",+ "::ffff:0808:0808",+ "64:ff9b::1",+ "100::1",+ "100:0:0:1::1",+ "2001::1",+ "2001:2::1",+ "2001:10::1",+ "2001:100::1",+ "ff02::1",+ "2001:db8::1",+ "3fff::1",+ "5f00::1",+ ]) {+ dnsMock.lookup.mockResolvedValueOnce([{ address, family: address.includes(":") ? 6 : 4 }]);+ await expect(+ fetchUrlForAgent(`https://special-${address.replaceAll(":", "-")}.example.com/article`),+ ).rejects.toThrow("URL_NOT_FETCHABLE");+ }++ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("blocks IPv4-mapped IPv6 DNS resolutions to private addresses", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ for (const address of ["::ffff:10.0.0.1", "::ffff:127.0.0.1", "::ffff:169.254.169.254"]) {+ dnsMock.lookup.mockResolvedValueOnce([{ address, family: 6 }]);+ await expect(fetchUrlForAgent(`https://${address.replaceAll(":", "-")}.example.com/article`)).rejects.toThrow(+ "URL_NOT_FETCHABLE",+ );+ }++ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("uses a pinned dispatcher lookup for the validated DNS address", async () => {+ dnsMock.lookup.mockResolvedValueOnce([{ address: "93.184.216.34", family: 4 }]);+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(responseWithUrl("Pinned DNS response", { contentType: "text/plain" }));+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://public.example.com/article")).resolves.toMatchObject({+ content: "Pinned DNS response",+ source: "local",+ });++ const [agent] = undiciMock.Agent.instances;+ const connect = agent?.options.connect as+ | {+ autoSelectFamily?: boolean;+ lookup?: (+ hostname: string,+ options: unknown,+ callback: (+ error: Error | null,+ address: string | Array<{ address: string; family: number }>,+ family?: number,+ ) => void,+ ) => void;+ }+ | undefined;++ expect(connect?.autoSelectFamily).toBe(false);+ await expect(+ new Promise<{ address: string; family: number }>((resolve, reject) => {+ connect?.lookup?.("public.example.com", {}, (error, address, family) => {+ if (error) reject(error);+ else if (typeof address === "string" && family) resolve({ address, family });+ else reject(new Error("Expected single address lookup result"));+ });+ }),+ ).resolves.toEqual({ address: "93.184.216.34", family: 4 });+ await expect(+ new Promise<Array<{ address: string; family: number }>>((resolve, reject) => {+ connect?.lookup?.("public.example.com", { all: true }, (error, addresses) => {+ if (error) reject(error);+ else if (Array.isArray(addresses)) resolve(addresses);+ else reject(new Error("Expected all-address lookup result"));+ });+ }),+ ).resolves.toEqual([{ address: "93.184.216.34", family: 4 }]);+ expect(dnsMock.lookup).toHaveBeenCalledTimes(1);+ });++ it("times out DNS validation before local fetch or Cloudflare fallback", async () => {+ vi.useFakeTimers();+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ dnsMock.lookup.mockReturnValueOnce(new Promise(() => undefined));+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ const result = fetchUrlForAgent("https://slow-dns.example.com/article");+ const rejection = expect(result).rejects.toThrow("URL_NOT_FETCHABLE");+ await vi.advanceTimersByTimeAsync(5_000);++ await rejection;+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("revalidates DNS for redirect targets before following them", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ dnsMock.lookup+ .mockResolvedValueOnce([{ address: "93.184.216.34", family: 4 }])+ .mockResolvedValueOnce([{ address: "fd00::1", family: 6 }]);+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(null, { status: 302, headers: { location: "https://cdn.example.com/final" } }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/start")).rejects.toThrow("URL_NOT_FETCHABLE");+ expect(dnsMock.lookup).toHaveBeenNthCalledWith(1, "example.com", { all: true });+ expect(dnsMock.lookup).toHaveBeenNthCalledWith(2, "cdn.example.com", { all: true });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("uses the latest validated redirect URL for Cloudflare fallback after network errors", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "/final" } }))+ .mockRejectedValueOnce(new Error("connect timeout"))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "network-job" }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({ result: { status: "completed", records: [{ markdown: "network fallback" }] } }),+ {+ contentType: "application/json",+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/start")).resolves.toMatchObject({+ url: "https://example.com/final",+ content: "network fallback",+ source: "cloudflare",+ });+ expect(fetchMock).toHaveBeenNthCalledWith(+ 3,+ "https://api.cloudflare.com/client/v4/accounts/account-id/browser-rendering/crawl",+ expect.objectContaining({+ body: expect.stringContaining('"url":"https://example.com/final"'),+ }),+ );+ });++ it("cancels redirect, non-OK, unsupported, and oversized response bodies", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const redirectCancel = vi.fn();+ const nonOkCancel = vi.fn();+ const unsupportedCancel = vi.fn();+ const oversizedCancel = vi.fn();+ const oversizedBody = new ReadableStream({+ start(controller) {+ controller.enqueue(new Uint8Array(2 * 1024 * 1024 + 1));+ },+ cancel: oversizedCancel,+ });+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(new ReadableStream({ cancel: redirectCancel }), {+ status: 302,+ headers: { location: "https://example.com/redirected" },+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl("ok ".repeat(80), { contentType: "text/plain", url: "https://example.com/redirected" }),+ )+ .mockResolvedValueOnce(new Response(new ReadableStream({ cancel: nonOkCancel }), { status: 500 }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "non-ok-job" }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({ result: { status: "completed", records: [{ markdown: "non-ok fallback" }] } }),+ { contentType: "application/json" },+ ),+ )+ .mockResolvedValueOnce(+ new Response(new ReadableStream({ cancel: unsupportedCancel }), {+ status: 200,+ headers: { "content-type": "application/pdf" },+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "unsupported-job" }), {+ contentType: "application/json",+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({ result: { status: "completed", records: [{ markdown: "unsupported fallback" }] } }),+ { contentType: "application/json" },+ ),+ )+ .mockResolvedValueOnce(new Response(oversizedBody, { status: 200, headers: { "content-type": "text/plain" } }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "oversized-job" }), {+ contentType: "application/json",+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({ result: { status: "completed", records: [{ markdown: "oversized fallback" }] } }),+ { contentType: "application/json" },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/redirect")).resolves.toMatchObject({ source: "local" });+ await expect(fetchUrlForAgent("https://example.com/non-ok")).resolves.toMatchObject({ content: "non-ok fallback" });+ await expect(fetchUrlForAgent("https://example.com/unsupported")).resolves.toMatchObject({+ content: "unsupported fallback",+ });+ await expect(fetchUrlForAgent("https://example.com/oversized")).resolves.toMatchObject({+ content: "oversized fallback",+ });++ expect(redirectCancel).toHaveBeenCalled();+ expect(nonOkCancel).toHaveBeenCalled();+ expect(unsupportedCancel).toHaveBeenCalled();+ expect(oversizedCancel).toHaveBeenCalled();+ });++ it("cancels Cloudflare non-OK crawl creation and poll response bodies", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const createCancel = vi.fn();+ const pollCancel = vi.fn();+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(responseWithUrl("binary", { contentType: "application/pdf" }))+ .mockResolvedValueOnce(+ new Response(new ReadableStream({ cancel: createCancel }), {+ status: 500,+ headers: { "content-type": "application/json" },+ }),+ )+ .mockResolvedValueOnce(responseWithUrl("binary", { contentType: "application/pdf" }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "poll-job" }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(+ new Response(new ReadableStream({ cancel: pollCancel }), {+ status: 503,+ headers: { "content-type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/create-fails")).rejects.toThrow("URL_FETCH_FAILED");+ await expect(fetchUrlForAgent("https://example.com/poll-fails")).rejects.toThrow("URL_FETCH_FAILED");++ expect(createCancel).toHaveBeenCalled();+ expect(pollCancel).toHaveBeenCalled();+ });++ it("falls back to Cloudflare when local Readability content is too small and credentials exist", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ responseWithUrl("<html><head><title>Thin</title></head><body><article><p>Tiny.</p></article></body></html>", {+ contentType: "text/html",+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "thin-job-id" }), {+ contentType: "application/json",+ }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({+ result: { status: "completed", records: [{ markdown: "rendered fallback for thin page" }] },+ }),+ {+ contentType: "application/json",+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/thin")).resolves.toMatchObject({+ content: "rendered fallback for thin page",+ source: "cloudflare",+ });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });++ it("parses supported Cloudflare markdown payload shapes", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(responseWithUrl("nope", { contentType: "application/octet-stream" }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "records-job" }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ result: { status: "completed", records: [{ markdown: "records shape" }] } }), {+ contentType: "application/json",+ }),+ )+ .mockResolvedValueOnce(responseWithUrl("nope", { contentType: "application/octet-stream" }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "markdown-job" }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ result: { markdown: "first shape" } }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(responseWithUrl("nope", { contentType: "application/octet-stream" }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "array-job" }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ result: [{ markdown: "array shape" }] }), { contentType: "application/json" }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/records")).resolves.toMatchObject({ content: "records shape" });+ await expect(fetchUrlForAgent("https://example.com/markdown")).resolves.toMatchObject({ content: "first shape" });+ await expect(fetchUrlForAgent("https://example.com/array")).resolves.toMatchObject({ content: "array shape" });+ });++ it("blocks private and non-HTTPS URLs before Cloudflare fallback", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = true;+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("http://example.com/article")).rejects.toThrow("URL_NOT_FETCHABLE");+ await expect(fetchUrlForAgent("https://localhost/internal")).rejects.toThrow("URL_NOT_FETCHABLE");+ await expect(fetchUrlForAgent("https://10.0.0.5/internal")).rejects.toThrow("URL_NOT_FETCHABLE");+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("blocks redirects to private and non-HTTPS URLs before following them or falling back to Cloudflare", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "https://localhost/internal" } }))+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "http://example.com/plain" } }));+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/private-redirect")).rejects.toThrow("URL_NOT_FETCHABLE");+ await expect(fetchUrlForAgent("https://example.com/http-redirect")).rejects.toThrow("URL_NOT_FETCHABLE");+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock).toHaveBeenNthCalledWith(+ 1,+ "https://example.com/private-redirect",+ expect.objectContaining({ redirect: "manual" }),+ );+ expect(fetchMock).toHaveBeenNthCalledWith(+ 2,+ "https://example.com/http-redirect",+ expect.objectContaining({ redirect: "manual" }),+ );+ });++ it("blocks redirects without Location before falling back to Cloudflare", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const fetchMock = vi.fn().mockResolvedValueOnce(new Response(null, { status: 302 }));+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/missing-location")).rejects.toThrow("URL_NOT_FETCHABLE");+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledWith(+ "https://example.com/missing-location",+ expect.objectContaining({ redirect: "manual" }),+ );+ });++ it("resolves relative HTTPS redirects and uses the final URL for local Readability extraction", async () => {+ const articleText =+ "This redirected article has enough readable content for extraction after following a relative Location header. ".repeat(+ 4,+ );+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "/final/article" } }))+ .mockResolvedValueOnce(+ responseWithUrl(+ `<html><head><title>Redirected</title></head><body><article><h1>Redirected</h1><p>${articleText}</p></article></body></html>`,+ { contentType: "text/html", url: "https://example.com/final/article" },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/start")).resolves.toMatchObject({+ url: "https://example.com/final/article",+ content: expect.stringContaining("redirected article"),+ source: "local",+ });+ expect(fetchMock).toHaveBeenNthCalledWith(+ 2,+ "https://example.com/final/article",+ expect.objectContaining({ redirect: "manual" }),+ );+ });++ it("falls back to Cloudflare when the local response exceeds the byte limit", async () => {+ envMock.CLOUDFLARE_ACCOUNT_ID = "account-id";+ envMock.CLOUDFLARE_API_TOKEN = "api-token";+ const oversized = "a".repeat(2 * 1024 * 1024 + 1);+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(responseWithUrl(oversized, { contentType: "text/plain" }))+ .mockResolvedValueOnce(+ responseWithUrl(JSON.stringify({ success: true, result: "huge-job-id" }), { contentType: "application/json" }),+ )+ .mockResolvedValueOnce(+ responseWithUrl(+ JSON.stringify({+ result: { status: "completed", records: [{ markdown: "fallback after oversized response" }] },+ }),+ {+ contentType: "application/json",+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchUrlForAgent("https://example.com/huge.txt")).resolves.toMatchObject({+ content: "fallback after oversized response",+ source: "cloudflare",+ });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });+});diff --git a/packages/api/src/services/agent-url.ts b/packages/api/src/services/agent-url.tsnew file mode 100644index 000000000..059a9744a--- /dev/null+++ b/packages/api/src/services/agent-url.ts@@ -0,0 +1,361 @@+import { lookup } from "node:dns/promises";+import { Readability } from "@mozilla/readability";+import { JSDOM } from "jsdom";+import { Agent, fetch as undiciFetch } from "undici";+import { env } from "@reactive-resume/env/server";+import { isPrivateOrLoopbackHost } from "@reactive-resume/utils/url-security.node";+import { assertFetchablePublicHttpsUrl } from "./ai-url-policy";++const MAX_FETCHED_TEXT_CHARS = 40_000;+const MAX_LOCAL_FETCH_BYTES = 2 * 1024 * 1024;+const MAX_LOCAL_REDIRECTS = 5;+const MAX_CLOUDFLARE_CRAWL_POLLS = 6;+const CLOUDFLARE_CRAWL_POLL_DELAY_MS = 500;+const LOCAL_FETCH_TIMEOUT_MS = 10_000;+const DNS_LOOKUP_TIMEOUT_MS = 5_000;+const CLOUDFLARE_CRAWL_CREATE_TIMEOUT_MS = 15_000;+const CLOUDFLARE_CRAWL_POLL_TIMEOUT_MS = 10_000;+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);++type FetchedUrlResult = {+ url: string;+ title: string | null;+ content: string;+ source: "local" | "cloudflare";+};++type FetchResponse = Awaited<ReturnType<typeof undiciFetch>>;+type ResolvedAddress = { address: string; family: number };++class LocalFetchError extends Error {+ constructor(+ message: string,+ readonly fallbackUrl: string,+ ) {+ super(message);+ }+}++function compactText(value: string) {+ return value.replace(/\s+/g, " ").trim().slice(0, MAX_FETCHED_TEXT_CHARS);+}++function extractReadableHtml(html: string, url: string) {+ const dom = new JSDOM(html, { url });++ try {+ const article = new Readability(dom.window.document).parse();+ const content = compactText(article?.textContent ?? "");++ if (content.length < 160) throw new Error("URL_READABILITY_FAILED");++ return {+ title: article?.title ? compactText(article.title) : null,+ content,+ };+ } finally {+ dom.window.close();+ }+}++async function readLimitedText(response: FetchResponse) {+ const reader = response.body?.getReader();+ if (!reader) return response.text();++ const chunks: Uint8Array[] = [];+ let size = 0;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ if (!value) continue;++ size += value.byteLength;+ if (size > MAX_LOCAL_FETCH_BYTES) {+ await reader.cancel("FETCHED_URL_TOO_LARGE");+ throw new Error("FETCHED_URL_TOO_LARGE");+ }+ chunks.push(value);+ }++ return new TextDecoder().decode(Buffer.concat(chunks));+}++function timeoutSignal(ms: number) {+ if (typeof AbortSignal.timeout === "function") return AbortSignal.timeout(ms);++ const controller = new AbortController();+ setTimeout(() => controller.abort(), ms);+ return controller.signal;+}++async function withTimeout<T>(promise: Promise<T>, ms: number, errorCode: string) {+ let timeout: NodeJS.Timeout | undefined;++ try {+ return await Promise.race([+ promise,+ new Promise<never>((_, reject) => {+ timeout = setTimeout(() => reject(new Error(errorCode)), ms);+ }),+ ]);+ } finally {+ if (timeout) clearTimeout(timeout);+ }+}++async function cancelResponseBody(response: FetchResponse) {+ try {+ await response.body?.cancel();+ } catch {+ // Best effort cleanup only; the original fetch/extraction error should stay authoritative.+ }+}++function isRedirectResponse(response: { status: number }) {+ return REDIRECT_STATUSES.has(response.status);+}++function resolveRedirectUrl(location: string, currentUrl: string) {+ try {+ return new URL(location, currentUrl).toString();+ } catch {+ throw new Error("URL_NOT_FETCHABLE");+ }+}++async function assertResolvesToPublicAddress(url: string) {+ const { hostname } = new URL(url);++ let addresses: ResolvedAddress[];+ try {+ addresses = await withTimeout(lookup(hostname, { all: true }), DNS_LOOKUP_TIMEOUT_MS, "URL_NOT_FETCHABLE");+ } catch {+ throw new Error("URL_NOT_FETCHABLE");+ }++ if (addresses.length === 0) throw new Error("URL_NOT_FETCHABLE");+ if (addresses.some(({ address }) => isPrivateOrLoopbackHost(address))) throw new Error("URL_NOT_FETCHABLE");++ const [address] = addresses;+ if (!address) throw new Error("URL_NOT_FETCHABLE");++ return address;+}++function createPinnedDispatcher(url: string, address: string, family: number) {+ const { hostname } = new URL(url);++ return new Agent({+ connect: {+ autoSelectFamily: false,+ servername: hostname,+ lookup: (_hostname, options, callback) => {+ if (typeof options === "object" && options && "all" in options && options.all) {+ callback(null, [{ address, family }]);+ return;+ }++ callback(null, address, family);+ },+ },+ });+}++async function fetchLocalResponse(inputUrl: string) {+ let url = assertFetchablePublicHttpsUrl(inputUrl);++ for (let redirectCount = 0; redirectCount <= MAX_LOCAL_REDIRECTS; redirectCount++) {+ const address = await assertResolvesToPublicAddress(url);+ const dispatcher = createPinnedDispatcher(url, address.address, address.family);+ let response: FetchResponse;++ try {+ response = await undiciFetch(url, {+ dispatcher,+ redirect: "manual",+ signal: timeoutSignal(LOCAL_FETCH_TIMEOUT_MS),+ headers: {+ accept: "text/html, text/plain;q=0.9, application/json;q=0.8",+ "user-agent": "ReactiveResumeAI/1.0",+ },+ });+ } catch (error) {+ await dispatcher.close();+ if (error instanceof Error && error.message === "URL_NOT_FETCHABLE") throw error;+ throw new LocalFetchError("URL_FETCH_FAILED", url);+ }++ if (!isRedirectResponse(response)) return { response, url, dispatcher };++ const location = response.headers.get("location");+ await cancelResponseBody(response);+ await dispatcher.close();+ if (!location) throw new Error("URL_NOT_FETCHABLE");+ if (redirectCount === MAX_LOCAL_REDIRECTS) throw new Error("URL_NOT_FETCHABLE");++ url = assertFetchablePublicHttpsUrl(resolveRedirectUrl(location, url));+ }++ throw new Error("URL_NOT_FETCHABLE");+}++async function fetchLocally(url: string): Promise<FetchedUrlResult> {+ const { response, url: responseUrl, dispatcher } = await fetchLocalResponse(url);++ try {+ if (!response.ok) {+ await cancelResponseBody(response);+ throw new LocalFetchError("URL_FETCH_FAILED", responseUrl);+ }++ const contentType = response.headers.get("content-type") ?? "";+ if (+ !contentType.includes("text/html") &&+ !contentType.includes("text/plain") &&+ !contentType.includes("application/json")+ ) {+ await cancelResponseBody(response);+ throw new LocalFetchError("URL_FETCH_UNSUPPORTED_CONTENT_TYPE", responseUrl);+ }++ const raw = await readLimitedText(response);+ const isHtml = contentType.includes("text/html");+ const extracted = isHtml ? extractReadableHtml(raw, responseUrl) : { title: null, content: compactText(raw) };++ return {+ url: responseUrl,+ title: extracted.title,+ content: extracted.content,+ source: "local",+ };+ } catch (error) {+ if (error instanceof LocalFetchError) throw error;+ if (error instanceof Error) throw new LocalFetchError(error.message, responseUrl);+ throw new LocalFetchError("URL_READABILITY_FAILED", responseUrl);+ } finally {+ await dispatcher.close();+ }+}++function extractCloudflareMarkdown(payload: unknown): string | null {+ if (!payload || typeof payload !== "object") return null;+ const record = payload as Record<string, unknown>;+ const result = record.result;++ if (result && typeof result === "object") {+ const resultRecord = result as Record<string, unknown>;+ if (Array.isArray(resultRecord.records)) {+ const [first] = resultRecord.records;+ const markdown = first && typeof first === "object" ? (first as Record<string, unknown>).markdown : null;+ if (typeof markdown === "string") return markdown;+ }+ if (typeof resultRecord.markdown === "string") return resultRecord.markdown;+ if (Array.isArray(resultRecord.pages)) {+ const [first] = resultRecord.pages;+ const markdown = first && typeof first === "object" ? (first as Record<string, unknown>).markdown : null;+ if (typeof markdown === "string") return markdown;+ }+ }+ if (Array.isArray(result)) {+ const [first] = result;+ const markdown = first && typeof first === "object" ? (first as Record<string, unknown>).markdown : null;+ if (typeof markdown === "string") return markdown;+ }++ return null;+}++function extractCloudflareJobId(payload: unknown): string | null {+ if (!payload || typeof payload !== "object") return null;+ const result = (payload as Record<string, unknown>).result;++ return typeof result === "string" && result.trim() ? result : null;+}++function extractCloudflareCrawlStatus(payload: unknown): string | null {+ if (!payload || typeof payload !== "object") return null;+ const result = (payload as Record<string, unknown>).result;+ if (!result || typeof result !== "object") return null;+ const status = (result as Record<string, unknown>).status;++ return typeof status === "string" ? status.toLowerCase() : null;+}++function wait(ms: number) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function fetchWithCloudflare(url: string): Promise<FetchedUrlResult> {+ if (!env.CLOUDFLARE_ACCOUNT_ID || !env.CLOUDFLARE_API_TOKEN) throw new Error("URL_READABILITY_FAILED");++ const crawlUrl = `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/browser-rendering/crawl`;+ const headers = {+ authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}`,+ };++ const response = await undiciFetch(crawlUrl, {+ method: "POST",+ signal: timeoutSignal(CLOUDFLARE_CRAWL_CREATE_TIMEOUT_MS),+ headers: {+ ...headers,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ url,+ crawlPurposes: ["ai-input"],+ formats: ["markdown"],+ render: true,+ limit: 1,+ depth: 0,+ }),+ });++ if (!response.ok) {+ await cancelResponseBody(response);+ throw new Error("URL_FETCH_FAILED");+ }++ const jobId = extractCloudflareJobId(await response.json());+ if (!jobId) throw new Error("URL_READABILITY_FAILED");++ let markdown: string | null = null;+ for (let attempt = 0; attempt < MAX_CLOUDFLARE_CRAWL_POLLS; attempt++) {+ const resultResponse = await undiciFetch(`${crawlUrl}/${encodeURIComponent(jobId)}?limit=1`, {+ headers,+ signal: timeoutSignal(CLOUDFLARE_CRAWL_POLL_TIMEOUT_MS),+ });+ if (!resultResponse.ok) {+ await cancelResponseBody(resultResponse);+ throw new Error("URL_FETCH_FAILED");+ }++ const payload = await resultResponse.json();+ markdown = extractCloudflareMarkdown(payload);+ if (markdown) break;++ const status = extractCloudflareCrawlStatus(payload);+ if (status !== "running" && status !== "queued") break;+ if (attempt < MAX_CLOUDFLARE_CRAWL_POLLS - 1) await wait(CLOUDFLARE_CRAWL_POLL_DELAY_MS);+ }++ if (!markdown) throw new Error("URL_READABILITY_FAILED");++ return {+ url,+ title: null,+ content: compactText(markdown),+ source: "cloudflare",+ };+}++export async function fetchUrlForAgent(input: string): Promise<FetchedUrlResult> {+ const url = assertFetchablePublicHttpsUrl(input);++ try {+ return await fetchLocally(url);+ } catch (error) {+ if (error instanceof Error && error.message === "URL_NOT_FETCHABLE") throw error;+ return fetchWithCloudflare(error instanceof LocalFetchError ? error.fallbackUrl : url);+ }+}diff --git a/packages/api/src/services/agent.test.ts b/packages/api/src/services/agent.test.tsnew file mode 100644index 000000000..d6b7032de--- /dev/null+++ b/packages/api/src/services/agent.test.ts@@ -0,0 +1,1202 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ORPCError } from "@orpc/client";++const dbMock = {+ select: vi.fn(),+ insert: vi.fn(),+ update: vi.fn(),+ delete: vi.fn(),+ transaction: vi.fn(async <T>(callback: (tx: typeof dbMock) => Promise<T>) => callback(dbMock)),+};++const clearActiveAgentRunIfCurrentMock = vi.fn();+const claimActiveAgentRunMock = vi.fn();+const storageServiceMock = {+ delete: vi.fn(),+ write: vi.fn(),+ read: vi.fn(),+};++const resumeServiceMock = {+ getById: vi.fn(),+ patch: vi.fn(),+ patchInTransaction: vi.fn(),+ notifyResumePatched: vi.fn(),+};++const aiProvidersServiceMock = {+ getRunnableById: vi.fn(),+ getDefaultRunnable: vi.fn(),+ markUsed: vi.fn(),+};++vi.mock("@reactive-resume/db/client", () => ({ db: dbMock }));+vi.mock("@reactive-resume/db/schema", () => ({+ agentThread: {+ id: "agent_threads.id",+ userId: "agent_threads.user_id",+ deletedAt: "agent_threads.deleted_at",+ archivedAt: "agent_threads.archived_at",+ status: "agent_threads.status",+ activeRunId: "agent_threads.active_run_id",+ activeStreamId: "agent_threads.active_stream_id",+ activeRunStartedAt: "agent_threads.active_run_started_at",+ aiProviderId: "agent_threads.ai_provider_id",+ workingResumeId: "agent_threads.working_resume_id",+ sourceResumeId: "agent_threads.source_resume_id",+ title: "agent_threads.title",+ lastMessageAt: "agent_threads.last_message_at",+ createdAt: "agent_threads.created_at",+ updatedAt: "agent_threads.updated_at",+ },+ agentMessage: {+ id: "agent_messages.id",+ threadId: "agent_messages.thread_id",+ userId: "agent_messages.user_id",+ role: "agent_messages.role",+ status: "agent_messages.status",+ sequence: "agent_messages.sequence",+ uiMessage: "agent_messages.ui_message",+ },+ agentAction: {+ id: "agent_actions.id",+ threadId: "agent_actions.thread_id",+ userId: "agent_actions.user_id",+ createdAt: "agent_actions.created_at",+ },+ agentAttachment: {+ id: "agent_attachments.id",+ threadId: "agent_attachments.thread_id",+ userId: "agent_attachments.user_id",+ messageId: "agent_attachments.message_id",+ storageKey: "agent_attachments.storage_key",+ filename: "agent_attachments.filename",+ mediaType: "agent_attachments.media_type",+ size: "agent_attachments.size",+ createdAt: "agent_attachments.created_at",+ },+ resume: { name: "resume.name", id: "resume.id", userId: "resume.user_id", slug: "resume.slug" },+ aiProvider: { label: "ai_provider.label", id: "ai_provider.id" },+}));++vi.mock("drizzle-orm", () => ({+ and: (...conditions: unknown[]) => ({ type: "and", conditions }),+ asc: (value: unknown) => ({ type: "asc", value }),+ count: () => ({ type: "count" }),+ desc: (value: unknown) => ({ type: "desc", value }),+ eq: (left: unknown, right: unknown) => ({ type: "eq", left, right }),+ inArray: (left: unknown, values: unknown[]) => ({ type: "inArray", left, values }),+ isNull: (value: unknown) => ({ type: "isNull", value }),+ max: (value: unknown) => ({ type: "max", value }),+ sql: () => ({ type: "sql" }),+}));++vi.mock("ai", () => ({+ convertToModelMessages: vi.fn(),+ stepCountIs: vi.fn(),+ ToolLoopAgent: vi.fn(),+}));++vi.mock("./ai", () => ({ getAgentModel: vi.fn() }));+vi.mock("./ai-credentials", () => ({ assertAgentEnvironment: vi.fn() }));+vi.mock("./ai-providers", () => ({ aiProvidersService: aiProvidersServiceMock }));+vi.mock("./resume", () => ({ resumeService: resumeServiceMock }));+vi.mock("./storage", () => ({ getStorageService: vi.fn(() => storageServiceMock), inferContentType: vi.fn() }));+vi.mock("./agent-patches", () => ({ createInverseResumePatches: vi.fn() }));+vi.mock("./agent-resume", () => ({+ buildAgentDraftResumeName: vi.fn(),+ buildUniqueAgentDraftSlug: vi.fn(),+}));+vi.mock("./agent-run-state", () => ({+ claimActiveAgentRun: claimActiveAgentRunMock,+ clearActiveAgentRunIfCurrent: clearActiveAgentRunIfCurrentMock,+}));+vi.mock("./agent-streams", () => ({+ agentStreamLifecycle: { create: vi.fn(), resume: vi.fn() },+}));+vi.mock("./agent-tools", () => ({+ buildAgentInstructions: vi.fn(),+ buildAgentTools: vi.fn(() => ({})),+}));+vi.mock("./agent-url", () => ({ fetchUrlForAgent: vi.fn() }));+vi.mock("@reactive-resume/schema/resume/default", () => ({ defaultResumeData: {} }));+vi.mock("@reactive-resume/utils/string", () => ({ generateId: () => "test-id" }));+vi.mock("@orpc/server", () => ({ streamToEventIterator: vi.fn() }));++beforeEach(() => {+ for (const mock of Object.values(dbMock)) mock.mockReset();+ dbMock.transaction.mockImplementation(async <T>(callback: (tx: typeof dbMock) => Promise<T>) => callback(dbMock));+ clearActiveAgentRunIfCurrentMock.mockReset();+ claimActiveAgentRunMock.mockReset();+ for (const mock of Object.values(storageServiceMock)) mock.mockReset();+ for (const mock of Object.values(resumeServiceMock)) mock.mockReset();+ for (const mock of Object.values(aiProvidersServiceMock)) mock.mockReset();+});++function buildArchivedThread(overrides: Record<string, unknown> = {}) {+ return {+ id: "thread-1",+ userId: "user-1",+ aiProviderId: "provider-1",+ workingResumeId: "resume-1",+ sourceResumeId: null,+ title: "Archived thread",+ status: "archived",+ activeRunId: null,+ activeStreamId: null,+ activeRunStartedAt: null,+ lastMessageAt: new Date("2026-05-01T00:00:00.000Z"),+ archivedAt: new Date("2026-05-02T00:00:00.000Z"),+ deletedAt: null,+ createdAt: new Date("2026-04-01T00:00:00.000Z"),+ updatedAt: new Date("2026-05-02T00:00:00.000Z"),+ ...overrides,+ };+}++function buildActiveThread(overrides: Record<string, unknown> = {}) {+ return buildArchivedThread({+ status: "active",+ title: "Active thread",+ activeRunId: null,+ activeStreamId: null,+ archivedAt: null,+ ...overrides,+ });+}++function buildAttachment(overrides: Record<string, unknown> = {}) {+ return {+ id: "attachment-1",+ userId: "user-1",+ threadId: "thread-1",+ messageId: null,+ storageKey: "uploads/user-1/agent/thread-1/attachment-1-note.txt",+ filename: "note.txt",+ mediaType: "text/plain",+ size: 5,+ createdAt: new Date("2026-05-01T00:00:00.000Z"),+ ...overrides,+ };+}++function selectLimitResult(rows: unknown[]) {+ const limit = vi.fn(async () => rows);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+}++function selectWhereResult(rows: unknown[]) {+ const where = vi.fn(async () => rows);+ const from = vi.fn(() => ({ where }));+ return { from };+}++function selectOrderByResult(rows: unknown[]) {+ const orderBy = vi.fn(async () => rows);+ const where = vi.fn(() => ({ orderBy }));+ const from = vi.fn(() => ({ where }));+ return { from };+}++describe("agentService.threads.get", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns isReadOnly: true when the thread is archived, even if the resume and provider are present", async () => {+ const archivedThread = buildArchivedThread();++ // First select call is `getThread` (limit), then three select calls for messages/actions/attachments (orderBy).+ const threadSelect = () => {+ const limit = vi.fn(async () => [archivedThread]);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+ };+ const emptyListSelect = () => {+ const orderBy = vi.fn(async () => []);+ const where = vi.fn(() => ({ orderBy }));+ const from = vi.fn(() => ({ where }));+ return { from };+ };++ dbMock.select+ .mockImplementationOnce(threadSelect)+ .mockImplementationOnce(emptyListSelect)+ .mockImplementationOnce(emptyListSelect)+ .mockImplementationOnce(emptyListSelect);++ resumeServiceMock.getById.mockResolvedValue({+ id: "resume-1",+ name: "Resume",+ data: {},+ updatedAt: new Date(),+ });++ const { agentService } = await import("./agent");++ const result = await agentService.threads.get({ id: "thread-1", userId: "user-1" });++ expect(result.isReadOnly).toBe(true);+ expect(result.thread.status).toBe("archived");+ expect(result.resume).toEqual(expect.objectContaining({ id: "resume-1" }));+ });+});++describe("buildAttachmentModelParts", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("converts readable, image, supported binary, and unsupported attachments into model parts", async () => {+ const { buildAttachmentModelParts } = await import("./agent");++ const imageBytes = new Uint8Array([1, 2, 3]);+ const pdfBytes = new Uint8Array([4, 5, 6]);+ const parts = buildAttachmentModelParts([+ { attachment: buildAttachment(), data: new TextEncoder().encode("hello") },+ {+ attachment: buildAttachment({+ id: "image-1",+ filename: "photo.png",+ mediaType: "image/png",+ size: imageBytes.byteLength,+ }),+ data: imageBytes,+ },+ {+ attachment: buildAttachment({+ id: "pdf-1",+ filename: "portfolio.pdf",+ mediaType: "application/pdf",+ size: pdfBytes.byteLength,+ }),+ data: pdfBytes,+ },+ {+ attachment: buildAttachment({+ id: "zip-1",+ filename: "archive.zip",+ mediaType: "application/zip",+ size: 7,+ }),+ data: new Uint8Array([7]),+ },+ ]);++ expect(parts).toEqual([+ expect.objectContaining({ type: "text", text: expect.stringContaining("hello") }),+ { type: "image", image: imageBytes, mediaType: "image/png" },+ { type: "file", data: pdfBytes, filename: "portfolio.pdf", mediaType: "application/pdf" },+ expect.objectContaining({ type: "text", text: expect.stringContaining("archive.zip") }),+ ]);+ });+});++describe("agentService.messages.send", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("strips forged agent attachment UI parts when no attachment IDs are selected", async () => {+ const activeThread = buildActiveThread();+ const persistedMessage = {+ id: "message-1",+ userId: "user-1",+ threadId: "thread-1",+ role: "user",+ status: "completed",+ sequence: 0,+ uiMessage: {+ id: "ui-message-1",+ role: "user",+ parts: [{ type: "text", text: "Use this file" }],+ },+ };+ const insertValues: unknown[] = [];++ dbMock.select+ .mockImplementationOnce(() => selectLimitResult([activeThread]))+ .mockImplementationOnce(() => selectWhereResult([{ maxSequence: -1 }]))+ .mockImplementationOnce(() => selectWhereResult([{ total: 1 }]))+ .mockImplementationOnce(() => selectOrderByResult([persistedMessage]));++ dbMock.insert.mockReturnValue({+ values: vi.fn((value) => {+ insertValues.push(value);+ return { returning: vi.fn(async () => [persistedMessage]) };+ }),+ });+ dbMock.update.mockReturnValue({ set: vi.fn(() => ({ where: vi.fn(async () => undefined) })) });++ claimActiveAgentRunMock.mockResolvedValue(true);+ aiProvidersServiceMock.getRunnableById.mockResolvedValue({+ id: "provider-1",+ provider: "openai",+ model: "gpt-5",+ apiKey: "secret",+ baseURL: null,+ });+ aiProvidersServiceMock.markUsed.mockResolvedValue(undefined);++ const { convertToModelMessages, ToolLoopAgent } = await import("ai");+ const { agentStreamLifecycle } = await import("./agent-streams");+ const { streamToEventIterator } = await import("@orpc/server");+ vi.mocked(convertToModelMessages).mockResolvedValue([+ { role: "user", content: [{ type: "text", text: "Use this file" }] },+ ]);+ class MockToolLoopAgent {+ stream = vi.fn(async () => ({ toUIMessageStream: vi.fn(() => new ReadableStream()) }));+ }+ vi.mocked(ToolLoopAgent).mockImplementation(MockToolLoopAgent as never);+ vi.mocked(agentStreamLifecycle.create).mockResolvedValue(new ReadableStream());+ vi.mocked(streamToEventIterator).mockReturnValue("iterator" as never);++ const { agentService } = await import("./agent");++ await agentService.messages.send({+ threadId: "thread-1",+ userId: "user-1",+ message: {+ id: "ui-message-1",+ role: "user",+ parts: [+ { type: "text", text: "Use this file" },+ {+ type: "file",+ url: "agent-attachment:foreign-attachment",+ mediaType: "text/plain",+ filename: "forged.txt",+ },+ ],+ // biome-ignore lint/suspicious/noExplicitAny: minimal fixture for unit test+ } as any,+ });++ expect(insertValues).toEqual([+ expect.objectContaining({+ uiMessage: expect.objectContaining({+ parts: [{ type: "text", text: "Use this file" }],+ }),+ }),+ ]);+ });++ it("persists canonical attachment UI parts, links selected attachments, and appends server-read model parts", async () => {+ const activeThread = buildActiveThread();+ const attachment = buildAttachment({+ filename: "canonical.txt",+ mediaType: "text/plain",+ size: 5,+ });+ const persistedMessage = {+ id: "message-1",+ userId: "user-1",+ threadId: "thread-1",+ role: "user",+ status: "completed",+ sequence: 0,+ uiMessage: {+ id: "ui-message-1",+ role: "user",+ parts: [+ { type: "text", text: "Use this file" },+ {+ type: "file",+ url: "agent-attachment:attachment-1",+ mediaType: "text/plain",+ filename: "canonical.txt",+ },+ ],+ },+ };+ const insertValues: unknown[] = [];+ const updateSets: unknown[] = [];++ dbMock.select+ .mockImplementationOnce(() => selectLimitResult([activeThread]))+ .mockImplementationOnce(() => selectWhereResult([attachment]))+ .mockImplementationOnce(() => selectWhereResult([{ maxSequence: -1 }]))+ .mockImplementationOnce(() => selectWhereResult([{ total: 1 }]))+ .mockImplementationOnce(() => selectOrderByResult([persistedMessage]));++ dbMock.insert.mockReturnValue({+ values: vi.fn((value) => {+ insertValues.push(value);+ return { returning: vi.fn(async () => [persistedMessage]) };+ }),+ });+ dbMock.update.mockImplementation(() => ({+ set: vi.fn((value) => {+ updateSets.push(value);+ return {+ where: vi.fn(() => ({+ returning: vi.fn(async () => [{ id: "attachment-1" }]),+ })),+ };+ }),+ }));++ claimActiveAgentRunMock.mockResolvedValue(true);+ aiProvidersServiceMock.getRunnableById.mockResolvedValue({+ id: "provider-1",+ provider: "openai",+ model: "gpt-5",+ apiKey: "secret",+ baseURL: null,+ });+ aiProvidersServiceMock.markUsed.mockResolvedValue(undefined);+ storageServiceMock.read.mockResolvedValue({ data: new TextEncoder().encode("hello"), contentType: "text/plain" });++ const { convertToModelMessages, ToolLoopAgent } = await import("ai");+ const { agentStreamLifecycle } = await import("./agent-streams");+ const { streamToEventIterator } = await import("@orpc/server");+ const streamMock = vi.fn(async () => ({+ toUIMessageStream: vi.fn(() => new ReadableStream()),+ }));+ vi.mocked(convertToModelMessages).mockResolvedValue([+ { role: "user", content: [{ type: "text", text: "Use this file" }] },+ ]);+ class MockToolLoopAgent {+ stream = streamMock;+ }+ vi.mocked(ToolLoopAgent).mockImplementation(MockToolLoopAgent as never);+ vi.mocked(agentStreamLifecycle.create).mockResolvedValue(new ReadableStream());+ vi.mocked(streamToEventIterator).mockReturnValue("iterator" as never);++ const { agentService } = await import("./agent");++ await agentService.messages.send({+ threadId: "thread-1",+ userId: "user-1",+ message: {+ id: "ui-message-1",+ role: "user",+ parts: [+ { type: "text", text: "Use this file" },+ {+ type: "file",+ url: "agent-attachment:attachment-1",+ mediaType: "application/octet-stream",+ filename: "forged-name.bin",+ },+ ],+ // biome-ignore lint/suspicious/noExplicitAny: minimal fixture for unit test+ } as any,+ attachmentIds: ["attachment-1"],+ });++ expect(insertValues).toEqual([+ expect.objectContaining({+ uiMessage: expect.objectContaining({+ parts: [+ { type: "text", text: "Use this file" },+ {+ type: "file",+ url: "agent-attachment:attachment-1",+ mediaType: "text/plain",+ filename: "canonical.txt",+ },+ ],+ }),+ }),+ ]);+ expect(updateSets).toContainEqual({ messageId: "message-1" });+ expect(streamMock).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: [+ {+ role: "user",+ content: [+ { type: "text", text: "Use this file" },+ expect.objectContaining({ type: "text", text: expect.stringContaining("hello") }),+ ],+ },+ ],+ }),+ );+ });++ it("merges an answered ask-user-question tool result into the existing assistant message", async () => {+ const activeThread = buildActiveThread();+ const userMessage = {+ id: "message-user-1",+ userId: "user-1",+ threadId: "thread-1",+ role: "user",+ status: "completed",+ sequence: 0,+ uiMessage: {+ id: "ui-user-1",+ role: "user",+ parts: [{ type: "text", text: "Change the name" }],+ },+ };+ const unansweredAssistantMessage = {+ id: "message-assistant-1",+ userId: "user-1",+ threadId: "thread-1",+ role: "assistant",+ status: "completed",+ sequence: 1,+ uiMessage: {+ id: "ui-assistant-1",+ role: "assistant",+ parts: [+ {+ type: "tool-ask_user_question",+ toolCallId: "call-1",+ state: "input-available",+ input: {+ question: "How broadly should I rename?",+ choices: ["Only change the main resume header name"],+ },+ },+ ],+ },+ };+ const answeredAssistantMessage = {+ ...unansweredAssistantMessage,+ uiMessage: {+ ...unansweredAssistantMessage.uiMessage,+ parts: [+ {+ type: "tool-ask_user_question",+ toolCallId: "call-1",+ state: "output-available",+ input: {+ question: "How broadly should I rename?",+ choices: ["Only change the main resume header name"],+ },+ output: "Only change the main resume header name",+ },+ ],+ },+ };+ const updateSets: unknown[] = [];++ dbMock.select+ .mockImplementationOnce(() => selectLimitResult([activeThread]))+ .mockImplementationOnce(() => selectOrderByResult([userMessage, unansweredAssistantMessage]))+ .mockImplementationOnce(() => selectOrderByResult([userMessage, answeredAssistantMessage]));++ dbMock.update.mockImplementation(() => ({+ set: vi.fn((value) => {+ updateSets.push(value);+ return { where: vi.fn(async () => undefined) };+ }),+ }));++ claimActiveAgentRunMock.mockResolvedValue(true);+ aiProvidersServiceMock.getRunnableById.mockResolvedValue({+ id: "provider-1",+ provider: "openai",+ model: "gpt-5",+ apiKey: "secret",+ baseURL: null,+ });+ aiProvidersServiceMock.markUsed.mockResolvedValue(undefined);++ const { convertToModelMessages, ToolLoopAgent } = await import("ai");+ const { agentStreamLifecycle } = await import("./agent-streams");+ const { streamToEventIterator } = await import("@orpc/server");+ vi.mocked(convertToModelMessages).mockResolvedValue([+ { role: "user", content: [{ type: "text", text: "Change the name" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1", toolName: "ask_user_question", input: {} }],+ },+ {+ role: "tool",+ content: [+ {+ type: "tool-result",+ toolCallId: "call-1",+ toolName: "ask_user_question",+ output: "Only change the main resume header name",+ },+ ],+ },+ ] as never);+ class MockToolLoopAgent {+ stream = vi.fn(async () => ({ toUIMessageStream: vi.fn(() => new ReadableStream()) }));+ }+ vi.mocked(ToolLoopAgent).mockImplementation(MockToolLoopAgent as never);+ vi.mocked(agentStreamLifecycle.create).mockResolvedValue(new ReadableStream());+ vi.mocked(streamToEventIterator).mockReturnValue("iterator" as never);++ const { agentService } = await import("./agent");++ await agentService.messages.send({+ threadId: "thread-1",+ userId: "user-1",+ message: {+ id: "ui-assistant-1",+ role: "assistant",+ parts: [+ {+ type: "tool-ask_user_question",+ toolCallId: "call-1",+ state: "output-available",+ output: "Only change the main resume header name",+ },+ ],+ // biome-ignore lint/suspicious/noExplicitAny: minimal fixture for unit test+ } as any,+ });++ expect(dbMock.insert).not.toHaveBeenCalled();+ expect(updateSets).toContainEqual(+ expect.objectContaining({+ uiMessage: expect.objectContaining({+ parts: [+ expect.objectContaining({+ type: "tool-ask_user_question",+ toolCallId: "call-1",+ state: "output-available",+ output: "Only change the main resume header name",+ }),+ ],+ }),+ }),+ );+ expect(convertToModelMessages).toHaveBeenCalledWith([userMessage.uiMessage, answeredAssistantMessage.uiMessage]);+ });++ it("repairs legacy user-answer messages that followed an unresolved ask-user-question tool call", async () => {+ const activeThread = buildActiveThread();+ const firstUserMessage = {+ id: "message-user-1",+ userId: "user-1",+ threadId: "thread-1",+ role: "user",+ status: "completed",+ sequence: 0,+ uiMessage: {+ id: "ui-user-1",+ role: "user",+ parts: [{ type: "text", text: "Change the name" }],+ },+ };+ const unresolvedAssistantMessage = {+ id: "message-assistant-1",+ userId: "user-1",+ threadId: "thread-1",+ role: "assistant",+ status: "completed",+ sequence: 1,+ uiMessage: {+ id: "ui-assistant-1",+ role: "assistant",+ parts: [+ {+ type: "tool-ask_user_question",+ toolCallId: "call-legacy",+ state: "input-available",+ input: {+ question: "How broadly should I rename?",+ choices: ["Only change the main resume header name"],+ },+ },+ ],+ },+ };+ const legacyAnswerMessage = {+ id: "message-user-2",+ userId: "user-1",+ threadId: "thread-1",+ role: "user",+ status: "completed",+ sequence: 2,+ uiMessage: {+ id: "ui-user-2",+ role: "user",+ parts: [{ type: "text", text: "Only change the main resume header name" }],+ },+ };+ const retryMessage = {+ id: "message-user-3",+ userId: "user-1",+ threadId: "thread-1",+ role: "user",+ status: "completed",+ sequence: 3,+ uiMessage: {+ id: "ui-user-3",+ role: "user",+ parts: [{ type: "text", text: "Retry" }],+ },+ };+ const updateSets: unknown[] = [];++ dbMock.select+ .mockImplementationOnce(() => selectLimitResult([activeThread]))+ .mockImplementationOnce(() => selectWhereResult([{ maxSequence: 2 }]))+ .mockImplementationOnce(() => selectWhereResult([{ total: 4 }]))+ .mockImplementationOnce(() =>+ selectOrderByResult([firstUserMessage, unresolvedAssistantMessage, legacyAnswerMessage, retryMessage]),+ );++ dbMock.insert.mockReturnValue({+ values: vi.fn(() => ({ returning: vi.fn(async () => [retryMessage]) })),+ });+ dbMock.update.mockImplementation(() => ({+ set: vi.fn((value) => {+ updateSets.push(value);+ return { where: vi.fn(async () => undefined) };+ }),+ }));++ claimActiveAgentRunMock.mockResolvedValue(true);+ aiProvidersServiceMock.getRunnableById.mockResolvedValue({+ id: "provider-1",+ provider: "openai",+ model: "gpt-5",+ apiKey: "secret",+ baseURL: null,+ });+ aiProvidersServiceMock.markUsed.mockResolvedValue(undefined);++ const { convertToModelMessages, ToolLoopAgent } = await import("ai");+ const { agentStreamLifecycle } = await import("./agent-streams");+ const { streamToEventIterator } = await import("@orpc/server");+ vi.mocked(convertToModelMessages).mockResolvedValue([{ role: "user", content: [{ type: "text", text: "Retry" }] }]);+ class MockToolLoopAgent {+ stream = vi.fn(async () => ({ toUIMessageStream: vi.fn(() => new ReadableStream()) }));+ }+ vi.mocked(ToolLoopAgent).mockImplementation(MockToolLoopAgent as never);+ vi.mocked(agentStreamLifecycle.create).mockResolvedValue(new ReadableStream());+ vi.mocked(streamToEventIterator).mockReturnValue("iterator" as never);++ const { agentService } = await import("./agent");++ await agentService.messages.send({+ threadId: "thread-1",+ userId: "user-1",+ // biome-ignore lint/suspicious/noExplicitAny: minimal fixture for unit test+ message: retryMessage.uiMessage as any,+ });++ expect(updateSets).toContainEqual(+ expect.objectContaining({+ uiMessage: expect.objectContaining({+ parts: [+ expect.objectContaining({+ type: "tool-ask_user_question",+ toolCallId: "call-legacy",+ state: "output-available",+ output: "Only change the main resume header name",+ }),+ ],+ }),+ }),+ );+ expect(convertToModelMessages).toHaveBeenCalledWith([+ firstUserMessage.uiMessage,+ expect.objectContaining({+ parts: [+ expect.objectContaining({+ toolCallId: "call-legacy",+ state: "output-available",+ output: "Only change the main resume header name",+ }),+ ],+ }),+ legacyAnswerMessage.uiMessage,+ retryMessage.uiMessage,+ ]);+ });++ it("rejects malformed attachment IDs before persisting a message", async () => {+ dbMock.select.mockImplementationOnce(() => selectLimitResult([buildActiveThread()]));+ aiProvidersServiceMock.getRunnableById.mockResolvedValue({+ id: "provider-1",+ provider: "openai",+ model: "gpt-5",+ apiKey: "secret",+ baseURL: null,+ });++ const { agentService } = await import("./agent");++ const sending = agentService.messages.send({+ threadId: "thread-1",+ userId: "user-1",+ // biome-ignore lint/suspicious/noExplicitAny: minimal fixture for unit test+ message: { id: "ui-message-1", role: "user", parts: [{ type: "text", text: "Use this file" }] } as any,+ attachmentIds: [123],+ });++ await expect(sending).rejects.toBeInstanceOf(ORPCError);+ await expect(sending).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message: "Attachment IDs must be non-empty strings.",+ });+ expect(dbMock.insert).not.toHaveBeenCalled();+ });++ it("rejects attachments that are missing, foreign, or already linked before persisting a message", async () => {+ dbMock.select+ .mockImplementationOnce(() => selectLimitResult([buildActiveThread()]))+ .mockImplementationOnce(() => selectWhereResult([]));++ aiProvidersServiceMock.getRunnableById.mockResolvedValue({+ id: "provider-1",+ provider: "openai",+ model: "gpt-5",+ apiKey: "secret",+ baseURL: null,+ });++ const { agentService } = await import("./agent");++ const sending = agentService.messages.send({+ threadId: "thread-1",+ userId: "user-1",+ // biome-ignore lint/suspicious/noExplicitAny: minimal fixture for unit test+ message: { id: "ui-message-1", role: "user", parts: [{ type: "text", text: "Use this file" }] } as any,+ attachmentIds: ["foreign-or-linked-attachment"],+ });++ await expect(sending).rejects.toBeInstanceOf(ORPCError);+ await expect(sending).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message: "One or more attachments are unavailable or already linked to a message.",+ });+ expect(dbMock.insert).not.toHaveBeenCalled();+ });++ it("throws CONFLICT when the underlying thread is archived", async () => {+ const archivedThread = buildArchivedThread();++ dbMock.select.mockImplementation(() => {+ const limit = vi.fn(async () => [archivedThread]);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+ });++ const { agentService } = await import("./agent");++ const sending = agentService.messages.send({+ threadId: "thread-1",+ userId: "user-1",+ // biome-ignore lint/suspicious/noExplicitAny: minimal fixture for unit test+ message: { id: "msg-1", role: "user", parts: [{ type: "text", text: "hi" }] } as any,+ });++ await expect(sending).rejects.toBeInstanceOf(ORPCError);+ await expect(sending).rejects.toMatchObject({ code: "CONFLICT", message: "This thread is archived." });++ // Ensure we never tried to claim a run or persist anything for an archived thread.+ expect(aiProvidersServiceMock.getRunnableById).not.toHaveBeenCalled();+ });+});++describe("agentService.threads.archive", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("skips active-run cleanup when there is no active run", async () => {+ const idleThread = buildArchivedThread({+ status: "active",+ activeRunId: null,+ activeStreamId: null,+ archivedAt: null,+ });++ dbMock.select.mockImplementation(() => {+ const limit = vi.fn(async () => [idleThread]);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+ });++ const updateWhere = vi.fn(async () => undefined);+ const updateSet = vi.fn(() => ({ where: updateWhere }));+ dbMock.update.mockReturnValue({ set: updateSet });++ const { agentService } = await import("./agent");++ await agentService.threads.archive({ id: "thread-1", userId: "user-1" });++ expect(clearActiveAgentRunIfCurrentMock).not.toHaveBeenCalled();+ expect(updateSet).toHaveBeenCalledWith(expect.objectContaining({ status: "archived" }));+ expect(updateWhere).toHaveBeenCalled();+ });++ it("clears active-run state when an active run is present, then flips status", async () => {+ const activeThread = buildArchivedThread({+ status: "active",+ activeRunId: "run-1",+ activeStreamId: "stream-1",+ archivedAt: null,+ });++ dbMock.select.mockImplementation(() => {+ const limit = vi.fn(async () => [activeThread]);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+ });++ const updateWhere = vi.fn(async () => undefined);+ const updateSet = vi.fn(() => ({ where: updateWhere }));+ dbMock.update.mockReturnValue({ set: updateSet });++ clearActiveAgentRunIfCurrentMock.mockResolvedValue(undefined);++ const { agentService } = await import("./agent");++ await agentService.threads.archive({ id: "thread-1", userId: "user-1" });++ expect(clearActiveAgentRunIfCurrentMock).toHaveBeenCalledWith({+ threadId: "thread-1",+ userId: "user-1",+ runId: "run-1",+ streamId: "stream-1",+ });+ expect(updateSet).toHaveBeenCalledWith(expect.objectContaining({ status: "archived" }));+ expect(updateWhere).toHaveBeenCalled();+ });++ it("still flips status when clearActiveAgentRunIfCurrent throws", async () => {+ const activeThread = buildArchivedThread({+ status: "active",+ activeRunId: "run-2",+ activeStreamId: "stream-2",+ archivedAt: null,+ });++ dbMock.select.mockImplementation(() => {+ const limit = vi.fn(async () => [activeThread]);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+ });++ const updateWhere = vi.fn(async () => undefined);+ const updateSet = vi.fn(() => ({ where: updateWhere }));+ dbMock.update.mockReturnValue({ set: updateSet });++ clearActiveAgentRunIfCurrentMock.mockRejectedValue(new Error("boom"));+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);++ const { agentService } = await import("./agent");++ await agentService.threads.archive({ id: "thread-1", userId: "user-1" });++ expect(clearActiveAgentRunIfCurrentMock).toHaveBeenCalled();+ expect(updateSet).toHaveBeenCalledWith(expect.objectContaining({ status: "archived" }));+ expect(consoleSpy).toHaveBeenCalled();++ consoleSpy.mockRestore();+ });+});++describe("agentService.threads.delete", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("throws NOT_FOUND when the thread does not belong to the user and skips destructive work", async () => {+ dbMock.select.mockImplementation(() => {+ const limit = vi.fn(async () => []);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+ });++ const { agentService } = await import("./agent");++ const deleting = agentService.threads.delete({ id: "thread-x", userId: "user-y" });++ await expect(deleting).rejects.toBeInstanceOf(ORPCError);+ await expect(deleting).rejects.toMatchObject({ code: "NOT_FOUND" });++ expect(storageServiceMock.delete).not.toHaveBeenCalled();+ expect(dbMock.delete).not.toHaveBeenCalled();+ expect(dbMock.update).not.toHaveBeenCalled();+ });++ it("proceeds with cleanup when the thread is owned by the user", async () => {+ const ownedThread = buildArchivedThread({+ id: "thread-own",+ userId: "user-own",+ status: "active",+ activeRunId: null,+ activeStreamId: null,+ archivedAt: null,+ });++ dbMock.select.mockImplementation(() => {+ const limit = vi.fn(async () => [ownedThread]);+ const where = vi.fn(() => ({ limit }));+ const from = vi.fn(() => ({ where }));+ return { from };+ });++ const deleteWhere = vi.fn(async () => undefined);+ dbMock.delete.mockReturnValue({ where: deleteWhere });++ const updateWhere = vi.fn(async () => undefined);+ const updateSet = vi.fn(() => ({ where: updateWhere }));+ dbMock.update.mockReturnValue({ set: updateSet });++ storageServiceMock.delete.mockResolvedValue(undefined);++ const { agentService } = await import("./agent");++ await agentService.threads.delete({ id: "thread-own", userId: "user-own" });++ expect(storageServiceMock.delete).toHaveBeenCalledWith("uploads/user-own/agent/thread-own");+ expect(dbMock.delete).toHaveBeenCalled();+ expect(updateSet).toHaveBeenCalledWith(expect.objectContaining({ status: "deleted" }));+ });+});++describe("agentService.actions.revert", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ function buildAction(overrides: Record<string, unknown> = {}) {+ return {+ id: "action-1",+ userId: "user-1",+ threadId: "thread-1",+ messageId: null,+ resumeId: "resume-1",+ kind: "resume_patch",+ status: "applied",+ title: "Tighten summary",+ summary: null,+ operations: [{ op: "replace", path: "/basics/name", value: "Bob" }],+ inverseOperations: [{ op: "replace", path: "/basics/name", value: "Alice" }],+ baseUpdatedAt: new Date("2026-05-01T00:00:00.000Z"),+ appliedUpdatedAt: new Date("2026-05-02T00:00:00.000Z"),+ revertedAt: null,+ revertMessage: null,+ createdAt: new Date("2026-05-02T00:00:00.000Z"),+ updatedAt: new Date("2026-05-02T00:00:00.000Z"),+ ...overrides,+ };+ }++ it("reverts an applied action, calls resumeService.patch with the inverse operations, and updates the DB row", async () => {+ const action = buildAction();+ const updatedAction = { ...action, status: "reverted", revertedAt: new Date(), revertMessage: null };++ dbMock.select.mockImplementation(() => selectLimitResult([action]));++ const updateReturning = vi.fn(async () => [updatedAction]);+ const updateWhere = vi.fn(() => ({ returning: updateReturning }));+ const updateSet = vi.fn(() => ({ where: updateWhere }));+ dbMock.update.mockReturnValue({ set: updateSet });++ resumeServiceMock.patchInTransaction.mockResolvedValue({+ id: "resume-1",+ updatedAt: new Date("2026-05-03T00:00:00.000Z"),+ });++ const { agentService } = await import("./agent");++ const result = await agentService.actions.revert({ id: "action-1", userId: "user-1" });++ expect(resumeServiceMock.patchInTransaction).toHaveBeenCalledWith(dbMock, {+ id: "resume-1",+ userId: "user-1",+ operations: action.inverseOperations,+ expectedUpdatedAt: action.appliedUpdatedAt,+ });+ expect(updateSet).toHaveBeenCalledWith(+ expect.objectContaining({+ status: "reverted",+ revertMessage: null,+ appliedUpdatedAt: new Date("2026-05-03T00:00:00.000Z"),+ }),+ );+ expect(result.status).toBe("reverted");+ });++ it("returns a conflicted action when resumeService.patch throws RESUME_VERSION_CONFLICT", async () => {+ const action = buildAction();+ const conflictedAction = {+ ...action,+ status: "conflicted",+ revertMessage: "The resume changed after this action was applied.",+ };++ dbMock.select.mockImplementation(() => selectLimitResult([action]));++ const updateReturning = vi.fn(async () => [conflictedAction]);+ const updateWhere = vi.fn(() => ({ returning: updateReturning }));+ const updateSet = vi.fn(() => ({ where: updateWhere }));+ dbMock.update.mockReturnValue({ set: updateSet });++ resumeServiceMock.patchInTransaction.mockRejectedValue(new ORPCError("RESUME_VERSION_CONFLICT"));++ const { agentService } = await import("./agent");++ const result = await agentService.actions.revert({ id: "action-1", userId: "user-1" });++ expect(resumeServiceMock.patchInTransaction).toHaveBeenCalled();+ expect(updateSet).toHaveBeenCalledWith(+ expect.objectContaining({+ status: "conflicted",+ revertMessage: "The resume changed after this action was applied.",+ }),+ );+ expect(updateWhere).toHaveBeenCalled();+ expect(updateReturning).toHaveBeenCalled();+ expect(result.status).toBe("conflicted");+ expect(result.revertMessage).toBe("The resume changed after this action was applied.");+ });++ it("returns the existing action unchanged when its status is already reverted", async () => {+ const action = buildAction({+ status: "reverted",+ revertedAt: new Date("2026-05-03T00:00:00.000Z"),+ });++ dbMock.select.mockImplementation(() => selectLimitResult([action]));++ const { agentService } = await import("./agent");++ const result = await agentService.actions.revert({ id: "action-1", userId: "user-1" });++ expect(resumeServiceMock.patch).not.toHaveBeenCalled();+ expect(dbMock.update).not.toHaveBeenCalled();+ expect(result.status).toBe("reverted");+ expect(result.id).toBe("action-1");+ });++ it("throws BAD_REQUEST when the action has no resumeId", async () => {+ const action = buildAction({ resumeId: null });++ dbMock.select.mockImplementation(() => selectLimitResult([action]));++ const { agentService } = await import("./agent");++ const reverting = agentService.actions.revert({ id: "action-1", userId: "user-1" });++ await expect(reverting).rejects.toBeInstanceOf(ORPCError);+ await expect(reverting).rejects.toMatchObject({ code: "BAD_REQUEST" });+ expect(resumeServiceMock.patch).not.toHaveBeenCalled();+ });++ it("throws NOT_FOUND when no matching action is found", async () => {+ dbMock.select.mockImplementation(() => selectLimitResult([]));++ const { agentService } = await import("./agent");++ const reverting = agentService.actions.revert({ id: "missing-id", userId: "user-1" });++ await expect(reverting).rejects.toBeInstanceOf(ORPCError);+ await expect(reverting).rejects.toMatchObject({ code: "NOT_FOUND" });+ expect(resumeServiceMock.patch).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/services/agent.ts b/packages/api/src/services/agent.tsnew file mode 100644index 000000000..8979b5c29--- /dev/null+++ b/packages/api/src/services/agent.ts@@ -0,0 +1,1260 @@+import type { Locale } from "@reactive-resume/utils/locale";+import type { JsonPatchOperation } from "@reactive-resume/utils/resume/patch";+import type { FilePart, ImagePart, ModelMessage, TextPart, UIMessage } from "ai";+import type { getModel } from "./ai";+import { ORPCError } from "@orpc/client";+import { streamToEventIterator } from "@orpc/server";+import { convertToModelMessages, stepCountIs, ToolLoopAgent } from "ai";+import { and, asc, count, desc, eq, inArray, isNull, max, sql } from "drizzle-orm";+import { db } from "@reactive-resume/db/client";+import * as schema from "@reactive-resume/db/schema";+import { defaultResumeData } from "@reactive-resume/schema/resume/default";+import { generateId } from "@reactive-resume/utils/string";+import { createInverseResumePatches } from "./agent-patches";+import { buildAgentDraftResumeName, buildUniqueAgentDraftSlug } from "./agent-resume";+import { claimActiveAgentRun, clearActiveAgentRunIfCurrent } from "./agent-run-state";+import { agentStreamLifecycle } from "./agent-streams";+import { buildAgentInstructions, buildAgentTools } from "./agent-tools";+import { fetchUrlForAgent } from "./agent-url";+import { getAgentModel } from "./ai";+import { assertAgentEnvironment } from "./ai-credentials";+import { aiProvidersService } from "./ai-providers";+import { resumeService } from "./resume";+import { getStorageService, inferContentType } from "./storage";++const MAX_AGENT_STEPS = 30;+const MAX_ATTACHMENTS_PER_MESSAGE = 10;+const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;+const MAX_THREAD_ATTACHMENT_BYTES = 100 * 1024 * 1024;+const READABLE_ATTACHMENT_TYPES = new Set(["text/plain", "text/markdown", "application/json"]);+const DIRECT_MODEL_FILE_ATTACHMENT_TYPES = new Set([+ "application/pdf",+ "audio/mpeg",+ "audio/mp3",+ "audio/wav",+ "audio/wave",+ "audio/x-wav",+]);+const AGENT_ATTACHMENT_URL_PREFIX = "agent-attachment:";+const MAX_ATTACHMENT_TEXT_CHARS = 40_000;++const activeRunControllers = new Map<string, AbortController>();+const canceledRunsWithPersistedPartial = new Set<string>();++type AgentThreadRecord = typeof schema.agentThread.$inferSelect;+type AgentMessageRecord = typeof schema.agentMessage.$inferSelect;+type AgentActionRecord = typeof schema.agentAction.$inferSelect;+type AgentAttachmentRecord = typeof schema.agentAttachment.$inferSelect;++type CreateThreadInput = {+ userId: string;+ locale: Locale;+ aiProviderId?: string;+ sourceResumeId?: string;+};++type SendMessageInput = {+ userId: string;+ threadId: string;+ message: UIMessage;+ attachmentIds?: unknown;+};++type CreateAttachmentInput = {+ userId: string;+ threadId: string;+ filename: string;+ mediaType: string;+ data: Uint8Array;+};++type AttachmentModelInput = {+ attachment: AgentAttachmentRecord;+ data: Uint8Array;+};++function cloneResumeData<T>(data: T): T {+ return structuredClone(data);+}++function toThreadSummary(row: AgentThreadRecord & { resumeName?: string | null; providerLabel?: string | null }) {+ return {+ id: row.id,+ title: row.title,+ status: row.status,+ sourceResumeId: row.sourceResumeId,+ workingResumeId: row.workingResumeId,+ aiProviderId: row.aiProviderId,+ resumeName: row.resumeName ?? null,+ providerLabel: row.providerLabel ?? null,+ activeRunId: row.activeRunId,+ lastMessageAt: row.lastMessageAt,+ archivedAt: row.archivedAt,+ deletedAt: row.deletedAt,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++function toMessage(row: AgentMessageRecord): UIMessage {+ return row.uiMessage as unknown as UIMessage;+}++function toAction(row: AgentActionRecord) {+ return {+ id: row.id,+ threadId: row.threadId,+ messageId: row.messageId,+ resumeId: row.resumeId,+ kind: row.kind,+ status: row.status,+ title: row.title,+ summary: row.summary,+ operations: row.operations,+ inverseOperations: row.inverseOperations,+ baseUpdatedAt: row.baseUpdatedAt,+ appliedUpdatedAt: row.appliedUpdatedAt,+ revertedAt: row.revertedAt,+ revertMessage: row.revertMessage,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++function toAttachment(row: AgentAttachmentRecord) {+ return {+ id: row.id,+ threadId: row.threadId,+ messageId: row.messageId,+ filename: row.filename,+ mediaType: row.mediaType,+ size: row.size,+ createdAt: row.createdAt,+ };+}++function attachmentUiPart(attachment: AgentAttachmentRecord): UIMessage["parts"][number] {+ return {+ type: "file",+ url: `${AGENT_ATTACHMENT_URL_PREFIX}${attachment.id}`,+ mediaType: attachment.mediaType,+ filename: attachment.filename,+ };+}++function withAttachmentUiParts(message: UIMessage, attachments: AgentAttachmentRecord[]): UIMessage {+ return {+ ...message,+ parts: [...withoutAgentAttachmentUiParts(message).parts, ...attachments.map(attachmentUiPart)],+ };+}++function withoutAgentAttachmentUiParts(message: UIMessage): UIMessage {+ return {+ ...message,+ parts: message.parts.filter((part) => !(part.type === "file" && part.url.startsWith(AGENT_ATTACHMENT_URL_PREFIX))),+ };+}++type AgentToolPart = UIMessage["parts"][number] & {+ errorText?: string;+ output?: unknown;+ state?: string;+ toolCallId?: string;+};++function isAnsweredAskUserQuestionPart(part: UIMessage["parts"][number]): part is AgentToolPart {+ const toolPart = part as AgentToolPart;+ return (+ toolPart.type === "tool-ask_user_question" &&+ typeof toolPart.toolCallId === "string" &&+ (toolPart.state === "output-available" || toolPart.state === "output-error")+ );+}++function mergeAskUserQuestionOutputs(existingMessage: UIMessage, incomingMessage: UIMessage): UIMessage {+ const answeredParts = new Map(+ incomingMessage.parts.filter(isAnsweredAskUserQuestionPart).map((part) => [part.toolCallId, part] as const),+ );++ let didMerge = false;+ const parts = existingMessage.parts.map((part) => {+ const existingPart = part as AgentToolPart;+ if (+ existingPart.type !== "tool-ask_user_question" ||+ typeof existingPart.toolCallId !== "string" ||+ existingPart.state !== "input-available"+ ) {+ return part;+ }++ const answeredPart = answeredParts.get(existingPart.toolCallId);+ if (!answeredPart) return part;++ didMerge = true;+ if (answeredPart.state === "output-error") {+ return {+ ...part,+ state: "output-error",+ errorText: answeredPart.errorText ?? "User answer failed.",+ } as UIMessage["parts"][number];+ }++ return {+ ...part,+ state: "output-available",+ output: answeredPart.output,+ } as UIMessage["parts"][number];+ });++ if (!didMerge) {+ throw new ORPCError("BAD_REQUEST", { message: "No matching unanswered user question was found." });+ }++ return { ...existingMessage, parts };+}++function getFirstUnansweredAskUserQuestionToolCallId(message: UIMessage) {+ const part = message.parts.find((part) => {+ const toolPart = part as AgentToolPart;+ return (+ toolPart.type === "tool-ask_user_question" &&+ typeof toolPart.toolCallId === "string" &&+ toolPart.state === "input-available"+ );+ }) as AgentToolPart | undefined;++ return part?.toolCallId;+}++function answerAskUserQuestionToolCall(message: UIMessage, toolCallId: string, answer: string) {+ return mergeAskUserQuestionOutputs(message, {+ ...message,+ parts: [+ {+ type: "tool-ask_user_question",+ toolCallId,+ state: "output-available",+ input: undefined,+ output: answer,+ } as UIMessage["parts"][number],+ ],+ });+}++function attachmentLabel(attachment: AgentAttachmentRecord) {+ return `${attachment.filename} (${attachment.mediaType}, ${attachment.size} bytes, attachmentId: ${attachment.id})`;+}++export function buildAttachmentModelParts(input: AttachmentModelInput[]): Array<TextPart | ImagePart | FilePart> {+ return input.map(({ attachment, data }) => {+ if (READABLE_ATTACHMENT_TYPES.has(attachment.mediaType)) {+ const text = new TextDecoder().decode(data).slice(0, MAX_ATTACHMENT_TEXT_CHARS);+ return {+ type: "text",+ text: `Attachment ${attachmentLabel(attachment)}:\n\n${text}`,+ };+ }++ if (attachment.mediaType.startsWith("image/")) {+ return {+ type: "image",+ image: data,+ mediaType: attachment.mediaType,+ };+ }++ if (DIRECT_MODEL_FILE_ATTACHMENT_TYPES.has(attachment.mediaType)) {+ return {+ type: "file",+ data,+ filename: attachment.filename,+ mediaType: attachment.mediaType,+ };+ }++ return {+ type: "text",+ text: `Attachment ${attachmentLabel(attachment)} is not included directly because this media type is not supported for model file input. Use the read_attachment tool if text extraction is available.`,+ };+ });+}++function appendUserModelParts(message: ModelMessage, parts: Array<TextPart | ImagePart | FilePart>): ModelMessage {+ if (parts.length === 0 || message.role !== "user") return message;++ const content =+ typeof message.content === "string" ? [{ type: "text" as const, text: message.content }] : message.content;+ return {+ ...message,+ content: [...content, ...parts],+ };+}++function uniqueAttachmentIds(ids: unknown) {+ if (ids === undefined) return [];+ if (!Array.isArray(ids)) {+ throw new ORPCError("BAD_REQUEST", { message: "Attachment IDs must be an array." });+ }++ if (ids.length > MAX_ATTACHMENTS_PER_MESSAGE) {+ throw new ORPCError("BAD_REQUEST", { message: "Too many attachments for one message." });+ }++ const unique = new Set<string>();+ for (const id of ids) {+ if (typeof id !== "string" || !id.trim()) {+ throw new ORPCError("BAD_REQUEST", { message: "Attachment IDs must be non-empty strings." });+ }+ unique.add(id.trim());+ }++ if (unique.size !== ids.length) {+ throw new ORPCError("BAD_REQUEST", { message: "Attachment IDs must be unique." });+ }++ if (unique.size > MAX_ATTACHMENTS_PER_MESSAGE) {+ throw new ORPCError("BAD_REQUEST", { message: "Too many attachments for one message." });+ }++ return Array.from(unique);+}++function normalizeAttachmentIds(ids: unknown) {+ const unique = uniqueAttachmentIds(ids);+ return unique;+}++async function getUnlinkedMessageAttachments(input: { ids: unknown; threadId: string; userId: string }) {+ const ids = normalizeAttachmentIds(input.ids);+ if (ids.length === 0) return [];++ const attachments = await db+ .select()+ .from(schema.agentAttachment)+ .where(+ and(+ eq(schema.agentAttachment.threadId, input.threadId),+ eq(schema.agentAttachment.userId, input.userId),+ inArray(schema.agentAttachment.id, ids),+ isNull(schema.agentAttachment.messageId),+ ),+ );++ if (attachments.length !== ids.length) {+ throw new ORPCError("BAD_REQUEST", {+ message: "One or more attachments are unavailable or already linked to a message.",+ });+ }++ const attachmentsById = new Map(attachments.map((attachment) => [attachment.id, attachment]));+ return ids.map((id) => {+ const attachment = attachmentsById.get(id);+ if (!attachment) {+ throw new ORPCError("BAD_REQUEST", {+ message: "One or more attachments are unavailable or already linked to a message.",+ });+ }++ return attachment;+ });+}++async function linkAttachmentsToMessage(input: {+ attachments: AgentAttachmentRecord[];+ messageId: string;+ threadId: string;+ userId: string;+}) {+ if (input.attachments.length === 0) return;++ const ids = input.attachments.map((attachment) => attachment.id);+ const linked = await db+ .update(schema.agentAttachment)+ .set({ messageId: input.messageId })+ .where(+ and(+ eq(schema.agentAttachment.threadId, input.threadId),+ eq(schema.agentAttachment.userId, input.userId),+ inArray(schema.agentAttachment.id, ids),+ isNull(schema.agentAttachment.messageId),+ ),+ )+ .returning({ id: schema.agentAttachment.id });++ if (linked.length !== ids.length) {+ throw new ORPCError("CONFLICT", { message: "One or more attachments were already linked to another message." });+ }+}++async function readAttachmentModelInputs(attachments: AgentAttachmentRecord[]): Promise<AttachmentModelInput[]> {+ const storage = getStorageService();+ const inputs = await Promise.all(+ attachments.map(async (attachment) => {+ const stored = await storage.read(attachment.storageKey);+ if (!stored) {+ throw new ORPCError("BAD_REQUEST", { message: `Attachment ${attachment.filename} could not be read.` });+ }++ return { attachment, data: stored.data };+ }),+ );++ return inputs;+}++function attachModelPartsToLatestUserMessage(+ messages: ModelMessage[],+ parts: Array<TextPart | ImagePart | FilePart>,+): ModelMessage[] {+ if (parts.length === 0) return messages;++ let index = -1;+ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex--) {+ if (messages[messageIndex]?.role === "user") {+ index = messageIndex;+ break;+ }+ }++ if (index === -1) return messages;++ return messages.map((message, messageIndex) =>+ messageIndex === index ? appendUserModelParts(message, parts) : message,+ );+}++async function getExistingResumeSlugs(userId: string) {+ const rows = await db+ .select({ slug: schema.resume.slug })+ .from(schema.resume)+ .where(eq(schema.resume.userId, userId));+ return new Set(rows.map((row) => row.slug));+}++async function createWorkingResume(input: CreateThreadInput) {+ if (input.sourceResumeId) {+ const source = await resumeService.getById({ id: input.sourceResumeId, userId: input.userId });+ const existingSlugs = await getExistingResumeSlugs(input.userId);+ const name = buildAgentDraftResumeName(source.name);+ const slug = buildUniqueAgentDraftSlug(source.name, existingSlugs);++ const id = await resumeService.create({+ userId: input.userId,+ name,+ slug,+ tags: [...source.tags],+ locale: input.locale,+ data: cloneResumeData(source.data),+ });++ return { id, source, title: name };+ }++ const existingSlugs = await getExistingResumeSlugs(input.userId);+ const name = "AI Draft";+ const id = await resumeService.create({+ userId: input.userId,+ name,+ slug: buildUniqueAgentDraftSlug(name, existingSlugs),+ tags: [],+ locale: input.locale,+ data: cloneResumeData(defaultResumeData),+ });++ return { id, source: null, title: name };+}++async function getThread(input: { id: string; userId: string }) {+ const [thread] = await db+ .select()+ .from(schema.agentThread)+ .where(+ and(+ eq(schema.agentThread.id, input.id),+ eq(schema.agentThread.userId, input.userId),+ isNull(schema.agentThread.deletedAt),+ ),+ )+ .limit(1);++ if (!thread) throw new ORPCError("NOT_FOUND");++ return thread;+}++async function getNextMessageSequence(threadId: string) {+ const [row] = await db+ .select({ maxSequence: max(schema.agentMessage.sequence) })+ .from(schema.agentMessage)+ .where(eq(schema.agentMessage.threadId, threadId));++ return (row?.maxSequence ?? -1) + 1;+}++async function persistMessage(input: {+ userId: string;+ threadId: string;+ message: UIMessage;+ status?: string;+ sequence?: number;+}) {+ const sequence = input.sequence ?? (await getNextMessageSequence(input.threadId));+ const [message] = await db+ .insert(schema.agentMessage)+ .values({+ userId: input.userId,+ threadId: input.threadId,+ role: input.message.role,+ status: input.status ?? "completed",+ sequence,+ uiMessage: input.message as unknown as Record<string, unknown>,+ })+ .returning();++ await db+ .update(schema.agentThread)+ .set({ lastMessageAt: new Date() })+ .where(and(eq(schema.agentThread.id, input.threadId), eq(schema.agentThread.userId, input.userId)));++ return message;+}++async function updateAssistantToolResultMessage(input: { userId: string; threadId: string; message: UIMessage }) {+ const existingRows = await listThreadMessages({ threadId: input.threadId, userId: input.userId });+ const existingRow = existingRows.find((row) => row.role === "assistant" && toMessage(row).id === input.message.id);+ if (!existingRow) {+ throw new ORPCError("BAD_REQUEST", { message: "The answered assistant message was not found." });+ }++ const mergedMessage = mergeAskUserQuestionOutputs(toMessage(existingRow), input.message);++ await db+ .update(schema.agentMessage)+ .set({+ status: "completed",+ uiMessage: mergedMessage as unknown as Record<string, unknown>,+ })+ .where(+ and(+ eq(schema.agentMessage.id, existingRow.id),+ eq(schema.agentMessage.threadId, input.threadId),+ eq(schema.agentMessage.userId, input.userId),+ ),+ );++ await db+ .update(schema.agentThread)+ .set({ lastMessageAt: new Date() })+ .where(and(eq(schema.agentThread.id, input.threadId), eq(schema.agentThread.userId, input.userId)));++ return mergedMessage;+}++async function repairLegacyAskUserQuestionAnswers(+ rows: AgentMessageRecord[],+ input: { threadId: string; userId: string },+) {+ const nextRows = [...rows];++ for (let index = 0; index < nextRows.length - 1; index++) {+ const assistantRow = nextRows[index];+ const answerRow = nextRows[index + 1];++ if (!assistantRow || !answerRow || assistantRow.role !== "assistant" || answerRow.role !== "user") continue;++ const assistantMessage = toMessage(assistantRow);+ const toolCallId = getFirstUnansweredAskUserQuestionToolCallId(assistantMessage);+ const answer = messageText(toMessage(answerRow));+ if (!toolCallId || !answer) continue;++ const mergedMessage = answerAskUserQuestionToolCall(assistantMessage, toolCallId, answer);+ nextRows[index] = {+ ...assistantRow,+ uiMessage: mergedMessage as unknown as AgentMessageRecord["uiMessage"],+ };++ await db+ .update(schema.agentMessage)+ .set({+ status: "completed",+ uiMessage: mergedMessage as unknown as Record<string, unknown>,+ })+ .where(+ and(+ eq(schema.agentMessage.id, assistantRow.id),+ eq(schema.agentMessage.threadId, input.threadId),+ eq(schema.agentMessage.userId, input.userId),+ ),+ );+ }++ return nextRows;+}++async function cleanupActiveRun(input: {+ threadId: string;+ userId: string;+ runId: string;+ streamId: string;+ primaryError?: unknown;+}) {+ activeRunControllers.delete(input.runId);+ canceledRunsWithPersistedPartial.delete(input.runId);++ try {+ await clearActiveAgentRunIfCurrent(input);+ } catch (error) {+ if (!input.primaryError) throw error;+ console.error("[agent] Failed to clear active run after run error", error);+ }+}++function messageText(message: UIMessage) {+ return message.parts+ .filter((part) => part.type === "text")+ .map((part) => part.text)+ .join(" ")+ .trim();+}++function buildThreadTitle(message: UIMessage, fallback: string) {+ const text = messageText(message);+ if (!text) return fallback;+ return text.length > 60 ? `${text.slice(0, 57)}...` : text;+}++async function listThreadMessages(input: { threadId: string; userId: string }) {+ return db+ .select()+ .from(schema.agentMessage)+ .where(and(eq(schema.agentMessage.threadId, input.threadId), eq(schema.agentMessage.userId, input.userId)))+ .orderBy(asc(schema.agentMessage.sequence));+}++async function readAttachment(input: { id: string; threadId: string; userId: string }) {+ const [attachment] = await db+ .select()+ .from(schema.agentAttachment)+ .where(+ and(+ eq(schema.agentAttachment.id, input.id),+ eq(schema.agentAttachment.threadId, input.threadId),+ eq(schema.agentAttachment.userId, input.userId),+ ),+ )+ .limit(1);++ if (!attachment) throw new Error("ATTACHMENT_NOT_FOUND");++ const stored = await getStorageService().read(attachment.storageKey);+ if (!stored) throw new Error("ATTACHMENT_NOT_FOUND");++ if (!READABLE_ATTACHMENT_TYPES.has(attachment.mediaType)) {+ return {+ id: attachment.id,+ filename: attachment.filename,+ mediaType: attachment.mediaType,+ size: attachment.size,+ content: null,+ note: "This attachment is provided directly to the model when its message is sent. Text extraction is not available through this tool for this media type.",+ };+ }++ return {+ id: attachment.id,+ filename: attachment.filename,+ mediaType: attachment.mediaType,+ size: attachment.size,+ content: new TextDecoder().decode(stored.data).slice(0, 40_000),+ };+}++async function applyResumePatch(input: {+ userId: string;+ threadId: string;+ resumeId: string;+ title: string;+ summary?: string;+ operations: JsonPatchOperation[];+}) {+ const before = await resumeService.getById({ id: input.resumeId, userId: input.userId });+ const inverseOperations = createInverseResumePatches(before.data, input.operations);++ const { action, patched } = await db.transaction(async (tx) => {+ const patched = await resumeService.patchInTransaction(tx, {+ id: input.resumeId,+ userId: input.userId,+ operations: input.operations,+ expectedUpdatedAt: before.updatedAt,+ });++ const [action] = await tx+ .insert(schema.agentAction)+ .values({+ userId: input.userId,+ threadId: input.threadId,+ resumeId: input.resumeId,+ kind: "resume_patch",+ status: "applied",+ title: input.title,+ ...(input.summary !== undefined ? { summary: input.summary } : {}),+ operations: input.operations,+ inverseOperations,+ baseUpdatedAt: before.updatedAt,+ appliedUpdatedAt: patched.updatedAt,+ })+ .returning();++ if (!action) throw new Error("AGENT_ACTION_CREATE_FAILED");++ return { action, patched };+ });++ await resumeService.notifyResumePatched({+ resumeId: patched.id,+ userId: input.userId,+ updatedAt: patched.updatedAt,+ });++ return {+ actionId: action.id,+ resumeId: input.resumeId,+ title: action.title,+ summary: action.summary,+ operations: action.operations,+ appliedUpdatedAt: action.appliedUpdatedAt.toISOString(),+ };+}++function createAgent(input: {+ userId: string;+ threadId: string;+ resumeId: string;+ provider: {+ provider: Parameters<typeof getModel>[0]["provider"];+ model: string;+ apiKey: string;+ baseURL?: string;+ };+ model: ReturnType<typeof getModel>;+}) {+ const tools = buildAgentTools({+ provider: input.provider,+ handlers: {+ fetchUrl: fetchUrlForAgent,+ readResume: async () => {+ const resume = await resumeService.getById({ id: input.resumeId, userId: input.userId });+ return {+ id: resume.id,+ name: resume.name,+ updatedAt: resume.updatedAt.toISOString(),+ patchRoot: "data",+ patchPathExamples: {+ visibleName: "/basics/name",+ },+ patchNotes: [+ "apply_resume_patch paths are rooted at the `data` object below.",+ "Do not prefix paths with `/data`.",+ "The resume file/title `name` metadata is read-only for apply_resume_patch.",+ ],+ data: resume.data,+ };+ },+ readAttachment: (attachmentId) =>+ readAttachment({ id: attachmentId, threadId: input.threadId, userId: input.userId }),+ applyResumePatch: ({ title, summary, operations }) =>+ applyResumePatch({+ userId: input.userId,+ threadId: input.threadId,+ resumeId: input.resumeId,+ title,+ ...(summary !== undefined ? { summary } : {}),+ operations,+ }),+ },+ });++ return new ToolLoopAgent({+ model: input.model,+ instructions: buildAgentInstructions({ hasProviderNativeSearch: "web_search" in tools }),+ stopWhen: stepCountIs(MAX_AGENT_STEPS),+ tools,+ });+}++export const agentService = {+ threads: {+ list: async (input: { userId: string }) => {+ assertAgentEnvironment();++ const rows = await db+ .select({+ id: schema.agentThread.id,+ userId: schema.agentThread.userId,+ aiProviderId: schema.agentThread.aiProviderId,+ sourceResumeId: schema.agentThread.sourceResumeId,+ workingResumeId: schema.agentThread.workingResumeId,+ title: schema.agentThread.title,+ status: schema.agentThread.status,+ activeRunId: schema.agentThread.activeRunId,+ activeStreamId: schema.agentThread.activeStreamId,+ activeRunStartedAt: schema.agentThread.activeRunStartedAt,+ lastMessageAt: schema.agentThread.lastMessageAt,+ archivedAt: schema.agentThread.archivedAt,+ deletedAt: schema.agentThread.deletedAt,+ createdAt: schema.agentThread.createdAt,+ updatedAt: schema.agentThread.updatedAt,+ resumeName: schema.resume.name,+ providerLabel: schema.aiProvider.label,+ })+ .from(schema.agentThread)+ .leftJoin(schema.resume, eq(schema.agentThread.workingResumeId, schema.resume.id))+ .leftJoin(schema.aiProvider, eq(schema.agentThread.aiProviderId, schema.aiProvider.id))+ .where(and(eq(schema.agentThread.userId, input.userId), isNull(schema.agentThread.deletedAt)))+ .orderBy(desc(schema.agentThread.lastMessageAt));++ return rows.map(toThreadSummary);+ },++ create: async (input: CreateThreadInput) => {+ assertAgentEnvironment();++ const selectedProvider = input.aiProviderId+ ? await aiProvidersService.getRunnableById({ id: input.aiProviderId, userId: input.userId })+ : await aiProvidersService.getDefaultRunnable({ userId: input.userId });++ if (!selectedProvider) throw new ORPCError("BAD_REQUEST", { message: "No tested AI provider is available." });++ const working = await createWorkingResume(input);+ const [thread] = await db+ .insert(schema.agentThread)+ .values({+ userId: input.userId,+ aiProviderId: selectedProvider.id,+ sourceResumeId: input.sourceResumeId ?? null,+ workingResumeId: working.id,+ title: "New thread",+ })+ .returning();++ if (!thread) throw new Error("AGENT_THREAD_CREATE_FAILED");++ return toThreadSummary({+ ...thread,+ resumeName: working.title,+ providerLabel: selectedProvider.label,+ });+ },++ get: async (input: { id: string; userId: string }) => {+ assertAgentEnvironment();++ const thread = await getThread(input);+ const [messages, actions, attachments, resume] = await Promise.all([+ listThreadMessages({ threadId: input.id, userId: input.userId }),+ db+ .select()+ .from(schema.agentAction)+ .where(and(eq(schema.agentAction.threadId, input.id), eq(schema.agentAction.userId, input.userId)))+ .orderBy(desc(schema.agentAction.createdAt)),+ db+ .select()+ .from(schema.agentAttachment)+ .where(and(eq(schema.agentAttachment.threadId, input.id), eq(schema.agentAttachment.userId, input.userId)))+ .orderBy(asc(schema.agentAttachment.createdAt)),+ thread.workingResumeId+ ? resumeService.getById({ id: thread.workingResumeId, userId: input.userId }).catch(() => null)+ : null,+ ]);++ return {+ thread: toThreadSummary(thread),+ messages: messages.map(toMessage),+ actions: actions.map(toAction),+ attachments: attachments.map(toAttachment),+ resume,+ isReadOnly: thread.status === "archived" || !thread.workingResumeId || !thread.aiProviderId || !resume,+ };+ },++ archive: async (input: { id: string; userId: string }) => {+ assertAgentEnvironment();++ const thread = await getThread({ id: input.id, userId: input.userId });+ const activeRunId = thread.activeRunId;+ const activeStreamId = thread.activeStreamId;++ if (activeRunId) {+ activeRunControllers.get(activeRunId)?.abort("USER_ARCHIVED");+ activeRunControllers.delete(activeRunId);+ try {+ await clearActiveAgentRunIfCurrent({+ threadId: input.id,+ userId: input.userId,+ runId: activeRunId,+ streamId: activeStreamId,+ });+ } catch (error) {+ console.error("[agent] Failed to clear active run during archive", error);+ }+ }++ await db+ .update(schema.agentThread)+ .set({ status: "archived", archivedAt: new Date() })+ .where(and(eq(schema.agentThread.id, input.id), eq(schema.agentThread.userId, input.userId)));+ },++ delete: async (input: { id: string; userId: string }) => {+ assertAgentEnvironment();++ await getThread({ id: input.id, userId: input.userId });++ await getStorageService().delete(`uploads/${input.userId}/agent/${input.id}`);+ await db.delete(schema.agentAttachment).where(eq(schema.agentAttachment.threadId, input.id));+ await db+ .update(schema.agentThread)+ .set({ status: "deleted", deletedAt: new Date() })+ .where(and(eq(schema.agentThread.id, input.id), eq(schema.agentThread.userId, input.userId)));+ },+ },++ messages: {+ send: async (input: SendMessageInput) => {+ assertAgentEnvironment();++ const thread = await getThread({ id: input.threadId, userId: input.userId });+ if (thread.status === "archived") {+ throw new ORPCError("CONFLICT", { message: "This thread is archived." });+ }+ if (thread.activeRunId) {+ throw new ORPCError("CONFLICT", { message: "This thread already has an active run." });+ }+ if (!thread.workingResumeId || !thread.aiProviderId) {+ throw new ORPCError("BAD_REQUEST", { message: "This thread is read-only." });+ }+ if (input.message.role !== "user" && input.message.role !== "assistant") {+ throw new ORPCError("BAD_REQUEST", { message: "Agent messages must be user messages or tool results." });+ }++ const runnableProvider = await aiProvidersService.getRunnableById({+ id: thread.aiProviderId,+ userId: input.userId,+ });+ const attachments = await getUnlinkedMessageAttachments({+ ids: input.attachmentIds ?? [],+ threadId: input.threadId,+ userId: input.userId,+ });+ const runId = generateId();+ const streamId = generateId();+ const controller = new AbortController();+ activeRunControllers.set(runId, controller);++ const claimed = await claimActiveAgentRun({ threadId: input.threadId, userId: input.userId, runId, streamId });+ if (!claimed) {+ activeRunControllers.delete(runId);+ throw new ORPCError("CONFLICT", { message: "This thread already has an active run." });+ }++ try {+ let attachmentsForModel: AgentAttachmentRecord[] = [];++ if (input.message.role === "assistant") {+ if (attachments.length > 0) {+ throw new ORPCError("BAD_REQUEST", { message: "Tool result messages cannot include attachments." });+ }++ await updateAssistantToolResultMessage({+ userId: input.userId,+ threadId: input.threadId,+ message: input.message,+ });+ } else {+ attachmentsForModel = attachments;+ const sequence = await getNextMessageSequence(input.threadId);+ const userMessage = withAttachmentUiParts(input.message, attachments);+ const persistedUserMessage = await persistMessage({+ userId: input.userId,+ threadId: input.threadId,+ message: userMessage,+ sequence,+ });+ if (!persistedUserMessage) throw new Error("AGENT_MESSAGE_CREATE_FAILED");+ await linkAttachmentsToMessage({+ attachments,+ messageId: persistedUserMessage.id,+ threadId: input.threadId,+ userId: input.userId,+ });++ const [messageCount] = await db+ .select({ total: count() })+ .from(schema.agentMessage)+ .where(eq(schema.agentMessage.threadId, input.threadId));++ if ((messageCount?.total ?? 0) === 1) {+ await db+ .update(schema.agentThread)+ .set({ title: buildThreadTitle(userMessage, thread.title) })+ .where(and(eq(schema.agentThread.id, input.threadId), eq(schema.agentThread.userId, input.userId)));+ }+ }++ await aiProvidersService.markUsed({ id: runnableProvider.id, userId: input.userId });++ const messageRows = await repairLegacyAskUserQuestionAnswers(+ await listThreadMessages({ threadId: input.threadId, userId: input.userId }),+ { threadId: input.threadId, userId: input.userId },+ );+ const messages = messageRows.map(toMessage);+ const modelMessages = await convertToModelMessages(messages.map(withoutAgentAttachmentUiParts));+ const attachmentModelParts = buildAttachmentModelParts(await readAttachmentModelInputs(attachmentsForModel));+ const agent = createAgent({+ userId: input.userId,+ threadId: input.threadId,+ resumeId: thread.workingResumeId,+ provider: {+ provider: runnableProvider.provider,+ model: runnableProvider.model,+ apiKey: runnableProvider.apiKey,+ baseURL: runnableProvider.baseURL ?? "",+ },+ model: getAgentModel({+ provider: runnableProvider.provider,+ model: runnableProvider.model,+ apiKey: runnableProvider.apiKey,+ baseURL: runnableProvider.baseURL ?? "",+ }),+ });++ const result = await agent.stream({+ messages: attachModelPartsToLatestUserMessage(modelMessages, attachmentModelParts),+ abortSignal: controller.signal,+ });++ return streamToEventIterator(+ await agentStreamLifecycle.create(streamId, () =>+ result.toUIMessageStream({+ originalMessages: messages,+ generateMessageId: generateId,+ sendSources: true,+ onFinish: async ({ responseMessage, isAborted }) => {+ let persistError: unknown;+ try {+ if (!(isAborted && canceledRunsWithPersistedPartial.has(runId))) {+ await persistMessage({+ userId: input.userId,+ threadId: input.threadId,+ message: responseMessage,+ status: isAborted ? "canceled" : "completed",+ });+ }+ } catch (error) {+ persistError = error;+ throw error;+ } finally {+ await cleanupActiveRun({+ threadId: input.threadId,+ userId: input.userId,+ runId,+ streamId,+ primaryError: persistError,+ });+ }+ },+ onError: (error) => (error instanceof Error ? error.message : "Agent run failed."),+ }),+ ),+ );+ } catch (error) {+ await cleanupActiveRun({+ threadId: input.threadId,+ userId: input.userId,+ runId,+ streamId,+ primaryError: error,+ });+ throw error;+ }+ },++ stop: async (input: { userId: string; threadId: string; partialMessage?: UIMessage }) => {+ assertAgentEnvironment();++ const thread = await getThread({ id: input.threadId, userId: input.userId });+ const activeRunId = thread.activeRunId;+ const activeStreamId = thread.activeStreamId;++ let persistError: unknown;+ let cleanupError: unknown;+ try {+ if (input.partialMessage) {+ await persistMessage({+ userId: input.userId,+ threadId: input.threadId,+ message: input.partialMessage,+ status: "canceled",+ });+ if (activeRunId) canceledRunsWithPersistedPartial.add(activeRunId);+ }+ } catch (error) {+ persistError = error;+ } finally {+ if (activeRunId) {+ activeRunControllers.get(activeRunId)?.abort("USER_STOPPED");+ activeRunControllers.delete(activeRunId);+ try {+ await clearActiveAgentRunIfCurrent({+ threadId: input.threadId,+ userId: input.userId,+ runId: activeRunId,+ streamId: activeStreamId,+ });+ } catch (error) {+ cleanupError = error;+ if (persistError) console.error("[agent] Failed to clear active run after stop persistence error", error);+ }+ }+ }++ if (persistError) throw persistError;+ if (cleanupError) throw cleanupError;+ },+ resume: async (input: { userId: string; threadId: string }) => {+ assertAgentEnvironment();+ const thread = await getThread({ id: input.threadId, userId: input.userId });+ return streamToEventIterator(await agentStreamLifecycle.resume(thread.activeStreamId));+ },+ },++ attachments: {+ create: async (input: CreateAttachmentInput) => {+ assertAgentEnvironment();+ await getThread({ id: input.threadId, userId: input.userId });++ const [aggregate] = await db+ .select({ totalBytes: sql<number>`coalesce(sum(${schema.agentAttachment.size}), 0)` })+ .from(schema.agentAttachment)+ .where(+ and(eq(schema.agentAttachment.threadId, input.threadId), eq(schema.agentAttachment.userId, input.userId)),+ );++ const [attachmentCount] = await db+ .select({ total: count() })+ .from(schema.agentAttachment)+ .where(+ and(eq(schema.agentAttachment.threadId, input.threadId), eq(schema.agentAttachment.userId, input.userId)),+ );++ if ((attachmentCount?.total ?? 0) >= MAX_ATTACHMENTS_PER_MESSAGE) throw new ORPCError("BAD_REQUEST");+ if (input.data.byteLength > MAX_ATTACHMENT_BYTES) throw new ORPCError("BAD_REQUEST");+ if ((aggregate?.totalBytes ?? 0) + input.data.byteLength > MAX_THREAD_ATTACHMENT_BYTES) {+ throw new ORPCError("BAD_REQUEST");+ }++ const mediaType = input.mediaType || inferContentType(input.filename);+ const id = generateId();+ const key = `uploads/${input.userId}/agent/${input.threadId}/${id}-${input.filename}`;++ await getStorageService().write({ key, data: input.data, contentType: mediaType, private: true });+ const [attachment] = await db+ .insert(schema.agentAttachment)+ .values({+ id,+ userId: input.userId,+ threadId: input.threadId,+ storageKey: key,+ filename: input.filename,+ mediaType,+ size: input.data.byteLength,+ })+ .returning();++ if (!attachment) throw new Error("AGENT_ATTACHMENT_CREATE_FAILED");++ return toAttachment(attachment);+ },++ delete: async (input: { id: string; userId: string }) => {+ assertAgentEnvironment();++ const [attachment] = await db+ .select()+ .from(schema.agentAttachment)+ .where(and(eq(schema.agentAttachment.id, input.id), eq(schema.agentAttachment.userId, input.userId)))+ .limit(1);++ if (!attachment) return;++ await getStorageService().delete(attachment.storageKey);+ await db+ .delete(schema.agentAttachment)+ .where(and(eq(schema.agentAttachment.id, input.id), eq(schema.agentAttachment.userId, input.userId)));+ },+ },++ actions: {+ revert: async (input: { id: string; userId: string }) => {+ assertAgentEnvironment();++ const [action] = await db+ .select()+ .from(schema.agentAction)+ .where(and(eq(schema.agentAction.id, input.id), eq(schema.agentAction.userId, input.userId)))+ .limit(1);++ if (!action) throw new ORPCError("NOT_FOUND");+ if (action.status === "reverted") return toAction(action);+ if (!action.resumeId) throw new ORPCError("BAD_REQUEST", { message: "The edited resume no longer exists." });++ try {+ const { updated, reverted } = await db.transaction(async (tx) => {+ const reverted = await resumeService.patchInTransaction(tx, {+ id: action.resumeId as string,+ userId: input.userId,+ operations: action.inverseOperations,+ expectedUpdatedAt: action.appliedUpdatedAt,+ });++ const [updated] = await tx+ .update(schema.agentAction)+ .set({+ status: "reverted",+ revertedAt: new Date(),+ revertMessage: null,+ appliedUpdatedAt: reverted.updatedAt,+ })+ .where(and(eq(schema.agentAction.id, input.id), eq(schema.agentAction.userId, input.userId)))+ .returning();++ if (!updated) throw new ORPCError("NOT_FOUND");+ return { updated, reverted };+ });++ await resumeService.notifyResumePatched({+ resumeId: reverted.id,+ userId: input.userId,+ updatedAt: reverted.updatedAt,+ });++ return toAction(updated);+ } catch (error) {+ if (error instanceof ORPCError && error.code === "RESUME_VERSION_CONFLICT") {+ const [updated] = await db+ .update(schema.agentAction)+ .set({ status: "conflicted", revertMessage: "The resume changed after this action was applied." })+ .where(and(eq(schema.agentAction.id, input.id), eq(schema.agentAction.userId, input.userId)))+ .returning();++ if (!updated) throw new ORPCError("NOT_FOUND");++ return toAction(updated);+ }++ throw error;+ }+ },+ },+};diff --git a/packages/api/src/services/ai-capabilities.test.ts b/packages/api/src/services/ai-capabilities.test.tsnew file mode 100644index 000000000..17e8f0c46--- /dev/null+++ b/packages/api/src/services/ai-capabilities.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import { isDirectOpenAIProvider, supportsOpenAIWebSearch } from "./ai-capabilities";++describe("AI provider capabilities", () => {+ it("identifies direct OpenAI base URL configs", () => {+ expect(isDirectOpenAIProvider({ provider: "openai", baseURL: "" })).toBe(true);+ expect(isDirectOpenAIProvider({ provider: "openai", baseURL: "https://api.openai.com/v1/" })).toBe(true);+ expect(isDirectOpenAIProvider({ provider: "openai", baseURL: "https://example.com/v1" })).toBe(false);+ expect(isDirectOpenAIProvider({ provider: "openai", baseURL: "https://api.openai.com/v1?proxy=1" })).toBe(false);+ expect(isDirectOpenAIProvider({ provider: "openai", baseURL: "https://api.openai.com/v1#fragment" })).toBe(false);+ expect(isDirectOpenAIProvider({ provider: "openrouter", baseURL: "https://api.openai.com/v1" })).toBe(false);+ });++ it("keeps the OpenAI web search model predicate conservative", () => {+ const allowedModels = [+ "gpt-5.5",+ "gpt-5.5-2026-04-23",+ "gpt-5.5-pro",+ "gpt-5.5-pro-2026-04-23",+ "gpt-5.4",+ "gpt-5.4-2026-03-05",+ "gpt-5.4-mini",+ "gpt-5.4-mini-2026-03-17",+ "gpt-5.4-nano",+ "gpt-5.4-nano-2026-03-17",+ "gpt-5.4-pro",+ "gpt-5.4-pro-2026-03-05",+ "gpt-5",+ "gpt-5-2025-08-07",+ "gpt-5-mini",+ "gpt-5-mini-2025-08-07",+ "gpt-5-nano",+ "gpt-5-nano-2025-08-07",+ "gpt-4.1",+ "gpt-4.1-2025-04-14",+ "gpt-4.1-mini",+ "gpt-4.1-mini-2025-04-14",+ "o4-mini",+ "o4-mini-2025-04-16",+ ];+ const deniedModels = [+ "gpt-4.1-nano",+ "gpt-4.1-nano-2025-04-14",+ "gpt-4o",+ "gpt-4o-mini",+ "gpt-4o-search-preview",+ "o1",+ "o1-2024-12-17",+ "o3",+ "o3-mini",+ "gpt-3.5-turbo",+ "gpt-5-codex",+ "gpt-5.1-codex",+ "gpt-5.5-codex",+ "gpt-4x1-2025-04-14",+ "gpt-5x5-2026-04-23",+ "gpt-5x5-pro-2026-04-23",+ "custom-model",+ ];++ for (const model of allowedModels) {+ expect(supportsOpenAIWebSearch(model), model).toBe(true);+ }++ for (const model of deniedModels) {+ expect(supportsOpenAIWebSearch(model), model).toBe(false);+ }+ });+});diff --git a/packages/api/src/services/ai-capabilities.ts b/packages/api/src/services/ai-capabilities.tsnew file mode 100644index 000000000..1a690be13--- /dev/null+++ b/packages/api/src/services/ai-capabilities.ts@@ -0,0 +1,90 @@+import type { AIProvider } from "@reactive-resume/ai/types";+import { AI_PROVIDER_DEFAULT_BASE_URLS } from "@reactive-resume/ai/types";++type AiProviderCapabilityInput = {+ provider: AIProvider;+ model: string;+ baseURL?: string | null;+};++function normalizeDirectOpenAIBaseUrl(baseURL: string) {+ try {+ const parsed = new URL(baseURL);+ if (parsed.search || parsed.hash) return null;+ return parsed.toString().replace(/\/+$/, "");+ } catch {+ return baseURL.trim().replace(/\/+$/, "");+ }+}++export function isDirectOpenAIProvider(input: Pick<AiProviderCapabilityInput, "provider" | "baseURL">) {+ if (input.provider !== "openai") return false;+ if (!input.baseURL?.trim()) return true;++ const baseURL = normalizeDirectOpenAIBaseUrl(input.baseURL);+ if (!baseURL) return false;++ return baseURL === normalizeDirectOpenAIBaseUrl(AI_PROVIDER_DEFAULT_BASE_URLS.openai);+}++const OPENAI_WEB_SEARCH_RESPONSES_MODEL_IDS = new Set([+ // Snapshot from official OpenAI model docs on 2026-05-13. These model pages list Responses+ // API support and Responses web search support. Most are also explicit in installed+ // @ai-sdk/openai OpenAIResponsesModelId; gpt-5.5-pro is accepted through the SDK's string+ // model ID fallback and openai.responses("gpt-5.5-pro") runtime construction.+ // https://developers.openai.com/api/docs/models/gpt-5.5-pro+ "gpt-5.5-pro",+ // https://developers.openai.com/api/docs/models/gpt-5.5+ "gpt-5.5",+ // https://developers.openai.com/api/docs/models/gpt-5.4+ "gpt-5.4",+ // https://developers.openai.com/api/docs/models/gpt-5.4-mini+ "gpt-5.4-mini",+ // https://developers.openai.com/api/docs/models/gpt-5.4-nano+ "gpt-5.4-nano",+ // https://developers.openai.com/api/docs/models/gpt-5.4-pro+ "gpt-5.4-pro",+ // https://developers.openai.com/api/docs/models/gpt-5+ "gpt-5",+ // https://developers.openai.com/api/docs/models/gpt-5-mini+ "gpt-5-mini",+ // https://developers.openai.com/api/docs/models/gpt-5-nano+ "gpt-5-nano",+ // https://developers.openai.com/api/docs/models/gpt-4.1+ "gpt-4.1",+ // https://developers.openai.com/api/docs/models/gpt-4.1-mini+ "gpt-4.1-mini",+ // https://developers.openai.com/api/docs/guides/tools-web-search?api-mode=responses+ "o4-mini",+]);++function isDateSnapshotForModel(model: string, modelId: string) {+ const snapshotPrefix = `${modelId}-`;+ if (!model.startsWith(snapshotPrefix)) return false;++ const suffix = model.slice(snapshotPrefix.length);+ const [year, month, day] = suffix.split("-");++ return (+ suffix.length === "YYYY-MM-DD".length &&+ year?.length === 4 &&+ month?.length === 2 &&+ day?.length === 2 &&+ [year, month, day].every((part) => /^\d+$/.test(part))+ );+}++export function supportsOpenAIWebSearch(model: string) {+ const normalized = model.trim().toLowerCase();+ if (!normalized || normalized.includes("codex")) return false;++ if (OPENAI_WEB_SEARCH_RESPONSES_MODEL_IDS.has(normalized)) return true;++ return Array.from(OPENAI_WEB_SEARCH_RESPONSES_MODEL_IDS).some((modelId) =>+ isDateSnapshotForModel(normalized, modelId),+ );+}++export function supportsProviderNativeWebSearch(provider: AiProviderCapabilityInput) {+ return isDirectOpenAIProvider(provider) && supportsOpenAIWebSearch(provider.model);+}diff --git a/packages/api/src/services/ai-credentials.test.ts b/packages/api/src/services/ai-credentials.test.tsnew file mode 100644index 000000000..5020b2da2--- /dev/null+++ b/packages/api/src/services/ai-credentials.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it, vi } from "vitest";++const envMock = vi.hoisted(() => ({+ ENCRYPTION_SECRET: "test-secret-with-enough-entropy",+ REDIS_URL: "redis://localhost:6379",+}));++vi.mock("@reactive-resume/env/server", () => ({ env: envMock }));++const {+ assertAgentEnvironment,+ decryptCredential,+ encryptCredential,+ fingerprintCredential,+ isAgentEnvironmentConfigured,+ redactEncryptedCredential,+} = await import("./ai-credentials");++describe("AI credential encryption", () => {+ it("encrypts and decrypts provider API keys without storing plaintext", () => {+ const encrypted = encryptCredential("sk-test-secret");++ expect(encrypted.encryptedApiKey).not.toContain("sk-test-secret");+ expect(encrypted.apiKeyPreview).toBe("sk-t...cret");+ expect(decryptCredential(encrypted.encryptedApiKey)).toBe("sk-test-secret");+ });++ it("generates salted non-revealable fingerprints", () => {+ const first = fingerprintCredential("sk-test-secret", "salt-a");+ const again = fingerprintCredential("sk-test-secret", "salt-a");+ const differentSalt = fingerprintCredential("sk-test-secret", "salt-b");++ expect(first).toBe(again);+ expect(first).not.toBe(differentSalt);+ expect(first).not.toContain("sk-test-secret");+ });++ it("redacts stored encrypted credential fields from API responses", () => {+ const encrypted = encryptCredential("sk-test-secret");++ const redacted = redactEncryptedCredential({+ encryptedApiKey: encrypted.encryptedApiKey,+ apiKeySalt: encrypted.apiKeySalt,+ apiKeyHash: encrypted.apiKeyHash,+ apiKeyPreview: encrypted.apiKeyPreview,+ });++ expect(redacted).toEqual({+ apiKeyFingerprint: encrypted.apiKeyHash,+ apiKeyPreview: encrypted.apiKeyPreview,+ });+ expect(JSON.stringify(redacted)).not.toContain(encrypted.encryptedApiKey);+ expect(JSON.stringify(redacted)).not.toContain(encrypted.apiKeySalt);+ });+});++describe("AI agent environment", () => {+ it("is available only when Redis and encryption secret are configured", () => {+ expect(isAgentEnvironmentConfigured()).toBe(true);+ expect(() => assertAgentEnvironment()).not.toThrow();++ envMock.REDIS_URL = "";+ expect(isAgentEnvironmentConfigured()).toBe(false);+ expect(() => assertAgentEnvironment()).toThrow("AGENT_ENVIRONMENT_UNAVAILABLE");++ envMock.REDIS_URL = "redis://localhost:6379";+ envMock.ENCRYPTION_SECRET = "";+ expect(isAgentEnvironmentConfigured()).toBe(false);+ expect(() => assertAgentEnvironment()).toThrow("AGENT_ENVIRONMENT_UNAVAILABLE");+ });+});diff --git a/packages/api/src/services/ai-credentials.ts b/packages/api/src/services/ai-credentials.tsnew file mode 100644index 000000000..c1791e547--- /dev/null+++ b/packages/api/src/services/ai-credentials.ts@@ -0,0 +1,113 @@+import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";+import { env } from "@reactive-resume/env/server";++const CIPHER = "aes-256-gcm";+const CREDENTIAL_VERSION = "v1";+const IV_BYTES = 12;+const SALT_BYTES = 16;++type StoredCredentialFields = {+ encryptedApiKey: string;+ apiKeySalt: string;+ apiKeyHash: string;+ apiKeyPreview: string;+};++type RedactedCredentialFields = {+ apiKeyFingerprint: string;+ apiKeyPreview: string;+};++function getEncryptionSecret() {+ return env.ENCRYPTION_SECRET?.trim() ?? "";+}++function getEncryptionKey() {+ const secret = getEncryptionSecret();+ if (!secret) throw new Error("AI_CREDENTIAL_ENCRYPTION_UNAVAILABLE");++ return createHash("sha256").update(secret).digest();+}++function encode(value: Buffer) {+ return value.toString("base64url");+}++function decode(value: string) {+ return Buffer.from(value, "base64url");+}++function makePreview(apiKey: string) {+ const trimmed = apiKey.trim();+ if (trimmed.length <= 8) return "••••";++ return `${trimmed.slice(0, 4)}...${trimmed.slice(-4)}`;+}++export function fingerprintCredential(apiKey: string, salt: string) {+ return createHash("sha256").update(salt).update(":").update(apiKey).digest("hex");+}++export function encryptCredential(apiKey: string): StoredCredentialFields {+ const iv = randomBytes(IV_BYTES);+ const salt = encode(randomBytes(SALT_BYTES));+ const cipher = createCipheriv(CIPHER, getEncryptionKey(), iv);++ const ciphertext = Buffer.concat([cipher.update(apiKey, "utf8"), cipher.final()]);+ const authTag = cipher.getAuthTag();+ const payload = [CREDENTIAL_VERSION, encode(iv), encode(authTag), encode(ciphertext)].join(".");++ return {+ encryptedApiKey: payload,+ apiKeySalt: salt,+ apiKeyHash: fingerprintCredential(apiKey, salt),+ apiKeyPreview: makePreview(apiKey),+ };+}++export function decryptCredential(payload: string) {+ const [version, encodedIv, encodedAuthTag, encodedCiphertext] = payload.split(".");+ if (version !== CREDENTIAL_VERSION || !encodedIv || !encodedAuthTag || !encodedCiphertext) {+ throw new Error("INVALID_ENCRYPTED_CREDENTIAL");+ }++ const decipher = createDecipheriv(CIPHER, getEncryptionKey(), decode(encodedIv));+ decipher.setAuthTag(decode(encodedAuthTag));++ return Buffer.concat([decipher.update(decode(encodedCiphertext)), decipher.final()]).toString("utf8");+}++export function credentialMatchesFingerprint(input: { apiKey: string; salt: string; hash: string }) {+ const nextHash = fingerprintCredential(input.apiKey, input.salt);+ const current = Buffer.from(input.hash, "hex");+ const next = Buffer.from(nextHash, "hex");++ return current.length === next.length && timingSafeEqual(current, next);+}++export function redactEncryptedCredential(fields: StoredCredentialFields): RedactedCredentialFields {+ return {+ apiKeyFingerprint: fields.apiKeyHash,+ apiKeyPreview: fields.apiKeyPreview,+ };+}++export function isCredentialEncryptionConfigured() {+ return !!getEncryptionSecret();+}++export function isAgentStreamingConfigured() {+ return !!env.REDIS_URL?.trim();+}++export function isAgentEnvironmentConfigured() {+ return isCredentialEncryptionConfigured() && isAgentStreamingConfigured();+}++export function assertCredentialEncryptionConfigured() {+ if (!isCredentialEncryptionConfigured()) throw new Error("AI_CREDENTIAL_ENCRYPTION_UNAVAILABLE");+}++export function assertAgentEnvironment() {+ if (!isAgentEnvironmentConfigured()) throw new Error("AGENT_ENVIRONMENT_UNAVAILABLE");+}diff --git a/packages/api/src/services/ai-providers.ts b/packages/api/src/services/ai-providers.tsnew file mode 100644index 000000000..bda35c145--- /dev/null+++ b/packages/api/src/services/ai-providers.ts@@ -0,0 +1,275 @@+import type { AIProvider } from "@reactive-resume/ai/types";+import { ORPCError } from "@orpc/client";+import { and, asc, desc, eq, sql } from "drizzle-orm";+import { aiProviderSchema } from "@reactive-resume/ai/types";+import { db } from "@reactive-resume/db/client";+import * as schema from "@reactive-resume/db/schema";+import { testConnection } from "./ai";+import {+ assertCredentialEncryptionConfigured,+ decryptCredential,+ encryptCredential,+ redactEncryptedCredential,+} from "./ai-credentials";+import { resolveAiBaseUrl } from "./ai-url-policy";++type AiProviderRecord = typeof schema.aiProvider.$inferSelect;++export type AiProviderResponse = {+ id: string;+ label: string;+ provider: AIProvider;+ model: string;+ baseURL: string | null;+ enabled: boolean;+ testStatus: string;+ testError: string | null;+ apiKeyPreview: string;+ apiKeyFingerprint: string;+ lastTestedAt: Date | null;+ lastUsedAt: Date | null;+ createdAt: Date;+ updatedAt: Date;+};++type CreateAiProviderInput = {+ userId: string;+ label: string;+ provider: AIProvider;+ model: string;+ baseURL?: string | null;+ apiKey: string;+};++type UpdateAiProviderInput = {+ id: string;+ userId: string;+ label?: string;+ provider?: AIProvider;+ model?: string;+ baseURL?: string | null;+ apiKey?: string;+ enabled?: boolean;+};++function toResponse(row: AiProviderRecord): AiProviderResponse {+ const provider = aiProviderSchema.parse(row.provider);+ const { apiKeyFingerprint, apiKeyPreview } = redactEncryptedCredential({+ encryptedApiKey: row.encryptedApiKey,+ apiKeySalt: row.apiKeySalt,+ apiKeyHash: row.apiKeyHash,+ apiKeyPreview: row.apiKeyPreview,+ });++ return {+ id: row.id,+ label: row.label,+ provider,+ model: row.model,+ baseURL: row.baseUrl,+ enabled: row.enabled,+ testStatus: row.testStatus,+ testError: row.testError,+ apiKeyPreview,+ apiKeyFingerprint,+ lastTestedAt: row.lastTestedAt,+ lastUsedAt: row.lastUsedAt,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++function normalizeBaseUrl(input: { provider: AIProvider; baseURL?: string | null }) {+ const trimmed = input.baseURL?.trim() ?? "";+ if (!trimmed) return null;++ return resolveAiBaseUrl({ provider: input.provider, baseURL: trimmed });+}++function orderByLastUsedAtDescNullsLast() {+ return desc(sql<Date>`coalesce(${schema.aiProvider.lastUsedAt}, '1970-01-01T00:00:00.000Z'::timestamptz)`);+}++async function getOwnedProvider(input: { id: string; userId: string }) {+ const [provider] = await db+ .select()+ .from(schema.aiProvider)+ .where(and(eq(schema.aiProvider.id, input.id), eq(schema.aiProvider.userId, input.userId)))+ .limit(1);++ if (!provider) throw new ORPCError("NOT_FOUND");++ return provider;+}++export const aiProvidersService = {+ list: async (input: { userId: string }) => {+ assertCredentialEncryptionConfigured();++ const providers = await db+ .select()+ .from(schema.aiProvider)+ .where(eq(schema.aiProvider.userId, input.userId))+ .orderBy(orderByLastUsedAtDescNullsLast(), asc(schema.aiProvider.createdAt));++ return providers.map(toResponse);+ },++ getRunnableById: async (input: { id: string; userId: string }) => {+ assertCredentialEncryptionConfigured();++ const provider = await getOwnedProvider(input);+ if (!provider.enabled || provider.testStatus !== "success") {+ throw new ORPCError("BAD_REQUEST", { message: "AI provider must be tested and enabled before use." });+ }++ return {+ ...toResponse(provider),+ apiKey: decryptCredential(provider.encryptedApiKey),+ baseURL: provider.baseUrl ?? "",+ };+ },++ getDefaultRunnable: async (input: { userId: string }) => {+ assertCredentialEncryptionConfigured();++ const [provider] = await db+ .select()+ .from(schema.aiProvider)+ .where(+ and(+ eq(schema.aiProvider.userId, input.userId),+ eq(schema.aiProvider.enabled, true),+ eq(schema.aiProvider.testStatus, "success"),+ ),+ )+ .orderBy(orderByLastUsedAtDescNullsLast(), asc(schema.aiProvider.createdAt))+ .limit(1);++ return provider+ ? {+ ...toResponse(provider),+ apiKey: decryptCredential(provider.encryptedApiKey),+ baseURL: provider.baseUrl ?? "",+ }+ : null;+ },++ create: async (input: CreateAiProviderInput) => {+ assertCredentialEncryptionConfigured();++ const encrypted = encryptCredential(input.apiKey.trim());+ const [provider] = await db+ .insert(schema.aiProvider)+ .values({+ userId: input.userId,+ label: input.label.trim(),+ provider: input.provider,+ model: input.model.trim(),+ baseUrl: normalizeBaseUrl(input),+ ...encrypted,+ })+ .returning();++ if (!provider) throw new Error("AI_PROVIDER_CREATE_FAILED");++ return toResponse(provider);+ },++ update: async (input: UpdateAiProviderInput) => {+ assertCredentialEncryptionConfigured();++ const existing = await getOwnedProvider(input);+ const provider = input.provider ?? aiProviderSchema.parse(existing.provider);+ const nextApiKey = input.apiKey?.trim();+ const encrypted = nextApiKey ? encryptCredential(nextApiKey) : {};+ const credentialChanged = !!nextApiKey;+ const nextBaseUrl =+ input.baseURL !== undefined ? normalizeBaseUrl({ provider, baseURL: input.baseURL }) : existing.baseUrl;+ const providerChanged = input.provider !== undefined && input.provider !== existing.provider;+ const modelChanged = input.model !== undefined && input.model.trim() !== existing.model;+ const baseUrlChanged = input.baseURL !== undefined && nextBaseUrl !== existing.baseUrl;+ const runtimeChanged = credentialChanged || providerChanged || modelChanged || baseUrlChanged;++ if (input.enabled === true && existing.testStatus !== "success" && !runtimeChanged) {+ throw new ORPCError("BAD_REQUEST", { message: "AI provider must be tested successfully before enabling." });+ }++ const [updated] = await db+ .update(schema.aiProvider)+ .set({+ ...(input.label !== undefined ? { label: input.label.trim() } : {}),+ ...(input.provider !== undefined ? { provider: input.provider } : {}),+ ...(input.model !== undefined ? { model: input.model.trim() } : {}),+ ...(input.baseURL !== undefined ? { baseUrl: nextBaseUrl } : {}),+ ...(input.enabled !== undefined && !runtimeChanged ? { enabled: input.enabled } : {}),+ ...(runtimeChanged ? { enabled: false, testStatus: "untested", lastTestedAt: null, testError: null } : {}),+ ...encrypted,+ })+ .where(and(eq(schema.aiProvider.id, input.id), eq(schema.aiProvider.userId, input.userId)))+ .returning();++ if (!updated) throw new ORPCError("NOT_FOUND");+ return toResponse(updated);+ },++ delete: async (input: { id: string; userId: string }) => {+ assertCredentialEncryptionConfigured();++ await db+ .delete(schema.aiProvider)+ .where(and(eq(schema.aiProvider.id, input.id), eq(schema.aiProvider.userId, input.userId)));+ },++ test: async (input: { id: string; userId: string }) => {+ assertCredentialEncryptionConfigured();++ const provider = await getOwnedProvider(input);+ const parsedProvider = aiProviderSchema.parse(provider.provider);+ const apiKey = decryptCredential(provider.encryptedApiKey);++ try {+ const ok = await testConnection({+ provider: parsedProvider,+ model: provider.model,+ apiKey,+ baseURL: provider.baseUrl ?? "",+ });++ const [updated] = await db+ .update(schema.aiProvider)+ .set({+ enabled: ok,+ testStatus: ok ? "success" : "failure",+ testError: ok ? null : "The provider test returned an unexpected response.",+ lastTestedAt: new Date(),+ })+ .where(and(eq(schema.aiProvider.id, input.id), eq(schema.aiProvider.userId, input.userId)))+ .returning();++ if (!updated) throw new ORPCError("NOT_FOUND");+ return toResponse(updated);+ } catch (error) {+ const [updated] = await db+ .update(schema.aiProvider)+ .set({+ enabled: false,+ testStatus: "failure",+ testError: error instanceof Error ? error.message : "Failed to test provider.",+ lastTestedAt: new Date(),+ })+ .where(and(eq(schema.aiProvider.id, input.id), eq(schema.aiProvider.userId, input.userId)))+ .returning();++ if (!updated) throw error;+ throw error;+ }+ },++ markUsed: async (input: { id: string; userId: string }) => {+ await db+ .update(schema.aiProvider)+ .set({ lastUsedAt: new Date() })+ .where(and(eq(schema.aiProvider.id, input.id), eq(schema.aiProvider.userId, input.userId)));+ },+};diff --git a/packages/api/src/services/ai-url-policy.test.ts b/packages/api/src/services/ai-url-policy.test.tsnew file mode 100644index 000000000..f9fc6709c--- /dev/null+++ b/packages/api/src/services/ai-url-policy.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it, vi } from "vitest";++const envMock = vi.hoisted(() => ({+ FLAG_ALLOW_UNSAFE_AI_BASE_URL: false,+}));++vi.mock("@reactive-resume/env/server", () => ({ env: envMock }));++const { assertFetchablePublicHttpsUrl, resolveAiBaseUrl } = await import("./ai-url-policy");++describe("AI provider base URL policy", () => {+ it("allows public HTTPS provider URLs", () => {+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = false;++ expect(resolveAiBaseUrl({ provider: "openai", baseURL: "https://api.openai.com/v1" })).toBe(+ "https://api.openai.com/v1",+ );+ });++ it("blocks private and non-HTTPS provider URLs by default", () => {+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = false;++ expect(() => resolveAiBaseUrl({ provider: "openai-compatible", baseURL: "https://localhost:11434/v1" })).toThrow(+ "INVALID_AI_BASE_URL",+ );+ expect(() => resolveAiBaseUrl({ provider: "openai-compatible", baseURL: "http://example.com/v1" })).toThrow(+ "INVALID_AI_BASE_URL",+ );+ });++ it("allows private and non-HTTPS provider URLs when explicitly enabled", () => {+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = true;++ expect(resolveAiBaseUrl({ provider: "openai-compatible", baseURL: "http://localhost:11434/v1" })).toBe(+ "http://localhost:11434/v1",+ );+ expect(resolveAiBaseUrl({ provider: "openai-compatible", baseURL: "https://10.0.0.5/v1" })).toBe(+ "https://10.0.0.5/v1",+ );+ });++ it("rejects non-HTTP schemes even when unsafe provider URLs are enabled", () => {+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = true;++ expect(() => resolveAiBaseUrl({ provider: "openai-compatible", baseURL: "file:///etc/passwd" })).toThrow(+ "INVALID_AI_BASE_URL",+ );+ expect(() => resolveAiBaseUrl({ provider: "openai-compatible", baseURL: "ftp://example.com/v1" })).toThrow(+ "INVALID_AI_BASE_URL",+ );+ });++ it("keeps URL-fetch tools public HTTPS only even when unsafe provider URLs are enabled", () => {+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = true;++ expect(() => assertFetchablePublicHttpsUrl("https://localhost/internal-job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("http://example.com/job")).toThrow("URL_NOT_FETCHABLE");+ expect(assertFetchablePublicHttpsUrl("https://example.com/job")).toBe("https://example.com/job");+ });++ it("blocks special-use IP literals for URL-fetch tools", () => {+ envMock.FLAG_ALLOW_UNSAFE_AI_BASE_URL = true;++ expect(() => assertFetchablePublicHttpsUrl("https://100.64.0.1/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://192.0.2.1/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://192.88.99.1/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://198.18.0.1/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://198.51.100.1/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://203.0.113.1/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://224.0.0.1/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[::]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[::ffff:8.8.8.8]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[::ffff:0808:0808]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[64:ff9b::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[100::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[100:0:0:1::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[2001::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[2001:100::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[2001:2::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[2001:10::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[ff02::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[2001:db8::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[3fff::1]/job")).toThrow("URL_NOT_FETCHABLE");+ expect(() => assertFetchablePublicHttpsUrl("https://[5f00::1]/job")).toThrow("URL_NOT_FETCHABLE");+ });+});diff --git a/packages/api/src/services/ai-url-policy.ts b/packages/api/src/services/ai-url-policy.tsnew file mode 100644index 000000000..db63916ac--- /dev/null+++ b/packages/api/src/services/ai-url-policy.ts@@ -0,0 +1,35 @@+import type { AIProvider } from "@reactive-resume/ai/types";+import { AI_PROVIDER_DEFAULT_BASE_URLS } from "@reactive-resume/ai/types";+import { env } from "@reactive-resume/env/server";+import { isPrivateOrLoopbackHost, parseUrl } from "@reactive-resume/utils/url-security.node";++type ResolveAiBaseUrlInput = {+ provider: AIProvider;+ baseURL?: string | null;+};++function assertSafeUrl(input: string, errorCode: string, options?: { allowUnsafe?: boolean }) {+ const parsed = parseUrl(input);+ if (!parsed) throw new Error(errorCode);+ if (parsed.username || parsed.password) throw new Error(errorCode);+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(errorCode);++ if (!options?.allowUnsafe) {+ if (parsed.protocol !== "https:") throw new Error(errorCode);+ if (isPrivateOrLoopbackHost(parsed.hostname)) throw new Error(errorCode);+ }++ parsed.hash = "";+ return parsed.toString();+}++export function resolveAiBaseUrl(input: ResolveAiBaseUrlInput) {+ const baseURL = input.baseURL?.trim() || AI_PROVIDER_DEFAULT_BASE_URLS[input.provider];+ if (!baseURL) throw new Error("INVALID_AI_BASE_URL");++ return assertSafeUrl(baseURL, "INVALID_AI_BASE_URL", { allowUnsafe: env.FLAG_ALLOW_UNSAFE_AI_BASE_URL });+}++export function assertFetchablePublicHttpsUrl(input: string) {+ return assertSafeUrl(input, "URL_NOT_FETCHABLE");+}diff --git a/packages/api/src/services/ai.ts b/packages/api/src/services/ai.tsindex c09977bfd..3d23a2c5b 100644--- a/packages/api/src/services/ai.ts+++ b/packages/api/src/services/ai.ts@@ -26,11 +26,11 @@ import {resumePatchProposalToolInputSchema,resumePatchProposalToolOutputSchema,} from "@reactive-resume/ai/tools/patch-proposal";-import { AI_PROVIDER_DEFAULT_BASE_URLS, aiProviderSchema } from "@reactive-resume/ai/types";-import { env } from "@reactive-resume/env/server";+import { aiProviderSchema } from "@reactive-resume/ai/types";import { resumeAnalysisOutputSchema, resumeAnalysisSchema } from "@reactive-resume/schema/resume/analysis";import { applyResumePatches } from "@reactive-resume/utils/resume/patch";-import { isPrivateOrLoopbackHost, parseUrl } from "@reactive-resume/utils/url-security.node";+import { supportsProviderNativeWebSearch } from "./ai-capabilities";+import { resolveAiBaseUrl } from "./ai-url-policy";const aiExtractionTemplate = buildAiExtractionTemplate();@@ -73,26 +73,9 @@ type GetModelInput = {const MAX_AI_FILE_BYTES = 10 * 1024 * 1024; // 10MBconst MAX_AI_FILE_BASE64_CHARS = Math.ceil((MAX_AI_FILE_BYTES * 4) / 3) + 4;-function resolveBaseUrl(input: GetModelInput): string {- const baseURL = input.baseURL?.trim() || AI_PROVIDER_DEFAULT_BASE_URLS[input.provider];-- if (!baseURL) throw new Error("INVALID_AI_BASE_URL");-- const parsedBaseURL = parseUrl(baseURL);- if (!parsedBaseURL) throw new Error("INVALID_AI_BASE_URL");- if (parsedBaseURL.username || parsedBaseURL.password) throw new Error("INVALID_AI_BASE_URL");-- if (!env.FLAG_ALLOW_UNSAFE_AI_BASE_URL) {- if (parsedBaseURL.protocol !== "https:") throw new Error("INVALID_AI_BASE_URL");- if (isPrivateOrLoopbackHost(parsedBaseURL.hostname)) throw new Error("INVALID_AI_BASE_URL");- }-- return parsedBaseURL.toString();-}--function getModel(input: GetModelInput) {+export function getModel(input: GetModelInput) {const { provider, model, apiKey } = input;- const baseURL = resolveBaseUrl(input);+ const baseURL = resolveAiBaseUrl(input);return match(provider).with("openai", () => createOpenAI({ apiKey, baseURL }).chat(model))@@ -100,6 +83,9 @@ function getModel(input: GetModelInput) {.with("gemini", () => createGoogleGenerativeAI({ apiKey, baseURL }).languageModel(model)).with("vercel-ai-gateway", () => createGateway({ apiKey, baseURL }).languageModel(model)).with("openrouter", () => createOpenAICompatible({ name: "openrouter", apiKey, baseURL }).languageModel(model))+ .with("openai-compatible", () =>+ createOpenAICompatible({ name: "openai-compatible", apiKey, baseURL }).languageModel(model),+ ).with("ollama", () => {const ollama = createOllama({name: "ollama",@@ -112,6 +98,12 @@ function getModel(input: GetModelInput) {.exhaustive();}+export function getAgentModel(input: GetModelInput) {+ if (!supportsProviderNativeWebSearch(input)) return getModel(input);++ return createOpenAI({ apiKey: input.apiKey, baseURL: resolveAiBaseUrl(input) }).responses(input.model);+}+export const aiCredentialsSchema = z.object({provider: aiProviderSchema,model: z.string().trim().min(1),@@ -126,7 +118,7 @@ export const fileInputSchema = z.object({type TestConnectionInput = z.infer<typeof aiCredentialsSchema>;-async function testConnection(input: TestConnectionInput): Promise<boolean> {+export async function testConnection(input: TestConnectionInput): Promise<boolean> {const RESPONSE_OK = "1";const result = await generateText({diff --git a/packages/api/src/services/resume.ts b/packages/api/src/services/resume.tsindex 0021686a1..d86324bf4 100644--- a/packages/api/src/services/resume.ts+++ b/packages/api/src/services/resume.ts@@ -23,6 +23,82 @@ import {import { publishResumeUpdated } from "./resume-events";import { getStorageService } from "./storage";+type DbOrTx = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];++function resumeVersionConflict(updatedAt: Date) {+ return new ORPCError("RESUME_VERSION_CONFLICT", {+ status: 409,+ message: "The resume changed after this patch was generated.",+ data: { updatedAt: updatedAt.toISOString() },+ });+}++async function applyResumePatchTx(+ client: DbOrTx,+ input: { id: string; userId: string; operations: JsonPatchOperation[]; expectedUpdatedAt?: Date },+) {+ const [existing] = await client+ .select({ data: schema.resume.data, isLocked: schema.resume.isLocked, updatedAt: schema.resume.updatedAt })+ .from(schema.resume)+ .where(and(eq(schema.resume.id, input.id), eq(schema.resume.userId, input.userId)))+ .for("update");++ if (!existing) throw new ORPCError("NOT_FOUND");+ if (existing.isLocked) throw new ORPCError("RESUME_LOCKED");+ if (input.expectedUpdatedAt && existing.updatedAt.getTime() !== input.expectedUpdatedAt.getTime()) {+ throw resumeVersionConflict(existing.updatedAt);+ }++ let patchedData: ResumeData;++ try {+ patchedData = applyResumePatches(existing.data, input.operations);+ } catch (error) {+ if (error instanceof ResumePatchError) {+ throw new ORPCError("INVALID_PATCH_OPERATIONS", {+ status: 400,+ message: error.message,+ data: { code: error.code, index: error.index, operation: error.operation },+ });+ }++ throw new ORPCError("INVALID_PATCH_OPERATIONS", {+ status: 400,+ message: error instanceof Error ? error.message : "Failed to apply patch operations",+ });+ }++ const [resume] = await client+ .update(schema.resume)+ .set({ data: patchedData })+ .where(+ and(+ eq(schema.resume.id, input.id),+ eq(schema.resume.isLocked, false),+ eq(schema.resume.userId, input.userId),+ ...(input.expectedUpdatedAt ? [eq(schema.resume.updatedAt, input.expectedUpdatedAt)] : []),+ ),+ )+ .returning({+ id: schema.resume.id,+ name: schema.resume.name,+ slug: schema.resume.slug,+ tags: schema.resume.tags,+ data: schema.resume.data,+ isPublic: schema.resume.isPublic,+ isLocked: schema.resume.isLocked,+ updatedAt: schema.resume.updatedAt,+ hasPassword: sql<boolean>`${schema.resume.password} IS NOT NULL`,+ });++ if (!resume) {+ if (input.expectedUpdatedAt) throw resumeVersionConflict(existing.updatedAt);+ throw new ORPCError("NOT_FOUND");+ }++ return resume;+}+const tags = {list: async (input: { userId: string }) => {const result = await db@@ -366,59 +442,7 @@ export const resumeService = {},patch: async (input: { id: string; userId: string; operations: JsonPatchOperation[]; expectedUpdatedAt?: Date }) => {- const [existing] = await db- .select({ data: schema.resume.data, isLocked: schema.resume.isLocked, updatedAt: schema.resume.updatedAt })- .from(schema.resume)- .where(and(eq(schema.resume.id, input.id), eq(schema.resume.userId, input.userId)));-- if (!existing) throw new ORPCError("NOT_FOUND");- if (existing.isLocked) throw new ORPCError("RESUME_LOCKED");- if (input.expectedUpdatedAt && existing.updatedAt.getTime() !== input.expectedUpdatedAt.getTime()) {- throw new ORPCError("RESUME_VERSION_CONFLICT", {- status: 409,- message: "The resume changed after this patch was generated.",- data: { updatedAt: existing.updatedAt.toISOString() },- });- }-- let patchedData: ResumeData;-- try {- patchedData = applyResumePatches(existing.data, input.operations);- } catch (error) {- if (error instanceof ResumePatchError) {- throw new ORPCError("INVALID_PATCH_OPERATIONS", {- status: 400,- message: error.message,- data: { code: error.code, index: error.index, operation: error.operation },- });- }-- throw new ORPCError("INVALID_PATCH_OPERATIONS", {- status: 400,- message: error instanceof Error ? error.message : "Failed to apply patch operations",- });- }-- const [resume] = await db- .update(schema.resume)- .set({ data: patchedData })- .where(- and(eq(schema.resume.id, input.id), eq(schema.resume.isLocked, false), eq(schema.resume.userId, input.userId)),- )- .returning({- id: schema.resume.id,- name: schema.resume.name,- slug: schema.resume.slug,- tags: schema.resume.tags,- data: schema.resume.data,- isPublic: schema.resume.isPublic,- isLocked: schema.resume.isLocked,- updatedAt: schema.resume.updatedAt,- hasPassword: sql<boolean>`${schema.resume.password} IS NOT NULL`,- });-- if (!resume) throw new ORPCError("NOT_FOUND");+ const resume = await applyResumePatchTx(db, input);await notifyResumeUpdated({type: "resume.updated",@@ -431,6 +455,18 @@ export const resumeService = {return resume;},+ patchInTransaction: applyResumePatchTx,++ notifyResumePatched: async (input: { resumeId: string; userId: string; updatedAt: Date }) => {+ await notifyResumeUpdated({+ type: "resume.updated",+ resumeId: input.resumeId,+ userId: input.userId,+ updatedAt: input.updatedAt.toISOString(),+ mutation: "patch",+ });+ },+setLocked: async (input: { id: string; userId: string; isLocked: boolean }) => {const [resume] = await db.update(schema.resume)diff --git a/packages/api/src/services/storage.test.ts b/packages/api/src/services/storage.test.tsindex c15b38041..ce16270a2 100644--- a/packages/api/src/services/storage.test.ts+++ b/packages/api/src/services/storage.test.ts@@ -33,7 +33,7 @@ vi.mock("@aws-sdk/client-s3", () => ({ListObjectsV2Command: vi.fn(),}));-const { inferContentType, isImageFile, processImageForUpload } = await import("./storage");+const { getStorageService, inferContentType, isImageFile, processImageForUpload } = await import("./storage");const makeFile = (bytes: Uint8Array, type = "image/png") =>({@@ -111,3 +111,16 @@ describe("isImageFile", () => {expect(isImageFile("")).toBe(false);});});++describe("LocalStorageService", () => {+ it("rejects private writes instead of silently storing them on the local filesystem", async () => {+ await expect(+ getStorageService().write({+ key: "uploads/user/agent/thread/file.txt",+ data: new TextEncoder().encode("private"),+ contentType: "text/plain",+ private: true,+ }),+ ).rejects.toThrow("Private storage writes are not supported by the local filesystem backend.");+ });+});diff --git a/packages/api/src/services/storage.ts b/packages/api/src/services/storage.tsindex c57410ddb..f19489801 100644--- a/packages/api/src/services/storage.ts+++ b/packages/api/src/services/storage.ts@@ -15,6 +15,7 @@ interface StorageWriteInput {key: string;data: Uint8Array;contentType: string;+ private?: boolean;}interface StorageReadResult {@@ -135,7 +136,13 @@ class LocalStorageService implements StorageService {}}- async write({ key, data }: StorageWriteInput): Promise<void> {+ async write({ key, data, private: isPrivate }: StorageWriteInput): Promise<void> {+ if (isPrivate) {+ throw new Error(+ "Private storage writes are not supported by the local filesystem backend. Configure S3 to store private attachments.",+ );+ }+const fullPath = this.resolvePath(key);await fs.mkdir(dirname(fullPath), { recursive: true });@@ -258,13 +265,13 @@ class S3StorageService implements StorageService {return response.Contents.map((object) => object.Key ?? "");}- async write({ key, data, contentType }: StorageWriteInput): Promise<void> {+ async write({ key, data, contentType, private: isPrivate }: StorageWriteInput): Promise<void> {const client = await this.getClient();const command = new PutObjectCommand({Bucket: this.bucket,Key: key,Body: data,- ACL: "public-read",+ ACL: isPrivate ? "private" : "public-read",ContentType: contentType,});diff --git a/packages/db/src/relations.ts b/packages/db/src/relations.tsindex b9a1af525..e96b635ee 100644--- a/packages/db/src/relations.ts+++ b/packages/db/src/relations.ts@@ -8,6 +8,11 @@ export const relations = defineRelations(schema, (r) => ({twoFactors: r.many.twoFactor(),passkeys: r.many.passkey(),resumes: r.many.resume(),+ aiProviders: r.many.aiProvider(),+ agentThreads: r.many.agentThread(),+ agentMessages: r.many.agentMessage(),+ agentAttachments: r.many.agentAttachment(),+ agentActions: r.many.agentAction(),apiKeys: r.many.apikey(),oauthClients: r.many.oauthClient(),oauthRefreshTokens: r.many.oauthRefreshToken(),@@ -59,6 +64,18 @@ export const relations = defineRelations(schema, (r) => ({from: r.resume.id,to: r.resumeAnalysis.resumeId,}),+ sourceAgentThreads: r.many.agentThread({+ from: r.resume.id,+ to: r.agentThread.sourceResumeId,+ }),+ workingAgentThreads: r.many.agentThread({+ from: r.resume.id,+ to: r.agentThread.workingResumeId,+ }),+ agentActions: r.many.agentAction({+ from: r.resume.id,+ to: r.agentAction.resumeId,+ }),},resumeStatistics: {resume: r.one.resume({@@ -72,6 +89,81 @@ export const relations = defineRelations(schema, (r) => ({to: r.resume.id,}),},+ aiProvider: {+ user: r.one.user({+ from: r.aiProvider.userId,+ to: r.user.id,+ }),+ threads: r.many.agentThread({+ from: r.aiProvider.id,+ to: r.agentThread.aiProviderId,+ }),+ },+ agentThread: {+ user: r.one.user({+ from: r.agentThread.userId,+ to: r.user.id,+ }),+ aiProvider: r.one.aiProvider({+ from: r.agentThread.aiProviderId,+ to: r.aiProvider.id,+ }),+ sourceResume: r.one.resume({+ from: r.agentThread.sourceResumeId,+ to: r.resume.id,+ }),+ workingResume: r.one.resume({+ from: r.agentThread.workingResumeId,+ to: r.resume.id,+ }),+ messages: r.many.agentMessage(),+ attachments: r.many.agentAttachment(),+ actions: r.many.agentAction(),+ },+ agentMessage: {+ user: r.one.user({+ from: r.agentMessage.userId,+ to: r.user.id,+ }),+ thread: r.one.agentThread({+ from: r.agentMessage.threadId,+ to: r.agentThread.id,+ }),+ attachments: r.many.agentAttachment(),+ actions: r.many.agentAction(),+ },+ agentAttachment: {+ user: r.one.user({+ from: r.agentAttachment.userId,+ to: r.user.id,+ }),+ thread: r.one.agentThread({+ from: r.agentAttachment.threadId,+ to: r.agentThread.id,+ }),+ message: r.one.agentMessage({+ from: r.agentAttachment.messageId,+ to: r.agentMessage.id,+ }),+ },+ agentAction: {+ user: r.one.user({+ from: r.agentAction.userId,+ to: r.user.id,+ }),+ thread: r.one.agentThread({+ from: r.agentAction.threadId,+ to: r.agentThread.id,+ }),+ message: r.one.agentMessage({+ from: r.agentAction.messageId,+ to: r.agentMessage.id,+ }),+ resume: r.one.resume({+ from: r.agentAction.resumeId,+ to: r.resume.id,+ }),+ },apikey: {user: r.one.user({from: r.apikey.referenceId,diff --git a/packages/db/src/schema/agent.test.ts b/packages/db/src/schema/agent.test.tsnew file mode 100644index 000000000..89da25d24--- /dev/null+++ b/packages/db/src/schema/agent.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { getTableColumns, getTableName } from "drizzle-orm";+import { agentAction, agentAttachment, agentMessage, agentThread, aiProvider } from "./agent";++describe("aiProvider table definition", () => {+ it("is named ai_providers and stores encrypted credentials metadata", () => {+ expect(getTableName(aiProvider)).toBe("ai_providers");++ const columns = getTableColumns(aiProvider);+ for (const name of [+ "id",+ "userId",+ "label",+ "provider",+ "model",+ "baseUrl",+ "encryptedApiKey",+ "apiKeySalt",+ "apiKeyHash",+ "apiKeyPreview",+ "testStatus",+ "lastTestedAt",+ "lastUsedAt",+ "enabled",+ "createdAt",+ "updatedAt",+ ]) {+ expect(columns[name as keyof typeof columns], name).toBeDefined();+ }+ });+});++describe("agent workspace table definitions", () => {+ it("declares threads, messages, attachments, and actions", () => {+ expect(getTableName(agentThread)).toBe("agent_threads");+ expect(getTableName(agentMessage)).toBe("agent_messages");+ expect(getTableName(agentAttachment)).toBe("agent_attachments");+ expect(getTableName(agentAction)).toBe("agent_actions");++ expect(getTableColumns(agentThread).workingResumeId).toBeDefined();+ expect(getTableColumns(agentThread).lastMessageAt).toBeDefined();+ expect(getTableColumns(agentMessage).uiMessage).toBeDefined();+ expect(getTableColumns(agentAttachment).storageKey).toBeDefined();+ expect(getTableColumns(agentAction).inverseOperations).toBeDefined();+ });+});diff --git a/packages/db/src/schema/agent.ts b/packages/db/src/schema/agent.tsnew file mode 100644index 000000000..608611f54--- /dev/null+++ b/packages/db/src/schema/agent.ts@@ -0,0 +1,178 @@+import type { JsonPatchOperation } from "@reactive-resume/utils/resume/patch";+import * as pg from "drizzle-orm/pg-core";+import { generateId } from "@reactive-resume/utils/string";+import { user } from "./auth";+import { resume } from "./resume";++export type AgentUiMessage = Record<string, unknown>;++export const aiProvider = pg.pgTable(+ "ai_providers",+ {+ id: pg+ .text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => generateId()),+ userId: pg+ .text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ label: pg.text("label").notNull(),+ provider: pg.text("provider").notNull(),+ model: pg.text("model").notNull(),+ baseUrl: pg.text("base_url"),+ encryptedApiKey: pg.text("encrypted_api_key").notNull(),+ apiKeySalt: pg.text("api_key_salt").notNull(),+ apiKeyHash: pg.text("api_key_hash").notNull(),+ apiKeyPreview: pg.text("api_key_preview").notNull(),+ testStatus: pg.text("test_status").notNull().default("untested"),+ testError: pg.text("test_error"),+ lastTestedAt: pg.timestamp("last_tested_at", { withTimezone: true }),+ lastUsedAt: pg.timestamp("last_used_at", { withTimezone: true }),+ enabled: pg.boolean("enabled").notNull().default(false),+ createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+ updatedAt: pg+ .timestamp("updated_at", { withTimezone: true })+ .notNull()+ .defaultNow()+ .$onUpdate(() => /* @__PURE__ */ new Date()),+ },+ (t) => [+ pg.index().on(t.userId, t.enabled),+ pg.index().on(t.userId, t.lastUsedAt.desc()),+ pg.index().on(t.userId, t.createdAt.asc()),+ ],+);++export const agentThread = pg.pgTable(+ "agent_threads",+ {+ id: pg+ .text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => generateId()),+ userId: pg+ .text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ aiProviderId: pg.text("ai_provider_id").references(() => aiProvider.id, { onDelete: "set null" }),+ sourceResumeId: pg.text("source_resume_id").references(() => resume.id, { onDelete: "set null" }),+ workingResumeId: pg.text("working_resume_id").references(() => resume.id, { onDelete: "set null" }),+ title: pg.text("title").notNull(),+ status: pg.text("status").notNull().default("active"),+ activeRunId: pg.text("active_run_id"),+ activeStreamId: pg.text("active_stream_id"),+ activeRunStartedAt: pg.timestamp("active_run_started_at", { withTimezone: true }),+ lastMessageAt: pg.timestamp("last_message_at", { withTimezone: true }).notNull().defaultNow(),+ archivedAt: pg.timestamp("archived_at", { withTimezone: true }),+ deletedAt: pg.timestamp("deleted_at", { withTimezone: true }),+ createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+ updatedAt: pg+ .timestamp("updated_at", { withTimezone: true })+ .notNull()+ .defaultNow()+ .$onUpdate(() => /* @__PURE__ */ new Date()),+ },+ (t) => [+ pg.index().on(t.userId, t.status, t.lastMessageAt.desc()),+ pg.index().on(t.workingResumeId),+ pg.index().on(t.aiProviderId),+ ],+);++export const agentMessage = pg.pgTable(+ "agent_messages",+ {+ id: pg+ .text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => generateId()),+ userId: pg+ .text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ threadId: pg+ .text("thread_id")+ .notNull()+ .references(() => agentThread.id, { onDelete: "cascade" }),+ role: pg.text("role").notNull(),+ status: pg.text("status").notNull().default("completed"),+ sequence: pg.integer("sequence").notNull(),+ uiMessage: pg.jsonb("ui_message").notNull().$type<AgentUiMessage>(),+ error: pg.text("error"),+ createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+ updatedAt: pg+ .timestamp("updated_at", { withTimezone: true })+ .notNull()+ .defaultNow()+ .$onUpdate(() => /* @__PURE__ */ new Date()),+ },+ (t) => [pg.uniqueIndex().on(t.threadId, t.sequence), pg.index().on(t.userId, t.createdAt.desc())],+);++export const agentAttachment = pg.pgTable(+ "agent_attachments",+ {+ id: pg+ .text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => generateId()),+ userId: pg+ .text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ threadId: pg+ .text("thread_id")+ .notNull()+ .references(() => agentThread.id, { onDelete: "cascade" }),+ messageId: pg.text("message_id").references(() => agentMessage.id, { onDelete: "set null" }),+ storageKey: pg.text("storage_key").notNull(),+ filename: pg.text("filename").notNull(),+ mediaType: pg.text("media_type").notNull(),+ size: pg.integer("size").notNull(),+ createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+ },+ (t) => [pg.index().on(t.threadId), pg.index().on(t.messageId), pg.index().on(t.userId)],+);++export const agentAction = pg.pgTable(+ "agent_actions",+ {+ id: pg+ .text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => generateId()),+ userId: pg+ .text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ threadId: pg+ .text("thread_id")+ .notNull()+ .references(() => agentThread.id, { onDelete: "cascade" }),+ messageId: pg.text("message_id").references(() => agentMessage.id, { onDelete: "set null" }),+ resumeId: pg.text("resume_id").references(() => resume.id, { onDelete: "set null" }),+ kind: pg.text("kind").notNull(),+ status: pg.text("status").notNull().default("applied"),+ title: pg.text("title").notNull(),+ summary: pg.text("summary"),+ operations: pg.jsonb("operations").notNull().$type<JsonPatchOperation[]>(),+ inverseOperations: pg.jsonb("inverse_operations").notNull().$type<JsonPatchOperation[]>(),+ baseUpdatedAt: pg.timestamp("base_updated_at", { withTimezone: true }).notNull(),+ appliedUpdatedAt: pg.timestamp("applied_updated_at", { withTimezone: true }).notNull(),+ revertedAt: pg.timestamp("reverted_at", { withTimezone: true }),+ revertMessage: pg.text("revert_message"),+ createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+ updatedAt: pg+ .timestamp("updated_at", { withTimezone: true })+ .notNull()+ .defaultNow()+ .$onUpdate(() => /* @__PURE__ */ new Date()),+ },+ (t) => [pg.index().on(t.threadId, t.createdAt.desc()), pg.index().on(t.resumeId), pg.index().on(t.messageId)],+);diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex 0f429ece9..e794bf234 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -1,2 +1,3 @@+export * from "./agent";export * from "./auth";export * from "./resume";diff --git a/packages/email/package.json b/packages/email/package.jsonindex f30a55e41..5ef470e26 100644--- a/packages/email/package.json+++ b/packages/email/package.json@@ -19,10 +19,10 @@"@reactive-resume/env": "workspace:*","nodemailer": "^8.0.7","react": "^19.2.6",- "react-email": "^6.1.3"+ "react-email": "^6.1.4"},"devDependencies": {- "@react-email/ui": "^6.1.3",+ "@react-email/ui": "^6.1.4","@reactive-resume/config": "workspace:*","@types/nodemailer": "^8.0.0","@types/react": "^19.2.14",diff --git a/packages/env/src/server.ts b/packages/env/src/server.tsindex bea1ae3a0..4b976a20e 100644--- a/packages/env/src/server.ts+++ b/packages/env/src/server.ts@@ -66,6 +66,12 @@ export const env = createEnv({S3_BUCKET: z.string().min(1).optional(),S3_FORCE_PATH_STYLE: z.stringbool().default(false),+ // AI Agent Workspace (optional until the agent feature is used)+ REDIS_URL: z.url({ protocol: /redis(s)?/ }).optional(),+ ENCRYPTION_SECRET: z.string().min(32, "ENCRYPTION_SECRET must be at least 32 characters").optional(),+ CLOUDFLARE_ACCOUNT_ID: z.string().min(1).optional(),+ CLOUDFLARE_API_TOKEN: z.string().min(1).optional(),+// Feature FlagsFLAG_DISABLE_SIGNUPS: z.stringbool().default(false),FLAG_DISABLE_EMAIL_AUTH: z.stringbool().default(false),diff --git a/packages/utils/src/url-security.node.test.ts b/packages/utils/src/url-security.node.test.tsindex e457a25de..22ab21e74 100644--- a/packages/utils/src/url-security.node.test.ts+++ b/packages/utils/src/url-security.node.test.ts@@ -8,6 +8,57 @@ import {} from "./url-security.node";describe("isPrivateOrLoopbackHost", () => {+ it.each([+ "0.0.0.0",+ "10.0.0.1",+ "100.64.0.1",+ "100.127.255.255",+ "127.0.0.1",+ "169.254.1.1",+ "172.16.0.1",+ "172.31.255.255",+ "192.0.0.1",+ "192.0.2.1",+ "192.88.99.1",+ "192.168.0.1",+ "198.18.0.1",+ "198.19.255.255",+ "198.51.100.1",+ "203.0.113.1",+ "224.0.0.1",+ "240.0.0.1",+ "255.255.255.255",+ ])("matches non-public/special-use IPv4 address %s", (address) => {+ expect(isPrivateOrLoopbackHost(address)).toBe(true);+ });++ it.each([+ "::",+ "::1",+ "::ffff:8.8.8.8",+ "::ffff:0808:0808",+ "64:ff9b::1",+ "64:ff9b:1::1",+ "100::1",+ "100:0:0:1::1",+ "2001::1",+ "2001:2::1",+ "2001:10::1",+ "2001:db8::1",+ "2002::1",+ "3fff::1",+ "5f00::1",+ "fc00::1",+ "fd12::1",+ "fe80::1",+ "fe81::1",+ "febf::1",+ "ff00::1",+ "ff02::1",+ ])("matches non-public/special-use IPv6 address %s", (address) => {+ expect(isPrivateOrLoopbackHost(address)).toBe(true);+ });+describe("loopback hostnames", () => {it("matches localhost", () => {expect(isPrivateOrLoopbackHost("localhost")).toBe(true);@@ -63,9 +114,43 @@ describe("isPrivateOrLoopbackHost", () => {expect(isPrivateOrLoopbackHost("0.0.0.0")).toBe(true);});+ it("matches 192.0.0.0/24", () => {+ expect(isPrivateOrLoopbackHost("192.0.0.1")).toBe(true);+ });++ it("matches documentation IPv4 ranges", () => {+ expect(isPrivateOrLoopbackHost("192.0.2.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("198.51.100.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("203.0.113.1")).toBe(true);+ });++ it("matches deprecated 6to4 relay anycast", () => {+ expect(isPrivateOrLoopbackHost("192.88.99.1")).toBe(true);+ });++ it("matches 100.64.0.0/10 (CGNAT)", () => {+ expect(isPrivateOrLoopbackHost("100.64.0.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("100.127.255.255")).toBe(true);+ });++ it("matches 198.18.0.0/15 (benchmarking)", () => {+ expect(isPrivateOrLoopbackHost("198.18.0.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("198.19.255.255")).toBe(true);+ });++ it("matches multicast, reserved, and broadcast IPv4 ranges", () => {+ expect(isPrivateOrLoopbackHost("224.0.0.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("240.0.0.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("255.255.255.255")).toBe(true);+ });+it("does NOT match public IPs", () => {expect(isPrivateOrLoopbackHost("8.8.8.8")).toBe(false);expect(isPrivateOrLoopbackHost("1.1.1.1")).toBe(false);+ expect(isPrivateOrLoopbackHost("93.184.216.34")).toBe(false);+ expect(isPrivateOrLoopbackHost("192.31.196.1")).toBe(false);+ expect(isPrivateOrLoopbackHost("192.52.193.1")).toBe(false);+ expect(isPrivateOrLoopbackHost("192.175.48.1")).toBe(false);});});@@ -77,10 +162,58 @@ describe("isPrivateOrLoopbackHost", () => {it("matches link-local fe80::/10", () => {expect(isPrivateOrLoopbackHost("fe80::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("fe81::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("febf::1")).toBe(true);+ });++ it("matches unspecified and multicast IPv6 ranges", () => {+ expect(isPrivateOrLoopbackHost("::")).toBe(true);+ expect(isPrivateOrLoopbackHost("ff00::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("ff02::1")).toBe(true);+ });++ it("matches NAT64 discard-only, benchmarking, and 6to4 IPv6 ranges", () => {+ expect(isPrivateOrLoopbackHost("64:ff9b::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("64:ff9b:1::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("100::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("100:0:0:1::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("2001::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("2001:2::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("2001:10::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("2002::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("3fff::1")).toBe(true);+ expect(isPrivateOrLoopbackHost("5f00::1")).toBe(true);+ });++ it("matches documentation IPv6 2001:db8::/32", () => {+ expect(isPrivateOrLoopbackHost("2001:db8::1")).toBe(true);+ });++ it("does NOT match IPv6 addresses outside fe80::/10", () => {+ expect(isPrivateOrLoopbackHost("fec0::1")).toBe(false);});it("does NOT match global IPv6", () => {- expect(isPrivateOrLoopbackHost("2001:db8::1")).toBe(false);+ expect(isPrivateOrLoopbackHost("2606:4700:4700::1111")).toBe(false);+ });++ it("matches IPv4-mapped IPv6 private and loopback addresses", () => {+ expect(isPrivateOrLoopbackHost("::ffff:10.0.0.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("::ffff:127.0.0.1")).toBe(true);+ expect(isPrivateOrLoopbackHost("::ffff:169.254.169.254")).toBe(true);+ expect(isPrivateOrLoopbackHost("[::ffff:192.168.1.1]")).toBe(true);+ expect(isPrivateOrLoopbackHost("::ffff:7f00:1")).toBe(true);+ expect(isPrivateOrLoopbackHost("::ffff:0a00:1")).toBe(true);+ expect(isPrivateOrLoopbackHost("[::ffff:7f00:1]")).toBe(true);+ });++ it("matches IPv4-mapped IPv6 public addresses because the mapped range is special-purpose", () => {+ expect(isPrivateOrLoopbackHost("::ffff:8.8.8.8")).toBe(true);+ expect(isPrivateOrLoopbackHost("::ffff:0808:0808")).toBe(true);+ });++ it("matches the broad 2001::/23 IETF protocol assignments range", () => {+ expect(isPrivateOrLoopbackHost("2001:100::1")).toBe(true);});});diff --git a/packages/utils/src/url-security.node.ts b/packages/utils/src/url-security.node.tsindex 24df0ec59..afca420d4 100644--- a/packages/utils/src/url-security.node.ts+++ b/packages/utils/src/url-security.node.ts@@ -8,6 +8,131 @@ function stripIpv6Brackets(hostname: string): string {return hostname.replace(/^\[/, "").replace(/\]$/, "");}+function normalizeIpv4MappedIpv6(hostname: string) {+ const normalized = stripIpv6Brackets(normalizeHostname(hostname));+ const mapped = normalized.match(/^::ffff:(?<address>.+)$/)?.groups?.address;+ if (!mapped) return normalized;++ if (isIP(mapped) === 4) return mapped;++ const hexMatch = mapped.match(/^(?<high>[0-9a-f]{1,4}):(?<low>[0-9a-f]{1,4})$/);+ if (!hexMatch?.groups) return normalized;++ const { high: highHex, low: lowHex } = hexMatch.groups;+ if (!highHex || !lowHex) return normalized;++ const high = Number.parseInt(highHex, 16);+ const low = Number.parseInt(lowHex, 16);+ if (Number.isNaN(high) || Number.isNaN(low) || high > 0xffff || low > 0xffff) return normalized;++ return [high >> 8, high & 0xff, low >> 8, low & 0xff].join(".");+}++function isIpv4MappedIpv6(hostname: string) {+ const normalized = stripIpv6Brackets(normalizeHostname(hostname));++ return normalized.startsWith("::ffff:");+}++const blockedIpv4Cidrs: Array<[number, number]> = [+ [knownIpv4ToNumber("0.0.0.0"), 8],+ [knownIpv4ToNumber("10.0.0.0"), 8],+ [knownIpv4ToNumber("100.64.0.0"), 10],+ [knownIpv4ToNumber("127.0.0.0"), 8],+ [knownIpv4ToNumber("169.254.0.0"), 16],+ [knownIpv4ToNumber("172.16.0.0"), 12],+ [knownIpv4ToNumber("192.0.0.0"), 24],+ [knownIpv4ToNumber("192.0.2.0"), 24],+ [knownIpv4ToNumber("192.88.99.0"), 24],+ [knownIpv4ToNumber("192.168.0.0"), 16],+ [knownIpv4ToNumber("198.18.0.0"), 15],+ [knownIpv4ToNumber("198.51.100.0"), 24],+ [knownIpv4ToNumber("203.0.113.0"), 24],+ [knownIpv4ToNumber("224.0.0.0"), 4],+ [knownIpv4ToNumber("240.0.0.0"), 4],+];++const blockedIpv6Cidrs: Array<[bigint, number]> = [+ [knownIpv6ToBigInt("::"), 128],+ [knownIpv6ToBigInt("::1"), 128],+ [knownIpv6ToBigInt("::ffff:0:0"), 96],+ [knownIpv6ToBigInt("64:ff9b::"), 96],+ [knownIpv6ToBigInt("64:ff9b:1::"), 48],+ [knownIpv6ToBigInt("100::"), 64],+ [knownIpv6ToBigInt("100:0:0:1::"), 64],+ [knownIpv6ToBigInt("2001::"), 23],+ [knownIpv6ToBigInt("2001:2::"), 48],+ [knownIpv6ToBigInt("2001:10::"), 28],+ [knownIpv6ToBigInt("2001:db8::"), 32],+ [knownIpv6ToBigInt("2002::"), 16],+ [knownIpv6ToBigInt("3fff::"), 20],+ [knownIpv6ToBigInt("5f00::"), 16],+ [knownIpv6ToBigInt("fc00::"), 7],+ [knownIpv6ToBigInt("fe80::"), 10],+ [knownIpv6ToBigInt("ff00::"), 8],+];++function ipv4ToNumber(hostname: string) {+ const octets = hostname.split(".").map((part) => Number.parseInt(part, 10));+ if (octets.length !== 4 || octets.some((octet) => Number.isNaN(octet) || octet < 0 || octet > 255)) return null;++ return (((octets[0] ?? 0) << 24) | ((octets[1] ?? 0) << 16) | ((octets[2] ?? 0) << 8) | (octets[3] ?? 0)) >>> 0;+}++function knownIpv4ToNumber(hostname: string) {+ const value = ipv4ToNumber(hostname);+ if (value === null) throw new Error(`Invalid IPv4 CIDR base: ${hostname}`);++ return value;+}++function isIpv4InCidr(address: number, base: number, prefix: number) {+ const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;++ return (address & mask) === (base & mask);+}++function expandIpv6(hostname: string) {+ const normalized = stripIpv6Brackets(normalizeHostname(hostname));+ const [head = "", tail = ""] = normalized.split("::", 2);+ const headParts = head ? head.split(":") : [];+ const tailParts = tail ? tail.split(":") : [];+ const missing = 8 - headParts.length - tailParts.length;+ if (missing < 0) return null;++ const parts = [...headParts, ...Array.from({ length: missing }, () => "0"), ...tailParts];+ if (parts.length !== 8) return null;++ const hextets = parts.map((part) => {+ if (!/^[0-9a-f]{1,4}$/.test(part)) return null;+ return Number.parseInt(part, 16);+ });++ return hextets.every((part) => part !== null && part >= 0 && part <= 0xffff) ? (hextets as number[]) : null;+}++function ipv6ToBigInt(hostname: string) {+ const hextets = expandIpv6(hostname);+ if (!hextets) return null;++ return hextets.reduce((value, hextet) => (value << 16n) | BigInt(hextet), 0n);+}++function knownIpv6ToBigInt(hostname: string) {+ const value = ipv6ToBigInt(hostname);+ if (value === null) throw new Error(`Invalid IPv6 CIDR base: ${hostname}`);++ return value;+}++function isIpv6InCidr(address: bigint, base: bigint, prefix: number) {+ const bits = 128n;+ const hostBits = bits - BigInt(prefix);+ const mask = prefix === 0 ? 0n : ((1n << bits) - 1n) ^ ((1n << hostBits) - 1n);++ return (address & mask) === (base & mask);+}+function isLoopbackOrLocalHostname(hostname: string) {const normalized = normalizeHostname(hostname);return (@@ -16,28 +141,23 @@ function isLoopbackOrLocalHostname(hostname: string) {}function isPrivateIPv4(hostname: string) {- const [first = 0, second = 0] = hostname.split(".").map((part) => Number.parseInt(part, 10));- if (Number.isNaN(first) || Number.isNaN(second)) return false;-- if (first === 10) return true;- if (first === 127) return true;- if (first === 169 && second === 254) return true;- if (first === 172 && second >= 16 && second <= 31) return true;- if (first === 192 && second === 168) return true;- if (first === 0) return true;+ const address = ipv4ToNumber(hostname);+ if (address === null) return false;- return false;+ return blockedIpv4Cidrs.some(([base, prefix]) => isIpv4InCidr(address, base ?? 0, prefix));}function isPrivateIPv6(hostname: string) {- const normalized = stripIpv6Brackets(normalizeHostname(hostname));- return (- normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe80:")- );+ const address = ipv6ToBigInt(hostname);+ if (address === null) return false;++ return blockedIpv6Cidrs.some(([base, prefix]) => isIpv6InCidr(address, base, prefix));}export function isPrivateOrLoopbackHost(hostname: string) {- const normalized = stripIpv6Brackets(normalizeHostname(hostname));+ if (isIpv4MappedIpv6(hostname)) return true;++ const normalized = normalizeIpv4MappedIpv6(hostname);if (isLoopbackOrLocalHostname(normalized)) return true;const ipVersion = isIP(normalized);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ec29bb277..3200fa27f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -61,13 +61,13 @@ importers:version: 6.0.3vitest:specifier: ^4.1.6- version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/web:dependencies:'@ai-sdk/react':- specifier: ^3.0.182- version: 3.0.182([email protected])([email protected])+ specifier: ^3.0.184+ version: 3.0.184([email protected])([email protected])'@base-ui/react':specifier: ^1.4.1@@ -106,19 +106,19 @@ importers:version: 1.14.3(@opentelemetry/[email protected])'@orpc/json-schema':specifier: ^1.14.3- version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/openapi':specifier: ^1.14.3- version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/server':specifier: ^1.14.3- version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/tanstack-query':specifier: ^1.14.3version: 1.14.3(@opentelemetry/[email protected])(@orpc/[email protected](@opentelemetry/[email protected]))(@tanstack/[email protected])'@orpc/zod':specifier: ^1.14.3- version: 1.14.3(@opentelemetry/[email protected])(@orpc/[email protected](@opentelemetry/[email protected]))(@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])+ version: 1.14.3(@opentelemetry/[email protected])(@orpc/[email protected](@opentelemetry/[email protected]))(@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])'@phosphor-icons/react':specifier: ^2.1.10@@ -180,29 +180,29 @@ importers:specifier: ^1.167.65version: 1.167.65([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@tiptap/extension-color':- specifier: ^3.23.2+ specifier: ^3.23.4'@tiptap/extension-highlight':- specifier: ^3.23.2- version: 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))+ specifier: ^3.23.4+ version: 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))'@tiptap/extension-table':- specifier: ^3.23.2+ specifier: ^3.23.4'@tiptap/extension-text-align':- specifier: ^3.23.2- version: 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))+ specifier: ^3.23.4+ version: 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))'@tiptap/extension-text-style':- specifier: ^3.23.2- version: 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))+ specifier: ^3.23.4+ version: 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))'@tiptap/pm':- specifier: ^3.23.2- version: 3.23.2+ specifier: ^3.23.4+ version: 3.23.4'@tiptap/react':- specifier: ^3.23.2- version: 3.23.2(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ specifier: ^3.23.4+ version: 3.23.4(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@tiptap/starter-kit':- specifier: ^3.23.2- version: 3.23.2+ specifier: ^3.23.4+ version: 3.23.4'@types/js-cookie':specifier: ^3.0.6version: 3.0.6@@ -212,6 +212,9 @@ importers:'@uiw/react-color-colorful':specifier: ^2.10.1+ ai:+ specifier: ^6.0.182+ version: 6.0.182([email protected])better-auth:specifier: 1.6.11version: 1.6.11(@opentelemetry/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])))([email protected](@opentelemetry/[email protected])(@types/[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])([email protected])@@ -251,6 +254,9 @@ importers:react-dom:specifier: ^19.2.6version: 19.2.6([email protected])+ react-markdown:+ specifier: ^10.1.0+ version: 10.1.0(@types/[email protected])([email protected])react-resizable-panels:specifier: ^4.11.1@@ -317,7 +323,7 @@ importers:version: 3.1.0nitro:specifier: 3.0.260429-beta- version: 3.0.260429-beta([email protected])([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 3.0.260429-beta([email protected])([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))typescript:specifier: ^6.0.3version: 6.0.3@@ -342,18 +348,12 @@ importers:fast-json-patch:specifier: ^3.1.1version: 3.1.1- immer:- specifier: ^11.1.8- version: 11.1.8jsonrepair:specifier: ^3.14.0version: 3.14.0zod:specifier: ^4.4.3version: 4.4.3- zustand:- specifier: ^5.0.13- version: 5.0.13(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))devDependencies:'@reactive-resume/config':specifier: workspace:*@@ -382,15 +382,18 @@ importers:'@aws-sdk/client-s3':specifier: ^3.1045.0version: 3.1045.0+ '@mozilla/readability':+ specifier: ^0.6.0+ version: 0.6.0'@orpc/client':specifier: ^1.14.3version: 1.14.3(@opentelemetry/[email protected])'@orpc/experimental-ratelimit':specifier: ^1.14.3- version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/server':specifier: ^1.14.3- version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ version: 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@reactive-resume/ai':specifier: workspace:*version: link:../ai@@ -413,8 +416,8 @@ importers:specifier: ^1.167.65version: 1.167.65([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))ai:- specifier: ^6.0.180- version: 6.0.180([email protected])+ specifier: ^6.0.182+ version: 6.0.182([email protected])bcrypt:specifier: ^6.0.0version: 6.0.0@@ -430,18 +433,30 @@ importers:es-toolkit:specifier: ^1.46.1version: 1.46.1+ ioredis:+ specifier: ^5.10.1+ version: 5.10.1+ jsdom:+ specifier: ^29.1.1+ version: 29.1.1(@noble/[email protected])ollama-ai-provider-v2:specifier: ^3.5.1react:specifier: ^19.2.6version: 19.2.6+ resumable-stream:+ specifier: ^2.2.12+ version: 2.2.12sharp:specifier: ^0.34.5version: 0.34.5ts-pattern:specifier: ^5.9.0version: 5.9.0+ undici:+ specifier: ^8.2.0+ version: 8.2.0zod:specifier: ^4.4.3version: 4.4.3@@ -452,6 +467,9 @@ importers:'@types/bcrypt':specifier: ^6.0.0version: 6.0.0+ '@types/jsdom':+ specifier: ^28.0.3+ version: 28.0.3'@typescript/native-preview':specifier: 7.0.0-dev.20260513.1version: 7.0.0-dev.20260513.1@@ -574,12 +592,12 @@ importers:specifier: ^19.2.6version: 19.2.6react-email:- specifier: ^6.1.3+ specifier: ^6.1.4devDependencies:'@react-email/ui':- specifier: ^6.1.3- version: 6.1.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ specifier: ^6.1.4+ version: 6.1.4(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@reactive-resume/config':specifier: workspace:*version: link:../config@@ -936,8 +954,8 @@ packages:resolution: {integrity: sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw==}engines: {node: '>=18'}- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-cnfF5N6XRsQ29VsSSoFqFpYQJx1y4sSCL3lGMIwgE0034aqn8i3+joRe52O9xV+EaJ7fziI7xn6ql7qjrf+Blw==}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-k8fQ11U3+lKzUCkiitevuH0MF++b7QPX7zrPRfXfNayLRZwrwvNuqXifB/6iIyQpSLNCfzhkqG117FW2EXCI5w==}engines: {node: '>=18'}peerDependencies:react: ^18 || ~19.0.1 || ~19.1.2 || ^19.2.1@@ -952,6 +970,21 @@ packages:peerDependencies:ajv: '>=8'+ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}++ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}++ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}++ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==}+'@authenio/[email protected]':resolution: {integrity: sha512-cTlrKttbrRHEw3W+0/I609A2Matj5JQaRvfLtEIGZvlN0RaPi+3ANsMeqAyCAVlH/lUIW2tmtBlSMni74lcXeg==}engines: {node: '>=12'}@@ -1879,6 +1912,10 @@ packages:cpu: [x64]os: [win32]+ '@bramus/[email protected]':+ resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}+ hasBin: true+'@colors/[email protected]':resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}engines: {node: '>=0.1.90'}@@ -1964,6 +2001,42 @@ packages:conventional-commits-parser:optional: true+ '@csstools/[email protected]':+ resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==}+ engines: {node: '>=20.19.0'}++ '@csstools/[email protected]':+ resolution: {integrity: sha512-bR9e6o2BDB12jzN/gIbjHa5wLJ4UjD1CB9pM7ehlc0ddk6EBz+yYS1EV2MF55/HUxrHcB/hehAyt5vhsA3hx7w==}+ engines: {node: '>=20.19.0'}+ peerDependencies:+ '@csstools/css-parser-algorithms': ^4.0.0+ '@csstools/css-tokenizer': ^4.0.0++ '@csstools/[email protected]':+ resolution: {integrity: sha512-U0KhLYmy2GVj6q4T3WaAe6NPuFYCPQoE3b0dRGxejWDgcPp8TP7S5rVdM5ZrFaqu4N67X8YaPBw14dQSYx3IyQ==}+ engines: {node: '>=20.19.0'}+ peerDependencies:+ '@csstools/css-parser-algorithms': ^4.0.0+ '@csstools/css-tokenizer': ^4.0.0++ '@csstools/[email protected]':+ resolution: {integrity: sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==}+ engines: {node: '>=20.19.0'}+ peerDependencies:+ '@csstools/css-tokenizer': ^4.0.0++ '@csstools/[email protected]':+ resolution: {integrity: sha512-SH60bMfrRCJF3morcdk57WklujF4Jr/EsQUzqkarfHXEFcAR1gg7fS/chAE922Sehgzc1/+Tz5H3Ypa1HiEKrg==}+ peerDependencies:+ css-tree: ^3.2.1+ peerDependenciesMeta:+ css-tree:+ optional: true++ '@csstools/[email protected]':+ resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==}+ engines: {node: '>=20.19.0'}+'@dnd-kit/[email protected]':resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}peerDependencies:@@ -2476,6 +2549,15 @@ packages:cpu: [x64]os: [win32]+ '@exodus/[email protected]':+ resolution: {integrity: sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}+ peerDependencies:+ '@noble/hashes': ^1.8.0 || ^2.0.0+ peerDependenciesMeta:+ '@noble/hashes':+ optional: true+'@floating-ui/[email protected]':resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}@@ -2691,6 +2773,9 @@ packages:'@types/node':optional: true+ '@ioredis/[email protected]':+ resolution: {integrity: sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==}+'@isaacs/[email protected]':resolution: {integrity: sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==}engines: {node: '>=18'}@@ -2808,6 +2893,10 @@ packages:'@cfworker/json-schema':optional: true+ '@mozilla/[email protected]':+ resolution: {integrity: sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ==}+ engines: {node: '>=14.0.0'}+'@mswjs/[email protected]':resolution: {integrity: sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==}engines: {node: '>=18'}@@ -3015,8 +3104,8 @@ packages:resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}engines: {node: '>=8.0.0'}- '@opentelemetry/[email protected]':- resolution: {integrity: sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw==}+ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==}engines: {node: '>=14'}'@orpc/[email protected]':@@ -3591,8 +3680,8 @@ packages:react: ^18.0 || ^19.0 || ^19.0.0-rcreact-dom: ^18.0 || ^19.0 || ^19.0.0-rc- '@react-email/[email protected]':- resolution: {integrity: sha512-h7IrGLKkbXYk2+yz9Dbeg1oU5q4lIdLZ+Go+bWlAe5OunvjkGPbCagO113n2k975uRuJX8L7couhbAuTYeLMwA==}+ '@react-email/[email protected]':+ resolution: {integrity: sha512-FyMCx7uNV0ugZY9ZWNAnWFTrXnYOhRQm97ybbZapJCQLu6uhZHmluXv2HcsSZ0RaMAzuLJgw0ziLQjq4uYEiNg==}'@react-pdf/[email protected]':resolution: {integrity: sha512-0I7pApDr1/RLAKbizuLy/IHTEa93LSPy/bEwYniboC3Xqnp6Od8xFJKbKEzGw2wh/5zKFFwl00g4t9RwgIMc3w==}@@ -4509,180 +4598,180 @@ packages:peerDependencies:'@testing-library/dom': '>=7.21.4'- '@tiptap/[email protected]':- resolution: {integrity: sha512-yjv2N7gaQMbIVfsSZHBMscLoybgetcTraXsSMrELAerl/jfRipg5S1dBXMFvgRy8Kh48+TGoH+5nqshxdOEGoQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-ni2LWE52bVeSt3L2HVBSmbBw+elc32ATej9C68EyKzN/8vR5ILxFn6RCdDTKm4asmwZyq2jys12dKmBdWMr9QA==}peerDependencies:- '@tiptap/pm': 3.23.2+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-BBN22/nUErRzUr1HI/Q4iPFBNavWoNC5Fx0KXp9oDOCCrCvj55rtGwLn2dB3r4vLfhjYvhEZ38wN+r7Y9RhORA==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-7YjSibNlPcy9eGK+tHt5G/Njr7nPxl+rZ3rCC6TwtLIRLSHPnoGDsfFOgTPkXxaQcE1a/VQwemnYfWc3kdIjDQ==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-onPFP260enNkjMGhR7sDSqaF80A4sgvMZ/VZLxp7zGa6DAfcuN4PyUQhZN61KmYgbUdr+qrAAMx+tPuid22F4g==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-3L9tnZ12i+98u5df2nV2zGu/sc3rhI87E3ocn1YYAO8PJUAgZnMwdet8JawCrS1uut5sRKlxo3SXEmdNfRVm/w==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-S0LZg6EMdkr5CiYAGmOwzuNPd2T18ZR5pWrgHHHZjt0IFqU01tBJa3zLzC1Vd7noPCec64ygW9S8+p8CHBgOIA==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-EPTpL/IFp/aTGZErBq/Mc3dKznj6G/qNEkVYWjueOn1oKApyT0P6WVHGvu/vpMdErhzmoGDuFPPGVS6T8Upx2Q==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-jhvu1qa8F53r//6DrLdA2OkTbRgY73NkQL51Ruozzi+JrfVIo3IfaTNRq01BXO5qcvNH7P/aDBF5cByvuiUMzQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-mXB2KZOz1R+E6VNTZ3vzdAk7ZDGKjPmsJEZIQg1B5qRycTKg49/rCCkLA2QnqAwX6BzS3mLLH1RWE2W0oXD7vg==}peerDependencies:- '@tiptap/extension-list': 3.23.2+ '@tiptap/extension-list': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-oWwjsLi+m7zHTqM0kYnnogjS3vFENCaLk3ue/1XE9ccpZlmmPzmK70hodB/UPylFJmgr3g726rhxViYv9LRS7A==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-UEU1w/85CSNKktbhESnIRmtjKcH7DeschReZA8err1wAnYLTKzid5ucnJSJ25iRg2V5Fnuws5gnPT5CVgdfXCQ==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-5yHYavvBEkxgWL6DCPYNHujxBXF7c812MFNoU62ljNJjIYDc2Mu8ftOie/ajNJbMLqwSVzCuGfG9swEuEKxY5g==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-C0TeRipMycUEBnV+Mzx6eLp/yZb6Vi/waP3Tkb0lO5/ikg7LWLB7AlmMunjIXEUcR/pJHID/aEh5PfJFpysUDg==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-4G5ikeZUB27YyI3F1MpopD+liTJYKeIQMRDbHdSIxce6TbTqsOXY5tMzKIEkRk85dF/edFcen8QE/AKr+/zXhg==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-8phVTsRgvT+0wnDh+z6eIIa0IksVRnLKM2Av89vPHOFUhCt/bJdolAfXSC+eWqxjgoYOikzi5yk3QHYbGvOu1Q==}peerDependencies:- '@tiptap/extension-text-style': 3.23.2+ '@tiptap/extension-text-style': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-Ff/MAaWPzFtb7nhPG6ETdu7/OqkD6cAmJfViBAiRqh9PPULH98fGDaMBm3TGa1s3XB7hGO7c/xVKxEdjYij5rg==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-YC4G6VkxT629rlqUTwD6XvOpxjvghn7fxrK4RbyKVJY2C6E1vgmX0won1Ast6v+qTE6iONOMS6f6VyPxSGjg4w==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-T7pVfIF5uDj043CDJlurNoMAmXPy36EjBz/YQVYrVMSSUbvUlOaL3xxoDODRmir29jVrmCROjaKwVExqooQTqQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-ujJQUIENk0RwVFCh5g/TOSEv1a7Pnam/cjHmSUqHWUNZkYS9aOqjm+JfURJPCinRS2oHvo3AARul5mkKgDJYcA==}peerDependencies:- '@tiptap/extensions': 3.23.2+ '@tiptap/extensions': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-1rfxx5X52h44jSS9R1fUx8sOaRpNq8CM0IR3EdjpthVvaRZ9XD1tKX4h5EcwGFqNiwtWXxNne2mV7ZJuH2UYsQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-eAc72bKM26yIPx0jsU8qdjE71vFNVu5R9jGbdItBMFc0SPLS4qY8g+8RJ+iWoLwbcSEpgooLS9D9sLfdAU+Tvw==}peerDependencies:'@floating-ui/dom': ^1.0.0- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-I3LKYVwyxRaiVaJxss98QWOXzZZrHmsJD3RgAZ0Uoguu3pL29Krn2tXfwp4FAd9NG79wdQHj20c+XuqJLNkAbw==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-RuyvOlIGP6UpVOc0Lw0L63jKLtYM49CNhPV2OMSfwwwbBZ3pJGos2/SqpYg71d3sn+qpsAopS4Pfr8iPZog73A==}peerDependencies:- '@tiptap/extensions': 3.23.2+ '@tiptap/extensions': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-3p00oC2caRAVtkOweJ9IjTgjhzm34R9tNyMCykzMRygC8CdO08Jv2JKvUaOeMVVmWZI+O9wkGUpaA2Drg6pY4g==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-ODlpZCi7n136BH9luM09EFL8Pg+bbRCd0tzCQM5BKMXRkLitYZA8Gl/f5DLmGJ50wzFsDPXK2Br2g9UvZK7COg==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-ldQh38ZWTIedSY6XsOkn1ULtk+mD/mezLogrvcVv8neez0qM/S25vyMZKqP7i2/x4i4ds1JYIJLw9y3HX/B69Q==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-8W9Hqi0J69Xbqg08nPf4xRMJXMccaKFAgUE1tvy5PAWJSQxOMwkKQXgZXxwe+80sOMUnV8qveBqUy/ODMPgAxQ==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-5DkjvdptftHFb0jBG/3ca5ZpwN+IPv4W37TXwBPcIsKZf4jPuvAYqaxMVQFyQRkxuHsxEEiXMrAsiXbRVKnMPQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-OyCnpFpLRWg9sWlXVMIsvo2bpf4cp7Gdz5b57eceNsr4Cm5RcHtJTiziKO6kSrSYLWdoL4T9m3SNvF5/7ekx0g==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-LbLACqe/OiTdYIq3zbsY7Ue7WOP+mYTGufNDfs8rSGcUbWI2GwUwoGRrTPBbLIesnuCdH6FyMB60Tg/HzjKaYw==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-EA4kK8ywZ4dQNOdxeZbplmDDs5T5LjMgHpqxRwukj9wwKiILOK5E3fcKm1fCKh9Q02w96jax6YVccHwmgJP3sQ==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-pauWOkom8riyZoIGn8I8uFE//uRgE6kL46Pd6PdSd5Wt6w/ao/le9Ju2Ln947NGjz/6whaDiFnBrkSbZEAhpmw==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-jUAHi+HZlg47BzgVIy6y/UH5vev7vPQ95jddhB5K3hC122kvWFMXlken7UOnqzbxNcHs2+4Oi/ZJirYMpT4P5w==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-h0D3Lwom0hGDsbpZ6tW0+DRKgBP0qSl4rO/iBfGk3Krb2CoyEn1yII3pSTd1PwAld7bHt/buURi6DWudQsIhgg==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-XjxltY7MomwfTs6jmN6Bw5bb/upb34lpyqv2RiXppFTK25Br7ipksRjUpWpB4/csZeg30qwrLGVKxCol38ffrw==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-I9Yed0mmBE6AAhc4Cc5UhZLZUMCft9XdPkdBM/wjcjpLwdMhdzelVQXEhNDyPfRkA1TTGs5VHlc6twjCPCTgLg==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-Q/JXosShD5oyDwukE6igdrZD2lb0ZgyoQTHYchk0pzU4frClFbn3RI1wKP+XeqKLhdO6KH2WZ9rERGH7PtDi7Q==}peerDependencies:- '@tiptap/extension-list': 3.23.2+ '@tiptap/extension-list': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-aE4PzCy+OWXXFc8UsrrYjcfEbyXCh8f7LuGgFPl8jf0JjgIK0FHmzWDg3912zWb5Ww66AF2j0KJzTB9NFOMWlw==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-9FezifCfuoc0o+5K6l4QNOOfelqxnDGg/f9oL1D/LFZPC54bPxpWWft9QCWOqyqZgyLCLjbCjciAlbgkrFUmmw==}peerDependencies:- '@tiptap/extension-list': 3.23.2+ '@tiptap/extension-list': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-tRbbjpOPrY4ApIHtn3ctnKIhkkioewMsZa5gJzqVB47LJFNyzLXLo/aID4sJRKTIMi1wd1fA9TiBKPe6KqczPA==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-yuauDm6qW/7q+ZO0YJBKQEGdnUm6DDTJM8AMp9bMZrT4jRf/zyUtNcZ91QEfFvBcyVuI+10PIOXtNPevhQ741Q==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-ZhMejT4jXfOEECqI60AVBzULl8AVN8BXk/9vjVnJHxBtcQxW+tIu5GHVZ4DPaCfTX7mH+hsceFMhQ2BvV7qvbg==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-+3ofyssYnOTa1+nFWEmCAY1ngn8nAV1xo25JnNNC87NMU9WkSgr93jB7/uUJP0uui1C2dBLlaup3XXm108yarw==}peerDependencies:- '@tiptap/extension-list': 3.23.2+ '@tiptap/extension-list': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-UzHx5zOi9fjhC9TAqHeD7BV5eJIA3t65pa2Mq8b54V9nrIg1yAlgiafU0WDWoom11TF+IWxz5JBsjlW0/P/VeQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-KbhXjCFzWphvFn5VU7E4dtmYDm+bssI1i0+CnXPWCXkjdaaX88ck68Xp1fKz8/bbI/CqlgiNDO/3TvqgtZ6woQ==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-m1BN3EXwYagzVdReGoI7McvuZFyolFwuXLgzU6c+RN7E+u+K68EY+2U3pJI5ee8UgPYGW4eBs/3BT/5k+0so3Q==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-Vnq5vW801zPbu1LtKeA5k4R241jY+hRjXeijYwIPxy15KzIiipY12518HiCf6/8kkRbMxgOfdYg9X4BRV3HV3g==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-2+jQxxDJ/EOlUtTqaw2V9y6qBOCtFihvKCwI0Je25TBZUVJq8KcNJZt2ky0JfPC6WAQmKymEwThl3guPrSjAKg==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-TRh6JMTRYXCWpwavGt3aAHH2f51ZzkhurfW3XvrURG3It8MvfuuY1xB1xba1ss5c0QLWlrKx6GVaSXrUCdFLlg==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-sXwTBQtYRQwcdU50NYf4vaS3LsGkSlM9chEz2/gORUuq2mvVTYhreZIwygk+Jp66XNtsE44UAmtbkFoELD87DQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-A3WVhAs6YFlkfa7hNgps21QLfitNZyWFBBepQusX35sz6BlaHSy9GVrTR/JjGwGIxhNoqU2SGApvf2xTuX89gQ==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-K2o1gMwn09nrd5ewftSy08U6LMC1cW3Cmml5+vHT9P/VeMtYwkbNg+9Mt1uFh7VfAZmlkj8d3u7RYqfl8xMVJA==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-jb9PBkvqqn14ju37VMYOmmva9t9Th7vutoio9iB7etcu4XhL/4Z8rYPZmO+9+HLros2TQ/1JeCNZzc8LzcuBiA==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-Ny4FC+BivfwACTuJO3QPe+BXtVFfzWQVBcfhlFlA7xTaeBktFeBavH2cEyXR8Qbez3Wio/Hn+bibT4d44EBLyg==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-q9kxver/MR18p66aWZHSPycnr9hcBFyVGeGj8gf+BQCzn5hpvtSYTfLvk1nq8GFhygdQ9/e3f7B5ovrm/jnpvw==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-HdPX1nZarOF8UkDccu6gBy6brZd4vDFCa5Mz1liw3B3D6UBiC+8vzE1YGHtggO+KEBBQYf4GgjT3qqIgOcsTEQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-F1ocPT10LV+seky25R1TMCRdc/Iof99jLcDSYDGr6mNEDY4ct2RvOeSM8aDdYq6CkH+vXt3i3JDeRwV23KzswQ==}peerDependencies:- '@tiptap/core': 3.23.2+ '@tiptap/core': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-kRHQ3nSbAfkFdxj9FtDdr4hpREndGgWFA6ZEAwlLeGUxf8QYTpuF9zb2yxdBPBlTc5+JsbPcskNt+u1PazGKYw==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-SlGPXauW8iKWG7wwuwC/0y/smLImp0h6GBIGgNnTBgIP/ThXQnjLMSZH0mW/REO87dQxkku01V3ARRywi+juhg==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':- resolution: {integrity: sha512-1kvsBqGNu2ZJ0P/lkxN0pAMqSyUcpkMIzE4xwGUIyAiD0pZV6dr+OCMwGWOTLllSyrn91xI5K7OLk3pYeCPKqA==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-+C5ngcoza47n3MjtjVBqBEBICPC0McdbwzJ+X6SSCviCLoqnSYanv5mIX9HWG0Q4fJ4BkdNM3VibZUxQaTbKyQ==}- '@tiptap/[email protected]':- resolution: {integrity: sha512-qfl70xRDQbwov8y5QvK+EiYk6JyoyzUimNtOmLSfeun2NjQwv67hW1iQ+c3geDbcwfUY5+h3XYMy1Lm+Bt46NQ==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-mb5aIY9PuLreOVLExqs+8BAI20I/8+jCUBfEIqheuFY2GRRuBiwczejSlYuADfVDBbPVN5uPw4UMADCaH5wueQ==}peerDependencies:- '@tiptap/core': 3.23.2- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4+ '@tiptap/pm': 3.23.4'@types/react': ^17.0.0 || ^18.0.0 || ^19.0.0'@types/react-dom': ^17.0.0 || ^18.0.0 || ^19.0.0react: ^17.0.0 || ^18.0.0 || ^19.0.0react-dom: ^17.0.0 || ^18.0.0 || ^19.0.0- '@tiptap/[email protected]':- resolution: {integrity: sha512-t0o//bLmlUW/3j9ke1wIrrKkvfVYcBiC/cowCUNwN/YQx9Bc3S++yInkR6hat4qI4+O49+NRknVeaF/Sp247QA==}+ '@tiptap/[email protected]':+ resolution: {integrity: sha512-3VhU+NO6/ec9DMj/5Ej0nzARSq42cXnqW+QHCmTL3FNXkXQz+tw1KlfruT5GGJ3M0RssjWjRC0a39N/4S3qxeA==}'@trickfilm400/[email protected]':resolution: {integrity: sha512-/67zpWDBLV+oYAEL682s1ktXL0HgqX76f6gaVGkGnVZlBbm1zd0v4Bz8MFF2GGhoX9rvfq3KSQHubFHwa6w6/Q==}@@ -4736,15 +4825,24 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}+'@types/[email protected]':resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}+'@types/[email protected]':resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}'@types/[email protected]':resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}+'@types/[email protected]':resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==}@@ -4757,6 +4855,15 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-/HQ2uFoetFTXuye8vzIcHw2z6Fwi7Hi/qcgC+RoS9NCyewiqxhVGqlG+ViGB6lkax481R6dmhf1I7lIGlzJStQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}+'@types/[email protected]':resolution: {integrity: sha512-z+pdZyxE+RTQE9AcboAZCb4otwcrvgHD+GlBpPgn0emDVt0ohrTMhAwlr2Wd9nZ+nihhYFxO2pThz3C5qSu2Eg==}@@ -4786,9 +4893,18 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==}+'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}+'@types/[email protected]':resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}@@ -4894,6 +5010,9 @@ packages:react: '>=16.9.0'react-dom: '>=16.9.0'+ '@ungap/[email protected]':+ resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==}+'@vercel/[email protected]':resolution: {integrity: sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==}engines: {node: '>= 20'}@@ -4977,8 +5096,8 @@ packages:resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}engines: {node: '>= 14'}- resolution: {integrity: sha512-tOyRbwD0PEjMZKGvYQcTsv95K2zktwwNhQ49QOUAh0g8MNprO7ELIO1SgANMuPc0BFtkP6Ny6OAdjq3TtxLCbQ==}+ resolution: {integrity: sha512-ooJdziFjYrYRcsCx107roqA8gDTI3P82nUfroNWIhVvwrkYzEN3W1l50YK+XNqkUew8AiimaW0/SLBewRXMuHQ==}engines: {node: '>=18'}peerDependencies:zod: ^3.25.76 || ^4.1.8@@ -5105,6 +5224,9 @@ packages:peerDependencies:'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0+ resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}+resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}@@ -5275,6 +5397,9 @@ packages:resolution: {integrity: sha512-hVLMUZFgR4JJ6ACt1uEESvQN1/dBVqPAKY0hgrV70eN3391K6juAfTjKZLKvOMsx8PxA7gsY1/tLMMTcfFLLpw==}+ resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}+resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}engines: {node: '>=18'}@@ -5287,6 +5412,18 @@ packages:resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==}engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}+ resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}++ resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}++ resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}++ resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}+resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}@@ -5355,6 +5492,10 @@ packages:resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}engines: {node: '>=6'}+ resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==}+ engines: {node: '>=0.10.0'}+resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==}peerDependencies:@@ -5379,6 +5520,9 @@ packages:resolution: {integrity: sha512-Bb6Cq8oq0IjDOe8wJmi4JeNn763Xs9cfrBcaylK1tPypWzyoy2G3l90v9k64kjphl/ZJjPIShFztenRomi8WTg==}engines: {node: '>=18'}+ resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}+resolution: {integrity: sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==}engines: {node: '>=14'}@@ -5529,6 +5673,10 @@ packages:resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}engines: {node: '>= 12'}+ resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}+resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==}engines: {node: '>= 0.4'}@@ -5581,6 +5729,12 @@ packages:supports-color:optional: true+ resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}++ resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==}+resolution: {integrity: sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==}peerDependencies:@@ -5620,6 +5774,10 @@ packages:resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==}+ resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==}+ engines: {node: '>=0.10'}+resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}engines: {node: '>= 0.8'}@@ -5635,6 +5793,9 @@ packages:resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}+ resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}+resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}@@ -5822,8 +5983,8 @@ packages:engines: {node: '>=0.10.0'}hasBin: true- resolution: {integrity: sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==}+ resolution: {integrity: sha512-JaBHwWcfIdmSAfWM5l3uwjGd431j8YEMikZ+K/2nXVuBqJKyZ0f+2h4n4JY5AyNiZmnY9qQr2RU3v9DxDmHMNg==}resolution: {integrity: sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==}@@ -5865,6 +6026,10 @@ packages:resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}engines: {node: '>=0.12'}+ resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}engines: {node: '>=6'}@@ -5949,6 +6114,9 @@ packages:engines: {node: '>=4'}hasBin: true+ resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}+resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}@@ -6004,6 +6172,9 @@ packages:resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==}+ resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}+resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}@@ -6302,6 +6473,12 @@ packages:resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}++ resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}+resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==}hasBin: true@@ -6322,6 +6499,10 @@ packages:resolution: {integrity: sha512-LgOWAkrN0rFaQpfdWBQlv/VhkOxb5AsBjk6NQVx4yEzWS923T07X0M1Y0VNko2H52HeSpZrZNNMJ0aFqsdVzQg==}+ resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}+resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}@@ -6329,6 +6510,9 @@ packages:resolution: {integrity: sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==}engines: {node: '>=14'}+ resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}+resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}@@ -6393,10 +6577,17 @@ packages:resolution: {integrity: sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==}engines: {node: ^20.17.0 || >=22.9.0}+ resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}+resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==}+ engines: {node: '>=12.22.0'}+resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==}engines: {node: '>= 12'}@@ -6405,6 +6596,12 @@ packages:resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}engines: {node: '>= 0.10'}+ resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==}++ resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==}+resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==}engines: {node: '>= 0.4'}@@ -6444,6 +6641,9 @@ packages:resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==}+resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==}engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}@@ -6469,6 +6669,9 @@ packages:resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==}+resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==}engines: {node: '>=20'}@@ -6520,6 +6723,9 @@ packages:resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}engines: {node: '>=12'}+ resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}+resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}@@ -6677,6 +6883,15 @@ packages:resolution: {integrity: sha512-9fqMSQbhJykSeii05nxKl4m6Eqn2P6rOlYiS+C5Dr/HPIU/7yZxu5qzbs40tgaFORiw2Amd0mirjxatXYMkIew==}+ resolution: {integrity: sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0}+ peerDependencies:+ canvas: ^3.0.0+ peerDependenciesMeta:+ canvas:+ optional: true+resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}engines: {node: '>=6'}@@ -6881,12 +7096,18 @@ packages:resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}- resolution: {integrity: sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==}+ resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==}resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}+ resolution: {integrity: sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==}++ resolution: {integrity: sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==}+resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==}@@ -6898,6 +7119,9 @@ packages:resolution: {integrity: sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==}engines: {node: '>=18'}+ resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}+resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}hasBin: true@@ -6932,6 +7156,30 @@ packages:resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==}++ resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}++ resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==}++ resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}++ resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}++ resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==}++ resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}++ resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}+resolution: {integrity: sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow==}@@ -6960,6 +7208,69 @@ packages:resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}engines: {node: '>= 8'}+ resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}++ resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}++ resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==}++ resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==}++ resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==}++ resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==}++ resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==}++ resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==}++ resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==}++ resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==}++ resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==}++ resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}++ resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==}++ resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==}++ resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==}++ resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==}++ resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==}++ resolution: {integrity: sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==}++ resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==}++ resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==}++ resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==}+resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}engines: {node: '>=8.6'}@@ -7297,6 +7608,9 @@ packages:resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}engines: {node: '>=6'}+ resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==}+resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}engines: {node: '>=8'}@@ -7317,6 +7631,9 @@ packages:resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}+ resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==}+resolution: {integrity: sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw==}@@ -7509,6 +7826,9 @@ packages:resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}+ resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}+resolution: {integrity: sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==}@@ -7597,8 +7917,8 @@ packages:peerDependencies:react: ^19.2.6- resolution: {integrity: sha512-S+zukMTZGGH9xc8lPynXmPN5plRZ8MdVkTNfqkgcavAyPeUXB5nuHhCGpJAcdt9hdtsN7vjvzqgQvXT9SkEE8A==}+ resolution: {integrity: sha512-UKCfry4W7zkAWoJX1ngaWgPrUazOebxI8IYrO8TBEqgFmmz97VqZ84ell2x36Fdvtzd/UI5e4ZOywlsXeydwgQ==}engines: {node: '>=20.0.0'}hasBin: truepeerDependencies:@@ -7614,6 +7934,12 @@ packages:resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}+ resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}+ peerDependencies:+ '@types/react': '>=18'+ react: '>=18'+resolution: {integrity: sha512-KhmiTUcnUNbLVdZbxMcV/+Rp+PyBt+eVJHu425eNwjSsDUtytvcwS/SBdBbbpM0c4+MnnOQBOs3AiColUesM8A==}engines: {node: '>=16.0.0'}@@ -7697,6 +8023,14 @@ packages:resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}engines: {node: '>=8'}+ resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==}+ engines: {node: '>=4'}++ resolution: {integrity: sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==}+ engines: {node: '>=4'}+resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}@@ -7730,6 +8064,12 @@ packages:resolution: {integrity: sha512-dLsljMd9sqwRkby8zhO1gSg3PnJIBFid8f4CQj/sXx+7cKx+E7u0PKhZ+U4wmhx7EfmtvnA318oVaIkAB1lRJw==}hasBin: true+ resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}++ resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==}+resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}engines: {node: '>=0.10.0'}@@ -7764,6 +8104,9 @@ packages:resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==}+ resolution: {integrity: sha512-e6boHekmb72MdWDn7vSV9kiuRb9K3CepcDj+3Z0NNhdAfld7uHbVU8+NKlHRf3LO2Chtj4cXuWL88StLg64eIw==}+resolution: {integrity: sha512-ILJRqVWBCTlg9r42fFgwVZx1gnFAcQF8mRoMkbgQfIrjEDf9nbBFDFx00oloOa+Q869FUtaYDXZvEfnecQSCoQ==}@@ -7829,6 +8172,10 @@ packages:resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==}engines: {node: '>=11.0.0'}+ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}+ engines: {node: '>=v12.22.7'}+resolution: {integrity: sha512-pFwF6H1XrSdYYNLfOcGlM28/j8CGLu8IvdrxqhjWULe2bPcKiKW4CV+OWqR/9fT52mywx65l7ysNkjLKBda7eA==}@@ -7980,6 +8327,9 @@ packages:engines: {node: '>= 8'}deprecated: The work that was done in this beta branch won't be included in future versions+ resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}+resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}engines: {node: '>= 10.x'}@@ -7992,6 +8342,9 @@ packages:resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}+ resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}+resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}engines: {node: '>= 0.8'}@@ -8048,6 +8401,9 @@ packages:resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}+ resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}+resolution: {integrity: sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==}engines: {node: '>=4'}@@ -8097,6 +8453,12 @@ packages:resolution: {integrity: sha512-zOh9jPYI+xrNOyisSelgym4tolKTJCQd5GBhK0+0xJvcYDcwlOoxF/rnFKQ2KRZknXSG9jWAp66fwP6AxN9STg==}+ resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}++ resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}+resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==}engines: {node: '>= 12.0.0'}@@ -8126,6 +8488,9 @@ packages:peerDependencies:react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}+resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==}engines: {node: '>=20'}@@ -8211,6 +8576,16 @@ packages:resolution: {integrity: sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA==}+ resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}++ resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}+resolution: {integrity: sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug==}@@ -8294,10 +8669,17 @@ packages:resolution: {integrity: sha512-w9IMgQrz4O0YN1LtB7K5P63vhlIOvC7opSmouCJ+ZywlPAlO9gIkJ+otk6LvGpAs2wg4econaCz3TvQ9xPoyuQ==}+ resolution: {integrity: sha512-AXNgS1Byr27fTI+2bsPEkV9CxkT8H6xNyRI68b3TatlZo3RkzlqQBLL+w7SmGPVpokjHbcuNVQUWE7FRTg+LRA==}+resolution: {integrity: sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==}engines: {node: '>=20.18.1'}+ resolution: {integrity: sha512-Z+4Hx9GE26Lh9Upwfnc8C7SsrpBPGaM/Gm6kMFtiG7c+5IvQKlXi/t+9x9DrrCh29cww5TSP9YdVaBcnLDs5fQ==}+ engines: {node: '>=22.19.0'}+resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}@@ -8331,6 +8713,9 @@ packages:resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}+resolution: {integrity: sha512-lMx9dX+KRmG8sq6gulYYpKWZc9RlGsgBR6aoO8Qsm3qvkSJ+3rAymr+TnV8EDMrIrwuFJ4kruzMWM/OpYzPoow==}engines: {node: '>=8'}@@ -8339,6 +8724,21 @@ packages:resolution: {integrity: sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==}engines: {node: '>=8'}+ resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}++ resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}++ resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}++ resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==}++ resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==}+resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}engines: {node: '>= 10.0.0'}@@ -8489,6 +8889,12 @@ packages:resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==}++ resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}+resolution: {integrity: sha512-t20zYkrSf868+j/p31cRIGN28Phrjm3nRSLR2fyc2tiWi4cZGVdv68yNlwnIINTkMTmPoMiSlc0OadaO7DXZaQ==}engines: {node: '>= 6'}@@ -8600,6 +9006,10 @@ packages:resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}+ resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==}engines: {node: 20 || >=22}@@ -8611,6 +9021,10 @@ packages:resolution: {integrity: sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==}+ resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}+ engines: {node: '>=20'}+resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}@@ -8627,6 +9041,14 @@ packages:resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}engines: {node: '>=18'}+ resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}+resolution: {integrity: sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==}@@ -8739,8 +9161,8 @@ packages:utf-8-validate:optional: true- resolution: {integrity: sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==}+ resolution: {integrity: sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==}engines: {node: '>=10.0.0'}peerDependencies:bufferutil: ^4.0.1@@ -8766,6 +9188,10 @@ packages:resolution: {integrity: sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==}hasBin: true+ resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==}engines: {node: '>=16.0.0'}@@ -8777,6 +9203,9 @@ packages:resolution: {integrity: sha512-bx8Q1STctnNaaDymWnkfQLKofs0mGNN7rLLapJlGuV3VlvegD7Ls4ggMjE3aUSWItCCzU0PEv45lI87iSigiCA==}engines: {node: '>=20.0'}+ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}+resolution: {integrity: sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw==}engines: {node: '>=0.6.0'}@@ -8861,6 +9290,9 @@ packages:use-sync-external-store:optional: true+ resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}+snapshots:'@adobe/[email protected]': {}@@ -8907,10 +9339,10 @@ snapshots:dependencies:json-schema: 0.4.0dependencies:'@ai-sdk/provider-utils': 4.0.27([email protected])- ai: 6.0.180([email protected])+ ai: 6.0.182([email protected])react: 19.2.6swr: 2.4.1([email protected])throttleit: 2.1.0@@ -8925,6 +9357,26 @@ snapshots:jsonpointer: 5.0.1leven: 3.1.0+ '@asamuzakjp/[email protected]':+ dependencies:+ '@asamuzakjp/generational-cache': 1.0.1+ '@csstools/css-calc': 3.2.0(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-color-parser': 4.1.0(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])+ '@csstools/css-tokenizer': 4.0.0++ '@asamuzakjp/[email protected]':+ dependencies:+ '@asamuzakjp/generational-cache': 1.0.1+ '@asamuzakjp/nwsapi': 2.3.9+ bidi-js: 1.0.3+ css-tree: 3.2.1+ is-potential-custom-element-name: 1.0.1++ '@asamuzakjp/[email protected]': {}++ '@asamuzakjp/[email protected]': {}+'@authenio/[email protected]':dependencies:'@xmldom/xmldom': 0.8.13@@ -10131,7 +10583,7 @@ snapshots:dependencies:'@better-auth/utils': 0.4.0'@better-fetch/fetch': 1.1.21- '@opentelemetry/semantic-conventions': 1.40.0+ '@opentelemetry/semantic-conventions': 1.41.1'@standard-schema/spec': 1.1.0better-call: 1.3.5([email protected])jose: 6.2.3@@ -10263,6 +10715,10 @@ snapshots:'@biomejs/[email protected]':optional: true+ '@bramus/[email protected]':+ dependencies:+ css-tree: 3.2.1+'@colors/[email protected]':optional: true@@ -10382,6 +10838,30 @@ snapshots:optionalDependencies:conventional-commits-parser: 6.4.0+ '@csstools/[email protected]': {}++ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':+ dependencies:+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])+ '@csstools/css-tokenizer': 4.0.0++ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':+ dependencies:+ '@csstools/color-helpers': 6.0.2+ '@csstools/css-calc': 3.2.0(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])+ '@csstools/css-tokenizer': 4.0.0++ '@csstools/[email protected](@csstools/[email protected])':+ dependencies:+ '@csstools/css-tokenizer': 4.0.0++ '@csstools/[email protected]([email protected])':+ optionalDependencies:+ css-tree: 3.2.1++ '@csstools/[email protected]': {}+'@dnd-kit/[email protected]([email protected])':dependencies:react: 19.2.6@@ -10676,6 +11156,10 @@ snapshots:'@esbuild/[email protected]':optional: true+ '@exodus/[email protected](@noble/[email protected])':+ optionalDependencies:+ '@noble/hashes': 2.2.0+'@floating-ui/[email protected]':dependencies:'@floating-ui/utils': 0.2.11@@ -10824,6 +11308,8 @@ snapshots:optionalDependencies:'@types/node': 25.7.0+ '@ioredis/[email protected]': {}+'@isaacs/[email protected]': {}'@jest/[email protected]':@@ -11010,6 +11496,8 @@ snapshots:transitivePeerDependencies:- supports-color+ '@mozilla/[email protected]': {}+'@mswjs/[email protected]':dependencies:'@open-draft/deferred-promise': 2.2.0@@ -11156,7 +11644,7 @@ snapshots:'@opentelemetry/[email protected]': {}- '@opentelemetry/[email protected]': {}+ '@opentelemetry/[email protected]': {}'@orpc/[email protected](@opentelemetry/[email protected])':dependencies:@@ -11176,10 +11664,10 @@ snapshots:transitivePeerDependencies:- '@opentelemetry/api'- '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':+ '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@orpc/client': 1.14.3(@opentelemetry/[email protected])- '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/shared': 1.14.3(@opentelemetry/[email protected])'@orpc/standard-server': 1.14.3(@opentelemetry/[email protected])transitivePeerDependencies:@@ -11190,12 +11678,12 @@ snapshots:'@orpc/[email protected]': {}- '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':+ '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@orpc/contract': 1.14.3(@opentelemetry/[email protected])'@orpc/interop': 1.14.3- '@orpc/openapi': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])- '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ '@orpc/openapi': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/shared': 1.14.3(@opentelemetry/[email protected])json-schema-typed: 8.0.2transitivePeerDependencies:@@ -11213,13 +11701,13 @@ snapshots:transitivePeerDependencies:- '@opentelemetry/api'- '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':+ '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@orpc/client': 1.14.3(@opentelemetry/[email protected])'@orpc/contract': 1.14.3(@opentelemetry/[email protected])'@orpc/interop': 1.14.3'@orpc/openapi-client': 1.14.3(@opentelemetry/[email protected])- '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/shared': 1.14.3(@opentelemetry/[email protected])'@orpc/standard-server': 1.14.3(@opentelemetry/[email protected])json-schema-typed: 8.0.2@@ -11230,7 +11718,7 @@ snapshots:- fastify- ws- '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':+ '@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@orpc/client': 1.14.3(@opentelemetry/[email protected])'@orpc/contract': 1.14.3(@opentelemetry/[email protected])@@ -11245,7 +11733,7 @@ snapshots:cookie: 1.1.1optionalDependencies:crossws: 0.4.5([email protected])- ws: 8.20.0+ ws: 8.20.1transitivePeerDependencies:- '@opentelemetry/api'- fastify@@ -11310,12 +11798,12 @@ snapshots:transitivePeerDependencies:- '@opentelemetry/api'- '@orpc/[email protected](@opentelemetry/[email protected])(@orpc/[email protected](@opentelemetry/[email protected]))(@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])':+ '@orpc/[email protected](@opentelemetry/[email protected])(@orpc/[email protected](@opentelemetry/[email protected]))(@orpc/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])':dependencies:'@orpc/contract': 1.14.3(@opentelemetry/[email protected])- '@orpc/json-schema': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])- '@orpc/openapi': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])- '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ '@orpc/json-schema': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ '@orpc/openapi': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ '@orpc/server': 1.14.3(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])'@orpc/shared': 1.14.3(@opentelemetry/[email protected])escape-string-regexp: 5.0.0wildcard-match: 5.1.4@@ -11732,7 +12220,7 @@ snapshots:react: 19.2.6react-dom: 19.2.6([email protected])- '@react-email/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':+ '@react-email/[email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected])':dependencies:esbuild: 0.28.0next: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -12679,140 +13167,140 @@ snapshots:dependencies:'@testing-library/dom': 10.4.1- '@tiptap/[email protected](@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected])':dependencies:- '@tiptap/pm': 3.23.2+ '@tiptap/pm': 3.23.4dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:'@floating-ui/dom': 1.7.6- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4optional: true- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:- '@tiptap/extension-list': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected])))':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected])))':dependencies:- '@tiptap/extension-text-style': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-text-style': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:- '@tiptap/extensions': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extensions': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:'@floating-ui/dom': 1.7.6- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4optional: true- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:- '@tiptap/extensions': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extensions': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2- linkifyjs: 4.3.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4+ linkifyjs: 4.3.3- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:- '@tiptap/extension-list': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:- '@tiptap/extension-list': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies:- '@tiptap/extension-list': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])+ '@tiptap/core': 3.23.4(@tiptap/[email protected])- '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4- '@tiptap/[email protected]':+ '@tiptap/[email protected]':dependencies:prosemirror-changeset: 2.4.1prosemirror-commands: 1.7.1@@ -12827,10 +13315,10 @@ snapshots:prosemirror-transform: 1.12.0prosemirror-view: 1.41.8- '@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ '@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4'@types/react': 19.2.14'@types/react-dom': 19.2.3(@types/[email protected])'@types/use-sync-external-store': 0.0.6@@ -12839,37 +13327,37 @@ snapshots:react-dom: 19.2.6([email protected])use-sync-external-store: 1.6.0([email protected])optionalDependencies:- '@tiptap/extension-bubble-menu': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/extension-floating-menu': 3.23.2(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-bubble-menu': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-floating-menu': 3.23.4(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])transitivePeerDependencies:- '@floating-ui/dom'- '@tiptap/[email protected]':- dependencies:- '@tiptap/core': 3.23.2(@tiptap/[email protected])- '@tiptap/extension-blockquote': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-bold': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-bullet-list': 3.23.2(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))- '@tiptap/extension-code': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-code-block': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/extension-document': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-dropcursor': 3.23.2(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))- '@tiptap/extension-gapcursor': 3.23.2(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))- '@tiptap/extension-hard-break': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-heading': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-horizontal-rule': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/extension-italic': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-link': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/extension-list': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/extension-list-item': 3.23.2(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))- '@tiptap/extension-list-keymap': 3.23.2(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))- '@tiptap/extension-ordered-list': 3.23.2(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))- '@tiptap/extension-paragraph': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-strike': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-text': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extension-underline': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))- '@tiptap/extensions': 3.23.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])- '@tiptap/pm': 3.23.2+ '@tiptap/[email protected]':+ dependencies:+ '@tiptap/core': 3.23.4(@tiptap/[email protected])+ '@tiptap/extension-blockquote': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-bold': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-bullet-list': 3.23.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-code': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-code-block': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-document': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-dropcursor': 3.23.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-gapcursor': 3.23.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-hard-break': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-heading': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-horizontal-rule': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-italic': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-link': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list-item': 3.23.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-list-keymap': 3.23.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-ordered-list': 3.23.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-paragraph': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-strike': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-text': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-underline': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extensions': 3.23.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/pm': 3.23.4'@trickfilm400/[email protected]':dependencies:@@ -12922,12 +13410,24 @@ snapshots:dependencies:'@types/node': 25.7.0+ '@types/[email protected]':+ dependencies:+ '@types/ms': 2.1.0+'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/estree': 1.0.9+'@types/[email protected]': {}'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/unist': 3.0.3+'@types/[email protected]': {}'@types/[email protected]':@@ -12940,6 +13440,19 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/node': 25.7.0+ '@types/tough-cookie': 4.0.5+ parse5: 8.0.1+ undici-types: 7.25.0++ '@types/[email protected]':+ dependencies:+ '@types/unist': 3.0.3++ '@types/[email protected]': {}+'@types/[email protected]':dependencies:undici-types: 7.21.0@@ -12972,8 +13485,14 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}+ '@types/[email protected]': {}++ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -13065,6 +13584,8 @@ snapshots:react: 19.2.6react-dom: 19.2.6([email protected])+ '@ungap/[email protected]': {}+'@vercel/[email protected]': {}'@vitejs/[email protected](@rolldown/[email protected](@babel/[email protected])(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':@@ -13086,7 +13607,7 @@ snapshots:obug: 2.1.1std-env: 4.1.0tinyrainbow: 3.1.0- vitest: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/[email protected]':dependencies:@@ -13150,7 +13671,7 @@ snapshots:dependencies:'@ai-sdk/gateway': 3.0.114([email protected])'@ai-sdk/provider': 3.0.10@@ -13293,6 +13814,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+@@ -13336,7 +13859,7 @@ snapshots:pg: 8.20.0react: 19.2.6react-dom: 19.2.6([email protected])- vitest: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))transitivePeerDependencies:- '@cloudflare/workers-types'- '@opentelemetry/api'@@ -13398,7 +13921,7 @@ snapshots:dependencies:baseline-browser-mapping: 2.10.29caniuse-lite: 1.0.30001792- electron-to-chromium: 1.5.353+ electron-to-chromium: 1.5.354node-releases: 2.0.44update-browserslist-db: 1.2.3([email protected])@@ -13433,6 +13956,8 @@ snapshots:+ [email protected]: {}+@@ -13442,6 +13967,14 @@ snapshots:+ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}+dependencies:boolbase: 1.0.0@@ -13530,6 +14063,8 @@ snapshots:+ [email protected]: {}+[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]):dependencies:'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])@@ -13556,6 +14091,8 @@ snapshots:dependencies:color-name: 2.1.0+ [email protected]: {}+@@ -13689,6 +14226,13 @@ snapshots:+ [email protected](@noble/[email protected]):+ dependencies:+ whatwg-mimetype: 5.0.0+ whatwg-url: 16.0.1(@noble/[email protected])+ transitivePeerDependencies:+ - '@noble/hashes'+dependencies:call-bound: 1.0.4@@ -13721,6 +14265,12 @@ snapshots:dependencies:ms: 2.1.3+ [email protected]: {}++ dependencies:+ character-entities: 2.0.2+optionalDependencies:babel-plugin-macros: 3.1.0@@ -13752,6 +14302,8 @@ snapshots:+ [email protected]: {}+@@ -13760,6 +14312,10 @@ snapshots:+ dependencies:+ dequal: 2.0.3+@@ -13848,7 +14404,7 @@ snapshots:dependencies:jake: 10.9.4- [email protected]: {}+ [email protected]: {}@@ -13893,6 +14449,8 @@ snapshots:+ [email protected]: {}+@@ -14085,6 +14643,8 @@ snapshots:+ [email protected]: {}+@@ -14174,6 +14734,8 @@ snapshots:+ [email protected]: {}+@@ -14455,7 +15017,7 @@ snapshots:'@types/ws': 8.18.1entities: 7.0.1whatwg-mimetype: 3.0.0- ws: 8.20.0+ ws: 8.20.1transitivePeerDependencies:- bufferutil- utf-8-validate@@ -14487,6 +15049,30 @@ snapshots:dependencies:function-bind: 1.1.2+ dependencies:+ '@types/estree': 1.0.9+ '@types/hast': 3.0.4+ '@types/unist': 3.0.3+ comma-separated-tokens: 2.0.3+ devlop: 1.1.0+ estree-util-is-identifier-name: 3.0.0+ hast-util-whitespace: 3.0.0+ mdast-util-mdx-expression: 2.0.1+ mdast-util-mdx-jsx: 3.2.0+ mdast-util-mdxjs-esm: 2.0.1+ property-information: 7.1.0+ space-separated-tokens: 2.0.2+ style-to-js: 1.1.21+ unist-util-position: 5.0.0+ vfile-message: 4.0.3+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/hast': 3.0.4+@@ -14504,6 +15090,12 @@ snapshots:+ [email protected](@noble/[email protected]):+ dependencies:+ '@exodus/bytes': 1.15.0(@noble/[email protected])+ transitivePeerDependencies:+ - '@noble/hashes'+@@ -14514,6 +15106,8 @@ snapshots:htmlparser2: 8.0.2selderee: 0.11.0+ [email protected]: {}+dependencies:domelementtype: 2.3.0@@ -14578,16 +15172,39 @@ snapshots:+ [email protected]: {}+dependencies:es-errors: 1.3.0hasown: 2.0.3side-channel: 1.1.0+ dependencies:+ '@ioredis/commands': 1.5.1+ cluster-key-slot: 1.1.2+ debug: 4.4.3+ denque: 2.1.0+ lodash.defaults: 4.2.0+ lodash.isarguments: 3.1.0+ redis-errors: 1.2.0+ redis-parser: 3.0.0+ standard-as-callback: 2.1.0+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ is-alphabetical: 2.0.1+ is-decimal: 2.0.1+dependencies:call-bind: 1.0.9@@ -14634,6 +15251,8 @@ snapshots:call-bound: 1.0.4has-tostringtag: 1.0.2+ [email protected]: {}+@@ -14656,6 +15275,8 @@ snapshots:dependencies:is-extglob: 2.1.1+ [email protected]: {}+@@ -14687,6 +15308,8 @@ snapshots:+ [email protected]: {}+@@ -14818,6 +15441,32 @@ snapshots:+ [email protected](@noble/[email protected]):+ dependencies:+ '@asamuzakjp/css-color': 5.1.11+ '@asamuzakjp/dom-selector': 7.1.1+ '@bramus/specificity': 2.4.2+ '@csstools/css-syntax-patches-for-csstree': 1.1.3([email protected])+ '@exodus/bytes': 1.15.0(@noble/[email protected])+ css-tree: 3.2.1+ data-urls: 7.0.0(@noble/[email protected])+ decimal.js: 10.6.0+ html-encoding-sniffer: 6.0.0(@noble/[email protected])+ is-potential-custom-element-name: 1.0.1+ lru-cache: 11.3.6+ parse5: 8.0.1+ saxes: 6.0.0+ symbol-tree: 3.2.4+ tough-cookie: 6.0.1+ undici: 7.25.0+ w3c-xmlserializer: 5.0.0+ webidl-conversions: 8.0.1+ whatwg-mimetype: 5.0.0+ whatwg-url: 16.0.1(@noble/[email protected])+ xml-name-validator: 5.0.0+ transitivePeerDependencies:+ - '@noble/hashes'+@@ -14984,10 +15633,14 @@ snapshots:- [email protected]: {}+ [email protected]: {}+ [email protected]: {}++ [email protected]: {}+@@ -15000,6 +15653,8 @@ snapshots:is-unicode-supported: 2.1.0yoctocolors: 2.1.2+ [email protected]: {}+dependencies:js-tokens: 4.0.0@@ -15030,6 +15685,95 @@ snapshots:+ dependencies:+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ decode-named-character-reference: 1.3.0+ devlop: 1.1.0+ mdast-util-to-string: 4.0.0+ micromark: 4.0.2+ micromark-util-decode-numeric-character-reference: 2.0.2+ micromark-util-decode-string: 2.0.1+ micromark-util-normalize-identifier: 2.0.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+ unist-util-stringify-position: 4.0.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/estree-jsx': 1.0.5+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.3+ mdast-util-to-markdown: 2.1.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/estree-jsx': 1.0.5+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ ccount: 2.0.1+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.3+ mdast-util-to-markdown: 2.1.2+ parse-entities: 4.0.2+ stringify-entities: 4.0.4+ unist-util-stringify-position: 4.0.0+ vfile-message: 4.0.3+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/estree-jsx': 1.0.5+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.3+ mdast-util-to-markdown: 2.1.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ unist-util-is: 6.0.1++ dependencies:+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ '@ungap/structured-clone': 1.3.1+ devlop: 1.1.0+ micromark-util-sanitize-uri: 2.0.1+ trim-lines: 3.0.1+ unist-util-position: 5.0.0+ unist-util-visit: 5.1.0+ vfile: 6.0.3++ dependencies:+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ longest-streak: 3.1.0+ mdast-util-phrasing: 4.1.0+ mdast-util-to-string: 4.0.0+ micromark-util-classify-character: 2.0.1+ micromark-util-decode-string: 2.0.1+ unist-util-visit: 5.1.0+ zwitch: 2.0.4++ dependencies:+ '@types/mdast': 4.0.4+@@ -15046,6 +15790,139 @@ snapshots:+ dependencies:+ decode-named-character-reference: 1.3.0+ devlop: 1.1.0+ micromark-factory-destination: 2.0.1+ micromark-factory-label: 2.0.1+ micromark-factory-space: 2.0.1+ micromark-factory-title: 2.0.1+ micromark-factory-whitespace: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-chunked: 2.0.1+ micromark-util-classify-character: 2.0.1+ micromark-util-html-tag-name: 2.0.1+ micromark-util-normalize-identifier: 2.0.1+ micromark-util-resolve-all: 2.0.1+ micromark-util-subtokenize: 2.1.0+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ devlop: 1.1.0+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-util-symbol: 2.0.1++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-util-chunked: 2.0.1+ micromark-util-types: 2.0.2++ dependencies:+ micromark-util-symbol: 2.0.1++ dependencies:+ decode-named-character-reference: 1.3.0+ micromark-util-character: 2.1.1+ micromark-util-decode-numeric-character-reference: 2.0.2+ micromark-util-symbol: 2.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ micromark-util-symbol: 2.0.1++ dependencies:+ micromark-util-types: 2.0.2++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-encode: 2.0.1+ micromark-util-symbol: 2.0.1++ dependencies:+ devlop: 1.1.0+ micromark-util-chunked: 2.0.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@types/debug': 4.1.13+ debug: 4.4.3+ decode-named-character-reference: 1.3.0+ devlop: 1.1.0+ micromark-core-commonmark: 2.0.3+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-chunked: 2.0.1+ micromark-util-combine-extensions: 2.0.1+ micromark-util-decode-numeric-character-reference: 2.0.2+ micromark-util-encode: 2.0.1+ micromark-util-normalize-identifier: 2.0.1+ micromark-util-resolve-all: 2.0.1+ micromark-util-sanitize-uri: 2.0.1+ micromark-util-subtokenize: 2.1.0+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+ transitivePeerDependencies:+ - supports-color+dependencies:braces: 3.0.3@@ -15170,7 +16047,7 @@ snapshots:- [email protected]([email protected])([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected]([email protected])([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:consola: 3.4.2crossws: 0.4.5([email protected])@@ -15185,7 +16062,7 @@ snapshots:rolldown: 1.0.0srvx: 0.11.15unenv: 2.0.0-rc.24- unstorage: 2.0.0-alpha.7([email protected])([email protected]([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])))([email protected])([email protected])+ unstorage: 2.0.0-alpha.7([email protected])([email protected]([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])))([email protected])([email protected])([email protected])optionalDependencies:dotenv: 17.4.2jiti: 2.7.0@@ -15308,11 +16185,11 @@ snapshots:dependencies:'@ai-sdk/provider': 3.0.10'@ai-sdk/provider-utils': 4.0.27([email protected])- ai: 6.0.180([email protected])+ ai: 6.0.182([email protected])zod: 4.4.3@@ -15436,6 +16313,16 @@ snapshots:dependencies:callsites: 3.1.0+ dependencies:+ '@types/unist': 2.0.11+ character-entities-legacy: 3.0.0+ character-reference-invalid: 2.0.1+ decode-named-character-reference: 1.3.0+ is-alphanumerical: 2.0.1+ is-decimal: 2.0.1+ is-hexadecimal: 2.0.1+dependencies:'@babel/code-frame': 7.29.0@@ -15460,6 +16347,10 @@ snapshots:dependencies:entities: 6.0.1+ dependencies:+ entities: 8.0.0+dependencies:leac: 0.6.0@@ -15621,6 +16512,8 @@ snapshots:object-assign: 4.1.1react-is: 16.13.1+ [email protected]: {}+dependencies:prosemirror-transform: 1.12.0@@ -15737,7 +16630,7 @@ snapshots:react: 19.2.6scheduler: 0.27.0dependencies:'@babel/parser': 7.27.0'@babel/traverse': 7.27.0@@ -15774,6 +16667,24 @@ snapshots:+ dependencies:+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ '@types/react': 19.2.14+ devlop: 1.1.0+ hast-util-to-jsx-runtime: 2.3.6+ html-url-attributes: 3.0.1+ mdast-util-to-hast: 13.2.1+ react: 19.2.6+ remark-parse: 11.0.0+ remark-rehype: 11.1.2+ unified: 11.0.5+ unist-util-visit: 5.1.0+ vfile: 6.0.3+ transitivePeerDependencies:+ - supports-color+dependencies:'@react-pdf/renderer': 4.5.1([email protected])@@ -15856,6 +16767,12 @@ snapshots:indent-string: 4.0.0strip-indent: 3.0.0+ [email protected]: {}++ dependencies:+ redis-errors: 1.2.0+@@ -15901,6 +16818,23 @@ snapshots:dependencies:jsesc: 3.1.0+ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-from-markdown: 2.0.3+ micromark-util-types: 2.0.2+ unified: 11.0.5+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ mdast-util-to-hast: 13.2.1+ unified: 11.0.5+ vfile: 6.0.3+@@ -15927,6 +16861,8 @@ snapshots:+ [email protected]: {}+@@ -16046,6 +16982,10 @@ snapshots:+ dependencies:+ xmlchars: 2.2.0+@@ -16289,12 +17229,16 @@ snapshots:dependencies:whatwg-url: 7.1.0+ [email protected]: {}++ [email protected]: {}+@@ -16374,6 +17318,11 @@ snapshots:dependencies:safe-buffer: 5.2.1+ dependencies:+ character-entities-html4: 2.1.0+ character-entities-legacy: 3.0.0+dependencies:get-own-enumerable-property-symbols: 3.0.2@@ -16416,6 +17365,14 @@ snapshots:+ dependencies:+ style-to-object: 1.0.14++ dependencies:+ inline-style-parser: 0.2.7+dependencies:client-only: 0.0.1@@ -16438,6 +17395,8 @@ snapshots:react: 19.2.6use-sync-external-store: 1.6.0([email protected])+ [email protected]: {}+@@ -16507,6 +17466,14 @@ snapshots:dependencies:punycode: 2.3.1+ dependencies:+ punycode: 2.3.1++ [email protected]: {}++ [email protected]: {}+dependencies:'@ts-morph/common': 0.27.0@@ -16608,8 +17575,12 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+dependencies:pathe: 2.0.3@@ -16641,12 +17612,45 @@ snapshots:+ dependencies:+ '@types/unist': 3.0.3+ bail: 2.0.2+ devlop: 1.1.0+ extend: 3.0.2+ is-plain-obj: 4.1.0+ trough: 2.2.0+ vfile: 6.0.3+dependencies:crypto-random-string: 2.0.0+ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.1++ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.1+ unist-util-visit-parents: 6.0.2+@@ -16657,10 +17661,11 @@ snapshots:picomatch: 4.0.4webpack-virtual-modules: 0.6.2- [email protected]([email protected])([email protected]([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])))([email protected])([email protected]):+ [email protected]([email protected])([email protected]([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])))([email protected])([email protected])([email protected]):optionalDependencies:chokidar: 5.0.0db0: 0.3.4([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))+ ioredis: 5.10.1lru-cache: 11.3.6ofetch: 2.0.0-alpha.3@@ -16708,6 +17713,16 @@ snapshots:+ dependencies:+ '@types/unist': 3.0.3+ unist-util-stringify-position: 4.0.0++ dependencies:+ '@types/unist': 3.0.3+ vfile-message: 4.0.3+dependencies:inherits: 2.0.4@@ -16745,7 +17760,7 @@ snapshots:optionalDependencies:vite: 8.0.12(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.6'@vitest/mocker': 4.1.6([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -16772,17 +17787,24 @@ snapshots:'@types/node': 25.7.0'@vitest/coverage-v8': 4.1.6([email protected])happy-dom: 20.9.0+ jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw+ dependencies:+ xml-name-validator: 5.0.0++ [email protected]: {}+@@ -16793,6 +17815,16 @@ snapshots:+ [email protected]: {}++ [email protected](@noble/[email protected]):+ dependencies:+ '@exodus/bytes': 1.15.0(@noble/[email protected])+ tr46: 6.0.0+ webidl-conversions: 8.0.1+ transitivePeerDependencies:+ - '@noble/hashes'+dependencies:lodash.sortby: 4.7.0@@ -16986,7 +18018,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies:@@ -17005,6 +18037,8 @@ snapshots:dependencies:sax: 1.6.0+ [email protected]: {}+@@ -17016,6 +18050,8 @@ snapshots:'@oozcitak/util': 10.0.0js-yaml: 4.1.1+ [email protected]: {}+@@ -17079,3 +18115,5 @@ snapshots:immer: 11.1.8react: 19.2.6use-sync-external-store: 1.6.0([email protected])++ [email protected]: {}diff --git a/turbo.json b/turbo.jsonindex aa59b0ff6..22c2d7eac 100644--- a/turbo.json+++ b/turbo.json@@ -34,6 +34,10 @@"S3_ENDPOINT","S3_BUCKET","S3_FORCE_PATH_STYLE",+ "REDIS_URL",+ "ENCRYPTION_SECRET",+ "CLOUDFLARE_ACCOUNT_ID",+ "CLOUDFLARE_API_TOKEN","FLAG_DISABLE_SIGNUPS","FLAG_DISABLE_EMAIL_AUTH","FLAG_DISABLE_IMAGE_PROCESSING",