7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(search): web search engines from the catalog, agent web search and dashboard (#1458)
suantea (asuan_suan)a2b78cef3fd5
diff --git a/client/src/App.tsx b/client/src/App.tsxindex 440582cf..457ec7bc 100644--- a/client/src/App.tsx+++ b/client/src/App.tsx@@ -38,6 +38,7 @@ import EmbeddingsPage from '@/pages/EmbeddingsPage'import ImagePage from '@/pages/ImagePage'import VideoPage from '@/pages/VideoPage'import AudioPage from '@/pages/AudioPage'+import SearchPage from '@/pages/SearchPage'import MediaDetailPage from '@/pages/MediaDetailPage'import EmbeddingDetailPage from '@/pages/EmbeddingDetailPage'import AnalyticsPage from '@/pages/AnalyticsPage'@@ -85,6 +86,7 @@ const modelItems = [{ to: '/models/image', labelKey: 'models.imageTab' },{ to: '/models/video', labelKey: 'models.videoTab' },{ to: '/models/audio', labelKey: 'models.audioTab' },+ { to: '/models/search', labelKey: 'search.tab' },{ to: '/models/fusion', labelKey: 'models.fusionTab' },]@@ -487,6 +489,7 @@ function App() {<Route path="/models/audio" element={<AudioPage />} /><Route path="/models/audio/:id" element={<MediaDetailPage modality="audio" />} /><Route path="/models/transcription/:id" element={<MediaDetailPage modality="transcription" />} />+ <Route path="/models/search" element={<SearchPage />} /><Route path="/playground" element={<PlaygroundPage />} /><Route path="/keys" element={<KeysPage />} /><Route path="/agents" element={<AgentsPage />} />diff --git a/client/src/components/command-palette.tsx b/client/src/components/command-palette.tsxindex 8b1c9bac..81d9b375 100644--- a/client/src/components/command-palette.tsx+++ b/client/src/components/command-palette.tsx@@ -8,6 +8,7 @@ import {ChartColumn,Clapperboard,Copy,+ Globe,Image as ImageIcon,KeyRound,Layers,@@ -111,6 +112,7 @@ export function CommandPalette() {{ id: 'p-image', group: 'pages', label: t('models.imageTab'), keywords: 'models image generation', icon: ImageIcon, run: go('/models/image') },{ id: 'p-video', group: 'pages', label: t('models.videoTab'), keywords: 'models video text to video generation mp4', icon: Clapperboard, run: go('/models/video') },{ id: 'p-audio', group: 'pages', label: t('models.audioTab'), keywords: 'models audio speech tts stt transcription whisper', icon: AudioLines, run: go('/models/audio') },+ { id: 'p-search', group: 'pages', label: t('search.tab'), keywords: 'models search web tavily exa firecrawl linkup', icon: Globe, run: go('/models/search') },{ id: 'p-fusion', group: 'pages', label: t('models.fusionTab'), keywords: 'models fusion synthesis panel judge', icon: Zap, run: go('/models/fusion') },{ id: 'p-playground', group: 'pages', label: t('nav.playground'), keywords: 'playground test chat try', icon: SquareTerminal, run: go('/playground') },{ id: 'p-keys', group: 'pages', label: t('nav.keys'), keywords: 'keys providers api tokens', icon: KeyRound, run: go('/keys') },diff --git a/client/src/components/keys/add-key-form.tsx b/client/src/components/keys/add-key-form.tsxindex 1c9e9c4d..9e975d1c 100644--- a/client/src/components/keys/add-key-form.tsx+++ b/client/src/components/keys/add-key-form.tsx@@ -12,6 +12,7 @@ import { useI18n } from '@/i18n'import { toast } from '@/lib/toast'import type { FallbackEntry } from '@/lib/routing'import { scopeCandidates, shouldOfferModelPicker, type ScopeCandidate } from '@/lib/model-scope-selection'+import { SEARCH_PROVIDERS } from '@/lib/search'import { GetKeyLink, PLATFORMS } from './shared'/** A key that just landed, plus the models the picker should offer for it.@@ -58,7 +59,7 @@ export function AddKeyForm({ onSuccess, initialPlatform }: { onSuccess: (offer?:queryKey: ['keys'],queryFn: () => apiFetch('/api/keys'),})- const addedPlatforms = useMemo(() => new Set(keys.map(k => k.platform)), [keys])+ const addedPlatforms = useMemo(() => new Set<string>(keys.map(k => k.platform)), [keys])const [hideAdded, setHideAdded] = useState(false)// #657 post-add scope picker: the platform's model list. This is the same@@ -88,14 +89,21 @@ export function AddKeyForm({ onSuccess, initialPlatform }: { onSuccess: (offer?:return { keyId, platformLabel: provider.label, candidates }}+ // Search providers (#1174) lead the list under their own heading: they hold+ // keys like any provider but never serve chat, so they must not read as one+ // more model host further down.const platformOptions = useMemo(- () => PLATFORMS+ () => [+ ...SEARCH_PROVIDERS.map(p => ({ ...p, group: t('search.pickerSearch') })),+ ...PLATFORMS.map(p => ({ ...p, group: t('search.pickerModels') })),+ ]// The selected provider always stays listed, so hiding added ones never// blanks out the trigger label..filter(p => !hideAdded || !addedPlatforms.has(p.value) || p.value === platform).map(p => ({value: p.value,label: p.label,+ group: p.group,sub: addedPlatforms.has(p.value) ? t('keys.discoverAlreadyAdded') : undefined,})),[hideAdded, addedPlatforms, platform, t],@@ -210,7 +218,7 @@ export function AddKeyForm({ onSuccess, initialPlatform }: { onSuccess: (offer?:/>{addAttempted && <FieldError error={platformError} />}{(() => {- const sel = PLATFORMS.find(p => p.value === platform)+ const sel = [...SEARCH_PROVIDERS, ...PLATFORMS].find(p => p.value === platform)return sel?.url ? <div className="pt-0.5"><GetKeyLink url={sel.url} /></div> : null})()}</div>diff --git a/client/src/components/keys/provider-list-search.test.tsx b/client/src/components/keys/provider-list-search.test.tsxnew file mode 100644index 00000000..bdbd85fc--- /dev/null+++ b/client/src/components/keys/provider-list-search.test.tsx@@ -0,0 +1,76 @@+// @vitest-environment jsdom+// #1174: search provider keys get their own section at the top of the Keys+// page, with a Search badge, and lose the model-only row actions. A page with+// no search keys keeps its old, section-less layout.+import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { I18nProvider } from '@/i18n'+import { apiFetch } from '@/lib/api'+import { ProviderList } from './provider-list'+import type { ApiKey, Platform } from '../../../../shared/types'++vi.mock('@/lib/api', () => ({ apiFetch: vi.fn() }))++const apiKey = (over: Partial<ApiKey>): ApiKey => ({+ id: 1, platform: 'groq', label: 'Prod key', maskedKey: 'gsk_…1234', baseUrl: null,+ status: 'healthy', enabled: true, keyless: false, exportable: true,+ createdAt: '2026-10-01 00:00:00', lastCheckedAt: null, lastHealthError: null, ...over,+})++let root: Root+let container: HTMLDivElement+let client: QueryClient++beforeAll(() => { (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true })+beforeEach(() => {+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container)+})+afterEach(() => { act(() => root.unmount()); client.clear(); container.remove() })++async function flush() { for (let i = 0; i < 4; i++) await act(async () => { await new Promise(r => setTimeout(r, 0)) }) }+async function mount(keys: ApiKey[]) {+ vi.mocked(apiFetch).mockReset().mockImplementation(async (path: string) => {+ if (path === '/api/keys') return keys+ if (path === '/api/health') return { platforms: [], keys: [], quotaStates: [] }+ if (path === '/api/settings/proxy') return { proxyUrl: '', enabled: false, bypassPlatforms: [], active: false }+ return {}+ })+ act(() => root.render(+ <QueryClientProvider client={client}><I18nProvider initialLocale="en"><ProviderList onAddKey={() => {}} /></I18nProvider></QueryClientProvider>+ ))+ await flush()+}++const headings = () => [...container.querySelectorAll('h2')].map(h => h.textContent)+const providers = () => [...container.querySelectorAll('h3')].map(h => h.textContent)++it('lists search keys first, under their own section, with a Search badge', async () => {+ await mount([+ apiKey({ id: 1, platform: 'groq' }),+ apiKey({ id: 2, platform: 'tavily', label: 'Search key', maskedKey: 'tvly…9999' }),+ ])+ expect(headings()).toEqual(['Search', 'Models'])+ expect(providers()[0]).toMatch(/^Tavily/)+ expect(container.textContent).toContain('never for chat')+ // The badge sits next to the provider name, not on the chat provider.+ const groqRow = [...container.querySelectorAll('h3')].find(h => h.textContent?.startsWith('Groq'))!.parentElement!+ expect(groqRow.textContent).not.toContain('Search')+})++it('keeps the old layout when no search key exists', async () => {+ await mount([apiKey({ id: 1, platform: 'groq' })])+ expect(headings()).toEqual([])+})++it('hides the edit-models action on a search key', async () => {+ await mount([apiKey({ id: 2, platform: 'tavily' as Platform, label: 'Search key' })])+ expect(container.querySelector('[aria-label="Edit models"]')).toBeNull()+ // A chat key still offers it.+ act(() => root.unmount())+ root = createRoot(container)+ await mount([apiKey({ id: 1, platform: 'groq' })])+ expect(container.querySelector('[aria-label="Edit models"]')).not.toBeNull()+})diff --git a/client/src/components/keys/provider-list.tsx b/client/src/components/keys/provider-list.tsxindex f56d7628..c1016977 100644--- a/client/src/components/keys/provider-list.tsx+++ b/client/src/components/keys/provider-list.tsx@@ -44,6 +44,7 @@ import { ModelScopeDialog } from './model-scope-dialog'import { TestModelsDialog } from './test-models-dialog'import { AddModelDialog } from './add-model-dialog'import { groupHandle } from '@/lib/endpoint-groups'+import { SEARCH_PROVIDERS, isSearchPlatform } from '@/lib/search'type StatusFilter = 'all' | 'healthy' | 'issues' | 'disabled'@@ -56,6 +57,8 @@ interface ProviderGroup {platform: string/** Custom endpoints only: the group label, or null for the default group. */customGroup?: string | null+ /** A web search provider (#1174): listed in its own section, never chat. */+ search?: booleankeys: ApiKey[]}@@ -314,7 +317,10 @@ export function ProviderList({ onAddKey }: { onAddKey: () => void }) {}group.keys.push(k)}+ // Search providers (#1174) come first, in their own section: their keys+ // serve /v1/search and agent web search, never a chat completion.const grouped: ProviderGroup[] = [+ ...SEARCH_PROVIDERS.map(p => ({ ...p, platform: p.value, search: true, keys: keys.filter(k => k.platform === p.value) })),...PLATFORMS.map(p => ({ ...p, platform: p.value, keys: keys.filter(k => k.platform === p.value) })),...[...customGroups.values()].sort((a, b) =>a.customGroup === null ? -1 : b.customGroup === null ? 1 : a.label.localeCompare(b.label)),@@ -416,8 +422,12 @@ export function ProviderList({ onAddKey }: { onAddKey: () => void }) {<EmptyState title={t('keys.noFilterMatch')} />) : (<div className="space-y-4">- {visibleGroups.map(group => {+ {visibleGroups.map((group, i) => {const expanded = isGroupExpanded(group)+ // Section headings appear only when search keys are on screen;+ // a Keys page without any reads exactly as it always has.+ const showSections = visibleGroups.some(g => g.search)+ const sectionStart = showSections && (i === 0 || !!visibleGroups[i - 1].search !== !!group.search)const healthyCount = group.keys.filter(k => statusOf(k) === 'healthy').lengthconst issueCount = group.keys.filter(k => statusOf(k) !== 'healthy').length// #787: once a selection exists in this group the checkboxes stay@@ -425,6 +435,14 @@ export function ProviderList({ onAddKey }: { onAddKey: () => void }) {const groupHasSelection = group.keys.some(k => selectedKeyIds.has(k.id))return (<div key={group.value}>+ {sectionStart && (+ <div className={`pb-2 ${i === 0 ? '' : 'pt-4'}`}>+ <h2 className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">+ {group.search ? t('search.keysSection') : t('search.keysModelsSection')}+ </h2>+ {group.search && <p className="text-xs text-muted-foreground">{t('search.keysSectionHint')}</p>}+ </div>+ )}<div className="flex items-center gap-2 pb-2"><Switchchecked={group.keys.some(k => k.enabled)}@@ -440,6 +458,11 @@ export function ProviderList({ onAddKey }: { onAddKey: () => void }) {aria-expanded={expanded}><h3 className="text-sm font-medium">{group.label}</h3>+ {group.search && (+ <Badge variant="outline" className="border-sky-600/30 text-[10px] text-sky-700 dark:text-sky-300">+ {t('search.badge')}+ </Badge>+ )}<Badge variant="secondary" className="tabular-nums">{group.keys.length}</Badge>{group.customGroup && (<Tooltip text={t('keys.groupHandleHint', { handle: groupHandle(group.customGroup) })}>@@ -473,7 +496,7 @@ export function ProviderList({ onAddKey }: { onAddKey: () => void }) {<DropdownMenuContent align="end" className="w-52">{/* Test every model this provider serves, one real ping each(custom endpoints test per key from the row instead). */}- {group.platform !== 'custom' && (+ {group.platform !== 'custom' && !group.search && (<DropdownMenuItem onClick={() => setTestTarget({ platform: group.platform, label: group.label })}>{t('keys.testModels')}<FlaskConical className="ml-auto size-3.5" />@@ -485,10 +508,12 @@ export function ProviderList({ onAddKey }: { onAddKey: () => void }) {<Copy className="ml-auto size-3.5" /></DropdownMenuItem>)}- <DropdownMenuItem onClick={() => setAddModelTarget({ platform: group.platform })}>- {t('keys.addCustomModel')}- <Sparkles className="ml-auto size-3.5" />- </DropdownMenuItem>+ {!group.search && (+ <DropdownMenuItem onClick={() => setAddModelTarget({ platform: group.platform })}>+ {t('keys.addCustomModel')}+ <Sparkles className="ml-auto size-3.5" />+ </DropdownMenuItem>+ )}{group.url && (<DropdownMenuItem onClick={() => window.open(group.url, '_blank', 'noopener,noreferrer')}>{t('keys.getApiKey')}@@ -689,7 +714,7 @@ export function ProviderList({ onAddKey }: { onAddKey: () => void }) {><Pencil className="size-3" /></Button>- {!k.keyless && (+ {!k.keyless && !isSearchPlatform(k.platform) && (<Tooltip text={t('keys.editModels')}><Buttonvariant="ghost"diff --git a/client/src/components/model-combobox.tsx b/client/src/components/model-combobox.tsxindex 1e9be28e..e692e3d2 100644--- a/client/src/components/model-combobox.tsx+++ b/client/src/components/model-combobox.tsx@@ -1,4 +1,4 @@-import { useState, type ReactNode } from 'react'+import { Fragment, useState, type ReactNode } from 'react'import { ChevronsUpDown, Check, Search } from 'lucide-react'import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'import { Tooltip } from '@/components/tooltip'@@ -21,6 +21,12 @@ export interface ModelComboOption {* "no image support" while the Playground has an image attached).*/note?: string+ /**+ * Section heading. Consecutive options sharing a group are listed under one+ * heading, drawn when the group changes (the Add key picker's Search vs+ * Models split). Options without one get no heading.+ */+ group?: string}export function ModelCombobox({@@ -125,35 +131,41 @@ export function ModelCombobox({<div className="px-2 py-6 text-center text-xs text-muted-foreground">{emptyText}</div>) : (filtered.map((o, i) => (- <button- key={o.value}- type="button"- onMouseEnter={() => setActive(i)}- onClick={() => pick(o.value)}- className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent hover:text-accent-foreground ${- o.value === value ? 'bg-accent/50' : i === active ? 'bg-muted' : ''- }`}- >- <Check className={`size-4 shrink-0 ${o.value === value ? 'opacity-100' : 'opacity-0'}`} />- <span className={`min-w-0 flex-1 truncate ${o.note ? 'opacity-50' : ''}`} title={o.label}>{o.label}</span>- {o.note && (- <span className="rounded px-1 py-0.5 text-[9px] font-semibold uppercase leading-none tracking-wide bg-amber-500/15 text-amber-600 dark:text-amber-400">- {o.note}- </span>- )}- {o.isNew && (- <span className="rounded px-1 py-0.5 text-[9px] font-semibold uppercase leading-none tracking-wide bg-emerald-500/15 text-emerald-600 dark:text-emerald-400">- {t('models.newBadge')}- </span>+ <Fragment key={o.value}>+ {o.group && o.group !== filtered[i - 1]?.group && (+ <div className="px-2 pt-2 pb-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ {o.group}+ </div>)}- {o.sub && ((o.platforms?.length ?? 0) > 1 ? (- <Tooltip text={t('models.servedBy', { providers: (o.platforms ?? []).join('\n') })}>- <span className="shrink-0 text-xs text-muted-foreground underline decoration-dotted underline-offset-2">{o.sub}</span>- </Tooltip>- ) : (- <span className="shrink-0 text-xs text-muted-foreground">{o.sub}</span>- ))}- </button>+ <button+ type="button"+ onMouseEnter={() => setActive(i)}+ onClick={() => pick(o.value)}+ className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent hover:text-accent-foreground ${+ o.value === value ? 'bg-accent/50' : i === active ? 'bg-muted' : ''+ }`}+ >+ <Check className={`size-4 shrink-0 ${o.value === value ? 'opacity-100' : 'opacity-0'}`} />+ <span className={`min-w-0 flex-1 truncate ${o.note ? 'opacity-50' : ''}`} title={o.label}>{o.label}</span>+ {o.note && (+ <span className="rounded px-1 py-0.5 text-[9px] font-semibold uppercase leading-none tracking-wide bg-amber-500/15 text-amber-600 dark:text-amber-400">+ {o.note}+ </span>+ )}+ {o.isNew && (+ <span className="rounded px-1 py-0.5 text-[9px] font-semibold uppercase leading-none tracking-wide bg-emerald-500/15 text-emerald-600 dark:text-emerald-400">+ {t('models.newBadge')}+ </span>+ )}+ {o.sub && ((o.platforms?.length ?? 0) > 1 ? (+ <Tooltip text={t('models.servedBy', { providers: (o.platforms ?? []).join('\n') })}>+ <span className="shrink-0 text-xs text-muted-foreground underline decoration-dotted underline-offset-2">{o.sub}</span>+ </Tooltip>+ ) : (+ <span className="shrink-0 text-xs text-muted-foreground">{o.sub}</span>+ ))}+ </button>+ </Fragment>)))}{footer}diff --git a/client/src/components/models-tabs.tsx b/client/src/components/models-tabs.tsxindex 439ef27c..8230b897 100644--- a/client/src/components/models-tabs.tsx+++ b/client/src/components/models-tabs.tsx@@ -19,6 +19,7 @@ export function ModelsTabs() {<NavLink to="/models/image" className={({ isActive }) => tab(isActive)}>{t('models.imageTab')}</NavLink><NavLink to="/models/video" className={({ isActive }) => tab(isActive)}>{t('models.videoTab')}</NavLink><NavLink to="/models/audio" className={({ isActive }) => tab(isActive)}>{t('models.audioTab')}</NavLink>+ <NavLink to="/models/search" className={({ isActive }) => tab(isActive)}>{t('search.tab')}</NavLink><NavLink to="/models/fusion" className={({ isActive }) => tab(isActive)}>{t('models.fusionTab')}</NavLink></div>)diff --git a/client/src/components/playground/liquid-composer.tsx b/client/src/components/playground/liquid-composer.tsxindex 28cebb77..c90f34c0 100644--- a/client/src/components/playground/liquid-composer.tsx+++ b/client/src/components/playground/liquid-composer.tsx@@ -1,6 +1,6 @@import { useEffect, useState, type ClipboardEvent, type KeyboardEvent, type RefObject } from 'react'import { Liquid } from 'liquid-gooey'-import { ArrowUp, Paperclip } from 'lucide-react'+import { ArrowUp, Globe, Paperclip, X } from 'lucide-react'import { Button } from '@/components/ui/button'import { DictationButton, type DictationPhase } from './dictation-button'import { DictationWave } from './dictation-wave'@@ -44,10 +44,12 @@ export interface LiquidComposerProps {labels: { attach: string; send: string; sending: string }/** Speech to text for the mic; the transcript is appended to `value`. */dictation: { available: boolean; model: string; apiKey: string | null | undefined; onText: (text: string) => void }+ /** Shown as a chip while web search is on (#1174); clicking it turns it off. */+ webSearch?: { label: string; offLabel: string; onDisable: () => void }}export function LiquidComposer({- inputRef, value, onChange, onKeyDown, onPaste, placeholder, hasContent, loading, onSend, onAttach, labels, dictation,+ inputRef, value, onChange, onKeyDown, onPaste, placeholder, hasContent, loading, onSend, onAttach, labels, dictation, webSearch,}: LiquidComposerProps) {// Set from input events; an empty value never counts as grown, so a// programmatic clear (send, new chat) drops back to one line by itself.@@ -96,6 +98,19 @@ export function LiquidComposer({><Paperclip className="size-4" /></Button>+ {webSearch && (+ <button+ type="button"+ onClick={webSearch.onDisable}+ aria-label={webSearch.offLabel}+ title={webSearch.offLabel}+ className={`group/ws inline-flex h-7 shrink-0 items-center gap-1 self-center rounded-full border border-sky-600/30 bg-background px-2 text-[11px] text-sky-700 transition-colors hover:border-foreground/20 hover:text-foreground dark:text-sky-300 ${grown ? 'mb-0.5' : ''}`}+ >+ <Globe className="size-3 group-hover/ws:hidden" />+ <X className="hidden size-3 group-hover/ws:block" />+ {webSearch.label}+ </button>+ )}{/* While the mic is open the field shows the voice, not the text:the textarea keeps its value and size, the wave paints over it. */}{/* A flex wrapper: an inline textarea inside a block div gets adiff --git a/client/src/components/playground/search-sources.tsx b/client/src/components/playground/search-sources.tsxnew file mode 100644index 00000000..b169d2e3--- /dev/null+++ b/client/src/components/playground/search-sources.tsx@@ -0,0 +1,38 @@+import { Globe } from 'lucide-react'+import { useI18n } from '@/i18n'+import { hostOf } from '@/lib/search'+import type { WebSearchMeta } from '@/lib/playground-conversations'++// The sources a web-searched answer was given (#1174), numbered to match the+// [n] citations the model was asked to use, with the engine that ran the+// search and how long it took.+export function SearchSources({ search }: { search: WebSearchMeta }) {+ const { t } = useI18n()+ return (+ <div className="mt-3 w-full rounded-xl border bg-muted/30 px-3 py-2 text-xs">+ <div className="mb-1 flex items-center gap-1.5 text-muted-foreground">+ <Globe className="size-3" />+ <span className="tabular-nums">+ {t('search.searched', { engine: search.engine, count: search.sources.length, latency: search.latency })}+ </span>+ </div>+ <ol className="space-y-0.5">+ {search.sources.map((source, i) => (+ <li key={`${i}-${source.url}`} className="flex min-w-0 gap-1.5">+ <span className="shrink-0 text-muted-foreground tabular-nums">[{i + 1}]</span>+ <a+ href={source.url}+ target="_blank"+ rel="noopener noreferrer"+ className="min-w-0 truncate underline underline-offset-2 hover:text-foreground"+ title={source.url}+ >+ {source.title || hostOf(source.url)}+ </a>+ <span className="shrink-0 text-muted-foreground">— {hostOf(source.url)}</span>+ </li>+ ))}+ </ol>+ </div>+ )+}diff --git a/client/src/components/playground/settings-rail.tsx b/client/src/components/playground/settings-rail.tsxindex d90fbd21..b577d235 100644--- a/client/src/components/playground/settings-rail.tsx+++ b/client/src/components/playground/settings-rail.tsx@@ -57,6 +57,13 @@ export interface SettingsRailProps {onSystemPromptChange: (value: string) => voidsampling: SamplingSettingsonSamplingChange: (next: SamplingSettings) => void+ /** Look the question up with POST /v1/search before answering (#1174). */+ webSearch: boolean+ onWebSearchChange: (enabled: boolean) => void+ /** False until at least one search key is configured. */+ webSearchAvailable: boolean+ /** Enabled engines in failover order, e.g. "Tavily → Exa". */+ webSearchChain: string}function SamplingControlRow({@@ -146,11 +153,15 @@ export function SettingsRail({onSystemPromptChange,sampling,onSamplingChange,+ webSearch,+ onWebSearchChange,+ webSearchAvailable,+ webSearchChain,}: SettingsRailProps) {const { t } = useI18n()// Anything the collapsed strip should own up to: a system prompt riding on// every request, or a knob overriding the provider's default.- const tweaked = samplingActiveCount(sampling) > 0 || systemPrompt.trim().length > 0+ const tweaked = samplingActiveCount(sampling) > 0 || systemPrompt.trim().length > 0 || webSearchreturn (<div@@ -270,6 +281,32 @@ export function SettingsRail({/>))}</div>++ <div className="space-y-2">+ <div className="space-y-0.5">+ <span className="block text-xs font-medium">{t('search.playgroundHeading')}</span>+ <p className="text-[11px] leading-snug text-muted-foreground">+ {webSearchAvailable ? t('search.playgroundHelp') : t('search.playgroundNoKeys')}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <label htmlFor="playground-web-search" className="flex-1 text-xs">+ {t('search.playgroundToggle')}+ </label>+ <Switch+ id="playground-web-search"+ size="sm"+ checked={webSearch && webSearchAvailable}+ onCheckedChange={onWebSearchChange}+ disabled={!webSearchAvailable}+ />+ </div>+ {webSearchAvailable && webSearchChain && (+ <p className="text-[11px] text-muted-foreground">+ {t('search.playgroundEngines', { chain: webSearchChain })}+ </p>+ )}+ </div></div></div></div>diff --git a/client/src/components/search-engines.test.tsx b/client/src/components/search-engines.test.tsxnew file mode 100644index 00000000..3ba3580a--- /dev/null+++ b/client/src/components/search-engines.test.tsx@@ -0,0 +1,85 @@+// @vitest-environment jsdom+// #1174: Models → Search lists the catalog's search engines in failover order,+// marks the first enabled one as default, badges Premium-first rows with the+// day they reach Free, and promotes an engine with PATCH priority 0.+import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { MemoryRouter } from 'react-router-dom'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { I18nProvider } from '@/i18n'+import { apiFetch } from '@/lib/api'+import type { SearchEngine } from '@/lib/search'+import { SearchEnginesView } from './search-engines'++vi.mock('@/lib/api', () => ({ apiFetch: vi.fn() }))++const engine = (over: Partial<SearchEngine>): SearchEngine => ({+ id: 1, platform: 'tavily', engineId: 'tavily-search', displayName: 'Tavily', priority: 0,+ enabled: true, quotaLabel: '1,000 credits/month', creditsPerQuery: 1, features: null,+ premiumSince: null, keyCount: 1, healthyKeyCount: 1, searchesThisMonth: 0, ...over,+})++let root: Root+let container: HTMLDivElement+let client: QueryClient++beforeAll(() => { (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true })+beforeEach(() => {+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } } })+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container)+})+afterEach(() => { act(() => root.unmount()); client.clear(); container.remove() })++async function flush() { for (let i = 0; i < 4; i++) await act(async () => { await new Promise(r => setTimeout(r, 0)) }) }+async function mount(engines: SearchEngine[]) {+ vi.mocked(apiFetch).mockReset().mockImplementation(async (path: string) => {+ if (path === '/api/search/engines') return engines+ if (path.startsWith('/api/analytics/search')) return { total: 0, today: 3, successRate: 100, avgLatencyMs: 0, byEngine: [], series: [] }+ return {}+ })+ act(() => root.render(+ <QueryClientProvider client={client}>+ <I18nProvider initialLocale="en">+ <MemoryRouter><SearchEnginesView /></MemoryRouter>+ </I18nProvider>+ </QueryClientProvider>+ ))+ await flush()+}++it('lists engines in priority order and marks the first enabled one as default', async () => {+ await mount([+ engine({ id: 2, platform: 'exa', engineId: 'exa-search', displayName: 'Exa', priority: 1, searchesThisMonth: 12 }),+ engine({ id: 1, searchesThisMonth: 40 }),+ ])+ const names = [...container.querySelectorAll('section span.font-mono')]+ .map(s => s.textContent)+ .filter(text => text?.endsWith('-search'))+ expect(names).toEqual(['tavily-search', 'exa-search'])+ expect(container.textContent).toContain('Default')+ // The month card sums the engine rows; today comes from the analytics call.+ expect(container.textContent).toContain('52 req this month')+ expect(container.textContent).toContain('3 req today')+})++it('badges a Premium-first engine with the day it reaches Free', async () => {+ const since = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()+ await mount([engine({ id: 3, platform: 'firecrawl', engineId: 'firecrawl-search', displayName: 'Firecrawl', premiumSince: since })])+ expect(container.textContent).toMatch(/Premium · free from/)+})++it('promotes an engine to default with priority 0', async () => {+ await mount([engine({ id: 1 }), engine({ id: 2, platform: 'exa', engineId: 'exa-search', displayName: 'Exa', priority: 1 })])+ const button = [...container.querySelectorAll('button')].find(b => b.textContent === 'Make default')!+ act(() => { button.click() })+ await flush()+ const patch = vi.mocked(apiFetch).mock.calls.find(([, init]) => init?.method === 'PATCH')+ expect(patch?.[0]).toBe('/api/search/engines/2')+ expect(JSON.parse(String(patch?.[1]?.body))).toEqual({ priority: 0 })+})++it('shows the empty state before the catalog carries any engine', async () => {+ await mount([])+ expect(container.textContent).toContain('No search engines yet')+})diff --git a/client/src/components/search-engines.tsx b/client/src/components/search-engines.tsxnew file mode 100644index 00000000..a0157952--- /dev/null+++ b/client/src/components/search-engines.tsx@@ -0,0 +1,184 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Globe } from 'lucide-react'+import { apiFetch } from '@/lib/api'+import { Switch } from '@/components/ui/switch'+import { EmptyState } from '@/components/empty-state'+import { CardSkeleton } from '@/components/ui/skeleton'+import { PageHeader } from '@/components/page-header'+import { ModelsTabs } from '@/components/models-tabs'+import { UsageSummaryCard } from '@/components/usage-summary-card'+import { useI18n } from '@/i18n'+import { engineChain, freeFromDate, type SearchAnalytics, type SearchEngine } from '@/lib/search'++const pill = 'text-[10px] rounded-full px-1.5 py-0.5 bg-muted text-muted-foreground'++// One engine from the catalog's `searchEngines` section. Its position in the+// failover order is shown as a number; the first enabled engine is the+// default, and any other can be promoted to it in one click.+function SearchEngineCard({+ engine: e,+ position,+ isDefault,+ onToggle,+ onMakeDefault,+ pending,+}: {+ engine: SearchEngine+ position: number | null+ isDefault: boolean+ onToggle: (enabled: boolean) => void+ onMakeDefault: () => void+ pending: boolean+}) {+ const { t, locale } = useI18n()+ const freeFrom = freeFromDate(e.premiumSince)+ const features = e.features ?? {}+ return (+ <section className={`rounded-3xl border bg-card p-5 ${e.enabled ? '' : 'opacity-60'}`}>+ <div className="mb-3 flex flex-wrap items-center gap-2">+ <span className="font-mono text-sm font-medium">{e.engineId}</span>+ {e.creditsPerQuery != null && (+ <span className={`${pill} tabular-nums`}>+ {e.creditsPerQuery === 1+ ? t('search.creditsPerSearchOne')+ : t('search.creditsPerSearchOther', { count: e.creditsPerQuery })}+ </span>+ )}+ {freeFrom && (+ <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-amber-600/15 text-amber-700 dark:bg-amber-400/15 dark:text-amber-400">+ {t('search.premiumBadge', {+ date: freeFrom.toLocaleDateString(locale, { day: 'numeric', month: 'short' }),+ })}+ </span>+ )}+ {features.news && <span className={pill}>{t('search.featureNews')}</span>}+ {features.answer && <span className={pill}>{t('search.featureAnswer')}</span>}+ {features.fullContent && <span className={pill}>{t('search.featureFullContent')}</span>}+ {isDefault ? (+ <span className="text-xs text-muted-foreground">{t('search.default')}</span>+ ) : e.enabled && (+ <button+ type="button"+ onClick={onMakeDefault}+ disabled={pending}+ className="text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground disabled:opacity-50"+ >+ {t('search.makeDefault')}+ </button>+ )}+ <span className="flex-1" />+ <span className="text-xs text-muted-foreground tabular-nums">+ {t('search.thisMonth', { count: e.searchesThisMonth })}+ </span>+ </div>++ <div className="flex items-center gap-3">+ <span className="w-4 text-center text-xs text-muted-foreground tabular-nums">{position ?? '–'}</span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">{e.displayName}</span>+ {e.keyCount === 0 && (+ <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-amber-600/15 text-amber-700 dark:bg-amber-400/15 dark:text-amber-400">+ {t('models.noKey')}+ </span>+ )}+ </div>+ <div className="truncate text-[11px] text-muted-foreground">+ {[e.platform, e.quotaLabel].filter(Boolean).join(' · ')}+ </div>+ </div>+ <Switch+ checked={e.enabled}+ onCheckedChange={onToggle}+ disabled={pending}+ aria-label={e.displayName}+ />+ </div>+ </section>+ )+}++// Models → Search: the catalog's search engines in failover order, with the+// same month-to-date usage card the media tabs use. Rows sync from the signed+// catalog like every other modality; the toggles and "Make default" are the+// operator's local overrides.+export function SearchEnginesView() {+ const { t } = useI18n()+ const queryClient = useQueryClient()++ const { data: engines = [], isLoading } = useQuery<SearchEngine[]>({+ queryKey: ['search-engines'],+ queryFn: () => apiFetch('/api/search/engines'),+ refetchInterval: 30_000,+ })++ // Only `today` is read here; the month total is the sum of the engine rows.+ const { data: analytics } = useQuery<SearchAnalytics>({+ queryKey: ['analytics', 'search', '30d'],+ queryFn: () => apiFetch('/api/analytics/search?range=30d'),+ refetchInterval: 30_000,+ })++ const update = useMutation({+ mutationFn: ({ id, ...body }: { id: number; enabled?: boolean; priority?: number }) =>+ apiFetch(`/api/search/engines/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['search-engines'] }),+ })++ const ordered = engines+ .slice()+ .sort((a, b) => a.priority - b.priority || a.displayName.localeCompare(b.displayName))+ const chain = engineChain(engines)+ const positions = new Map(chain.map((e, i) => [e.id, i + 1]))+ const total = engines.reduce((n, e) => n + e.searchesThisMonth, 0)++ return (+ <div>+ <PageHeader title={t('models.title')} description={t('search.pageDesc')} divider={false} actions={<ModelsTabs />} />++ <div className="space-y-4">+ <p className="text-xs text-muted-foreground">+ {t('search.endpointHint')}{' '}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">POST /v1/search</code>{' '}+ {t('search.agentsHint')}+ </p>++ {engines.length > 0 && (+ <UsageSummaryCard+ unit="requests"+ total={total}+ requestsToday={analytics?.today ?? 0}+ rows={ordered.map(e => ({+ label: e.displayName,+ platform: e.platform,+ quotaLabel: e.quotaLabel,+ amount: e.searchesThisMonth,+ requestsToday: 0,+ }))}+ />+ )}++ {isLoading ? (+ <>+ <CardSkeleton />+ <CardSkeleton />+ </>+ ) : ordered.length === 0 ? (+ <EmptyState icon={Globe} title={t('search.empty')} />+ ) : (+ ordered.map(e => (+ <SearchEngineCard+ key={e.id}+ engine={e}+ position={positions.get(e.id) ?? null}+ isDefault={chain[0]?.id === e.id}+ onToggle={enabled => update.mutate({ id: e.id, enabled })}+ onMakeDefault={() => update.mutate({ id: e.id, priority: 0 })}+ pending={update.isPending}+ />+ ))+ )}+ </div>+ </div>+ )+}diff --git a/client/src/i18n/locales/am.json b/client/src/i18n/locales/am.jsonindex a5026aa3..90b5d8af 100644--- a/client/src/i18n/locales/am.json+++ b/client/src/i18n/locales/am.json@@ -1227,5 +1227,42 @@"releaseNotes": "የልቀት ማስታወሻዎች","tryAgain": "እንደገና ሞክር","offline": "የበይነመረብ ግንኙነትዎን ያረጋግጡና እንደገና ይሞክሩ።"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ar.json b/client/src/i18n/locales/ar.jsonindex ba9f91da..9616e9b6 100644--- a/client/src/i18n/locales/ar.json+++ b/client/src/i18n/locales/ar.json@@ -1227,5 +1227,42 @@"releaseNotes": "ملاحظات الإصدار","tryAgain": "أعد المحاولة","offline": "تحقّق من اتصالك بالإنترنت ثم أعد المحاولة."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/az.json b/client/src/i18n/locales/az.jsonindex ea9099fe..358ef5c4 100644--- a/client/src/i18n/locales/az.json+++ b/client/src/i18n/locales/az.json@@ -1227,5 +1227,42 @@"releaseNotes": "Buraxılış qeydləri","tryAgain": "Yenidən cəhd et","offline": "İnternet bağlantınızı yoxlayın və yenidən cəhd edin."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/bg.json b/client/src/i18n/locales/bg.jsonindex 23a8709e..9b73766e 100644--- a/client/src/i18n/locales/bg.json+++ b/client/src/i18n/locales/bg.json@@ -1227,5 +1227,42 @@"releaseNotes": "Бележки по изданието","tryAgain": "Опитай отново","offline": "Проверете интернет връзката си и опитайте отново."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/bn.json b/client/src/i18n/locales/bn.jsonindex cb71fe00..929c1e1e 100644--- a/client/src/i18n/locales/bn.json+++ b/client/src/i18n/locales/bn.json@@ -1227,5 +1227,42 @@"releaseNotes": "রিলিজ নোট","tryAgain": "আবার চেষ্টা করুন","offline": "আপনার ইন্টারনেট সংযোগ দেখে আবার চেষ্টা করুন।"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/cs.json b/client/src/i18n/locales/cs.jsonindex 0d87be11..df27525d 100644--- a/client/src/i18n/locales/cs.json+++ b/client/src/i18n/locales/cs.json@@ -1227,5 +1227,42 @@"releaseNotes": "Poznámky k vydání","tryAgain": "Zkusit znovu","offline": "Zkontrolujte připojení k internetu a zkuste to znovu."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/da.json b/client/src/i18n/locales/da.jsonindex b94fd7f7..64a3676e 100644--- a/client/src/i18n/locales/da.json+++ b/client/src/i18n/locales/da.json@@ -1227,5 +1227,42 @@"releaseNotes": "Udgivelsesnoter","tryAgain": "Prøv igen","offline": "Tjek din internetforbindelse, og prøv igen."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/de.json b/client/src/i18n/locales/de.jsonindex bd2002a6..898edb38 100644--- a/client/src/i18n/locales/de.json+++ b/client/src/i18n/locales/de.json@@ -1227,5 +1227,42 @@"releaseNotes": "Versionshinweise","tryAgain": "Erneut versuchen","offline": "Prüfen Sie Ihre Internetverbindung und versuchen Sie es erneut."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/el.json b/client/src/i18n/locales/el.jsonindex 77bc1ba4..ef56505e 100644--- a/client/src/i18n/locales/el.json+++ b/client/src/i18n/locales/el.json@@ -1227,5 +1227,42 @@"releaseNotes": "Σημειώσεις έκδοσης","tryAgain": "Δοκιμάστε ξανά","offline": "Ελέγξτε τη σύνδεσή σας στο διαδίκτυο και δοκιμάστε ξανά."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex b2510f52..a1400968 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -1226,5 +1226,42 @@"releaseNotes": "Release notes","tryAgain": "Try again","offline": "Check your internet connection and try again."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}}diff --git a/client/src/i18n/locales/es.json b/client/src/i18n/locales/es.jsonindex f8f8136c..05ffb4ed 100644--- a/client/src/i18n/locales/es.json+++ b/client/src/i18n/locales/es.json@@ -1227,5 +1227,42 @@"releaseNotes": "Notas de la versión","tryAgain": "Reintentar","offline": "Comprueba tu conexión a internet y vuelve a intentarlo."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/fa.json b/client/src/i18n/locales/fa.jsonindex 0f92ab08..6722dec6 100644--- a/client/src/i18n/locales/fa.json+++ b/client/src/i18n/locales/fa.json@@ -1227,5 +1227,42 @@"releaseNotes": "یادداشتهای انتشار","tryAgain": "دوباره تلاش کنید","offline": "اتصال اینترنت خود را بررسی کنید و دوباره تلاش کنید."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/fi.json b/client/src/i18n/locales/fi.jsonindex dbf492dc..837c452c 100644--- a/client/src/i18n/locales/fi.json+++ b/client/src/i18n/locales/fi.json@@ -1227,5 +1227,42 @@"releaseNotes": "Julkaisutiedot","tryAgain": "Yritä uudelleen","offline": "Tarkista internetyhteys ja yritä uudelleen."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/fr.json b/client/src/i18n/locales/fr.jsonindex 2b961d7b..27d80c6d 100644--- a/client/src/i18n/locales/fr.json+++ b/client/src/i18n/locales/fr.json@@ -1227,5 +1227,42 @@"releaseNotes": "Notes de version","tryAgain": "Réessayer","offline": "Vérifiez votre connexion internet et réessayez."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/gu.json b/client/src/i18n/locales/gu.jsonindex e2428fd2..d838ad19 100644--- a/client/src/i18n/locales/gu.json+++ b/client/src/i18n/locales/gu.json@@ -1227,5 +1227,42 @@"releaseNotes": "રિલીઝ નોંધો","tryAgain": "ફરી પ્રયાસ કરો","offline": "તમારું ઇન્ટરનેટ કનેક્શન તપાસો અને ફરી પ્રયાસ કરો."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ha.json b/client/src/i18n/locales/ha.jsonindex 0f643d30..c5b3afed 100644--- a/client/src/i18n/locales/ha.json+++ b/client/src/i18n/locales/ha.json@@ -1227,5 +1227,42 @@"releaseNotes": "Bayanan fitarwa","tryAgain": "Sake gwadawa","offline": "Duba haɗin intanet ɗinka sannan ka sake gwadawa."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/he.json b/client/src/i18n/locales/he.jsonindex ffd4b19b..9602bd25 100644--- a/client/src/i18n/locales/he.json+++ b/client/src/i18n/locales/he.json@@ -1227,5 +1227,42 @@"releaseNotes": "הערות גרסה","tryAgain": "נסו שוב","offline": "בדקו את החיבור לאינטרנט ונסו שוב."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/hi.json b/client/src/i18n/locales/hi.jsonindex d518fe7c..6606da88 100644--- a/client/src/i18n/locales/hi.json+++ b/client/src/i18n/locales/hi.json@@ -1227,5 +1227,42 @@"releaseNotes": "रिलीज़ नोट्स","tryAgain": "फिर से कोशिश करें","offline": "अपना इंटरनेट कनेक्शन जाँचें और फिर से कोशिश करें।"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/hr.json b/client/src/i18n/locales/hr.jsonindex c5c9c9cd..5d9b55a3 100644--- a/client/src/i18n/locales/hr.json+++ b/client/src/i18n/locales/hr.json@@ -1227,5 +1227,42 @@"releaseNotes": "Bilješke o izdanju","tryAgain": "Pokušaj ponovno","offline": "Provjerite internetsku vezu i pokušajte ponovno."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/hu.json b/client/src/i18n/locales/hu.jsonindex d74f9c32..61eed167 100644--- a/client/src/i18n/locales/hu.json+++ b/client/src/i18n/locales/hu.json@@ -1227,5 +1227,42 @@"releaseNotes": "Kiadási jegyzetek","tryAgain": "Próbálja újra","offline": "Ellenőrizze az internetkapcsolatot, és próbálja újra."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/id.json b/client/src/i18n/locales/id.jsonindex b094e8a3..ba0e46e2 100644--- a/client/src/i18n/locales/id.json+++ b/client/src/i18n/locales/id.json@@ -1227,5 +1227,42 @@"releaseNotes": "Catatan rilis","tryAgain": "Coba lagi","offline": "Periksa koneksi internet Anda lalu coba lagi."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ig.json b/client/src/i18n/locales/ig.jsonindex 4fcd5839..de31a20f 100644--- a/client/src/i18n/locales/ig.json+++ b/client/src/i18n/locales/ig.json@@ -1227,5 +1227,42 @@"releaseNotes": "Ndetu mwepụta","tryAgain": "Nwaa ọzọ","offline": "Lelee njikọ ịntanetị gị ma nwaa ọzọ."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/it.json b/client/src/i18n/locales/it.jsonindex 0e7bf3da..3f301328 100644--- a/client/src/i18n/locales/it.json+++ b/client/src/i18n/locales/it.json@@ -1227,5 +1227,42 @@"releaseNotes": "Note di rilascio","tryAgain": "Riprova","offline": "Controlla la connessione a internet e riprova."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ja.json b/client/src/i18n/locales/ja.jsonindex 1993e66d..5c5021ab 100644--- a/client/src/i18n/locales/ja.json+++ b/client/src/i18n/locales/ja.json@@ -1227,5 +1227,42 @@"releaseNotes": "リリースノート","tryAgain": "再試行","offline": "インターネット接続を確認して、もう一度お試しください。"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ka.json b/client/src/i18n/locales/ka.jsonindex 407064f5..c9f6fdf2 100644--- a/client/src/i18n/locales/ka.json+++ b/client/src/i18n/locales/ka.json@@ -1227,5 +1227,42 @@"releaseNotes": "გამოშვების შენიშვნები","tryAgain": "ხელახლა ცდა","offline": "შეამოწმეთ ინტერნეტკავშირი და სცადეთ ხელახლა."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/km.json b/client/src/i18n/locales/km.jsonindex 8cdec71b..9e55979a 100644--- a/client/src/i18n/locales/km.json+++ b/client/src/i18n/locales/km.json@@ -1227,5 +1227,42 @@"releaseNotes": "កំណត់ចំណាំការចេញផ្សាយ","tryAgain": "ព្យាយាមម្ដងទៀត","offline": "សូមពិនិត្យការតភ្ជាប់អ៊ីនធឺណិត ហើយព្យាយាមម្ដងទៀត។"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/kn.json b/client/src/i18n/locales/kn.jsonindex 341451f5..8ae2318b 100644--- a/client/src/i18n/locales/kn.json+++ b/client/src/i18n/locales/kn.json@@ -1227,5 +1227,42 @@"releaseNotes": "ಬಿಡುಗಡೆ ಟಿಪ್ಪಣಿಗಳು","tryAgain": "ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ","offline": "ನಿಮ್ಮ ಇಂಟರ್ನೆಟ್ ಸಂಪರ್ಕ ಪರಿಶೀಲಿಸಿ ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ko.json b/client/src/i18n/locales/ko.jsonindex c401199b..fe7409cd 100644--- a/client/src/i18n/locales/ko.json+++ b/client/src/i18n/locales/ko.json@@ -1227,5 +1227,42 @@"releaseNotes": "릴리스 노트","tryAgain": "다시 시도","offline": "인터넷 연결을 확인한 후 다시 시도하세요."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/lt.json b/client/src/i18n/locales/lt.jsonindex f24c4264..cedd1626 100644--- a/client/src/i18n/locales/lt.json+++ b/client/src/i18n/locales/lt.json@@ -1227,5 +1227,42 @@"releaseNotes": "Leidimo pastabos","tryAgain": "Bandyti dar kartą","offline": "Patikrinkite interneto ryšį ir bandykite dar kartą."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ml.json b/client/src/i18n/locales/ml.jsonindex 90baf528..c4f3e071 100644--- a/client/src/i18n/locales/ml.json+++ b/client/src/i18n/locales/ml.json@@ -1227,5 +1227,42 @@"releaseNotes": "റിലീസ് കുറിപ്പുകൾ","tryAgain": "വീണ്ടും ശ്രമിക്കുക","offline": "ഇന്റർനെറ്റ് കണക്ഷൻ പരിശോധിച്ച് വീണ്ടും ശ്രമിക്കുക."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/mr.json b/client/src/i18n/locales/mr.jsonindex 3bdc75c5..847ec8d5 100644--- a/client/src/i18n/locales/mr.json+++ b/client/src/i18n/locales/mr.json@@ -1227,5 +1227,42 @@"releaseNotes": "रिलीझ नोट्स","tryAgain": "पुन्हा प्रयत्न करा","offline": "तुमचे इंटरनेट कनेक्शन तपासा आणि पुन्हा प्रयत्न करा."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ms.json b/client/src/i18n/locales/ms.jsonindex d4d8bbfd..408c52d7 100644--- a/client/src/i18n/locales/ms.json+++ b/client/src/i18n/locales/ms.json@@ -1227,5 +1227,42 @@"releaseNotes": "Nota keluaran","tryAgain": "Cuba lagi","offline": "Semak sambungan internet anda dan cuba lagi."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/my.json b/client/src/i18n/locales/my.jsonindex 89915df8..aec9dfb2 100644--- a/client/src/i18n/locales/my.json+++ b/client/src/i18n/locales/my.json@@ -1227,5 +1227,42 @@"releaseNotes": "ထုတ်ဝေမှု မှတ်စုများ","tryAgain": "ထပ်ကြိုးစားပါ","offline": "အင်တာနက်ချိတ်ဆက်မှုကို စစ်ဆေးပြီး ထပ်ကြိုးစားပါ။"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ne.json b/client/src/i18n/locales/ne.jsonindex b384d1e9..2efecfdb 100644--- a/client/src/i18n/locales/ne.json+++ b/client/src/i18n/locales/ne.json@@ -1227,5 +1227,42 @@"releaseNotes": "रिलिज नोटहरू","tryAgain": "फेरि प्रयास गर्नुहोस्","offline": "आफ्नो इन्टरनेट जडान जाँच गरी फेरि प्रयास गर्नुहोस्।"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/nl.json b/client/src/i18n/locales/nl.jsonindex 1dd41f13..a9f86e7e 100644--- a/client/src/i18n/locales/nl.json+++ b/client/src/i18n/locales/nl.json@@ -1227,5 +1227,42 @@"releaseNotes": "Release-opmerkingen","tryAgain": "Opnieuw proberen","offline": "Controleer je internetverbinding en probeer het opnieuw."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/no.json b/client/src/i18n/locales/no.jsonindex f115f456..9a90752a 100644--- a/client/src/i18n/locales/no.json+++ b/client/src/i18n/locales/no.json@@ -1227,5 +1227,42 @@"releaseNotes": "Versjonsnotater","tryAgain": "Prøv igjen","offline": "Sjekk internettforbindelsen og prøv igjen."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/or.json b/client/src/i18n/locales/or.jsonindex 31551c91..ee8721e8 100644--- a/client/src/i18n/locales/or.json+++ b/client/src/i18n/locales/or.json@@ -1227,5 +1227,42 @@"releaseNotes": "ରିଲିଜ୍ ନୋଟ୍","tryAgain": "ପୁଣି ଚେଷ୍ଟା କରନ୍ତୁ","offline": "ଆପଣଙ୍କ ଇଣ୍ଟରନେଟ୍ ସଂଯୋଗ ଯାଞ୍ଚ କରି ପୁଣି ଚେଷ୍ଟା କରନ୍ତୁ।"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/pa.json b/client/src/i18n/locales/pa.jsonindex 8508fa1a..7beba94b 100644--- a/client/src/i18n/locales/pa.json+++ b/client/src/i18n/locales/pa.json@@ -1227,5 +1227,42 @@"releaseNotes": "ਰਿਲੀਜ਼ ਨੋਟਸ","tryAgain": "ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ","offline": "ਆਪਣਾ ਇੰਟਰਨੈੱਟ ਕਨੈਕਸ਼ਨ ਜਾਂਚੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/pl.json b/client/src/i18n/locales/pl.jsonindex 151c5d2b..55a8a69b 100644--- a/client/src/i18n/locales/pl.json+++ b/client/src/i18n/locales/pl.json@@ -1227,5 +1227,42 @@"releaseNotes": "Informacje o wydaniu","tryAgain": "Spróbuj ponownie","offline": "Sprawdź połączenie z internetem i spróbuj ponownie."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/pt-BR.json b/client/src/i18n/locales/pt-BR.jsonindex 45cecb6e..4477ee17 100644--- a/client/src/i18n/locales/pt-BR.json+++ b/client/src/i18n/locales/pt-BR.json@@ -1227,5 +1227,42 @@"releaseNotes": "Notas da versão","tryAgain": "Tentar novamente","offline": "Verifique sua conexão com a internet e tente novamente."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/pt-PT.json b/client/src/i18n/locales/pt-PT.jsonindex c0964a61..d7937565 100644--- a/client/src/i18n/locales/pt-PT.json+++ b/client/src/i18n/locales/pt-PT.json@@ -1227,5 +1227,42 @@"releaseNotes": "Notas da versão","tryAgain": "Tentar novamente","offline": "Verifique a sua ligação à internet e tente novamente."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ro.json b/client/src/i18n/locales/ro.jsonindex aaf792c6..4ef1efda 100644--- a/client/src/i18n/locales/ro.json+++ b/client/src/i18n/locales/ro.json@@ -1227,5 +1227,42 @@"releaseNotes": "Note de lansare","tryAgain": "Încearcă din nou","offline": "Verifică conexiunea la internet și încearcă din nou."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ru.json b/client/src/i18n/locales/ru.jsonindex 24600203..75a5e425 100644--- a/client/src/i18n/locales/ru.json+++ b/client/src/i18n/locales/ru.json@@ -1227,5 +1227,42 @@"releaseNotes": "Примечания к выпуску","tryAgain": "Повторить","offline": "Проверьте подключение к интернету и повторите попытку."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/si.json b/client/src/i18n/locales/si.jsonindex d89aa7fe..f2f24f94 100644--- a/client/src/i18n/locales/si.json+++ b/client/src/i18n/locales/si.json@@ -1227,5 +1227,42 @@"releaseNotes": "නිකුතු සටහන්","tryAgain": "නැවත උත්සාහ කරන්න","offline": "ඔබගේ අන්තර්ජාල සම්බන්ධතාවය පරීක්ෂා කර නැවත උත්සාහ කරන්න."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/sk.json b/client/src/i18n/locales/sk.jsonindex 90420473..38a7e824 100644--- a/client/src/i18n/locales/sk.json+++ b/client/src/i18n/locales/sk.json@@ -1227,5 +1227,42 @@"releaseNotes": "Poznámky k vydaniu","tryAgain": "Skúsiť znova","offline": "Skontrolujte pripojenie na internet a skúste to znova."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/sr.json b/client/src/i18n/locales/sr.jsonindex 6dc7a996..03e951fa 100644--- a/client/src/i18n/locales/sr.json+++ b/client/src/i18n/locales/sr.json@@ -1227,5 +1227,42 @@"releaseNotes": "Белешке о издању","tryAgain": "Покушај поново","offline": "Проверите интернет везу и покушајте поново."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/sv.json b/client/src/i18n/locales/sv.jsonindex d31d2a79..60ab6f97 100644--- a/client/src/i18n/locales/sv.json+++ b/client/src/i18n/locales/sv.json@@ -1227,5 +1227,42 @@"releaseNotes": "Versionsinformation","tryAgain": "Försök igen","offline": "Kontrollera internetanslutningen och försök igen."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/sw.json b/client/src/i18n/locales/sw.jsonindex 8e0995f5..68699ccd 100644--- a/client/src/i18n/locales/sw.json+++ b/client/src/i18n/locales/sw.json@@ -1227,5 +1227,42 @@"releaseNotes": "Maelezo ya toleo","tryAgain": "Jaribu tena","offline": "Kagua muunganisho wako wa intaneti kisha ujaribu tena."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ta.json b/client/src/i18n/locales/ta.jsonindex 30a406d0..64375746 100644--- a/client/src/i18n/locales/ta.json+++ b/client/src/i18n/locales/ta.json@@ -1227,5 +1227,42 @@"releaseNotes": "வெளியீட்டுக் குறிப்புகள்","tryAgain": "மீண்டும் முயல்க","offline": "இணைய இணைப்பைச் சரிபார்த்து மீண்டும் முயலவும்."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/te.json b/client/src/i18n/locales/te.jsonindex 328dd41c..a2be8f72 100644--- a/client/src/i18n/locales/te.json+++ b/client/src/i18n/locales/te.json@@ -1227,5 +1227,42 @@"releaseNotes": "విడుదల గమనికలు","tryAgain": "మళ్లీ ప్రయత్నించండి","offline": "మీ ఇంటర్నెట్ కనెక్షన్ను తనిఖీ చేసి మళ్లీ ప్రయత్నించండి."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/th.json b/client/src/i18n/locales/th.jsonindex 0ca2bdd4..4e459395 100644--- a/client/src/i18n/locales/th.json+++ b/client/src/i18n/locales/th.json@@ -1227,5 +1227,42 @@"releaseNotes": "บันทึกประจำรุ่น","tryAgain": "ลองอีกครั้ง","offline": "ตรวจสอบการเชื่อมต่ออินเทอร์เน็ตแล้วลองอีกครั้ง"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/tl.json b/client/src/i18n/locales/tl.jsonindex dc17b795..c1e7db59 100644--- a/client/src/i18n/locales/tl.json+++ b/client/src/i18n/locales/tl.json@@ -1227,5 +1227,42 @@"releaseNotes": "Mga release note","tryAgain": "Subukang muli","offline": "Tingnan ang iyong koneksyon sa internet at subukang muli."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/tr.json b/client/src/i18n/locales/tr.jsonindex 9abbd362..d8128fae 100644--- a/client/src/i18n/locales/tr.json+++ b/client/src/i18n/locales/tr.json@@ -1227,5 +1227,42 @@"releaseNotes": "Sürüm notları","tryAgain": "Tekrar dene","offline": "İnternet bağlantınızı kontrol edip tekrar deneyin."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/uk.json b/client/src/i18n/locales/uk.jsonindex eb81ca37..b28230e5 100644--- a/client/src/i18n/locales/uk.json+++ b/client/src/i18n/locales/uk.json@@ -1227,5 +1227,42 @@"releaseNotes": "Примітки до випуску","tryAgain": "Спробувати ще раз","offline": "Перевірте підключення до інтернету й спробуйте ще раз."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/ur.json b/client/src/i18n/locales/ur.jsonindex 8a1c7956..613381ae 100644--- a/client/src/i18n/locales/ur.json+++ b/client/src/i18n/locales/ur.json@@ -1227,5 +1227,42 @@"releaseNotes": "ریلیز نوٹس","tryAgain": "دوبارہ کوشش کریں","offline": "اپنا انٹرنیٹ کنکشن چیک کریں اور دوبارہ کوشش کریں۔"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/uz.json b/client/src/i18n/locales/uz.jsonindex 2973ad9b..fd951c20 100644--- a/client/src/i18n/locales/uz.json+++ b/client/src/i18n/locales/uz.json@@ -1227,5 +1227,42 @@"releaseNotes": "Reliz eslatmalari","tryAgain": "Qayta urinish","offline": "Internet aloqangizni tekshirib, qayta urinib ko‘ring."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/vi.json b/client/src/i18n/locales/vi.jsonindex a07c63d7..de5f2985 100644--- a/client/src/i18n/locales/vi.json+++ b/client/src/i18n/locales/vi.json@@ -1227,5 +1227,42 @@"releaseNotes": "Ghi chú phát hành","tryAgain": "Thử lại","offline": "Kiểm tra kết nối internet rồi thử lại."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/yo.json b/client/src/i18n/locales/yo.jsonindex e03ed14d..377c7aca 100644--- a/client/src/i18n/locales/yo.json+++ b/client/src/i18n/locales/yo.json@@ -1227,5 +1227,42 @@"releaseNotes": "Àkọsílẹ̀ ìtújáde","tryAgain": "Gbìyànjú lẹ́ẹ̀kan sí i","offline": "Ṣàyẹ̀wò ìsopọ̀ íńtánẹ́ẹ̀tì rẹ kí o sì gbìyànjú lẹ́ẹ̀kan sí i."+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/zh-CN.json b/client/src/i18n/locales/zh-CN.jsonindex f9668ef6..0c0419ad 100644--- a/client/src/i18n/locales/zh-CN.json+++ b/client/src/i18n/locales/zh-CN.json@@ -1227,5 +1227,42 @@"releaseNotes": "发行说明","tryAgain": "重试","offline": "请检查网络连接后重试。"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/i18n/locales/zh-TW.json b/client/src/i18n/locales/zh-TW.jsonindex 0ec68bff..9721a68d 100644--- a/client/src/i18n/locales/zh-TW.json+++ b/client/src/i18n/locales/zh-TW.json@@ -1227,5 +1227,42 @@"releaseNotes": "版本資訊","tryAgain": "重試","offline": "請檢查網路連線後再試一次。"+ },+ "search": {+ "tab": "Search",+ "pageDesc": "Web search engines your apps and agents can call. Engines are tried in priority order; when one runs out of free credits the next one takes over.",+ "endpointHint": "Search via",+ "agentsHint": "— also answers web searches from Claude Code and Codex. New engines reach Premium first and Free 30 days later.",+ "empty": "No search engines yet. They sync from the catalog.",+ "creditsPerSearchOne": "1 credit / search",+ "creditsPerSearchOther": "{count} credits / search",+ "default": "Default",+ "makeDefault": "Make default",+ "premiumBadge": "Premium · free from {date}",+ "thisMonth": "{count} this month",+ "featureNews": "news",+ "featureAnswer": "sourced answers",+ "featureFullContent": "also reads pages",+ "badge": "Search",+ "keysSection": "Search",+ "keysSectionHint": "Web search keys. Used by /v1/search and by Claude Code / Codex web search, never for chat.",+ "keysModelsSection": "Models",+ "pickerSearch": "Search",+ "pickerModels": "Models",+ "playgroundHeading": "Web search",+ "playgroundHelp": "Looks things up with your search keys before answering, and lists sources.",+ "playgroundNoKeys": "Add a search key on the Keys page to turn this on.",+ "playgroundToggle": "Search the web",+ "playgroundEngines": "Engines: {chain}",+ "playgroundFailed": "Web search failed, answering without it: {reason}",+ "chipOn": "Web search on",+ "chipOff": "Turn off web search",+ "searched": "Searched the web · {engine} · {count} sources · {latency} ms",+ "analyticsByEngine": "Searches by engine",+ "analyticsSummary": "Search summary",+ "analyticsSearches": "Searches",+ "analyticsToday": "Today",+ "agentsBadgeClaude": "Web search: WebSearch tool served by your search keys",+ "agentsBadgeCodex": "Web search: web_search tool served by your search keys"}-}\ No newline at end of file+}diff --git a/client/src/lib/playground-conversations.ts b/client/src/lib/playground-conversations.tsindex 9f0169cb..a99b82eb 100644--- a/client/src/lib/playground-conversations.ts+++ b/client/src/lib/playground-conversations.ts@@ -51,9 +51,18 @@ export interface ChatMessage {fusionPanel?: FusionPanelEntry[]fusionJudge?: { platform: string; model: string } | nullfusionStreaming?: boolean+ // Set when the question was looked up on the web first (#1174).+ webSearch?: WebSearchMeta}}+/** The web search an answer was grounded on: engine, timing, numbered sources. */+export interface WebSearchMeta {+ engine: string+ latency: number+ sources: { title: string; url: string }[]+}+/** Sidebar row: enough to list a conversation, never its transcript. */export interface ConversationSummary {id: numberdiff --git a/client/src/lib/routing.ts b/client/src/lib/routing.tsindex b72a93a3..21109d7c 100644--- a/client/src/lib/routing.ts+++ b/client/src/lib/routing.ts@@ -458,6 +458,11 @@ export const platformColors: Record<string, string> = {volcengine: '#00b8d9',longcat: '#ffd100',xfyun: '#1f6fd0',+ // Web search providers (#1174).+ tavily: '#f97316',+ exa: '#2563eb',+ firecrawl: '#ef4444',+ linkup: '#10b981',}// ── Grouped (unified) rendering ──────────────────────────────────────────────diff --git a/client/src/lib/search.test.ts b/client/src/lib/search.test.tsnew file mode 100644index 00000000..1f08b102--- /dev/null+++ b/client/src/lib/search.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from 'vitest'+import {+ engineChain,+ freeFromDate,+ hostOf,+ isSearchPlatform,+ searchContextMessage,+ searchProviderName,+ type SearchEngine,+} from './search'++const engine = (over: Partial<SearchEngine>): SearchEngine => ({+ id: 1,+ platform: 'tavily',+ engineId: 'tavily-search',+ displayName: 'Tavily',+ priority: 0,+ enabled: true,+ quotaLabel: '',+ creditsPerQuery: 1,+ features: null,+ premiumSince: null,+ keyCount: 1,+ healthyKeyCount: 1,+ searchesThisMonth: 0,+ ...over,+})++describe('search platforms', () => {+ it('recognises the search providers and nothing else', () => {+ expect(isSearchPlatform('tavily')).toBe(true)+ expect(isSearchPlatform('linkup')).toBe(true)+ expect(isSearchPlatform('groq')).toBe(false)+ expect(isSearchPlatform('custom')).toBe(false)+ })++ it('shortens the provider label to its name', () => {+ expect(searchProviderName('exa')).toBe('Exa')+ expect(searchProviderName('unknown')).toBe('unknown')+ })+})++describe('freeFromDate', () => {+ const now = Date.parse('2026-10-13T00:00:00Z')++ it('is null for rows without a premium stamp', () => {+ expect(freeFromDate(null, now)).toBeNull()+ expect(freeFromDate('not a date', now)).toBeNull()+ })++ it('returns the day the row reaches the free catalog', () => {+ expect(freeFromDate('2026-10-13T00:00:00Z', now)?.toISOString()).toBe('2026-11-12T00:00:00.000Z')+ })++ it('is null once the 30-day lag has passed', () => {+ expect(freeFromDate('2026-09-01T00:00:00Z', now)).toBeNull()+ })+})++describe('engineChain', () => {+ it('keeps enabled engines in priority order', () => {+ const chain = engineChain([+ engine({ id: 2, displayName: 'Exa', priority: 1 }),+ engine({ id: 3, displayName: 'Linkup', priority: 3, enabled: false }),+ engine({ id: 1, displayName: 'Tavily', priority: 0 }),+ ])+ expect(chain.map(e => e.displayName)).toEqual(['Tavily', 'Exa'])+ })+})++describe('searchContextMessage', () => {+ it('numbers the sources and caps long snippets', () => {+ const text = searchContextMessage({+ query: 'what is freellmapi',+ provider: 'tavily',+ engine: 'tavily-search',+ results: [+ { title: 'README', url: 'https://github.com/x/y', content: 'a'.repeat(700), score: 0.9 },+ { title: '', url: 'https://www.freellmapi.co/docs', content: 'docs', score: 0.5 },+ ],+ })+ expect(text).toContain('[1] README (https://github.com/x/y)')+ expect(text).toContain('[2] freellmapi.co (https://www.freellmapi.co/docs)')+ expect(text).toContain(`${'a'.repeat(600)}…`)+ expect(text).not.toContain('a'.repeat(601))+ })++ it('falls back to the raw string for an unparseable url', () => {+ expect(hostOf('not a url')).toBe('not a url')+ })+})diff --git a/client/src/lib/search.ts b/client/src/lib/search.tsnew file mode 100644index 00000000..45b73d37--- /dev/null+++ b/client/src/lib/search.ts@@ -0,0 +1,127 @@+// Web search (#1174): the dashboard side of POST /v1/search and the catalog's+// `searchEngines` section. Search providers hold keys like any other platform,+// but they never serve chat, so the Keys page, the add-key picker and the+// Models tabs all treat them as their own group.++import type { SearchPlatform as SharedSearchPlatform } from '@freellmapi/shared/types'++// Mirrors SEARCH_PLATFORMS in shared/types.ts. The client only imports types+// from shared, so the list is repeated here; the two assertions below fail the+// typecheck if either side gains a platform the other lacks.+export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup'] as const+export type SearchPlatform = (typeof SEARCH_PLATFORMS)[number]+const sharedCoversClient: SharedSearchPlatform = '' as SearchPlatform+const clientCoversShared: SearchPlatform = '' as SharedSearchPlatform+void sharedCoversClient+void clientCoversShared++export function isSearchPlatform(platform: string): platform is SearchPlatform {+ return (SEARCH_PLATFORMS as readonly string[]).includes(platform)+}++// Same shape and job as PLATFORMS in components/keys/shared.tsx: the label+// names the free allowance, `url` is where the key is created.+export const SEARCH_PROVIDERS: { value: SearchPlatform; label: string; url: string }[] = [+ { value: 'tavily', label: 'Tavily (1,000 searches/month)', url: 'https://app.tavily.com/home' },+ { value: 'exa', label: 'Exa ($10 search credits/month)', url: 'https://dashboard.exa.ai/api-keys' },+ { value: 'firecrawl', label: 'Firecrawl (1,000 credits/month)', url: 'https://www.firecrawl.dev/app/api-keys' },+ { value: 'linkup', label: 'Linkup (€5 credits/month)', url: 'https://app.linkup.so/api-keys' },+]++/** Short provider name for chips and badges ("Tavily", not the full label). */+export function searchProviderName(platform: string): string {+ const label = SEARCH_PROVIDERS.find(p => p.value === platform)?.label+ return label ? label.replace(/\s*\(.*\)$/, '') : platform+}++/** GET /api/search/engines row. */+export interface SearchEngine {+ id: number+ platform: string+ engineId: string+ displayName: string+ priority: number+ enabled: boolean+ quotaLabel: string+ creditsPerQuery: number | null+ features: { news?: boolean; answer?: boolean; fullContent?: boolean } | null+ premiumSince: string | null+ keyCount: number+ healthyKeyCount: number+ searchesThisMonth: number+}++/** GET /api/analytics/search response. */+export interface SearchAnalytics {+ total: number+ today: number+ successRate: number+ avgLatencyMs: number+ byEngine: { engineId: string; displayName: string; count: number }[]+ series: { date: string; engineId: string; count: number }[]+}++export interface SearchHit {+ title: string+ url: string+ content: string+ score: number+}++/** POST /v1/search response. */+export interface SearchResult {+ query: string+ answer?: string+ results: SearchHit[]+ provider: string+ engine: string+}++// New catalog rows reach Free installs this long after they reach Premium.+const FREE_TIER_LAG_MS = 30 * 24 * 60 * 60 * 1000++/**+ * When a Premium-first engine reaches the free catalog, or null when it is+ * already free (no stamp, an unreadable stamp, or the lag has passed).+ */+export function freeFromDate(premiumSince: string | null, now: number = Date.now()): Date | null {+ if (!premiumSince) return null+ const since = Date.parse(premiumSince)+ if (Number.isNaN(since)) return null+ const freeAt = since + FREE_TIER_LAG_MS+ return freeAt > now ? new Date(freeAt) : null+}++/** Enabled engines in failover order, for the "Auto (Tavily → Exa)" line. */+export function engineChain(engines: SearchEngine[]): SearchEngine[] {+ return engines+ .filter(e => e.enabled)+ .slice()+ .sort((a, b) => a.priority - b.priority || a.displayName.localeCompare(b.displayName))+}++export function hostOf(url: string): string {+ try {+ return new URL(url).hostname.replace(/^www\./, '')+ } catch {+ return url+ }+}++/**+ * The system message the Playground sends ahead of a web-searched question:+ * numbered sources the model is told to cite as [n]. Snippets are capped so a+ * long page cannot crowd the question out of a small context window.+ */+export function searchContextMessage(result: SearchResult, maxSnippet = 600): string {+ const lines = result.results.map((hit, i) => {+ const snippet = hit.content.length > maxSnippet ? `${hit.content.slice(0, maxSnippet)}…` : hit.content+ return `[${i + 1}] ${hit.title || hostOf(hit.url)} (${hit.url})\n${snippet}`+ })+ return [+ `Web search results for "${result.query}":`,+ ...(result.answer ? [`Summary: ${result.answer}`] : []),+ ...lines,+ 'Use these results to answer, and cite them inline as [1], [2] where they support a claim. If they do not answer the question, say so.',+ ].join('\n\n')+}diff --git a/client/src/pages/AgentsPage.tsx b/client/src/pages/AgentsPage.tsxindex 7bb995f1..ecb9a609 100644--- a/client/src/pages/AgentsPage.tsx+++ b/client/src/pages/AgentsPage.tsx@@ -1,6 +1,6 @@import { useState } from 'react'import { useQuery } from '@tanstack/react-query'-import { CheckCircle2, ExternalLink } from 'lucide-react'+import { CheckCircle2, ExternalLink, Globe } from 'lucide-react'import { apiFetch } from '@/lib/api'import { useI18n } from '@/i18n'import { PageHeader } from '@/components/page-header'@@ -50,6 +50,13 @@ const analyticsIds: Record<string, string> = {cursor: 'cursor',}+// Agents whose built-in web search tool the gateway serves from the search+// keys (#1174): Claude Code's WebSearch and Codex's web_search.+const WEB_SEARCH_TOOL_KEYS: Record<string, string> = {+ claude: 'search.agentsBadgeClaude',+ codex: 'search.agentsBadgeCodex',+}+function masked(value: string): string {if (value.length < 12) return '••••••••'return `${value.slice(0, 8)}${'•'.repeat(12)}${value.slice(-4)}`@@ -145,6 +152,15 @@ export default function AgentsPage() {</CardAction></CardHeader><CardContent className="flex flex-1 flex-col gap-4">+ {WEB_SEARCH_TOOL_KEYS[tool.id] && (+ <Badge+ variant="outline"+ className="h-auto w-fit whitespace-normal border-sky-600/30 py-0.5 text-[11px] text-sky-700 dark:text-sky-300"+ >+ <Globe />+ {t(WEB_SEARCH_TOOL_KEYS[tool.id])}+ </Badge>+ )}<div><p className="text-xs font-medium">{t('agents.setupLabel')}</p><p className="mt-0.5 text-xs text-muted-foreground">diff --git a/client/src/pages/AnalyticsPage.tsx b/client/src/pages/AnalyticsPage.tsxindex e700f54d..62e3031f 100644--- a/client/src/pages/AnalyticsPage.tsx+++ b/client/src/pages/AnalyticsPage.tsx@@ -18,6 +18,7 @@ import {Coins,Gauge,GitBranch,+ Globe,KeyRound,Layers,List,@@ -43,6 +44,7 @@ import { sortRows, useTableSort, type SortValueFn } from '@/lib/table-sort'import { platformColors } from '@/lib/routing'import { categoryAxisProps, verticalCategoryAxisProps } from '@/lib/chart-axis'import { useI18n } from '@/i18n'+import type { SearchAnalytics } from '@/lib/search'type TimeRange = '24h' | '7d' | '30d' | '90d'@@ -608,6 +610,15 @@ export default function AnalyticsPage() {queryFn: () => apiFetch<RecentErrorRow[]>(`/api/analytics/errors?range=${range}`),})+ // Web search usage (#1174). Its two panels sit under the token chart and+ // only appear once this install has run a search in the window; an older+ // server without the endpoint simply has none.+ const { data: searchStats } = useQuery({+ queryKey: ['analytics', 'search', range],+ queryFn: () => apiFetch<SearchAnalytics>(`/api/analytics/search?range=${range}`),+ retry: false,+ })+const { data: errorDist } = useQuery({queryKey: ['analytics', 'error-distribution', range],queryFn: () => apiFetch<ErrorDistribution>(`/api/analytics/error-distribution?range=${range}`),@@ -806,6 +817,49 @@ export default function AnalyticsPage() {</Panel></div>+ {searchStats && searchStats.total > 0 && (+ <>+ <Panel icon={Globe} title={t('search.analyticsByEngine')}>+ <div className="space-y-2.5">+ {searchStats.byEngine+ .slice()+ .sort((a, b) => b.count - a.count)+ .map(row => {+ const max = Math.max(...searchStats.byEngine.map(r => r.count), 1)+ const platform = row.engineId.split('-')[0]+ return (+ <div key={row.engineId} className="flex items-center gap-3 text-xs">+ <span className="w-24 shrink-0 truncate text-muted-foreground" title={row.engineId}>{row.displayName}</span>+ <div className="h-2.5 flex-1 overflow-hidden rounded-full bg-muted">+ <div+ className="h-full rounded-full"+ style={{ width: `${(row.count / max) * 100}%`, backgroundColor: platformColors[platform] ?? primaryFill }}+ />+ </div>+ <span className="w-10 shrink-0 text-right tabular-nums">{row.count}</span>+ </div>+ )+ })}+ </div>+ </Panel>+ <Panel icon={Activity} title={t('search.analyticsSummary')}>+ <div className="grid grid-cols-2 gap-3">+ {[+ { label: t('search.analyticsSearches'), value: String(searchStats.total) },+ { label: t('analytics.successRate'), value: `${Math.round(searchStats.successRate * 10) / 10}%` },+ { label: t('analytics.avgLatency'), value: `${Math.round(searchStats.avgLatencyMs)} ms` },+ { label: t('search.analyticsToday'), value: String(searchStats.today) },+ ].map(cell => (+ <div key={cell.label} className="rounded-2xl border px-3 py-2">+ <p className="text-[11px] uppercase tracking-wider text-muted-foreground">{cell.label}</p>+ <p className="mt-0.5 text-lg font-semibold tabular-nums">{cell.value}</p>+ </div>+ ))}+ </div>+ </Panel>+ </>+ )}+<Panel icon={Server} title={t('analytics.requestsByProvider')}>{byPlatform.length === 0 ? (<p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>diff --git a/client/src/pages/PlaygroundPage.tsx b/client/src/pages/PlaygroundPage.tsxindex d0a5ba14..4e1bdbf3 100644--- a/client/src/pages/PlaygroundPage.tsx+++ b/client/src/pages/PlaygroundPage.tsx@@ -32,6 +32,8 @@ import { readChatStream } from '@/lib/playground-stream'import { ConversationSidebar } from '@/components/playground/conversation-sidebar'import { SettingsRail } from '@/components/playground/settings-rail'import { LiquidComposer } from '@/components/playground/liquid-composer'+import { SearchSources } from '@/components/playground/search-sources'+import { engineChain, searchContextMessage, searchProviderName, type SearchEngine, type SearchResult } from '@/lib/search'import { ModelMakerIcon } from '@/components/model-maker-icon'import { composerHasContent } from '@/lib/composer-geometry'import {@@ -61,6 +63,7 @@ import {updateConversation,writeActiveConversationId,type ChatMessage,+ type WebSearchMeta,type ConversationSummary,type FusionPanelEntry,} from '@/lib/playground-conversations'@@ -217,6 +220,16 @@ export default function PlaygroundPage() {setSampling(next)writeSampling(next)}+ // "Search the web" (#1174): look the question up with POST /v1/search first+ // and hand the model numbered sources to cite. A preference like the+ // sampling knobs, so it is remembered here rather than per conversation.+ const [webSearch, setWebSearch] = useState<boolean>(+ () => localStorage.getItem('playground.webSearch') === '1',+ )+ const updateWebSearch = (enabled: boolean) => {+ setWebSearch(enabled)+ localStorage.setItem('playground.webSearch', enabled ? '1' : '0')+ }const [input, setInput] = useState('')const [loading, setLoading] = useState(false)const [selectedModel, setSelectedModel] = useState<string>(@@ -276,6 +289,17 @@ export default function PlaygroundPage() {queryFn: () => apiFetch('/api/media'),})const mediaModels = mediaData?.models ?? []++ // Engines that can actually run a search: enabled, with a key behind them.+ // An older server without the endpoint just leaves the switch unavailable.+ const { data: searchEngines = [] } = useQuery<SearchEngine[]>({+ queryKey: ['search-engines'],+ queryFn: () => apiFetch('/api/search/engines'),+ retry: false,+ })+ const usableEngines = engineChain(searchEngines).filter(e => e.keyCount > 0)+ const webSearchAvailable = usableEngines.length > 0+ const webSearchOn = webSearch && webSearchAvailableconst transcriptionAvailable = hasTranscription(mediaModels)const [dictationChoice, setDictationChoice] = useState<string>(() => localStorage.getItem(DICTATION_MODEL_STORAGE_KEY) ?? DICTATION_AUTO,@@ -662,6 +686,7 @@ export default function PlaygroundPage() {start: number,routedVia: string | null,fallbackAttempts: string | null,+ webSearchMeta?: WebSearchMeta,) => {const via = routedVia? { platform: routedVia.split('/')[0], model: routedVia.split('/').slice(1).join('/') }@@ -687,6 +712,7 @@ export default function PlaygroundPage() {model: via?.model,latency: Date.now() - start,fallbackAttempts: fallbackAttempts ? parseInt(fallbackAttempts) : undefined,+ ...(webSearchMeta ? { webSearch: webSearchMeta } : {}),},})}@@ -780,12 +806,44 @@ export default function PlaygroundPage() {try {const headers: Record<string, string> = { 'Content-Type': 'application/json' }if (keyData?.apiKey) headers['Authorization'] = `Bearer ${keyData.apiKey}`+ const base = import.meta.env.BASE_URL.replace(/\/$/, '')++ // Web search first, when it is on and there is a question to look up. A+ // failed search is reported and the question is answered without it.+ let searchContext: string | null = null+ let webSearchMeta: WebSearchMeta | undefined+ if (webSearchOn && text) {+ const searchStart = Date.now()+ try {+ const res = await fetch(`${base}/v1/search`, {+ method: 'POST',+ headers,+ body: JSON.stringify({ query: text, max_results: 5 }),+ })+ if (!res.ok) {+ const err = await res.json().catch(() => ({ error: { message: `HTTP ${res.status}` } }))+ throw new Error(err.error?.message ?? err.message ?? `HTTP ${res.status}`)+ }+ const found = await res.json() as SearchResult+ if (found.results.length > 0) {+ searchContext = searchContextMessage(found)+ webSearchMeta = {+ engine: searchProviderName(found.provider),+ latency: Date.now() - searchStart,+ sources: found.results.map(r => ({ title: r.title, url: r.url })),+ }+ }+ } catch (err) {+ toast.error(t('search.playgroundFailed', { reason: err instanceof Error ? err.message : String(err) }))+ }+ }const isFusion = selectedModel === 'fusion'const sysPrompt = systemPrompt.trim()const body: any = {messages: [...(sysPrompt ? [{ role: 'system', content: sysPrompt }] : []),+ ...(searchContext ? [{ role: 'system', content: searchContext }] : []),...newMessages.map(m => ({ role: m.role, content: toMessageContent(m.content, m.images) })),],// Only the knobs switched on in the settings rail: temperature, top_p@@ -803,7 +861,6 @@ export default function PlaygroundPage() {const controller = new AbortController()abortRef.current = controller- const base = import.meta.env.BASE_URL.replace(/\/$/, '')const start = Date.now()const res = await fetch(`${base}/v1/chat/completions`, {method: 'POST',@@ -840,7 +897,7 @@ export default function PlaygroundPage() {// fall back to the buffered path rather than trusting that: a proxy in// front of us, or a future non-streaming route, can still hand back JSON.if (!isFusion && res.body && (res.headers.get('Content-Type') ?? '').includes('text/event-stream')) {- await streamChat(res.body, newMessages, start, routedVia, fallbackAttempts)+ await streamChat(res.body, newMessages, start, routedVia, fallbackAttempts, webSearchMeta)return}@@ -868,6 +925,7 @@ export default function PlaygroundPage() {fallbackAttempts: fallbackAttempts ? parseInt(fallbackAttempts) : undefined,fusionPanel: fusion?.panel,fusionJudge: fusion?.judge,+ ...(webSearchMeta ? { webSearch: webSearchMeta } : {}),},}]setMessages(answered)@@ -1028,6 +1086,9 @@ export default function PlaygroundPage() {<ArtifactHostContext.Provider value={artifactHost}><Markdown>{msg.content}</Markdown></ArtifactHostContext.Provider>+ {msg.meta?.webSearch && msg.meta.webSearch.sources.length > 0 && (+ <SearchSources search={msg.meta.webSearch} />+ )}</>) : (<div className="whitespace-pre-wrap">{msg.content}</div>@@ -1194,6 +1255,9 @@ export default function PlaygroundPage() {inputRef.current?.focus()},}}+ webSearch={webSearchOn+ ? { label: t('search.chipOn'), offLabel: t('search.chipOff'), onDisable: () => updateWebSearch(false) }+ : undefined}/></div></div>@@ -1228,6 +1292,10 @@ export default function PlaygroundPage() {onSystemPromptChange={updateSystemPrompt}sampling={sampling}onSamplingChange={updateSampling}+ webSearch={webSearch}+ onWebSearchChange={updateWebSearch}+ webSearchAvailable={webSearchAvailable}+ webSearchChain={usableEngines.map(e => e.displayName).join(' → ')}/>)}</div>diff --git a/client/src/pages/SearchPage.tsx b/client/src/pages/SearchPage.tsxnew file mode 100644index 00000000..7fbfcba5--- /dev/null+++ b/client/src/pages/SearchPage.tsx@@ -0,0 +1,5 @@+import { SearchEnginesView } from '@/components/search-engines'++export default function SearchPage() {+ return <SearchEnginesView />+}diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex 0c7725d3..841e5c5e 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -43,6 +43,7 @@ const REQUEST_MODEL_ATTRIBUTION_FILENAME = '20260913_000001_request_model_attribconst KEY_MONTHLY_USAGE_FILENAME = '20260914_000001_key_monthly_usage.ts';const QUOTA_SNAPSHOT_FRESHNESS_FILENAME = '20260915_000001_quota_snapshot_freshness.ts';const CUSTOM_ENDPOINT_GROUP_LABEL_FILENAME = '20260930_000001_custom_endpoint_group_label.ts';+const SEARCH_ENGINES_FILENAME = '20261013_000001_search_engines.ts';interface SchemaRow {type: string;@@ -132,6 +133,7 @@ describe('migration round trip', () => {KEY_MONTHLY_USAGE_FILENAME,QUOTA_SNAPSHOT_FRESHNESS_FILENAME,CUSTOM_ENDPOINT_GROUP_LABEL_FILENAME,+ SEARCH_ENGINES_FILENAME,]);} finally {db.close();diff --git a/server/src/__tests__/helpers/search-engines.ts b/server/src/__tests__/helpers/search-engines.tsnew file mode 100644index 00000000..0eb6da41--- /dev/null+++ b/server/src/__tests__/helpers/search-engines.ts@@ -0,0 +1,19 @@+import { getDb } from '../../db/index.js';++// Search engines only ever arrive through the catalog's `searchEngines`+// registry (nothing is bundled), so tests that exercise routing seed the four+// engines the catalog publishes, in its priority order.+const ENGINES = [+ { platform: 'tavily', engineId: 'tavily-search', displayName: 'Tavily Search', quotaLabel: '1,000 credits/month, no card', meta: { creditsPerQuery: 1, features: { news: true, answer: true, fullContent: false } } },+ { platform: 'exa', engineId: 'exa-search', displayName: 'Exa Search', quotaLabel: '$10/month in credits', meta: { creditsPerQuery: null, features: { news: true, answer: false, fullContent: true } } },+ { platform: 'firecrawl', engineId: 'firecrawl-search', displayName: 'Firecrawl Search', quotaLabel: '1,000 credits/month, no card', meta: { creditsPerQuery: 2, features: { news: true, answer: false, fullContent: true } } },+ { platform: 'linkup', engineId: 'linkup-search', displayName: 'Linkup Search', quotaLabel: '€5/month in credits', meta: { creditsPerQuery: 1, features: { news: false, answer: true, fullContent: false } } },+];++export function seedSearchEngines(): void {+ const insert = getDb().prepare(`+ INSERT OR IGNORE INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, meta_json)+ VALUES (?, ?, ?, 'search', ?, 1, ?, ?)+ `);+ ENGINES.forEach((e, i) => insert.run(e.platform, e.engineId, e.displayName, i, e.quotaLabel, JSON.stringify(e.meta)));+}diff --git a/server/src/__tests__/lib/module-purity.test.ts b/server/src/__tests__/lib/module-purity.test.tsindex 8b2c07e8..bad6b841 100644--- a/server/src/__tests__/lib/module-purity.test.ts+++ b/server/src/__tests__/lib/module-purity.test.ts@@ -43,6 +43,8 @@ const PURE_MODULES = ['provider-identity.ts','provider-size-parser.ts','retry-hint.ts',+ // Search platform list; the provider list, keys route and search service import it.+ 'search-platforms.ts','structured-output.ts','tool-args.ts','tool-call-rescue.ts',diff --git a/server/src/__tests__/providers/search-providers.test.ts b/server/src/__tests__/providers/search-providers.test.tsnew file mode 100644index 00000000..4cfe842a--- /dev/null+++ b/server/src/__tests__/providers/search-providers.test.ts@@ -0,0 +1,63 @@+import { describe, it, expect, afterEach, vi } from 'vitest';+import { TavilyProvider } from '../../providers/tavily.js';+import { ExaProvider } from '../../providers/exa.js';+import { FirecrawlProvider } from '../../providers/firecrawl.js';+import { LinkupProvider } from '../../providers/linkup.js';+import { getProvider } from '../../providers/index.js';++// Search platforms (#1174) validate keys without spending search credits and+// refuse chat outright.++const realFetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+});++function respond(status: number) {+ const fn = vi.fn(() => Promise.resolve(new Response('{}', { status })));+ globalThis.fetch = fn as unknown as typeof fetch;+ return fn;+}++const cases = [+ { provider: new TavilyProvider(), url: 'https://api.tavily.com/usage', method: 'GET' },+ { provider: new ExaProvider(), url: 'https://api.exa.ai/search', method: 'POST' },+ { provider: new FirecrawlProvider(), url: 'https://api.firecrawl.dev/v2/team/credit-usage', method: 'GET' },+ { provider: new LinkupProvider(), url: 'https://api.linkup.so/v1/credits/balance', method: 'GET' },+];++describe.each(cases)('$provider.name key validation', ({ provider, url, method }) => {+ it('probes a no-cost endpoint', async () => {+ const fn = respond(200);+ expect(await provider.validateKey('k')).toBe(true);+ const [calledUrl, init] = (fn.mock.calls as unknown as [string, RequestInit][])[0];+ expect(calledUrl).toBe(url);+ expect(init.method).toBe(method);+ });++ it('treats 401 as an invalid key', async () => {+ respond(401);+ expect(await provider.validateKey('k')).toMatchObject({ valid: false });+ });++ it('treats other 4xx (empty probe body, spent credits) as authenticated', async () => {+ respond(400);+ expect(await provider.validateKey('k')).toBe(true);+ });++ it('reports 5xx as inconclusive', async () => {+ respond(503);+ expect(await provider.validateKey('k')).toMatchObject({ valid: false });+ });++ it('refuses chat completions with a 422', async () => {+ await expect(provider.chatCompletion('k', [], 'm')).rejects.toMatchObject({ status: 422 });+ });+});++describe('registry', () => {+ it('registers every search platform', () => {+ for (const p of ['tavily', 'exa', 'firecrawl', 'linkup'] as const) expect(getProvider(p)?.platform).toBe(p);+ });+});diff --git a/server/src/__tests__/routes/agent-web-search.test.ts b/server/src/__tests__/routes/agent-web-search.test.tsnew file mode 100644index 00000000..024b0d1c--- /dev/null+++ b/server/src/__tests__/routes/agent-web-search.test.ts@@ -0,0 +1,351 @@+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';+import type { Express } from 'express';++// Agent web search (#1174): Claude Code's Anthropic `web_search_*` server tool+// and Codex's Responses `web_search` tool are answered from the gateway's+// search pool. runSearch is mocked; the routed model is a mocked Groq upstream+// that first calls `web_search`, then answers.++const runSearchMock = vi.hoisted(() => vi.fn());+vi.mock('../../services/search.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../services/search.js')>();+ return { ...actual, runSearch: runSearchMock };+});++import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey, setSetting } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { mintDashboardToken } from '../helpers/auth.js';+import { encodeHitContent, filterHitsByDomain } from '../../lib/web-search-tool.js';+import { seedSearchEngines } from '../helpers/search-engines.js';++let app: Express;+let dashToken = '';++async function post(path: string, body: any, headers: Record<string, string> = {}) {+ const server = app.listen(0, '127.0.0.1');+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...headers },+ body: JSON.stringify(body),+ });+ const text = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(text); } catch { /* SSE */ }+ return { status: res.status, text, body: json };+}++function sseEvents(text: string): Array<{ event: string; data: any }> {+ const out: Array<{ event: string; data: any }> = [];+ for (const block of text.split('\n\n')) {+ let event: string | null = null;+ let data: string | null = null;+ for (const line of block.split('\n')) {+ if (line.startsWith('event: ')) event = line.slice(7).trim();+ else if (line.startsWith('data: ')) data = line.slice(6);+ }+ if (event && data) out.push({ event, data: JSON.parse(data) });+ }+ return out;+}++const anthropicHeaders = () => ({ 'x-api-key': getUnifiedApiKey(), 'anthropic-version': '2023-06-01' });+const bearer = () => ({ Authorization: `Bearer ${getUnifiedApiKey()}` });++const searchCall = (query: string, id = 'call_s1') => ({+ id: 'chatcmpl-s', object: 'chat.completion', created: 1, model: 'openai/gpt-oss-120b',+ choices: [{ index: 0, message: { role: 'assistant', content: null, tool_calls: [{ id, type: 'function', function: { name: 'web_search', arguments: JSON.stringify({ query }) } }] }, finish_reason: 'tool_calls' }],+ usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 },+});+const answer = (text: string) => ({+ id: 'chatcmpl-a', object: 'chat.completion', created: 1, model: 'openai/gpt-oss-120b',+ choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 20, completion_tokens: 5, total_tokens: 25 },+});++/** Mock Groq with a queue of JSON chat completions; captures forwarded bodies. */+function mockGroq(responses: any[]) {+ const bodies: any[] = [];+ const origFetch = global.fetch;+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {+ const u = typeof url === 'string' ? url : url.toString();+ if (u.includes('api.groq.com/openai/v1/chat/completions')) {+ bodies.push(JSON.parse(String((init as RequestInit).body)));+ const next = responses.shift();+ if (!next) throw new Error('no mocked Groq response left');+ return { ok: true, json: () => Promise.resolve(next) } as any;+ }+ return origFetch(url as any, init);+ });+ return bodies;+}++const HITS = [+ { title: 'Release notes', url: 'https://example.com/news/1', content: 'Version 9 shipped on Monday.', score: 0.9 },+ { title: 'Blog', url: 'https://blocked.test/post', content: 'Unrelated.', score: 0.5 },+];++function addSearchKey() {+ const { encrypted, iv, authTag } = encrypt('tvly-test');+ getDb().prepare("INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled) VALUES ('tavily', 't', ?, ?, ?, 'healthy', 1)")+ .run(encrypted, iv, authTag);+}++describe('agent web search served from the search pool', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ seedSearchEngines();+ app = createApp();+ dashToken = mintDashboardToken();+ setSetting('enable_mcp', '1');+ });++ beforeEach(async () => {+ const db = getDb();+ db.prepare('DELETE FROM api_keys').run();+ db.prepare('DELETE FROM requests').run();+ db.prepare('DELETE FROM rate_limit_cooldowns').run();+ db.prepare('DELETE FROM rate_limit_usage').run();+ db.prepare(`INSERT INTO settings (key, value) VALUES ('expose_cc_discovery_aliases', '0')+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run();+ const { status } = await post('/api/keys', { platform: 'groq', key: 'gsk_web_search_test', label: 'g' }, { Authorization: `Bearer ${dashToken}` });+ expect(status).toBe(201);+ runSearchMock.mockReset();+ runSearchMock.mockResolvedValue({ query: 'q', results: HITS, provider: 'tavily', engine: 'tavily-search', modelId: 'search' });+ });++ afterEach(() => vi.restoreAllMocks());++ describe('Anthropic web_search server tool', () => {+ const request = (extra: Record<string, unknown> = {}) => ({+ model: 'claude-sonnet-4-5',+ max_tokens: 256,+ messages: [{ role: 'user', content: 'What shipped this week?' }],+ tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: 3 }],+ ...extra,+ });++ it('runs the search and returns server_tool_use + web_search_tool_result blocks', async () => {+ addSearchKey();+ const bodies = mockGroq([searchCall('version 9 release'), answer('Version 9 shipped on Monday.')]);+ const { status, body } = await post('/v1/messages', request(), anthropicHeaders());++ expect(status).toBe(200);+ expect(runSearchMock).toHaveBeenCalledTimes(1);+ expect(runSearchMock.mock.calls[0][0]).toBe('version 9 release');+ const types = body.content.map((b: any) => b.type);+ expect(types).toEqual(['server_tool_use', 'web_search_tool_result', 'text']);+ const [use, result, text] = body.content;+ expect(use.id).toMatch(/^srvtoolu_/);+ expect(use).toMatchObject({ name: 'web_search', input: { query: 'version 9 release' } });+ expect(result.tool_use_id).toBe(use.id);+ expect(result.content[0]).toMatchObject({ type: 'web_search_result', url: 'https://example.com/news/1', title: 'Release notes', page_age: null });+ expect(typeof result.content[0].encrypted_content).toBe('string');+ expect(text.text).toBe('Version 9 shipped on Monday.');+ expect(body.stop_reason).toBe('end_turn');+ expect(body.usage).toEqual({ input_tokens: 30, output_tokens: 8, server_tool_use: { web_search_requests: 1 } });++ // The model saw a function tool, then the results as a tool message.+ expect(bodies[0].tools.map((t: any) => t.function.name)).toEqual(['web_search']);+ expect(bodies[0].tools[0].function.parameters.required).toEqual(['query']);+ const toolMsg = bodies[1].messages.find((m: any) => m.role === 'tool');+ expect(toolMsg.content).toContain('https://example.com/news/1');+ expect(toolMsg.content).toContain('Version 9 shipped on Monday.');+ });++ it('streams the same blocks as SSE with web_search_requests in message_delta', async () => {+ addSearchKey();+ mockGroq([searchCall('version 9 release'), answer('Done.')]);+ const { status, text } = await post('/v1/messages', request({ stream: true }), anthropicHeaders());++ expect(status).toBe(200);+ const events = sseEvents(text).filter(e => e.event !== 'ping');+ expect(events[0].event).toBe('message_start');+ const starts = events.filter(e => e.event === 'content_block_start').map(e => e.data.content_block.type);+ expect(starts).toEqual(['server_tool_use', 'web_search_tool_result', 'text']);+ const jsonDelta = events.find(e => e.event === 'content_block_delta' && e.data.delta.type === 'input_json_delta');+ expect(JSON.parse(jsonDelta!.data.delta.partial_json)).toEqual({ query: 'version 9 release' });+ const resultStart = events.find(e => e.event === 'content_block_start' && e.data.content_block.type === 'web_search_tool_result');+ expect(resultStart!.data.content_block.content[0].url).toBe('https://example.com/news/1');+ const delta = events.find(e => e.event === 'message_delta');+ expect(delta!.data.delta.stop_reason).toBe('end_turn');+ expect(delta!.data.usage.server_tool_use).toEqual({ web_search_requests: 1 });+ expect(events.at(-1)!.event).toBe('message_stop');+ });++ it('honours max_uses with a max_uses_exceeded error result', async () => {+ addSearchKey();+ mockGroq([searchCall('first'), searchCall('second', 'call_s2'), answer('ok')]);+ const { body } = await post('/v1/messages', request({ tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: 1 }] }), anthropicHeaders());++ expect(runSearchMock).toHaveBeenCalledTimes(1);+ const results = body.content.filter((b: any) => b.type === 'web_search_tool_result');+ expect(results).toHaveLength(2);+ expect(results[1].content).toEqual({ type: 'web_search_tool_result_error', error_code: 'max_uses_exceeded' });+ expect(body.usage.server_tool_use.web_search_requests).toBe(1);+ });++ it('applies allowed_domains and blocked_domains to the hits', async () => {+ addSearchKey();+ mockGroq([searchCall('news'), answer('ok')]);+ const { body } = await post('/v1/messages', request({ tools: [{ type: 'web_search_20250305', name: 'web_search', blocked_domains: ['blocked.test'] }] }), anthropicHeaders());+ const result = body.content.find((b: any) => b.type === 'web_search_tool_result');+ expect(result.content.map((r: any) => r.url)).toEqual(['https://example.com/news/1']);+ expect(filterHitsByDomain(HITS, { allowedDomains: ['blocked.test'] }).map(h => h.url)).toEqual(['https://blocked.test/post']);+ expect(filterHitsByDomain(HITS, { allowedDomains: ['example.com/news'] })).toHaveLength(1);+ });++ it('defers the search when the model also calls a client tool', async () => {+ addSearchKey();+ const mixed = searchCall('q');+ mixed.choices[0].message.tool_calls.push({ id: 'call_w', type: 'function', function: { name: 'get_weather', arguments: '{"city":"Paris"}' } });+ mockGroq([mixed]);+ const tools = [+ { type: 'web_search_20250305', name: 'web_search' },+ { name: 'get_weather', input_schema: { type: 'object', properties: { city: { type: 'string' } } } },+ ];+ const { body } = await post('/v1/messages', request({ tools }), anthropicHeaders());+ expect(runSearchMock).not.toHaveBeenCalled();+ expect(body.content.map((b: any) => b.type)).toEqual(['tool_use']);+ expect(body.content[0].name).toBe('get_weather');+ expect(body.stop_reason).toBe('tool_use');+ });++ it('turns replayed search blocks into text the routed model can read', async () => {+ addSearchKey();+ const bodies = mockGroq([answer('Following up.')]);+ const hit = { title: 'Release notes', url: 'https://example.com/news/1', content: 'Version 9 shipped on Monday.', score: 1 };+ await post('/v1/messages', request({+ messages: [+ { role: 'user', content: 'What shipped?' },+ { role: 'assistant', content: [+ { type: 'server_tool_use', id: 'srvtoolu_1', name: 'web_search', input: { query: 'version 9' } },+ { type: 'web_search_tool_result', tool_use_id: 'srvtoolu_1', content: [{ type: 'web_search_result', url: hit.url, title: hit.title, encrypted_content: encodeHitContent(hit), page_age: null }] },+ { type: 'text', text: 'Version 9 shipped.' },+ ] },+ { role: 'user', content: 'And when?' },+ ],+ }), anthropicHeaders());+ const assistant = bodies[0].messages.find((m: any) => m.role === 'assistant');+ expect(assistant.content).toContain('[Searched the web for: version 9]');+ expect(assistant.content).toContain('https://example.com/news/1');+ expect(assistant.content).toContain('Version 9 shipped on Monday.');+ });++ it('keeps the old behaviour when no search key is configured', async () => {+ const bodies = mockGroq([answer('No search here.')]);+ const { status, body } = await post('/v1/messages', request(), anthropicHeaders());+ expect(status).toBe(200);+ expect(runSearchMock).not.toHaveBeenCalled();+ expect(body.content).toEqual([{ type: 'text', text: 'No search here.' }]);+ expect(body.usage.server_tool_use).toBeUndefined();+ // The server tool still reaches the model as an (empty-schema) function, as before.+ expect(bodies[0].tools[0].function.parameters).toEqual({ type: 'object', properties: {} });+ });++ it('passes a first-turn error through with its real status', async () => {+ addSearchKey();+ const { status, body } = await post('/v1/messages', request(), { 'x-api-key': 'wrong' });+ expect(status).toBe(401);+ expect(body.type).toBe('error');+ expect(runSearchMock).not.toHaveBeenCalled();+ });+ });++ describe('Responses web_search tool', () => {+ const request = (extra: Record<string, unknown> = {}) => ({+ model: 'auto',+ input: 'What shipped this week?',+ tools: [{ type: 'web_search' }],+ ...extra,+ });++ it('runs the search and reports a web_search_call item before the answer', async () => {+ addSearchKey();+ const bodies = mockGroq([searchCall('version 9 release'), answer('Version 9 shipped on Monday.')]);+ const { status, body } = await post('/v1/responses', request(), bearer());++ expect(status).toBe(200);+ expect(runSearchMock).toHaveBeenCalledTimes(1);+ expect(body.object).toBe('response');+ expect(body.output.map((i: any) => i.type)).toEqual(['web_search_call', 'message']);+ expect(body.output[0]).toMatchObject({+ type: 'web_search_call', status: 'completed',+ action: { type: 'search', query: 'version 9 release', sources: [{ type: 'url', url: 'https://example.com/news/1' }, { type: 'url', url: 'https://blocked.test/post' }] },+ });+ expect(body.output[0].id).toMatch(/^ws_/);+ expect(body.output_text).toBe('Version 9 shipped on Monday.');+ expect(body.usage.input_tokens).toBe(30);+ expect(bodies[0].tools.map((t: any) => t.function.name)).toEqual(['web_search']);+ expect(bodies[1].messages.find((m: any) => m.role === 'tool').content).toContain('Version 9 shipped on Monday.');+ });++ it('streams web_search_call events and a completed response', async () => {+ addSearchKey();+ mockGroq([searchCall('version 9 release'), answer('Done.')]);+ const { status, text } = await post('/v1/responses', request({ stream: true }), bearer());++ expect(status).toBe(200);+ const events = sseEvents(text);+ const names = events.map(e => e.event);+ expect(names[0]).toBe('response.created');+ expect(names).toContain('response.web_search_call.searching');+ expect(names).toContain('response.web_search_call.completed');+ const completed = events.find(e => e.event === 'response.completed')!.data.response;+ expect(completed.output.map((i: any) => i.type)).toEqual(['web_search_call', 'message']);+ expect(completed.id).toBe(events[0].data.response.id);+ const seq = events.map(e => e.data.sequence_number);+ expect(seq).toEqual([...seq].sort((a, b) => a - b));+ });++ it('drops the tool as before when no search key is configured', async () => {+ const bodies = mockGroq([answer('Plain answer.')]);+ const { status, body } = await post('/v1/responses', request(), bearer());+ expect(status).toBe(200);+ expect(runSearchMock).not.toHaveBeenCalled();+ expect(body.output.map((i: any) => i.type)).toEqual(['message']);+ expect(bodies[0].tools).toBeUndefined();+ });++ it('turns a replayed web_search_call into a note on the next assistant turn', async () => {+ const bodies = mockGroq([answer('ok')]);+ await post('/v1/responses', {+ model: 'auto',+ input: [+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'What shipped?' }] },+ { type: 'web_search_call', id: 'ws_1', status: 'completed', action: { type: 'search', query: 'version 9', sources: [{ type: 'url', url: 'https://example.com/news/1' }] } },+ { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'Version 9 shipped.' }] },+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'When?' }] },+ ],+ }, bearer());+ const assistants = bodies[0].messages.filter((m: any) => m.role === 'assistant');+ expect(assistants).toHaveLength(1);+ expect(assistants[0].content).toContain('[Searched the web for: version 9. Sources: https://example.com/news/1]');+ expect(assistants[0].content).toContain('Version 9 shipped.');+ });+ });++ describe('MCP web_search tool', () => {+ async function rpc(message: unknown) {+ return post('/mcp', message, bearer());+ }++ it('searches through runSearch and returns the hits', async () => {+ const { status, body } = await rpc({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'web_search', arguments: { query: 'version 9', max_results: 3, topic: 'news' } } });+ expect(status).toBe(200);+ expect(runSearchMock).toHaveBeenCalledWith('version 9', { maxResults: 3, topic: 'news' });+ const data = JSON.parse(body.result.content[0].text);+ expect(data.provider).toBe('tavily');+ expect(data.results[0]).toEqual({ title: 'Release notes', url: 'https://example.com/news/1', content: 'Version 9 shipped on Monday.' });+ });++ it('reports a missing query as a tool error', async () => {+ const { body } = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'web_search', arguments: {} } });+ expect(body.result.isError).toBe(true);+ });+ });+});diff --git a/server/src/__tests__/routes/conversations.test.ts b/server/src/__tests__/routes/conversations.test.tsindex 9411e193..92ba172f 100644--- a/server/src/__tests__/routes/conversations.test.ts+++ b/server/src/__tests__/routes/conversations.test.ts@@ -42,6 +42,7 @@ const ASSISTANT_TURN = {fallbackAttempts: 1,fusionPanel: [{ platform: 'groq', model: 'a', status: 'ok', content: 'A' }],fusionJudge: { platform: 'cerebras', model: 'j' },+ webSearch: { engine: 'tavily-search', latency: 420, sources: [{ title: 'T', url: 'https://t' }] },},};diff --git a/server/src/__tests__/routes/mcp.test.ts b/server/src/__tests__/routes/mcp.test.tsindex c1fb17b8..15b8f14d 100644--- a/server/src/__tests__/routes/mcp.test.ts+++ b/server/src/__tests__/routes/mcp.test.ts@@ -141,6 +141,7 @@ describe('MCP server (/mcp, stateless Streamable HTTP)', () => {'routing_info','set_routing_strategy','usage_summary',+ 'web_search',]);for (const tool of body.result.tools) {expect(tool.title.length).toBeGreaterThan(5);diff --git a/server/src/__tests__/routes/search.test.ts b/server/src/__tests__/routes/search.test.tsnew file mode 100644index 00000000..0379c8d7--- /dev/null+++ b/server/src/__tests__/routes/search.test.ts@@ -0,0 +1,149 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { clearAllCooldowns } from '../../services/ratelimit.js';+import { mintDashboardToken } from '../helpers/auth.js';+import { seedSearchEngines } from '../helpers/search-engines.js';++// HTTP surface of web search (#1174): POST /v1/search and GET+// /v1/search/engines for API callers, /api/search/engines and+// /api/analytics/search for the dashboard, and the 'search' kind on the+// provider checklist.++const realFetch = globalThis.fetch;+let dashToken = '';++function addKey(platform: string): number {+ const { encrypted, iv, authTag } = encrypt(`${platform}-key`);+ const row = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES (?, 'test', ?, ?, ?, 'healthy', 1)+ `).run(platform, encrypted, iv, authTag);+ return Number(row.lastInsertRowid);+}++async function call(app: Express, method: string, path: string, opts: { body?: unknown; auth?: 'dash' | 'api' | null } = {}) {+ const server = app.listen(0, '127.0.0.1');+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));+ const addr = server.address() as any;+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };+ const auth = opts.auth === undefined ? (path.startsWith('/api') ? 'dash' : 'api') : opts.auth;+ if (auth === 'dash') headers.Authorization = `Bearer ${dashToken}`;+ if (auth === 'api') headers.Authorization = `Bearer ${getUnifiedApiKey()}`;+ const res = await realFetch(`http://127.0.0.1:${addr.port}${path}`, {+ method,+ headers,+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),+ });+ const body = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body, headers: res.headers };+}++function mockUpstream(handler: (url: string) => Response) {+ globalThis.fetch = vi.fn((url: string) => Promise.resolve(handler(String(url)))) as unknown as typeof fetch;+}++describe('search routes', () => {+ let app: Express;++ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ seedSearchEngines();+ clearAllCooldowns(Number.MAX_SAFE_INTEGER);+ app = createApp();+ dashToken = mintDashboardToken();+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('POST /v1/search requires the gateway key', async () => {+ const { status } = await call(app, 'POST', '/v1/search', { body: { query: 'q' }, auth: null });+ expect(status).toBe(401);+ });++ it('POST /v1/search returns a 503 with a code when no search key exists', async () => {+ const { status, body } = await call(app, 'POST', '/v1/search', { body: { query: 'q' } });+ expect(status).toBe(503);+ expect(body.error.code).toBe('no_search_keys');+ });++ it('POST /v1/search serves hits with provider and engine', async () => {+ addKey('tavily');+ mockUpstream(() => new Response(JSON.stringify({ results: [{ title: 'T', url: 'https://t', content: 'c', score: 0.5 }] }), { status: 200 }));+ const { status, body } = await call(app, 'POST', '/v1/search', { body: { query: 'q', max_results: 2 } });+ expect(status).toBe(200);+ expect(body).toEqual({+ query: 'q',+ results: [{ title: 'T', url: 'https://t', content: 'c', score: 0.5 }],+ provider: 'tavily',+ engine: 'tavily-search',+ });+ });++ it('POST /v1/search forwards Retry-After when every engine is rate limited', async () => {+ addKey('tavily');+ mockUpstream(() => new Response('{}', { status: 429, headers: { 'retry-after': '7' } }));+ const { status, headers, body } = await call(app, 'POST', '/v1/search', { body: { query: 'q' } });+ expect(status).toBe(429);+ expect(headers.get('retry-after')).toBe('7');+ expect(body.error.type).toBe('rate_limit_error');+ });++ it('GET /v1/search/engines lists the enabled engines and whether each is usable', async () => {+ addKey('exa');+ const { status, body } = await call(app, 'GET', '/v1/search/engines');+ expect(status).toBe(200);+ expect(body.data.map((e: any) => e.id)).toEqual(['tavily-search', 'exa-search', 'firecrawl-search', 'linkup-search']);+ expect(body.data.find((e: any) => e.id === 'exa-search').available).toBe(true);+ expect(body.data.find((e: any) => e.id === 'tavily-search').available).toBe(false);+ });++ it('GET/PATCH /api/search/engines lists, reorders and toggles engines', async () => {+ const list = await call(app, 'GET', '/api/search/engines');+ expect(list.status).toBe(200);+ expect(list.body[0]).toMatchObject({ engineId: 'tavily-search', priority: 0, enabled: true, keyCount: 0, isCustom: false });+ const firecrawl = list.body.find((e: any) => e.engineId === 'firecrawl-search');++ const moved = await call(app, 'PATCH', `/api/search/engines/${firecrawl.id}`, { body: { priority: 0, enabled: false } });+ expect(moved.status).toBe(200);+ expect(moved.body).toMatchObject({ engineId: 'firecrawl-search', priority: 0, enabled: false });++ const bad = await call(app, 'PATCH', `/api/search/engines/${firecrawl.id}`, { body: {} });+ expect(bad.status).toBe(400);+ const missing = await call(app, 'PATCH', '/api/search/engines/999999', { body: { enabled: true } });+ expect(missing.status).toBe(404);+ });++ it('GET /api/analytics/search returns the search summary', async () => {+ getDb().prepare(`INSERT INTO search_requests (engine_id, platform, status, latency_ms, result_count) VALUES ('exa-search', 'exa', 'ok', 300, 5)`).run();+ const { status, body } = await call(app, 'GET', '/api/analytics/search?range=30d');+ expect(status).toBe(200);+ expect(body).toMatchObject({ total: 1, successRate: 100, avgLatencyMs: 300 });+ expect(body.byEngine).toEqual([{ engineId: 'exa-search', displayName: 'Exa Search', count: 1 }]);+ });++ it('marks search platforms on the provider checklist and keeps engines off the media list', async () => {+ const providers = await call(app, 'GET', '/api/keys/providers');+ const kinds = Object.fromEntries(providers.body.providers.map((p: any) => [p.platform, p.kind]));+ expect(kinds).toMatchObject({ tavily: 'search', exa: 'search', firecrawl: 'search', linkup: 'search', groq: 'chat' });++ const media = await call(app, 'GET', '/api/media');+ expect(media.body.models.some((m: any) => m.modality === 'search')).toBe(false);+ });++ it('registers a custom search relay through POST /api/media/custom', async () => {+ const created = await call(app, 'POST', '/api/media/custom', {+ body: { baseUrl: 'https://search.example.com', model: 'my-searxng', modality: 'search', apiKey: 'k' },+ });+ expect(created.status).toBe(201);+ const engines = await call(app, 'GET', '/api/search/engines');+ expect(engines.body.find((e: any) => e.engineId === 'my-searxng')).toMatchObject({ isCustom: true, keyCount: 1 });+ });+});diff --git a/server/src/__tests__/services/catalog-sync.test.ts b/server/src/__tests__/services/catalog-sync.test.tsindex 1fe563db..49c1d0a6 100644--- a/server/src/__tests__/services/catalog-sync.test.ts+++ b/server/src/__tests__/services/catalog-sync.test.ts@@ -733,3 +733,101 @@ describe('applyCatalog: generative media meta', () => {expect(reapplyCachedCatalog().reapplied).toBe(false);});});++// Web search engines (#1174) ride their own optional registry into+// media_models with modality 'search', on the same rules as video: a catalog+// without the key keeps the bundled baseline, one with it is a full snapshot.+describe('applyCatalog: searchEngines', () => {+ type CatalogSearch = NonNullable<AnyCatalog['searchEngines']>[number];++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ function searchRoster(): CatalogSearch[] {+ return [+ {+ platform: 'exa', engineId: 'exa-search', displayName: 'Exa Search', priority: 0, enabled: true,+ quotaLabel: '$10/month in credits', creditsPerQuery: null,+ features: { news: true, answer: false, fullContent: true },+ },+ {+ platform: 'tavily', engineId: 'tavily-search', displayName: 'Tavily Search', priority: 1, enabled: true,+ quotaLabel: '1,000 credits/month', creditsPerQuery: 1,+ features: { news: true, answer: true }, premiumSince: '2026-10-13T00:00:00.000Z',+ },+ ];+ }++ function searchCatalog(entries?: CatalogSearch[]): AnyCatalog {+ const catalog = catalogOf(existingAsCatalogModels());+ if (entries) catalog.searchEngines = entries;+ return catalog;+ }++ function searchRows(): Array<{ platform: string; model_id: string; enabled: number; priority: number; quota_label: string; meta_json: string | null }> {+ return getDb().prepare(`+ SELECT platform, model_id, enabled, priority, quota_label, meta_json+ FROM media_models WHERE modality = 'search' ORDER BY priority, id+ `).all() as any;+ }++ it('ships no search engines until a catalog carries the registry', () => {+ expect(searchRows()).toEqual([]);+ });++ it('applies the registry as a full snapshot with metadata in meta_json', () => {+ applyCatalog(getDb(), searchCatalog(searchRoster()));+ expect(searchRows().map(r => `${r.platform}:${r.model_id}`)).toEqual(['exa:exa-search', 'tavily:tavily-search']);+ expect(searchRows()[0].quota_label).toBe('$10/month in credits');+ expect(JSON.parse(searchRows()[1].meta_json!)).toEqual({+ creditsPerQuery: 1,+ features: { news: true, answer: true },+ premiumSince: '2026-10-13T00:00:00.000Z',+ });+ });++ it('keeps existing engines when a catalog omits the optional registry', () => {+ applyCatalog(getDb(), searchCatalog(undefined));+ expect(searchRows()).toHaveLength(2);+ });++ it('removes every engine when the registry is empty (a free catalog before an engine ages in)', () => {+ const counts = applyCatalog(getDb(), searchCatalog([]));+ expect(counts.removed).toBeGreaterThanOrEqual(2);+ expect(searchRows()).toEqual([]);+ applyCatalog(getDb(), searchCatalog(searchRoster()));+ expect(searchRows()).toHaveLength(2);+ });++ it('keeps a local disable across catalog applies', () => {+ getDb().prepare("UPDATE media_models SET enabled = 0 WHERE model_id = 'exa-search'").run();+ applyCatalog(getDb(), searchCatalog(searchRoster()));+ expect(searchRows().find(r => r.model_id === 'exa-search')!.enabled).toBe(0);+ });++ it('never prunes a custom search relay', () => {+ getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)+ VALUES ('custom', 'my-searxng', 'My SearXNG', 'search', 9, 1, 'custom endpoint')+ `).run();+ applyCatalog(getDb(), searchCatalog(searchRoster()));+ expect(searchRows().map(r => r.model_id)).toContain('my-searxng');+ });++ it('skips an engine whose platform has no search adapter in this binary', () => {+ const roster = searchRoster();+ roster.push({ platform: 'brave', engineId: 'brave-search', displayName: 'Brave', priority: 5, enabled: true });+ const counts = applyCatalog(getDb(), searchCatalog(roster));+ expect(counts.skippedUnknownPlatform).toBeGreaterThanOrEqual(1);+ expect(searchRows().map(r => r.model_id)).not.toContain('brave-search');+ });++ it('rejects a malformed searchEngines entry before applying the cached catalog', () => {+ const catalog = searchCatalog(searchRoster());+ (catalog.searchEngines![0] as any).priority = 'first';+ setSetting('catalog_applied_json', JSON.stringify(catalog));+ expect(reapplyCachedCatalog().reapplied).toBe(false);+ });+});diff --git a/server/src/__tests__/services/search.test.ts b/server/src/__tests__/services/search.test.tsnew file mode 100644index 00000000..6ece8370--- /dev/null+++ b/server/src/__tests__/services/search.test.ts@@ -0,0 +1,252 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { clearAllCooldowns } from '../../services/ratelimit.js';+import {+ runSearch,+ SearchError,+ listSearchEngines,+ updateSearchEngine,+ searchAnalytics,+ searchAvailable,+ decodeEntities,+} from '../../services/search.js';+import { SEARCH_PLATFORMS as SHARED_SEARCH_PLATFORMS } from '../../../../shared/types.js';+import { SEARCH_PLATFORMS } from '../../lib/search-platforms.js';+import { seedSearchEngines } from '../helpers/search-engines.js';++const realFetch = globalThis.fetch;++function addKey(platform: string, raw = `${platform}-test-key`): number {+ const { encrypted, iv, authTag } = encrypt(raw);+ const row = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES (?, 'test', ?, ?, ?, 'healthy', 1)+ `).run(platform, encrypted, iv, authTag);+ return Number(row.lastInsertRowid);+}++function addCustomRelay(baseUrl: string, engineId = 'my-relay'): number {+ const { encrypted, iv, authTag } = encrypt('relay-key');+ const key = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)+ VALUES ('custom', 'relay', ?, ?, ?, 'healthy', 1, ?)+ `).run(encrypted, iv, authTag, baseUrl);+ const keyId = Number(key.lastInsertRowid);+ getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id)+ VALUES ('custom', ?, ?, 'search', 99, 1, 'custom endpoint', ?)+ `).run(engineId, engineId, keyId);+ return keyId;+}++function json(body: unknown, status = 200, headers: Record<string, string> = {}) {+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } });+}++type Call = [string, RequestInit];+function mockFetch(handler: (url: string, init: RequestInit) => Response | Promise<Response>) {+ const fn = vi.fn((url: string, init: RequestInit) => Promise.resolve(handler(url, init)));+ globalThis.fetch = fn as unknown as typeof fetch;+ return fn;+}+const calls = (fn: ReturnType<typeof mockFetch>) => fn.mock.calls as unknown as Call[];+const bodyOf = (call: Call) => JSON.parse(call[1].body as string);++function logRows() {+ return getDb().prepare('SELECT engine_id, platform, status, result_count FROM search_requests ORDER BY id').all() as+ Array<{ engine_id: string; platform: string; status: string; result_count: number }>;+}++describe('search platforms', () => {+ it('server runtime list matches the shared list', () => {+ expect([...SEARCH_PLATFORMS]).toEqual([...SHARED_SEARCH_PLATFORMS]);+ });+});++describe('search service', () => {+ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ seedSearchEngines();+ clearAllCooldowns(Number.MAX_SAFE_INTEGER);+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('lists the catalog engines in priority order', () => {+ expect(listSearchEngines().map(e => e.engineId)).toEqual(['tavily-search', 'exa-search', 'firecrawl-search', 'linkup-search']);+ expect(searchAvailable()).toBe(false);+ });++ it('answers 503 no_search_keys when no engine has a key', async () => {+ await expect(runSearch('q')).rejects.toMatchObject({ status: 503, code: 'no_search_keys' });+ });++ it('skips engines without keys and maps Exa hits (text → content, rank scores)', async () => {+ addKey('exa');+ const fn = mockFetch(() => json({+ results: [+ { title: 'A', url: 'https://a', text: 'alpha' },+ { title: 'no url', text: 'x' },+ { title: 'B', url: 'https://b', text: 'beta' },+ ],+ }));+ const out = await runSearch('what', { topic: 'news', maxResults: 3 });+ expect(calls(fn)).toHaveLength(1);+ expect(calls(fn)[0][0]).toBe('https://api.exa.ai/search');+ expect(new Headers(calls(fn)[0][1].headers).get('x-api-key')).toBe('exa-test-key');+ expect(bodyOf(calls(fn)[0])).toMatchObject({ query: 'what', numResults: 3, category: 'news' });+ expect(out).toMatchObject({ provider: 'exa', engine: 'exa-search' });+ expect(out.results).toEqual([+ { title: 'A', url: 'https://a', content: 'alpha', score: 1 },+ { title: 'B', url: 'https://b', content: 'beta', score: 0.5 },+ ]);+ expect(logRows()).toEqual([{ engine_id: 'exa-search', platform: 'exa', status: 'ok', result_count: 2 }]);+ });++ it('passes Tavily topic/answer through and keeps its scores', async () => {+ addKey('tavily');+ const fn = mockFetch(() => json({ answer: '42', results: [{ title: 'T', url: 'https://t', content: 'c', score: 0.83 }] }));+ const out = await runSearch('q', { includeAnswer: true, topic: 'general' });+ expect(calls(fn)[0][0]).toBe('https://api.tavily.com/search');+ expect(bodyOf(calls(fn)[0])).toEqual({ query: 'q', max_results: 5, topic: 'general', include_answer: true });+ expect(out.answer).toBe('42');+ expect(out.results[0].score).toBe(0.83);+ });++ it('maps Firecrawl news hits and Linkup sourced answers', async () => {+ addKey('firecrawl');+ let fn = mockFetch(() => json({ success: true, data: { news: [{ title: 'N', url: 'https://n', snippet: 'fresh' }] } }));+ let out = await runSearch('q', { topic: 'news' });+ expect(bodyOf(calls(fn)[0])).toMatchObject({ query: 'q', limit: 5, sources: ['news'] });+ expect(out.results).toEqual([{ title: 'N', url: 'https://n', content: 'fresh', score: 1 }]);++ updateSearchEngine(listSearchEngines().find(e => e.engineId === 'firecrawl-search')!.id, { enabled: false });+ addKey('linkup');+ fn = mockFetch(() => json({ answer: 'yes', sources: [{ name: 'S', url: 'https://s', snippet: 'src' }] }));+ out = await runSearch('q', { includeAnswer: true });+ expect(calls(fn)[0][0]).toBe('https://api.linkup.so/v1/search');+ expect(bodyOf(calls(fn)[0])).toMatchObject({ q: 'q', depth: 'standard', outputType: 'sourcedAnswer', maxResults: 5 });+ expect(out).toMatchObject({ answer: 'yes', provider: 'linkup', results: [{ title: 'S', url: 'https://s', content: 'src' }] });+ });++ it('tries a custom relay before the catalog engines', async () => {+ addKey('tavily');+ addCustomRelay('https://relay.example/v1');+ const fn = mockFetch(url => url.startsWith('https://relay.example')+ ? json({ error: 'down' }, 500)+ : json({ results: [{ title: 'T', url: 'https://t', content: 'c', score: 1 }] }));+ const out = await runSearch('q');+ expect(calls(fn).map(c => c[0])).toEqual(['https://relay.example/v1/search', 'https://api.tavily.com/search']);+ expect(out.provider).toBe('tavily');+ expect(logRows().map(r => `${r.platform}:${r.status}`)).toEqual(['custom:error', 'tavily:ok']);+ });++ it('cools a rate-limited key down and fails over to the next engine', async () => {+ addKey('tavily');+ addKey('exa');+ const fn = mockFetch(url => url.includes('tavily')+ ? json({ detail: 'slow down' }, 429, { 'retry-after': '120' })+ : json({ results: [{ title: 'E', url: 'https://e', text: 'x' }] }));+ expect((await runSearch('q')).provider).toBe('exa');+ // The benched Tavily key is skipped on the next search.+ await runSearch('q2');+ expect(calls(fn).map(c => new URL(c[0]).host)).toEqual(['api.tavily.com', 'api.exa.ai', 'api.exa.ai']);+ });++ it('tries every key of an engine before moving on, and benches spent credits', async () => {+ addKey('tavily', 'spent');+ addKey('tavily', 'fresh');+ const fn = mockFetch((_url, init) => new Headers(init.headers).get('Authorization') === 'Bearer spent'+ ? json({ detail: 'plan limit' }, 432)+ : json({ results: [{ title: 'T', url: 'https://t', content: 'c' }] }));+ const out = await runSearch('q');+ expect(out.provider).toBe('tavily');+ await runSearch('q');+ const auths = calls(fn).map(c => new Headers(c[1].headers).get('Authorization'));+ // At most one attempt on the spent key, whichever order the keys came in.+ expect(auths.filter(a => a === 'Bearer spent').length).toBeLessThanOrEqual(1);+ expect(auths.at(-1)).toBe('Bearer fresh');+ });++ it('returns 429 with the soonest Retry-After when every engine is rate limited', async () => {+ addKey('tavily');+ addKey('exa');+ mockFetch(url => json({}, 429, { 'retry-after': url.includes('exa') ? '30' : '90' }));+ const err = await runSearch('q').catch(e => e) as SearchError;+ expect(err).toBeInstanceOf(SearchError);+ expect(err.status).toBe(429);+ expect(err.retryAfterMs).toBe(30_000);+ });++ it('reports a provider 401 as a 502, never as the caller’s auth failure', async () => {+ addKey('tavily');+ mockFetch(() => json({ detail: 'bad key' }, 401));+ await expect(runSearch('q')).rejects.toMatchObject({ status: 502 });+ // The rejected key is benched, so the next search is a retryable 429.+ await expect(runSearch('q')).rejects.toMatchObject({ status: 429, code: 'search_keys_cooling_down' });+ });++ it('pins an engine by id and rejects unknown or disabled ones', async () => {+ addKey('tavily');+ addKey('exa');+ const fn = mockFetch(() => json({ results: [{ title: 'E', url: 'https://e', text: 'x' }] }));+ expect((await runSearch('q', { engine: 'exa-search' })).engine).toBe('exa-search');+ expect(calls(fn)).toHaveLength(1);+ await expect(runSearch('q', { engine: 'nope' })).rejects.toMatchObject({ status: 400 });+ updateSearchEngine(listSearchEngines().find(e => e.engineId === 'exa-search')!.id, { enabled: false });+ await expect(runSearch('q', { engine: 'exa-search' })).rejects.toMatchObject({ status: 400 });+ });++ it('reorders engines locally and lists key and usage counts', async () => {+ addKey('linkup');+ const linkup = listSearchEngines().find(e => e.engineId === 'linkup-search')!;+ expect(updateSearchEngine(linkup.id, { priority: 0 })).toBe(true);+ const order = listSearchEngines();+ expect(order.map(e => e.engineId)).toEqual(['linkup-search', 'tavily-search', 'exa-search', 'firecrawl-search']);+ expect(order.map(e => e.priority)).toEqual([0, 1, 2, 3]);+ expect(order[0]).toMatchObject({ keyCount: 1, healthyKeyCount: 1, searchesThisMonth: 0, isCustom: false });++ mockFetch(() => json({ results: [{ type: 'text', name: 'L', url: 'https://l', content: 'c' }] }));+ await runSearch('q');+ expect(listSearchEngines()[0].searchesThisMonth).toBe(1);+ expect(updateSearchEngine(999_999, { enabled: false })).toBe(false);+ });++ it('derives freeFrom 30 days after premiumSince', () => {+ getDb().prepare(`UPDATE media_models SET meta_json = ? WHERE model_id = 'exa-search'`)+ .run(JSON.stringify({ premiumSince: '2026-10-13T00:00:00.000Z' }));+ const exa = listSearchEngines().find(e => e.engineId === 'exa-search')!;+ expect(exa.freeFrom).toBe('2026-11-12T00:00:00.000Z');+ });++ it('summarises searches per engine and per day', async () => {+ addKey('tavily');+ addKey('exa');+ mockFetch(url => url.includes('tavily')+ ? json({}, 500)+ : json({ results: [{ title: 'E', url: 'https://e', text: 'x' }] }));+ await runSearch('a');+ await runSearch('b');+ const stats = searchAnalytics('7d');+ expect(stats.total).toBe(2);+ expect(stats.today).toBe(2);+ expect(stats.successRate).toBe(50);+ expect(stats.byEngine).toEqual([{ engineId: 'exa-search', displayName: 'Exa Search', count: 2 }]);+ expect(stats.series).toHaveLength(1);+ expect(stats.series[0]).toMatchObject({ engineId: 'exa-search', count: 2 });+ });+});++describe('decodeEntities', () => {+ it('turns HTML entities in titles into plain text', () => {+ expect(decodeEntities('Quelle est la capitale de l'Australie ?')).toBe("Quelle est la capitale de l'Australie ?");+ expect(decodeEntities('Tom & Jerry "live" — ok')).toBe('Tom & Jerry "live" \u2014 ok');+ expect(decodeEntities('&bogus; stays')).toBe('&bogus; stays');+ expect(decodeEntities('plain')).toBe('plain');+ });+});diff --git a/server/src/app.ts b/server/src/app.tsindex 833e4501..581bd442 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -16,6 +16,7 @@ import { fallbackRouter } from './routes/fallback.js';import { profilesRouter } from './routes/profiles.js';import { embeddingsRouter } from './routes/embeddings.js';import { mediaRouter } from './routes/media.js';+import { searchRouter } from './routes/search.js';import { analyticsRouter } from './routes/analytics.js';import { healthRouter } from './routes/health.js';import { freeTierRouter } from './routes/free-tier.js';@@ -258,6 +259,7 @@ export function createApp(config?: Config) {app.use('/api/fallback', requireAuth, fallbackRouter);app.use('/api/embeddings', requireAuth, embeddingsRouter);app.use('/api/media', requireAuth, mediaRouter);+ app.use('/api/search', requireAuth, searchRouter);app.use('/api/analytics', requireAuth, analyticsRouter);app.use('/api/health', requireAuth, healthRouter);app.use('/api/free-tier', requireAuth, freeTierRouter);diff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex ec1b633f..93d3501f 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -38,6 +38,7 @@ import * as keyMonthlyUsage from '../migrations/20260914_000001_key_monthly_usagimport * as quotaSnapshotFreshness from '../migrations/20260915_000001_quota_snapshot_freshness.js';import * as requestModelAttribution from '../migrations/20260913_000001_request_model_attribution.js';import * as customEndpointGroupLabel from '../migrations/20260930_000001_custom_endpoint_group_label.js';+import * as searchEngines from '../migrations/20261013_000001_search_engines.js';export interface MigrationModule {up(db: Db): void;@@ -88,6 +89,7 @@ export const REQUEST_MODEL_ATTRIBUTION_FILENAME = '20260913_000001_request_modelexport const CUSTOM_ENDPOINT_GROUP_LABEL_FILENAME = '20260930_000001_custom_endpoint_group_label.ts';export const KEY_MONTHLY_USAGE_FILENAME = '20260914_000001_key_monthly_usage.ts';export const QUOTA_SNAPSHOT_FRESHNESS_FILENAME = '20260915_000001_quota_snapshot_freshness.ts';+export const SEARCH_ENGINES_FILENAME = '20261013_000001_search_engines.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },@@ -129,4 +131,5 @@ export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: KEY_MONTHLY_USAGE_FILENAME, module: keyMonthlyUsage },{ filename: QUOTA_SNAPSHOT_FRESHNESS_FILENAME, module: quotaSnapshotFreshness },{ filename: CUSTOM_ENDPOINT_GROUP_LABEL_FILENAME, module: customEndpointGroupLabel },+ { filename: SEARCH_ENGINES_FILENAME, module: searchEngines },];diff --git a/server/src/db/migrations/20261013_000001_search_engines.ts b/server/src/db/migrations/20261013_000001_search_engines.tsnew file mode 100644index 00000000..a7849f46--- /dev/null+++ b/server/src/db/migrations/20261013_000001_search_engines.ts@@ -0,0 +1,44 @@+// Migration: search request log (#1174)+// Created: 2026-10-13+//+// DOWN: reversible (drops search_requests)+//+// Search engines live in media_models with modality = 'search' and+// model_id = the engine id, maintained by the catalog's `searchEngines`+// registry exactly like video rows. Nothing is seeded here on purpose: new+// engines reach Premium installs first and Free installs 30 days later through+// the catalog, so a bundled baseline would hand every install all of them on+// day one and then have the free catalog's sync take them away again.+//+// search_requests is its own log rather than more `requests` rows: a search+// has no tokens or model, and keeping it out of `requests` keeps the chat+// analytics, success rates and request log free of search traffic.++import type { Db } from '../types.js';++export function up(db: Db): void {+ db.exec(`+ CREATE TABLE IF NOT EXISTS search_requests (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ engine_id TEXT NOT NULL,+ platform TEXT NOT NULL,+ key_id INTEGER,+ status TEXT NOT NULL CHECK (status IN ('ok', 'error')),+ latency_ms INTEGER NOT NULL DEFAULT 0,+ result_count INTEGER NOT NULL DEFAULT 0,+ client_agent TEXT,+ error TEXT+ );+ CREATE INDEX IF NOT EXISTS idx_search_requests_created_at ON search_requests(created_at);+ CREATE INDEX IF NOT EXISTS idx_search_requests_engine_created ON search_requests(engine_id, created_at);+ `);+}++export function down(db: Db): void {+ db.exec(`+ DROP INDEX IF EXISTS idx_search_requests_engine_created;+ DROP INDEX IF EXISTS idx_search_requests_created_at;+ DROP TABLE IF EXISTS search_requests;+ `);+}diff --git a/server/src/docs/openapi.ts b/server/src/docs/openapi.tsindex 30e0a4af..059068ff 100644--- a/server/src/docs/openapi.ts+++ b/server/src/docs/openapi.ts@@ -35,6 +35,7 @@ export const openapiSpec = {tags: [{ name: 'Chat', description: 'OpenAI-compatible chat and completion endpoints' },{ name: 'Media', description: 'Image generation and text-to-speech' },+ { name: 'Search', description: 'Web search over your Tavily, Exa, Firecrawl and Linkup keys' },{ name: 'Responses', description: 'OpenAI Responses API (Codex CLI wire format)' },{ name: 'Anthropic', description: 'Anthropic Messages API (Claude Code and the Anthropic SDKs)' },{ name: 'Models', description: 'Model discovery' },@@ -171,6 +172,106 @@ export const openapiSpec = {},},},+ '/v1/search': {+ post: {+ tags: ['Search'],+ operationId: 'createSearch',+ summary: 'Search the web',+ description:+ 'Web search routed over the search engines in the catalog (Tavily, Exa, Firecrawl, Linkup) and any ' ++ 'custom search relay. Omit `engine` (or set `auto`) to fail over across engines that have a key; ' ++ 'rate-limited or out-of-credit keys cool down and the next one is tried.',+ requestBody: {+ required: true,+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ required: ['query'],+ properties: {+ query: { type: 'string', example: 'latest Node.js LTS release' },+ max_results: { type: 'integer', minimum: 1, maximum: 20, default: 5 },+ topic: { type: 'string', enum: ['general', 'news'] },+ include_answer: { type: 'boolean', description: 'Ask engines that support it (Tavily, Linkup) for a short answer.' },+ engine: { type: 'string', description: 'Pin one engine id from GET /v1/search/engines, or `auto`.' },+ },+ },+ },+ },+ },+ responses: {+ '200': {+ description: 'Search hits from the first engine that answered.',+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ properties: {+ query: { type: 'string' },+ answer: { type: 'string' },+ results: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ title: { type: 'string' },+ url: { type: 'string' },+ content: { type: 'string' },+ score: { type: 'number' },+ },+ },+ },+ provider: { type: 'string', example: 'tavily' },+ engine: { type: 'string', example: 'tavily-search' },+ },+ },+ },+ },+ },+ '400': { $ref: '#/components/responses/BadRequest' },+ '401': { $ref: '#/components/responses/Unauthorized' },+ '429': { $ref: '#/components/responses/RateLimited' },+ '502': { $ref: '#/components/responses/UpstreamError' },+ },+ },+ },+ '/v1/search/engines': {+ get: {+ tags: ['Search'],+ operationId: 'listSearchEngines',+ summary: 'List search engines',+ description: 'The enabled search engines, in failover order, and whether each has a usable key.',+ responses: {+ '200': {+ description: 'Search engines.',+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ properties: {+ object: { type: 'string', example: 'list' },+ data: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ id: { type: 'string', example: 'tavily-search' },+ object: { type: 'string', example: 'search_engine' },+ provider: { type: 'string', example: 'tavily' },+ name: { type: 'string' },+ available: { type: 'boolean' },+ },+ },+ },+ },+ },+ },+ },+ },+ '401': { $ref: '#/components/responses/Unauthorized' },+ },+ },+ },'/v1/videos/generations': {post: {tags: ['Media'],diff --git a/server/src/lib/anthropic-web-search.ts b/server/src/lib/anthropic-web-search.tsnew file mode 100644index 00000000..cd12f73c--- /dev/null+++ b/server/src/lib/anthropic-web-search.ts@@ -0,0 +1,315 @@+import type { Request, Response } from 'express';+import {+ WEB_SEARCH_TOOL_NAME,+ WEB_SEARCH_FUNCTION_DESCRIPTION,+ WEB_SEARCH_FUNCTION_PARAMETERS,+ hasSearchCapability,+ performWebSearch,+ formatOutcomeForModel,+ encodeHitContent,+ decodeHitContent,+ newServerToolUseId,+ invokeHandlerCaptured,+ copyCapturedHeaders,+ resolveMaxSearches,+ type WebSearchOutcome,+ type DomainFilter,+} from './web-search-tool.js';++// Anthropic `web_search_*` server tool (Claude Code's WebSearch) served from+// the gateway's search pool (#1174). The client sees what api.anthropic.com+// would send: `server_tool_use` + `web_search_tool_result` blocks ahead of the+// answer, `usage.server_tool_use.web_search_requests`, and the matching SSE+// events when it streams. The routed model only ever sees a plain function+// tool named `web_search`; each of its calls is executed here and fed back+// until it answers, a client tool is called, or max_uses runs out.++const HEARTBEAT_MS = 5_000;++/** `web_search_20250305`, `web_search_20260209`, `web_search_20260318`, … */+export function isWebSearchServerTool(tool: unknown): boolean {+ const type = (tool as { type?: unknown } | null)?.type;+ return typeof type === 'string' && /^web_search_\d{8}$/.test(type);+}++type Block = Record<string, any>;++interface Usage { input_tokens: number; output_tokens: number }++function isOurSearchCall(block: Block): boolean {+ return block?.type === 'tool_use' && block?.name === WEB_SEARCH_TOOL_NAME;+}++function resultBlock(toolUseId: string, outcome: WebSearchOutcome): Block {+ if (!outcome.ok) {+ return { type: 'web_search_tool_result', tool_use_id: toolUseId, content: { type: 'web_search_tool_result_error', error_code: outcome.errorCode } };+ }+ return {+ type: 'web_search_tool_result',+ tool_use_id: toolUseId,+ content: outcome.results.map(hit => ({+ type: 'web_search_result',+ url: hit.url,+ title: hit.title || hit.url,+ encrypted_content: encodeHitContent(hit),+ page_age: null,+ })),+ };+}++/** Earlier search blocks a client replays → text the routed model can read.+ * Used by the request converter for both our own and real Anthropic blocks. */+export function serverToolUseToText(block: Block): string {+ if (block?.name !== WEB_SEARCH_TOOL_NAME) return '';+ const query = typeof block?.input?.query === 'string' ? block.input.query : '';+ return query ? `[Searched the web for: ${query}]` : '';+}++export function webSearchResultToText(block: Block): string {+ const content = block?.content;+ if (!Array.isArray(content)) return '[Web search returned an error]';+ if (content.length === 0) return '[Web search returned no results]';+ const lines = ['[Web search results]'];+ for (const hit of content) {+ if (!hit || typeof hit.url !== 'string') continue;+ lines.push(`- ${typeof hit.title === 'string' && hit.title ? hit.title : hit.url} (${hit.url})`);+ const extract = decodeHitContent(hit.encrypted_content);+ if (extract) lines.push(` ${extract.replace(/\s+/g, ' ').trim()}`);+ }+ return lines.join('\n');+}++class AnthropicSse {+ private index = 0;+ private started = false;+ private heartbeat: NodeJS.Timeout | null = null;+ constructor(private res: Response) {}++ get committed(): boolean { return this.started; }++ private write(event: string, data: unknown): void {+ if (this.res.writableEnded || this.res.destroyed) return;+ try {+ this.res.write(`event: ${event}\n`);+ this.res.write(`data: ${JSON.stringify(data)}\n\n`);+ } catch { /* socket teardown race */ }+ }++ start(first: { id: string; model: string }, inputTokens: number): void {+ if (this.started) return;+ this.res.setHeader('Content-Type', 'text/event-stream');+ this.res.setHeader('Cache-Control', 'no-cache');+ this.res.setHeader('Connection', 'keep-alive');+ this.write('message_start', {+ type: 'message_start',+ message: {+ id: first.id, type: 'message', role: 'assistant', model: first.model,+ content: [], stop_reason: null, stop_sequence: null,+ usage: { input_tokens: inputTokens, output_tokens: 0 },+ },+ });+ this.started = true;+ // Searches and follow-up turns can take a while; Anthropic's own stream+ // sends `ping` events, which every SDK ignores but which keep idle+ // watchdogs and proxies from cutting the connection.+ this.heartbeat = setInterval(() => this.write('ping', { type: 'ping' }), HEARTBEAT_MS);+ this.heartbeat.unref?.();+ }++ block(block: Block): void {+ const idx = this.index++;+ const start = (contentBlock: Block) => this.write('content_block_start', { type: 'content_block_start', index: idx, content_block: contentBlock });+ const delta = (d: Block) => this.write('content_block_delta', { type: 'content_block_delta', index: idx, delta: d });+ switch (block.type) {+ case 'text':+ start({ type: 'text', text: '' });+ if (block.text) delta({ type: 'text_delta', text: block.text });+ break;+ case 'thinking':+ start({ type: 'thinking', thinking: '' });+ if (block.thinking) delta({ type: 'thinking_delta', thinking: block.thinking });+ break;+ case 'tool_use':+ case 'server_tool_use': {+ const { input, ...rest } = block;+ start({ ...rest, input: {} });+ delta({ type: 'input_json_delta', partial_json: JSON.stringify(input ?? {}) });+ break;+ }+ default:+ // web_search_tool_result is delivered whole in content_block_start.+ start(block);+ }+ this.write('content_block_stop', { type: 'content_block_stop', index: idx });+ }++ finish(stopReason: string | null, usage: Record<string, unknown>): void {+ this.stopHeartbeat();+ this.write('message_delta', { type: 'message_delta', delta: { stop_reason: stopReason, stop_sequence: null }, usage });+ this.write('message_stop', { type: 'message_stop' });+ try { this.res.end(); } catch { /* already closed */ }+ }++ fail(message: string): void {+ this.stopHeartbeat();+ this.write('error', { type: 'error', error: { type: 'api_error', message } });+ try { this.res.end(); } catch { /* already closed */ }+ }++ stopHeartbeat(): void {+ if (this.heartbeat) clearInterval(this.heartbeat);+ this.heartbeat = null;+ }+}++/**+ * Serve a /v1/messages request that carries a web_search server tool from the+ * search pool. Returns false (nothing sent) when the request has no such tool+ * or no search key is configured — the caller then runs the normal handler.+ */+export async function maybeServeAnthropicWebSearch(+ handler: (req: Request, res: Response) => Promise<void>,+ req: Request,+ res: Response,+): Promise<boolean> {+ const body = req.body;+ if (!body || typeof body !== 'object' || !Array.isArray(body.tools) || !Array.isArray(body.messages)) return false;+ const searchTool = body.tools.find(isWebSearchServerTool);+ if (!searchTool || !hasSearchCapability()) return false;++ const filter: DomainFilter = {+ allowedDomains: Array.isArray(searchTool.allowed_domains) ? searchTool.allowed_domains.filter((d: unknown) => typeof d === 'string') : undefined,+ blockedDomains: Array.isArray(searchTool.blocked_domains) ? searchTool.blocked_domains.filter((d: unknown) => typeof d === 'string') : undefined,+ };+ const maxUses = resolveMaxSearches(searchTool.max_uses);+ // One function tool stands in for the server tool; any other server tools+ // (and duplicates) keep their current pass-through handling.+ let replaced = false;+ const tools = body.tools.flatMap((t: Block) => {+ if (!isWebSearchServerTool(t)) return [t];+ if (replaced) return [];+ replaced = true;+ return [{ name: WEB_SEARCH_TOOL_NAME, description: WEB_SEARCH_FUNCTION_DESCRIPTION, input_schema: WEB_SEARCH_FUNCTION_PARAMETERS }];+ });++ const wantsStream = body.stream === true;+ const sse = wantsStream ? new AnthropicSse(res) : null;+ const assembled: Block[] = [];+ const usage: Usage = { input_tokens: 0, output_tokens: 0 };+ let searchesRun = 0;+ let searchRequests = 0;+ let messages: Block[] = [...body.messages];+ // max_uses bounds real searches; one extra turn lets the model answer after+ // the last search (or after being told the limit is spent).+ const maxTurns = maxUses + 2;++ const emit = (block: Block) => {+ assembled.push(block);+ sse?.block(block);+ };++ try {+ for (let turn = 0; turn < maxTurns; turn++) {+ const lastTurn = turn === maxTurns - 1;+ let toolChoice = body.tool_choice;+ // A forced web_search choice would loop forever after the first search.+ if (turn > 0 && toolChoice && (toolChoice.type === 'any' || (toolChoice.type === 'tool' && toolChoice.name === WEB_SEARCH_TOOL_NAME))) {+ toolChoice = { type: 'auto' };+ }+ const innerBody = {+ ...body,+ stream: false,+ messages,+ tools,+ ...(toolChoice !== undefined ? { tool_choice: toolChoice } : {}),+ };+ const captured = await invokeHandlerCaptured(handler, req, res, innerBody);+ if (res.writableEnded || res.destroyed) return true;++ if (captured.status !== 200 || captured.body?.type !== 'message') {+ if (sse?.committed) {+ const msg = captured.body?.error?.message ?? `upstream error (HTTP ${captured.status})`;+ sse.fail(String(msg));+ } else {+ copyCapturedHeaders(captured, res);+ res.status(captured.status).json(captured.body);+ }+ return true;+ }++ const reply = captured.body;+ usage.input_tokens += Number(reply.usage?.input_tokens) || 0;+ usage.output_tokens += Number(reply.usage?.output_tokens) || 0;+ copyCapturedHeaders(captured, res);+ if (sse && !sse.committed) sse.start({ id: reply.id, model: reply.model }, Number(reply.usage?.input_tokens) || 0);++ const content: Block[] = Array.isArray(reply.content) ? reply.content : [];+ const searchCalls = content.filter(isOurSearchCall);+ const clientCalls = content.filter(b => b?.type === 'tool_use' && !isOurSearchCall(b));++ // Final turn: no search requested, a client tool must run first (the+ // real API also defers the search then), or the turn budget is spent.+ if (searchCalls.length === 0 || clientCalls.length > 0 || lastTurn) {+ const finalBlocks = content.filter(b => !isOurSearchCall(b));+ let stopReason = reply.stop_reason ?? 'end_turn';+ if (stopReason === 'tool_use' && clientCalls.length === 0) stopReason = 'end_turn';+ for (const block of finalBlocks) emit(block);+ const finalUsage = {+ input_tokens: usage.input_tokens,+ output_tokens: usage.output_tokens,+ server_tool_use: { web_search_requests: searchRequests },+ };+ if (sse) {+ sse.finish(stopReason, finalUsage);+ } else {+ res.status(200).json({+ id: reply.id,+ type: 'message',+ role: 'assistant',+ model: reply.model,+ content: assembled,+ stop_reason: stopReason,+ stop_sequence: reply.stop_sequence ?? null,+ usage: finalUsage,+ });+ }+ return true;+ }++ // Run this turn's searches, mirroring each as server_tool_use + result+ // for the client and as tool_result for the routed model.+ const toolResults: Block[] = [];+ for (const block of content) {+ if (!isOurSearchCall(block)) {+ emit(block);+ continue;+ }+ const query = typeof block.input?.query === 'string' ? block.input.query : '';+ let outcome: WebSearchOutcome;+ if (searchesRun >= maxUses) {+ outcome = { ok: false, query, errorCode: 'max_uses_exceeded', message: 'max uses exceeded' };+ } else {+ searchesRun++;+ outcome = await performWebSearch(block.input?.query, filter);+ if (outcome.ok) searchRequests++;+ }+ const serverId = newServerToolUseId();+ emit({ type: 'server_tool_use', id: serverId, name: WEB_SEARCH_TOOL_NAME, input: { query } });+ emit(resultBlock(serverId, outcome));+ toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: formatOutcomeForModel(outcome) });+ }+ messages = [...messages, { role: 'assistant', content }, { role: 'user', content: toolResults }];+ }+ } catch (err: unknown) {+ const message = err instanceof Error ? err.message : String(err);+ if (sse?.committed) {+ sse.fail(`web search failed: ${message}`);+ } else if (!res.headersSent) {+ res.status(500).json({ type: 'error', error: { type: 'api_error', message: `web search failed: ${message}` } });+ }+ return true;+ } finally {+ sse?.stopHeartbeat();+ }+ return true;+}diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex 7ee050a0..57999d61 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -96,6 +96,10 @@ export const PREFIX_MAP: Record<string, string> = {OPENROUTER_: 'openrouter',GITHUB_: 'github',COHERE_: 'cohere',+ TAVILY_: 'tavily',+ EXA_: 'exa',+ FIRECRAWL_: 'firecrawl',+ LINKUP_: 'linkup',CLOUDFLARE_: 'cloudflare',ZHIPU_: 'zhipu',OLLAMA_: 'ollama',@@ -232,6 +236,10 @@ export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {xfyun: 'xfyun',spark: 'xfyun',iflytek: 'xfyun',+ tavily: 'tavily',+ exa: 'exa',+ firecrawl: 'firecrawl',+ linkup: 'linkup',};export function detectPlatform(prefix: string): string | null {diff --git a/server/src/lib/proxy.ts b/server/src/lib/proxy.tsindex 454710f9..f0f6d379 100644--- a/server/src/lib/proxy.ts+++ b/server/src/lib/proxy.ts@@ -560,7 +560,7 @@ async function resolveDispatcher(): Promise<{ dispatcher: unknown; isSocks: bool* written to `requests.request_type` so the abort message and the row* column agree on terminology.*/-export type ProxyRequestType = 'chat' | 'embedding' | 'image' | 'video' | 'audio' | 'transcription' | 'moderation' | 'unknown';+export type ProxyRequestType = 'chat' | 'embedding' | 'image' | 'video' | 'audio' | 'transcription' | 'moderation' | 'search' | 'unknown';/*** Build an AbortError DOMException whose `message` carries a compact triagediff --git a/server/src/lib/responses-web-search.ts b/server/src/lib/responses-web-search.tsnew file mode 100644index 00000000..e519e080--- /dev/null+++ b/server/src/lib/responses-web-search.ts@@ -0,0 +1,305 @@+import crypto from 'crypto';+import type { Request, Response } from 'express';+import {+ WEB_SEARCH_TOOL_NAME,+ WEB_SEARCH_FUNCTION_DESCRIPTION,+ WEB_SEARCH_FUNCTION_PARAMETERS,+ hasSearchCapability,+ performWebSearch,+ formatOutcomeForModel,+ newWebSearchCallId,+ invokeHandlerCaptured,+ copyCapturedHeaders,+ resolveMaxSearches,+ type WebSearchOutcome,+ type DomainFilter,+} from './web-search-tool.js';++// OpenAI Responses `web_search` tool (Codex) served from the gateway's search+// pool (#1174). Before this the tool was dropped at conversion and the model+// could not search at all. The routed model sees a plain `web_search`+// function; each call runs here and is reported to the client as a+// `web_search_call` output item (action.type 'search', with its sources),+// exactly where OpenAI would put it, ahead of the final answer.++const HEARTBEAT_MS = 5_000;+// Commit the stream (response.created) if the first model turn has not come+// back by then, so Codex's stream idle watchdog sees events. A faster first+// turn that fails keeps its real HTTP status instead.+const STREAM_COMMIT_AFTER_MS = 3_000;++/** `web_search`, `web_search_preview`, and their dated variants. */+export function isResponsesWebSearchTool(tool: unknown): boolean {+ const type = (tool as { type?: unknown } | null)?.type;+ return typeof type === 'string' && /^web_search(_preview)?(_\d{4}_\d{2}_\d{2})?$/.test(type);+}++type Item = Record<string, any>;++/** A replayed web_search_call item → a note the routed model can read. */+export function webSearchCallToText(item: Item): string {+ const action = item?.action;+ const query = typeof action?.query === 'string' ? action.query : '';+ if (!query) return '';+ const sources = Array.isArray(action?.sources)+ ? action.sources.map((s: Item) => s?.url).filter((u: unknown): u is string => typeof u === 'string')+ : [];+ return sources.length > 0+ ? `[Searched the web for: ${query}. Sources: ${sources.slice(0, 10).join(', ')}]`+ : `[Searched the web for: ${query}]`;+}++function isOurSearchCall(item: Item): boolean {+ return item?.type === 'function_call' && item?.name === WEB_SEARCH_TOOL_NAME;+}++function searchCallItem(id: string, query: string, outcome: WebSearchOutcome | null): Item {+ const sources = outcome?.ok ? outcome.results.map(hit => ({ type: 'url', url: hit.url })) : undefined;+ return {+ type: 'web_search_call',+ id,+ status: outcome ? (outcome.ok ? 'completed' : 'failed') : 'in_progress',+ action: { type: 'search', query, ...(sources ? { sources } : {}) },+ };+}++function itemText(item: Item): string {+ if (item?.type !== 'message' || !Array.isArray(item.content)) return '';+ return item.content.map((p: Item) => (p?.type === 'output_text' && typeof p.text === 'string' ? p.text : '')).join('');+}++class ResponsesSse {+ private seq = 0;+ private outputIndex = 0;+ private started = false;+ private heartbeat: NodeJS.Timeout | null = null;+ private skeleton: Item;+ constructor(private res: Response, responseId: string, model: string) {+ this.skeleton = { id: responseId, object: 'response', created_at: Math.floor(Date.now() / 1000), status: 'in_progress', model, output: [], output_text: '' };+ }++ get committed(): boolean { return this.started; }++ private write(event: string, payload: Record<string, unknown>): void {+ if (this.res.writableEnded || this.res.destroyed) return;+ try {+ this.res.write(`event: ${event}\n`);+ this.res.write(`data: ${JSON.stringify({ type: event, sequence_number: this.seq++, ...payload })}\n\n`);+ } catch { /* socket teardown race */ }+ }++ start(): void {+ if (this.started) return;+ this.res.setHeader('Content-Type', 'text/event-stream');+ this.res.setHeader('Cache-Control', 'no-cache');+ this.res.setHeader('Connection', 'keep-alive');+ this.write('response.created', { response: this.skeleton });+ this.write('response.in_progress', { response: this.skeleton });+ this.started = true;+ // Same keep-alive Fusion uses: Codex's client watchdog ignores SSE+ // comments but resets on any standard event.+ this.heartbeat = setInterval(() => this.write('response.in_progress', { response: this.skeleton }), HEARTBEAT_MS);+ this.heartbeat.unref?.();+ }++ searchStarted(item: Item): number {+ const idx = this.outputIndex++;+ this.write('response.output_item.added', { output_index: idx, item });+ this.write('response.web_search_call.in_progress', { output_index: idx, item_id: item.id });+ this.write('response.web_search_call.searching', { output_index: idx, item_id: item.id });+ return idx;+ }++ searchDone(idx: number, item: Item): void {+ this.write('response.web_search_call.completed', { output_index: idx, item_id: item.id });+ this.write('response.output_item.done', { output_index: idx, item });+ }++ item(item: Item): void {+ const idx = this.outputIndex++;+ if (item.type === 'message') {+ const text = itemText(item);+ this.write('response.output_item.added', { output_index: idx, item: { ...item, status: 'in_progress', content: [] } });+ this.write('response.content_part.added', { item_id: item.id, output_index: idx, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } });+ if (text) this.write('response.output_text.delta', { item_id: item.id, output_index: idx, content_index: 0, delta: text });+ this.write('response.output_text.done', { item_id: item.id, output_index: idx, content_index: 0, text });+ this.write('response.content_part.done', { item_id: item.id, output_index: idx, content_index: 0, part: { type: 'output_text', text, annotations: [] } });+ } else if (item.type === 'function_call') {+ this.write('response.output_item.added', { output_index: idx, item: { ...item, status: 'in_progress', arguments: '' } });+ if (item.arguments) this.write('response.function_call_arguments.delta', { item_id: item.id, output_index: idx, delta: item.arguments });+ this.write('response.function_call_arguments.done', { item_id: item.id, output_index: idx, arguments: item.arguments ?? '' });+ } else {+ this.write('response.output_item.added', { output_index: idx, item });+ }+ this.write('response.output_item.done', { output_index: idx, item });+ }++ complete(response: Item): void {+ this.stopHeartbeat();+ this.write('response.completed', { response });+ try { this.res.end(); } catch { /* already closed */ }+ }++ fail(error: Item): void {+ this.stopHeartbeat();+ this.write('response.failed', { response: { ...this.skeleton, status: 'failed', error } });+ try { this.res.end(); } catch { /* already closed */ }+ }++ stopHeartbeat(): void {+ if (this.heartbeat) clearInterval(this.heartbeat);+ this.heartbeat = null;+ }+}++/**+ * Serve a /v1/responses request that carries a `web_search` tool from the+ * search pool. Returns false (nothing sent) when the request has no such+ * tool, is a Fusion request, or no search key exists — the caller then runs+ * the normal handler, which drops the tool exactly as before.+ */+export async function maybeServeResponsesWebSearch(+ handler: (req: Request, res: Response) => Promise<void>,+ req: Request,+ res: Response,+): Promise<boolean> {+ const body = req.body;+ if (!body || typeof body !== 'object' || !Array.isArray(body.tools)) return false;+ if (body.fusion != null || body.model === 'fusion') return false;+ if (typeof body.input !== 'string' && !Array.isArray(body.input)) return false;+ const searchTool = body.tools.find(isResponsesWebSearchTool);+ if (!searchTool || !hasSearchCapability()) return false;++ const filter: DomainFilter = {+ allowedDomains: Array.isArray(searchTool.filters?.allowed_domains) ? searchTool.filters.allowed_domains.filter((d: unknown) => typeof d === 'string') : undefined,+ blockedDomains: Array.isArray(searchTool.filters?.blocked_domains) ? searchTool.filters.blocked_domains.filter((d: unknown) => typeof d === 'string') : undefined,+ };+ const maxSearches = resolveMaxSearches(body.max_tool_calls);+ let replaced = false;+ const tools = body.tools.flatMap((t: Item) => {+ if (!isResponsesWebSearchTool(t)) return [t];+ if (replaced) return [];+ replaced = true;+ return [{ type: 'function', name: WEB_SEARCH_TOOL_NAME, description: WEB_SEARCH_FUNCTION_DESCRIPTION, parameters: WEB_SEARCH_FUNCTION_PARAMETERS, strict: false }];+ });++ const responseId = `resp_${crypto.randomBytes(16).toString('hex')}`;+ const wantsStream = body.stream === true;+ const sse = wantsStream ? new ResponsesSse(res, responseId, typeof body.model === 'string' ? body.model : 'auto') : null;+ const assembled: Item[] = [];+ const usage = { input_tokens: 0, output_tokens: 0 };+ let searchesRun = 0;+ let input: Item[] = typeof body.input === 'string'+ ? [{ type: 'message', role: 'user', content: body.input }]+ : [...body.input];+ const maxTurns = maxSearches + 2;+ let commitTimer: NodeJS.Timeout | null = null;++ const emitItem = (item: Item) => {+ assembled.push(item);+ sse?.item(item);+ };++ try {+ for (let turn = 0; turn < maxTurns; turn++) {+ const lastTurn = turn === maxTurns - 1;+ let toolChoice = body.tool_choice;+ if (turn > 0 && toolChoice === 'required') toolChoice = 'auto';+ const innerBody = {+ ...body,+ stream: false,+ input,+ tools,+ ...(toolChoice !== undefined ? { tool_choice: toolChoice } : {}),+ };+ if (sse && !sse.committed && turn === 0) {+ commitTimer = setTimeout(() => sse.start(), STREAM_COMMIT_AFTER_MS);+ commitTimer.unref?.();+ }+ const captured = await invokeHandlerCaptured(handler, req, res, innerBody);+ if (commitTimer) { clearTimeout(commitTimer); commitTimer = null; }+ if (res.writableEnded || res.destroyed) return true;++ if (captured.status !== 200 || captured.body?.object !== 'response') {+ if (sse?.committed) {+ const error = captured.body?.error ?? { message: `upstream error (HTTP ${captured.status})`, type: 'server_error' };+ sse.fail(error);+ } else {+ copyCapturedHeaders(captured, res);+ res.status(captured.status).json(captured.body);+ }+ return true;+ }++ const reply = captured.body;+ usage.input_tokens += Number(reply.usage?.input_tokens) || 0;+ usage.output_tokens += Number(reply.usage?.output_tokens) || 0;+ copyCapturedHeaders(captured, res);+ sse?.start();++ const output: Item[] = Array.isArray(reply.output) ? reply.output : [];+ const searchCalls = output.filter(isOurSearchCall);+ const clientCalls = output.filter(item => item?.type === 'function_call' && !isOurSearchCall(item));++ if (searchCalls.length === 0 || clientCalls.length > 0 || lastTurn) {+ for (const item of output) if (!isOurSearchCall(item)) emitItem(item);+ const finalResponse = {+ ...reply,+ id: responseId,+ status: 'completed',+ output: assembled,+ output_text: assembled.map(itemText).join(''),+ usage: {+ ...(reply.usage ?? {}),+ input_tokens: usage.input_tokens,+ output_tokens: usage.output_tokens,+ total_tokens: usage.input_tokens + usage.output_tokens,+ },+ };+ if (sse) sse.complete(finalResponse);+ else res.status(200).json(finalResponse);+ return true;+ }++ const followUp: Item[] = [];+ for (const item of output) {+ if (!isOurSearchCall(item)) {+ emitItem(item);+ // Interim assistant text goes back into the next turn's history;+ // reasoning items have no chat equivalent and are dropped anyway.+ if (item.type === 'message') followUp.push(item);+ continue;+ }+ let args: Item = {};+ try { args = JSON.parse(item.arguments ?? '{}'); } catch { /* malformed → invalid input */ }+ const query = typeof args.query === 'string' ? args.query : '';+ const callId = newWebSearchCallId();+ const progressIdx = sse?.searchStarted(searchCallItem(callId, query, null));+ let outcome: WebSearchOutcome;+ if (searchesRun >= maxSearches) {+ outcome = { ok: false, query, errorCode: 'max_uses_exceeded', message: 'max searches exceeded' };+ } else {+ searchesRun++;+ outcome = await performWebSearch(args.query, filter);+ }+ const done = searchCallItem(callId, query, outcome);+ assembled.push(done);+ if (sse && progressIdx !== undefined) sse.searchDone(progressIdx, done);+ followUp.push(+ { type: 'function_call', call_id: item.call_id, name: WEB_SEARCH_TOOL_NAME, arguments: item.arguments ?? '{}' },+ { type: 'function_call_output', call_id: item.call_id, output: formatOutcomeForModel(outcome) },+ );+ }+ input = [...input, ...followUp];+ }+ } catch (err: unknown) {+ const message = err instanceof Error ? err.message : String(err);+ if (sse?.committed) sse.fail({ message: `web search failed: ${message}`, type: 'server_error' });+ else if (!res.headersSent) res.status(500).json({ error: { message: `web search failed: ${message}`, type: 'server_error' } });+ return true;+ } finally {+ if (commitTimer) clearTimeout(commitTimer);+ sse?.stopHeartbeat();+ }+ return true;+}diff --git a/server/src/lib/search-platforms.ts b/server/src/lib/search-platforms.tsnew file mode 100644index 00000000..7a54d447--- /dev/null+++ b/server/src/lib/search-platforms.ts@@ -0,0 +1,13 @@+import type { SearchPlatform } from '@freellmapi/shared/types.js';++// Runtime copy of shared/types.ts SEARCH_PLATFORMS. The server only ever+// imports types from @freellmapi/shared (it is not compiled into dist), so the+// list lives here too; a test pins the two together.+export const SEARCH_PLATFORMS: readonly SearchPlatform[] = ['tavily', 'exa', 'firecrawl', 'linkup'];++const SEARCH_PLATFORM_SET = new Set<string>(SEARCH_PLATFORMS);++/** True for platforms whose keys serve web search only, never chat. */+export function isSearchPlatform(platform: string): platform is SearchPlatform {+ return SEARCH_PLATFORM_SET.has(platform);+}diff --git a/server/src/lib/web-search-tool.ts b/server/src/lib/web-search-tool.tsnew file mode 100644index 00000000..2750d635--- /dev/null+++ b/server/src/lib/web-search-tool.ts@@ -0,0 +1,266 @@+import crypto from 'crypto';+import type { Request, Response } from 'express';+import { runSearch, SearchError, searchAvailable } from '../services/search.js';++// Shared plumbing for answering an agent's built-in web search from the+// gateway's own search pool (#1174): Codex's Responses `web_search` tool and+// Claude Code's Anthropic `web_search_*` server tool. Both surfaces hand the+// routed model a plain function tool named `web_search`, run the model's calls+// here through runSearch, and replay the results until the model answers.+//+// With no search-capable key the surfaces never reach this module and keep+// their previous behaviour (the built-in tool is dropped or passed through).++/** The function name the routed model sees. Matches both protocols' built-in+ * tool name, so a model that already knows the convention calls it naturally. */+export const WEB_SEARCH_TOOL_NAME = 'web_search';++export const WEB_SEARCH_FUNCTION_DESCRIPTION =+ 'Search the web for current information. Use it when the answer depends on recent events, prices, '+ + 'releases or anything that may have changed since your training data. Returns titles, URLs and '+ + 'short extracts; cite the URLs you rely on.';++export const WEB_SEARCH_FUNCTION_PARAMETERS = {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'The search query.' },+ },+ required: ['query'],+ additionalProperties: false,+} as const;++/** Default and ceiling for searches per request when the client sets none. */+export const DEFAULT_MAX_SEARCHES = 5;+export const MAX_SEARCHES_CEILING = 20;+const RESULTS_PER_SEARCH = 5;+const MAX_QUERY_CHARS = 400;+const EXTRACT_CHARS = 1_200;++/** True when at least one enabled search engine has a usable key — the same+ * check /v1/search routes with, so agents' web search only switches on when a+ * search can actually run. */+export function hasSearchCapability(): boolean {+ try {+ return searchAvailable();+ } catch {+ return false;+ }+}++export interface WebSearchHit {+ title: string;+ url: string;+ content: string;+ score: number;+}++export type WebSearchErrorCode = 'too_many_requests' | 'invalid_tool_input' | 'max_uses_exceeded' | 'query_too_long' | 'unavailable';++export type WebSearchOutcome =+ | { ok: true; query: string; results: WebSearchHit[]; engine?: string; provider?: string }+ | { ok: false; query: string; errorCode: WebSearchErrorCode; message: string };++export interface DomainFilter {+ allowedDomains?: string[];+ blockedDomains?: string[];+}++function normalizeDomainRule(rule: string): { host: string; path: string } | null {+ const trimmed = rule.trim().toLowerCase().replace(/^[a-z]+:\/\//, '');+ if (!trimmed) return null;+ const slash = trimmed.indexOf('/');+ const host = (slash === -1 ? trimmed : trimmed.slice(0, slash)).replace(/^\*\./, '').replace(/^www\./, '');+ const path = slash === -1 ? '' : trimmed.slice(slash);+ return host ? { host, path } : null;+}++function urlMatchesRule(url: URL, rule: { host: string; path: string }): boolean {+ const host = url.hostname.toLowerCase().replace(/^www\./, '');+ if (host !== rule.host && !host.endsWith(`.${rule.host}`)) return false;+ return rule.path === '' || url.pathname.toLowerCase().startsWith(rule.path);+}++/** Apply allowed/blocked domain lists (Anthropic `allowed_domains`, Responses+ * `filters.allowed_domains`). Search providers differ in native support, so+ * the gateway filters the hits itself. */+export function filterHitsByDomain(hits: WebSearchHit[], filter: DomainFilter): WebSearchHit[] {+ const allowed = (filter.allowedDomains ?? []).map(normalizeDomainRule).filter((r): r is NonNullable<typeof r> => r != null);+ const blocked = (filter.blockedDomains ?? []).map(normalizeDomainRule).filter((r): r is NonNullable<typeof r> => r != null);+ if (allowed.length === 0 && blocked.length === 0) return hits;+ return hits.filter(hit => {+ let url: URL;+ try { url = new URL(hit.url); } catch { return false; }+ if (blocked.some(rule => urlMatchesRule(url, rule))) return false;+ if (allowed.length > 0 && !allowed.some(rule => urlMatchesRule(url, rule))) return false;+ return true;+ });+}++/** Restrict a query to the allowed domains with `site:` operators, so a+ * provider returns in-scope hits instead of the post-filter emptying them. */+function scopedQuery(query: string, filter: DomainFilter): string {+ const allowed = (filter.allowedDomains ?? []).map(normalizeDomainRule).filter((r): r is NonNullable<typeof r> => r != null);+ if (allowed.length === 0 || allowed.length > 5) return query;+ const sites = allowed.map(r => `site:${r.host}`).join(' OR ');+ return `${query} (${sites})`;+}++/** Run one search on behalf of an agent. Never throws: failures become the+ * protocol's in-band error result so the model can carry on without it. */+export async function performWebSearch(rawQuery: unknown, filter: DomainFilter = {}): Promise<WebSearchOutcome> {+ const query = typeof rawQuery === 'string' ? rawQuery.trim() : '';+ if (!query) return { ok: false, query: '', errorCode: 'invalid_tool_input', message: 'missing query' };+ if (query.length > MAX_QUERY_CHARS) return { ok: false, query, errorCode: 'query_too_long', message: 'query too long' };+ try {+ const response = await runSearch(scopedQuery(query, filter), { maxResults: RESULTS_PER_SEARCH * 2 });+ const hits = filterHitsByDomain(response.results, filter).slice(0, RESULTS_PER_SEARCH);+ const engine = (response as { engine?: unknown }).engine;+ return {+ ok: true,+ query,+ results: hits,+ provider: response.provider,+ ...(typeof engine === 'string' ? { engine } : {}),+ };+ } catch (err: unknown) {+ const status = err instanceof SearchError ? err.status : 502;+ const message = err instanceof Error ? err.message : String(err);+ return { ok: false, query, errorCode: status === 429 ? 'too_many_requests' : 'unavailable', message };+ }+}++/** The tool-result text the routed model reads for one search. */+export function formatOutcomeForModel(outcome: WebSearchOutcome): string {+ if (!outcome.ok) {+ if (outcome.errorCode === 'max_uses_exceeded') {+ return 'Web search is unavailable: the search limit for this request has been reached. Answer with what you already have.';+ }+ return `Web search failed (${outcome.errorCode}). Answer from what you already know, and say the search did not work if it matters.`;+ }+ if (outcome.results.length === 0) return `No web results found for "${outcome.query}".`;+ const lines = [`Web results for "${outcome.query}":`];+ outcome.results.forEach((hit, i) => {+ lines.push('', `[${i + 1}] ${hit.title || hit.url}`, `URL: ${hit.url}`);+ const extract = hit.content.replace(/\s+/g, ' ').trim().slice(0, EXTRACT_CHARS);+ if (extract) lines.push(extract);+ });+ return lines.join('\n');+}++// ── Replay of earlier search results ────────────────────────────────────────+// Clients send previous turns back verbatim. Anthropic results carry an opaque+// `encrypted_content` per hit; ours is a tagged base64url JSON of the extract,+// so a later turn can restore what the model read. Foreign (real Anthropic)+// blobs are left opaque and only the title/URL survive.++const CONTENT_TAG = 'fllm1.';++export function encodeHitContent(hit: WebSearchHit): string {+ const payload = JSON.stringify({ c: hit.content.slice(0, EXTRACT_CHARS) });+ return CONTENT_TAG + Buffer.from(payload, 'utf8').toString('base64url');+}++export function decodeHitContent(encrypted: unknown): string {+ if (typeof encrypted !== 'string' || !encrypted.startsWith(CONTENT_TAG)) return '';+ try {+ const parsed = JSON.parse(Buffer.from(encrypted.slice(CONTENT_TAG.length), 'base64url').toString('utf8'));+ return typeof parsed?.c === 'string' ? parsed.c : '';+ } catch {+ return '';+ }+}++export function newServerToolUseId(): string {+ return `srvtoolu_${crypto.randomBytes(12).toString('hex')}`;+}++export function newWebSearchCallId(): string {+ return `ws_${crypto.randomBytes(16).toString('hex')}`;+}++// ── In-process re-entry into a route handler ────────────────────────────────+// The search loop re-runs the surface's own handler (auth, routing, failover,+// analytics, tool repair — all unchanged) once per model turn, non-streaming,+// and captures what it would have sent. Only the response members those+// handlers touch are implemented.++export interface CapturedResponse {+ status: number;+ body: any;+ headers: Record<string, string>;+}++type Handler = (req: Request, res: Response) => Promise<void> | void;++class CaptureResponse {+ statusCode = 200;+ headers: Record<string, string> = {};+ body: any = undefined;+ writableEnded = false;+ destroyed = false;+ headersSent = false;+ locals: Record<string, unknown> = {};+ private closeListeners: Array<() => void> = [];+ private chunks: string[] = [];++ status(code: number) { this.statusCode = code; return this; }+ setHeader(name: string, value: unknown) { this.headers[name.toLowerCase()] = String(value); return this; }+ getHeader(name: string) { return this.headers[name.toLowerCase()]; }+ removeHeader(name: string) { delete this.headers[name.toLowerCase()]; }+ json(body: unknown) { this.body = body; this.finish(); return this; }+ send(body: unknown) { this.body = body; this.finish(); return this; }+ write(chunk: unknown) { this.headersSent = true; this.chunks.push(String(chunk)); return true; }+ end(chunk?: unknown) {+ if (chunk != null) this.chunks.push(String(chunk));+ if (this.body === undefined && this.chunks.length > 0) this.body = this.chunks.join('');+ this.finish();+ return this;+ }+ flushHeaders() { this.headersSent = true; }+ on(event: string, fn: () => void) { if (event === 'close') this.closeListeners.push(fn); return this; }+ once(event: string, fn: () => void) { return this.on(event, fn); }+ off() { return this; }+ removeListener() { return this; }+ /** The real client went away: tell the inner handler, as a socket close would. */+ abort() { this.destroyed = true; for (const fn of this.closeListeners) { try { fn(); } catch { /* ignore */ } } }+ private finish() {+ if (this.writableEnded) return;+ this.headersSent = true;+ this.writableEnded = true;+ for (const fn of this.closeListeners) { try { fn(); } catch { /* ignore */ } }+ }+}++/** Run `handler` with `body` in place of the client's body and capture its+ * reply. A disconnect of the real client aborts the inner call. */+export async function invokeHandlerCaptured(handler: Handler, req: Request, outer: Response, body: unknown): Promise<CapturedResponse> {+ const capture = new CaptureResponse();+ const innerReq = Object.create(req) as Request;+ Object.defineProperty(innerReq, 'body', { value: body, writable: true, enumerable: true, configurable: true });+ const onOuterClose = () => { if (!outer.writableEnded) capture.abort(); };+ outer.on('close', onOuterClose);+ try {+ await handler(innerReq, capture as unknown as Response);+ } finally {+ outer.off('close', onOuterClose);+ }+ let parsed = capture.body;+ if (typeof parsed === 'string') {+ try { parsed = JSON.parse(parsed); } catch { /* keep raw */ }+ }+ return { status: capture.statusCode, body: parsed, headers: capture.headers };+}++/** Copy the inner turn's diagnostic headers onto the real response. */+export function copyCapturedHeaders(captured: CapturedResponse, res: Response): void {+ for (const [name, value] of Object.entries(captured.headers)) {+ if (name === 'content-type' || name === 'content-length') continue;+ try { res.setHeader(name, value); } catch { /* headers already sent */ }+ }+}++/** Clamp a client-supplied max_uses. */+export function resolveMaxSearches(raw: unknown): number {+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 1) return DEFAULT_MAX_SEARCHES;+ return Math.min(Math.floor(raw), MAX_SEARCHES_CEILING);+}diff --git a/server/src/providers/exa.ts b/server/src/providers/exa.tsnew file mode 100644index 00000000..3590dd31--- /dev/null+++ b/server/src/providers/exa.ts@@ -0,0 +1,23 @@+import type { Platform } from '@freellmapi/shared/types.js';+import type { KeyValidationResult } from './base.js';+import { SearchOnlyProvider } from './search-only.js';++export const EXA_BASE_URL = 'https://api.exa.ai';++// Exa (exa.ai): recurring monthly free credits. Exa has no free "who am I"+// endpoint and the health checker validates every key every few minutes, so a+// real search probe would burn the free credits within days. Instead the probe+// sends a search with no query: Exa authenticates first, so a bad key answers+// 401 while a good one fails body validation with a 400 and spends nothing.+export class ExaProvider extends SearchOnlyProvider {+ readonly platform: Platform = 'exa';+ readonly name = 'Exa';++ async validateKey(apiKey: string): Promise<KeyValidationResult> {+ return this.probe(`${EXA_BASE_URL}/search`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },+ body: JSON.stringify({}),+ });+ }+}diff --git a/server/src/providers/firecrawl.ts b/server/src/providers/firecrawl.tsnew file mode 100644index 00000000..195659ec--- /dev/null+++ b/server/src/providers/firecrawl.ts@@ -0,0 +1,19 @@+import type { Platform } from '@freellmapi/shared/types.js';+import type { KeyValidationResult } from './base.js';+import { SearchOnlyProvider } from './search-only.js';++export const FIRECRAWL_BASE_URL = 'https://api.firecrawl.dev/v2';++// Firecrawl (firecrawl.dev): 1,000 free credits a month. Validation reads the+// team's credit balance, which spends nothing.+export class FirecrawlProvider extends SearchOnlyProvider {+ readonly platform: Platform = 'firecrawl';+ readonly name = 'Firecrawl';++ async validateKey(apiKey: string): Promise<KeyValidationResult> {+ return this.probe(`${FIRECRAWL_BASE_URL}/team/credit-usage`, {+ method: 'GET',+ headers: { Authorization: `Bearer ${apiKey}` },+ });+ }+}diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex 21e611c0..deb518f8 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -3,6 +3,10 @@ import type { BaseProvider } from './base.js';import { GoogleProvider } from './google.js';import { OpenAICompatProvider } from './openai-compat.js';import { CohereProvider } from './cohere.js';+import { TavilyProvider } from './tavily.js';+import { ExaProvider } from './exa.js';+import { FirecrawlProvider } from './firecrawl.js';+import { LinkupProvider } from './linkup.js';import { CloudflareProvider } from './cloudflare.js';import { AIHordeProvider } from './aihorde.js';import { ModelScopeProvider } from './modelscope.js';@@ -200,6 +204,13 @@ register(new OpenAICompatProvider({// Cohere - OpenAI-compatible via Cohere compatibility endpointregister(new CohereProvider());+// Web search APIs (#1174). They serve /v1/search and the agents' web_search+// tools, never chat (see providers/search-only.ts); they are registered so+// their keys can be added and health-checked like every platform.+register(new TavilyProvider());+register(new ExaProvider());+register(new FirecrawlProvider());+register(new LinkupProvider());// Cloudflare Workers AI - OpenAI-compatible endpoint (key = "account_id:token")register(new CloudflareProvider());diff --git a/server/src/providers/linkup.ts b/server/src/providers/linkup.tsnew file mode 100644index 00000000..750a2f62--- /dev/null+++ b/server/src/providers/linkup.ts@@ -0,0 +1,19 @@+import type { Platform } from '@freellmapi/shared/types.js';+import type { KeyValidationResult } from './base.js';+import { SearchOnlyProvider } from './search-only.js';++export const LINKUP_BASE_URL = 'https://api.linkup.so/v1';++// Linkup (linkup.so): monthly free credit top-up. Validation reads the credit+// balance, which spends nothing.+export class LinkupProvider extends SearchOnlyProvider {+ readonly platform: Platform = 'linkup';+ readonly name = 'Linkup';++ async validateKey(apiKey: string): Promise<KeyValidationResult> {+ return this.probe(`${LINKUP_BASE_URL}/credits/balance`, {+ method: 'GET',+ headers: { Authorization: `Bearer ${apiKey}` },+ });+ }+}diff --git a/server/src/providers/search-only.ts b/server/src/providers/search-only.tsnew file mode 100644index 00000000..e220597b--- /dev/null+++ b/server/src/providers/search-only.ts@@ -0,0 +1,48 @@+import type { ChatCompletionChunk, ChatCompletionResponse, ChatMessage } from '@freellmapi/shared/types.js';+import { BaseProvider, type CompletionOptions, type KeyValidationResult } from './base.js';+import { proxyFetch } from '../lib/proxy.js';++// Base for web search APIs (#1174). Their keys live in the normal api_keys+// pool so they register, validate and show health like every other platform,+// but they are consumed only by services/search.ts (POST /v1/search and the+// agents' web_search tools). They never get chat rows, so the chat router+// cannot pick them; a chat call that still reaches one is a routing mistake+// and is refused with a 422 rather than mis-served.++const VALIDATE_TIMEOUT_MS = 10_000;++export abstract class SearchOnlyProvider extends BaseProvider {+ private chatRefusal(): Error {+ return Object.assign(+ new Error(`${this.name} is a search provider: its key serves POST /v1/search, not chat completions`),+ { status: 422 },+ );+ }++ async chatCompletion(_apiKey: string, _messages: ChatMessage[], _modelId: string, _options?: CompletionOptions): Promise<ChatCompletionResponse> {+ throw this.chatRefusal();+ }++ // eslint-disable-next-line require-yield -- a rejected async iterator: the throw surfaces on first next()+ async *streamChatCompletion(_apiKey: string, _messages: ChatMessage[], _modelId: string, _options?: CompletionOptions): AsyncGenerator<ChatCompletionChunk> {+ throw this.chatRefusal();+ }++ /** Shared verdict for a validation probe: 401/403 is a bad key, any other+ * 4xx (usage cap, out of credits, malformed probe) still proves the key+ * authenticated, and 5xx/transport failures are inconclusive. */+ protected async probe(url: string, init: RequestInit): Promise<KeyValidationResult> {+ let res: Response;+ try {+ res = await proxyFetch(url, { ...init, signal: AbortSignal.timeout(VALIDATE_TIMEOUT_MS) }, this.platform, 'search', VALIDATE_TIMEOUT_MS);+ } catch (err) {+ return { valid: false, error: `${this.name} key validation inconclusive: ${err instanceof Error ? err.message : String(err)}` };+ }+ if (res.ok) return true;+ if (res.status === 401 || res.status === 403) {+ return { valid: false, error: `${this.name} key validation failed (HTTP ${res.status}): invalid API key` };+ }+ if (res.status >= 400 && res.status < 500) return true;+ return { valid: false, error: `${this.name} key validation inconclusive (HTTP ${res.status})` };+ }+}diff --git a/server/src/providers/tavily.ts b/server/src/providers/tavily.tsnew file mode 100644index 00000000..c8b9a2c8--- /dev/null+++ b/server/src/providers/tavily.ts@@ -0,0 +1,19 @@+import type { Platform } from '@freellmapi/shared/types.js';+import type { KeyValidationResult } from './base.js';+import { SearchOnlyProvider } from './search-only.js';++export const TAVILY_BASE_URL = 'https://api.tavily.com';++// Tavily (tavily.com): 1,000 free credits a month. Validation reads GET /usage,+// which costs no credits (a search probe would spend one per check).+export class TavilyProvider extends SearchOnlyProvider {+ readonly platform: Platform = 'tavily';+ readonly name = 'Tavily';++ async validateKey(apiKey: string): Promise<KeyValidationResult> {+ return this.probe(`${TAVILY_BASE_URL}/usage`, {+ method: 'GET',+ headers: { Authorization: `Bearer ${apiKey}` },+ });+ }+}diff --git a/server/src/routes/analytics.ts b/server/src/routes/analytics.tsindex 52be54a0..d6578c52 100644--- a/server/src/routes/analytics.ts+++ b/server/src/routes/analytics.ts@@ -4,6 +4,7 @@ import { getDb } from '../db/index.js';import { FALLBACK_INPUT_PER_M, FALLBACK_OUTPUT_PER_M } from '../db/model-pricing.js';import { providerIdFor, providerDisplayName } from '../lib/provider-identity.js';import { normalizeBaseUrl } from '../lib/endpoint-scope.js';+import { searchAnalytics, type SearchAnalyticsRange } from '../services/search.js';export const analyticsRouter = Router();@@ -83,6 +84,16 @@ function readLifetimeSettings() {}// Summary stats+// Web searches (#1174) live in their own log (search_requests), so they never+// show up in the chat totals above; the dashboard's search cards read this.+const SEARCH_RANGES: readonly SearchAnalyticsRange[] = ['24h', '7d', '30d', '90d', 'all'];++analyticsRouter.get('/search', (req: Request, res: Response) => {+ const raw = typeof req.query.range === 'string' ? req.query.range : '7d';+ const range = (SEARCH_RANGES as readonly string[]).includes(raw) ? raw as SearchAnalyticsRange : '7d';+ res.json(searchAnalytics(range));+});+analyticsRouter.get('/summary', (req: Request, res: Response) => {const range = (req.query.range as string) ?? '7d';const since = getSinceTimestamp(range);diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.tsindex dab33a8f..2144b438 100644--- a/server/src/routes/anthropic.ts+++ b/server/src/routes/anthropic.ts@@ -31,6 +31,7 @@ import type { ReasoningEffort } from '../lib/sampling-params.js';import { buildModelListing } from '../services/model-listing.js';import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';import { normalizeMessageImages } from '../lib/image-normalize.js';+import { maybeServeAnthropicWebSearch, serverToolUseToText, webSearchResultToText } from '../lib/anthropic-web-search.js';// Anthropic-compatible Messages API (`POST /v1/messages`). This is a thin// translation layer over the SAME router/fallback/analytics machinery the@@ -325,6 +326,13 @@ function convertRequest(input: AnthropicRequest): ConvertedRequest {tool_call_id: String((block as any).tool_use_id ?? ''),content: flattenToolResult((block as any).content),});+ } else if (type === 'server_tool_use') {+ // A replayed web search (ours, or real Anthropic's): the routed model+ // has no server tool, so the search and its results come back as text.+ const note = serverToolUseToText(block as any);+ if (note) textParts.push(note);+ } else if (type === 'web_search_tool_result') {+ textParts.push(webSearchResultToText(block as any));} else if (type === 'document') {// A document that is already text costs nothing to inline. One that// needs decoding cannot be served by any provider here, and dropping@@ -441,7 +449,15 @@ function rescuedToToolCalls(}));}+// Requests carrying a web_search server tool are served through the search+// loop (lib/anthropic-web-search.ts) when a search key exists; it re-enters+// handleMessages once per model turn. Everything else goes straight through.anthropicRouter.post('/messages', async (req: Request, res: Response) => {+ if (await maybeServeAnthropicWebSearch(handleMessages, req, res)) return;+ await handleMessages(req, res);+});++export async function handleMessages(req: Request, res: Response): Promise<void> {const start = Date.now();if (!authenticate(req, res)) return;@@ -779,7 +795,7 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {sendExhaustion(res, exhaustion);},});-});+}// Thrown by streamCompletion once the SSE response is underway, so the outer// loop knows the request is finished (honestly errored mid-stream) and mustdiff --git a/server/src/routes/conversations.ts b/server/src/routes/conversations.tsindex a83ec0ad..1a9de2ab 100644--- a/server/src/routes/conversations.ts+++ b/server/src/routes/conversations.ts@@ -39,6 +39,13 @@ const metaSchema = z.object({error: z.string().optional(),})).optional(),fusionJudge: z.object({ platform: z.string(), model: z.string() }).nullable().optional(),+ // Playground "Search the web" (#1174): the engine that ran and the sources+ // shown under the answer, so a reloaded chat keeps its citations.+ webSearch: z.object({+ engine: z.string().max(200).optional(),+ latency: z.number().optional(),+ sources: z.array(z.object({ title: z.string().max(1000), url: z.string().max(4000) })).max(50).optional(),+ }).optional(),});const messageSchema = z.object({diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex ab6f0851..1f6ddb42 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -16,6 +16,7 @@ import { getMonthlyBudgetCaps, getMonthlyUsage, nextMonthResetAt } from '../servimport { resolveCustomEndpointKey, customEndpointKeyIds, siblingEndpointKeyId, endpointHasCredential, normalizeGroupLabel, setCustomEndpointGroup } from '../services/custom-endpoint.js';import { registerCustomModels, registerCustomChatModels } from '../services/custom-model-register.js';import { registerCustomMediaModel } from '../services/custom-media-register.js';+import { isSearchPlatform } from '../lib/search-platforms.js';import { discoverEndpointModels, probeEndpointModel, classifyModelId, ModelDiscoveryError } from '../services/model-discovery.js';import { probeEmbeddingDimensions, registerCustomEmbeddingModel } from '../services/embeddings.js';import { endpointScopeForBaseUrl, normalizeBaseUrl } from '../lib/endpoint-scope.js';@@ -54,7 +55,7 @@ const PLATFORMS = ['moondream','freeai','google', 'groq', 'cerebras', 'sail', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare', 'bai', 'radeon', 'nvidia', 'mistral',- 'openrouter', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama',+ 'openrouter', 'github', 'cohere', 'tavily', 'exa', 'firecrawl', 'linkup', 'cloudflare', 'zhipu', 'ollama','kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'ovh', 'agnes', 'reka', 'siliconflow','routeway', 'bazaarlink', 'ainative', 'aion', 'anyapi', 'requesty', 'navy', 'nara', 'sealion', 'orcarouter', 'unorouter', 'xkiro', 'modelscope','qianfan', 'volcengine', 'longcat', 'xfyun', 'aihorde', 'custom',@@ -254,6 +255,12 @@ function openAICompatBaseUrl(platform: string): string | null {// the base URL, and only offers the custom-provider route where it works.function noModelsNotice(platform: string): string | undefined {if (enabledModelCount(platform) > 0) return undefined;+ // Search keys have engines, not models (#1174): a key whose engine is off+ // or not in this catalog gets told where engines live instead of the chat+ // advice below.+ if (isSearchPlatform(platform)) {+ return `Key saved, but no ${platform} search engine is turned on. Turn it on from Models → Search.`;+ }// #1348: a built-in provider the catalog does not carry fills its model list// from its own /models, so the Premium and custom-provider advice below// would send the operator the wrong way.@@ -309,6 +316,9 @@ keysRouter.get('/providers', (_req: Request, res: Response) => {return {platform: p.platform,name: p.name,+ // 'search' keys serve /v1/search and the agents' web_search tools,+ // never chat (#1174); the dashboard groups them separately.+ kind: isSearchPlatform(p.platform) ? 'search' as const : 'chat' as const,keyless: p.keyless,configured: keyCount > 0,keyCount,diff --git a/server/src/routes/mcp.ts b/server/src/routes/mcp.tsindex 70f6d5d8..da70d56b 100644--- a/server/src/routes/mcp.ts+++ b/server/src/routes/mcp.ts@@ -2,6 +2,7 @@ import { Router } from 'express';import type { NextFunction, Request, Response } from 'express';import { getDb, getUnifiedApiKey, getSetting } from '../db/index.js';import { extractApiToken, timingSafeStringEqual } from './proxy.js';+import { runSearch } from '../services/search.js';import { buildModelListing } from '../services/model-listing.js';import { supportedParametersForPlatforms } from '../lib/sampling-params.js';import { getRoutingScores, getRoutingStrategy, setRoutingStrategy } from '../services/router.js';@@ -355,6 +356,23 @@ function healthcheck(): unknown {};}+async function webSearch(args: Record<string, unknown>): Promise<unknown> {+ const query = typeof args.query === 'string' ? args.query.trim() : '';+ if (!query) throw new Error('query is required');+ const maxResults = typeof args.max_results === 'number' && Number.isFinite(args.max_results)+ ? Math.min(Math.max(Math.floor(args.max_results), 1), 20)+ : 5;+ const topic = args.topic === 'news' ? 'news' : 'general';+ const result = await runSearch(query, { maxResults, topic });+ return {+ query: result.query,+ provider: result.provider,+ ...((result as { engine?: unknown }).engine ? { engine: (result as { engine?: unknown }).engine } : {}),+ ...(result.answer ? { answer: result.answer } : {}),+ results: result.results.map(r => ({ title: r.title, url: r.url, content: r.content })),+ };+}+// ── Tool registry ────────────────────────────────────────────────────────interface McpTool {@@ -474,6 +492,22 @@ const TOOLS: Record<string, McpTool> = {annotations: READ_ONLY_LOCAL,run: () => getCacheStats(),},+ web_search: {+ title: 'Search the web',+ description: 'Search the web through the search providers configured in FreeLLMAPI (Tavily, Exa, Firecrawl, Linkup, or a custom search endpoint). Returns titles, URLs and short extracts. Spends the search provider\'s free quota, not model tokens.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ properties: {+ query: { type: 'string', minLength: 1, maxLength: 400, description: 'The search query.' },+ max_results: { type: 'integer', minimum: 1, maximum: 20, default: 5 },+ topic: { type: 'string', enum: ['general', 'news'], default: 'general' },+ },+ required: ['query'],+ },+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },+ run: webSearch,+ },compression_stats: {title: 'Inspect prompt-compression savings',description: 'Prompt-compression statistics: requests compressed, estimated tokens saved, fidelity-gate discards, and per-engine savings.',@@ -504,7 +538,7 @@ async function dispatchRpc(msg: JsonRpcRequest, id: number | string | null, req:protocolVersion: PROTOCOL_VERSION,capabilities: { tools: {} },serverInfo: { name: 'freellmapi', version: '1.0.0' },- instructions: 'Use ask_freellmapi when the user explicitly asks FreeLLMAPI or one of its models to perform a text task. Use healthcheck before troubleshooting availability; list_models for model choice; provider_health, usage_summary, cache_stats, compression_stats, and routing_info for diagnostics. set_routing_strategy changes server state.',+ instructions: 'Use ask_freellmapi when the user explicitly asks FreeLLMAPI or one of its models to perform a text task. Use healthcheck before troubleshooting availability; list_models for model choice; provider_health, usage_summary, cache_stats, compression_stats, and routing_info for diagnostics. set_routing_strategy changes server state. web_search searches the web through the configured search providers.',});}case 'ping':diff --git a/server/src/routes/media.ts b/server/src/routes/media.tsindex 76a3f35a..4ce8d3e6 100644--- a/server/src/routes/media.ts+++ b/server/src/routes/media.ts@@ -106,7 +106,10 @@ const customMediaSchema = z.object({// 'transcription' registers a custom OpenAI-compatible STT endpoint. The// media_models table, GET /api/media/usage, the /v1/audio/transcriptions// handler and the media service's 'custom' adapter all accept it.- modality: z.enum(['image', 'audio', 'transcription']),+ // 'search' registers a custom web search relay (Tavily wire shape at+ // POST {base_url}/search), listed on the Search page and tried first by+ // POST /v1/search (#1174).+ modality: z.enum(['image', 'audio', 'transcription', 'search']),apiKey: z.string().optional(),label: z.string().optional(),quotaLabel: z.string().optional(),diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 0449e750..50ba050a 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -7,6 +7,7 @@ import { type RouteResult, type ResolvedChain, type ChainRow, routeRequest, resoimport { secondsUntilNextMonth } from '../services/key-budget.js';import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';import { runRerank, RerankError, rerankRetryAfterSec } from '../services/rerank.js';+import { runSearch, SearchError, searchRetryAfterSec, listSearchEngines } from '../services/search.js';import { retryAfterSeconds } from '../lib/retry-hint.js';import { runImageGeneration, runVideoGeneration, runSpeech, runTranscription, MediaError, MAX_TRANSCRIPTION_BYTES } from '../services/media.js';import multer from 'multer';@@ -738,6 +739,77 @@ proxyRouter.post('/rerank', async (req: Request, res: Response) => {}});+// Web search over the key pool (#1174). Engines are catalog rows (Tavily,+// Exa, Firecrawl, Linkup, plus custom relays speaking Tavily's wire shape);+// the first engine that returns hits wins. See services/search.ts.+const SearchBody = z.object({+ query: z.string().min(1),+ max_results: z.number().int().positive().optional(),+ topic: z.enum(['general', 'news']).optional(),+ include_answer: z.boolean().optional(),+ engine: z.string().min(1).optional(),+});++proxyRouter.post('/search', async (req: Request, res: Response) => {+ if (!requireInferenceAuth(req, res)) return;+ const parsed = SearchBody.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: 'Invalid request: `query` is required', type: 'invalid_request_error' } });+ return;+ }+ // A departed client drops the upstream search instead of spending a credit.+ const abort = new AbortController();+ res.on('close', () => { if (!res.writableFinished) abort.abort(); });+ try {+ const result = await runSearch(parsed.data.query, {+ maxResults: parsed.data.max_results,+ topic: parsed.data.topic,+ includeAnswer: parsed.data.include_answer,+ engine: parsed.data.engine,+ signal: abort.signal,+ });+ res.json({+ query: result.query,+ ...(result.answer !== undefined ? { answer: result.answer } : {}),+ results: result.results,+ provider: result.provider,+ engine: result.engine,+ });+ } catch (err: any) {+ if (res.headersSent || abort.signal.aborted) return;+ const status = err instanceof SearchError ? err.status : 502;+ if (err instanceof SearchError) {+ const retryAfter = searchRetryAfterSec(err);+ if (retryAfter !== undefined) res.setHeader('Retry-After', String(retryAfter));+ }+ const type = status === 400 ? 'invalid_request_error' : status === 429 ? 'rate_limit_error' : 'server_error';+ res.status(status).json({+ error: {+ message: `search error: ${err?.message ?? 'unknown'}`,+ type,+ ...(err instanceof SearchError && err.code ? { code: err.code } : {}),+ },+ });+ }+});++// The engines a caller can pin with `engine` on POST /v1/search.+proxyRouter.get('/search/engines', (req: Request, res: Response) => {+ if (!requireInferenceAuth(req, res)) return;+ res.json({+ object: 'list',+ data: listSearchEngines()+ .filter(e => e.enabled)+ .map(e => ({+ id: e.engineId,+ object: 'search_engine',+ provider: e.platform,+ name: e.displayName,+ available: e.healthyKeyCount > 0,+ })),+ });+});+// OpenAI-compatible image generation. Routed through the media catalog (its own// table, never the chat router): `model: "auto"` (or omitted) tries every enabled// image provider in order; a provider model id pins to that one. Failover isdiff --git a/server/src/routes/responses.ts b/server/src/routes/responses.tsindex faa30f53..710dac2f 100644--- a/server/src/routes/responses.ts+++ b/server/src/routes/responses.ts@@ -39,6 +39,7 @@ import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';import { isClientAbortError, newClientAbortError, newHedgeAbortError } from '../lib/error-classify.js';import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';+import { maybeServeResponsesWebSearch, webSearchCallToText } from '../lib/responses-web-search.js';import {FUSION_MODEL_ID,FusionError,@@ -352,11 +353,30 @@ export function toChatMessages(req: ResponsesRequest): ChatMessage[] {}const messages: ChatMessage[] = [];+ // Replayed web_search_call items (served by the gateway's search pool, or+ // by OpenAI) become a short note on the assistant turn that follows, so the+ // model keeps the context of what it searched without an extra assistant+ // turn (consecutive assistant turns 400 on strict upstreams, #96).+ let pendingSearchNotes: string[] = [];+ const flushSearchNotes = () => {+ if (pendingSearchNotes.length === 0) return;+ messages.push({ role: 'assistant', content: pendingSearchNotes.join('\n') });+ pendingSearchNotes = [];+ };const items = req.input;for (let i = 0; i < items.length; i++) {const item = items[i];+ if ('type' in item && item.type === 'web_search_call') {+ const note = webSearchCallToText(item as Record<string, unknown>);+ if (note) pendingSearchNotes.push(note);+ continue;+ }+ if (!('type' in item && item.type === 'message' && (item as { role?: string }).role === 'assistant')) {+ flushSearchNotes();+ }+if ('type' in item && item.type === 'function_call') {// Parallel tool calls replay as consecutive standalone function_call// items (no preceding assistant message item). Fold the run into one@@ -399,7 +419,7 @@ export function toChatMessages(req: ResponsesRequest): ChatMessage[] {const m = item as z.infer<typeof messageItemSchema>;// 'developer' is the Responses-era system role.const role = m.role === 'developer' ? 'system' : m.role;- const content = partsToChatContent(m.content);+ let content = partsToChatContent(m.content);if (role === 'system') {// Hoist system/developer messages to the start of the conversation:@@ -411,6 +431,14 @@ export function toChatMessages(req: ResponsesRequest): ChatMessage[] {}if (role === 'assistant') {+ const searchNotes = pendingSearchNotes;+ pendingSearchNotes = [];+ if (searchNotes.length > 0) {+ const notes = searchNotes.join('\n');+ content = typeof content === 'string'+ ? (content.length > 0 ? `${notes}\n\n${content}` : notes)+ : [{ type: 'text', text: notes }, ...content];+ }// A Responses assistant turn is a message item followed by its// function_call items. Merge them into a single chat assistant message// (content + tool_calls); emitting consecutive assistant turns makes@@ -444,6 +472,7 @@ export function toChatMessages(req: ResponsesRequest): ChatMessage[] {messages.push({ role, content });}+ flushSearchNotes();return [...systemMessages, ...messages];}@@ -621,7 +650,15 @@ function quotaContextForRoute(route: RouteResult, endpoint: string): QuotaObserv};}+// A `web_search` tool is served through the search loop+// (lib/responses-web-search.ts) when a search key exists; it re-enters+// handleResponses once per model turn. Everything else goes straight through.responsesRouter.post('/responses', async (req: Request, res: Response) => {+ if (await maybeServeResponsesWebSearch(handleResponses, req, res)) return;+ await handleResponses(req, res);+});++export async function handleResponses(req: Request, res: Response): Promise<void> {const start = Date.now();const requestGroupId = getRequestGroupId(req);res.setHeader('X-Request-ID', requestGroupId);@@ -1618,4 +1655,4 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {}},});-});+}diff --git a/server/src/routes/search.ts b/server/src/routes/search.tsnew file mode 100644index 00000000..81839eb7--- /dev/null+++ b/server/src/routes/search.ts@@ -0,0 +1,39 @@+import { Router } from 'express';+import type { Request, Response } from 'express';+import { z } from 'zod';+import { listSearchEngines, updateSearchEngine } from '../services/search.js';++// Dashboard: the Models → Search page (#1174). Engines come from the catalog's+// searchEngines registry (plus custom relays); this lists them with key and+// usage counts and lets the operator switch one off or change the order.+export const searchRouter = Router();++searchRouter.get('/engines', (_req: Request, res: Response) => {+ res.json(listSearchEngines());+});++const patchSchema = z.object({+ enabled: z.boolean().optional(),+ priority: z.number().int().min(0).optional(),+}).refine(p => p.enabled !== undefined || p.priority !== undefined, {+ message: 'Provide enabled and/or priority',+});++searchRouter.patch('/engines/:id', (req: Request, res: Response) => {+ const id = Number(req.params.id);+ if (!Number.isInteger(id) || id <= 0) {+ res.status(400).json({ error: { message: 'Invalid engine id' } });+ return;+ }+ const parsed = patchSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });+ return;+ }+ if (!updateSearchEngine(id, parsed.data)) {+ res.status(404).json({ error: { message: 'Search engine not found' } });+ return;+ }+ const engine = listSearchEngines().find(e => e.id === id);+ res.json(engine);+});diff --git a/server/src/services/catalog-sync.ts b/server/src/services/catalog-sync.tsindex 2dab93e2..62eefa8f 100644--- a/server/src/services/catalog-sync.ts+++ b/server/src/services/catalog-sync.ts@@ -3,6 +3,7 @@ import type { Db } from '../db/types.js';import { getDb, getSetting, setSetting } from '../db/index.js';import { hasProvider } from '../providers/index.js';import { MEDIA_PLATFORMS, TRANSCRIPTION_PLATFORMS, VIDEO_PLATFORMS } from './media.js';+import { SEARCH_ENGINE_PLATFORMS, SEARCH_MODALITY } from './search.js';import { EMBEDDING_PLATFORMS } from './embeddings.js';import type { Platform } from '@freellmapi/shared/types.js';import type { Scheduler } from '../lib/scheduler.js';@@ -161,6 +162,23 @@ interface CatalogVideoModel {providerModelId?: string;}+interface CatalogSearchEngine {+ platform: string;+ /** Engine id, stored as media_models.model_id (e.g. 'tavily-search'). */+ engineId: string;+ displayName: string;+ /** Failover order within the search chain, lower first. */+ priority: number;+ enabled: boolean;+ /** Short display note, mirrored into media_models.quota_label. */+ quotaLabel?: string;+ creditsPerQuery?: number | null;+ features?: { news?: boolean; answer?: boolean; fullContent?: boolean };+ /** When the engine entered the live (Premium) tier; free installs get it+ * 30 days later through the monthly snapshot. */+ premiumSince?: string;+}+interface Catalog {version: string;generatedAt: string;@@ -178,6 +196,10 @@ interface Catalog {/** Text-to-video registry. Kept out of `models` so pre-video binaries ignore* it rather than routing unknown-modality rows through chat. */videoModels?: CatalogVideoModel[];+ /** Web search engine registry (#1174), landing in media_models with+ * modality='search'. A separate optional key for the same reason as+ * videoModels: binaries that predate search ignore it. */+ searchEngines?: CatalogSearchEngine[];/** Platforms the catalog service manages even when this tier ships no rows* for them (#1348): a provider still inside its Premium window, or one the* audit deliberately keeps at zero rows. Names only, never model rows, so@@ -254,6 +276,20 @@ function isCatalog(value: unknown): value is Catalog {!!m?.limits &&typeof m.limits === 'object',) &&+ (c.searchEngines === undefined ||+ (Array.isArray(c.searchEngines) &&+ c.searchEngines.every(+ (e) =>+ typeof e?.platform === 'string' &&+ typeof e?.engineId === 'string' &&+ typeof e?.displayName === 'string' &&+ typeof e?.priority === 'number' &&+ typeof e?.enabled === 'boolean' &&+ (e.quotaLabel === undefined || typeof e.quotaLabel === 'string') &&+ (e.creditsPerQuery === undefined || e.creditsPerQuery === null || typeof e.creditsPerQuery === 'number') &&+ (e.features === undefined || (typeof e.features === 'object' && e.features !== null)) &&+ (e.premiumSince === undefined || typeof e.premiumSince === 'string'),+ ))) &&(c.managedPlatforms === undefined ||(Array.isArray(c.managedPlatforms) && c.managedPlatforms.every((p) => typeof p === 'string'))) &&c.quirks.every((q) => typeof q?.slug === 'string' && Array.isArray(q?.targets))@@ -294,6 +330,7 @@ function catalogPlatforms(catalog: Catalog): Set<string> {for (const m of catalog.embeddings ?? []) platforms.add(m.platform);for (const m of catalog.transcriptionModels ?? []) platforms.add(m.platform);for (const m of catalog.videoModels ?? []) platforms.add(m.platform);+ for (const e of catalog.searchEngines ?? []) platforms.add(e.platform);for (const p of catalog.managedPlatforms ?? []) platforms.add(p);return platforms;}@@ -420,6 +457,7 @@ function applyCatalogInner(db: Db, catalog: Catalog): NonNullable<SyncResult['coconst inEmbeddingCatalog = new Set<string>();const inTranscriptionCatalog = new Set<string>();const inVideoCatalog = new Set<string>();+ const inSearchCatalog = new Set<string>();for (const m of catalog.models) {// Media modalities are gated on MEDIA_PLATFORMS (decoupled from the chat@@ -549,6 +587,47 @@ function applyCatalogInner(db: Db, catalog: Catalog): NonNullable<SyncResult['co}}+ // Search engines (#1174): their own optional full snapshot, exactly like+ // video. A catalog without the key leaves existing engine rows alone.+ // A local disable survives (catalog enable never overrides it) and the+ // dashboard's local engine order lives in settings, not in `priority`.+ if (catalog.searchEngines) {+ for (const e of catalog.searchEngines) {+ if (!SEARCH_ENGINE_PLATFORMS.has(e.platform)) {+ counts.skippedUnknownPlatform++;+ continue;+ }+ if (isCatalogModelTombstoned(db, 'media', e.platform, e.engineId)) continue;+ inSearchCatalog.add(`${e.platform}:${e.engineId}`);+ const meta: Record<string, unknown> = {};+ if (e.creditsPerQuery !== undefined) meta.creditsPerQuery = e.creditsPerQuery;+ if (e.features && typeof e.features === 'object') {+ meta.features = {+ ...(typeof e.features.news === 'boolean' ? { news: e.features.news } : {}),+ ...(typeof e.features.answer === 'boolean' ? { answer: e.features.answer } : {}),+ ...(typeof e.features.fullContent === 'boolean' ? { fullContent: e.features.fullContent } : {}),+ };+ }+ if (typeof e.premiumSince === 'string') meta.premiumSince = e.premiumSince;+ const fields = {+ displayName: e.displayName,+ modality: SEARCH_MODALITY,+ priority: e.priority,+ quotaLabel: e.quotaLabel ?? '',+ metaJson: JSON.stringify(meta),+ };+ const row = selectMedia.get(e.platform, e.engineId) as { id: number; enabled: number } | undefined;+ if (row) {+ const enabled = e.enabled ? row.enabled : 0;+ updateMedia.run({ ...fields, id: row.id, enabled });+ counts.updated++;+ } else {+ insertMedia.run({ ...fields, platform: e.platform, modelId: e.engineId, enabled: e.enabled ? 1 : 0 });+ counts.inserted++;+ }+ }+ }+// Embeddings are their own full snapshot. Older catalogs omit this field;// in that case retain the app's bundled embedding baseline untouched.if (catalog.embeddings) {@@ -713,6 +792,22 @@ function applyCatalogInner(db: Db, catalog: Catalog): NonNullable<SyncResult['co}}+ // Prune search engines only when the catalog carries the searchEngines+ // snapshot. Custom search relays (platform 'custom') are the user's own+ // and never pruned.+ if (catalog.searchEngines) {+ const searchCandidates = db+ .prepare('SELECT id, platform, model_id FROM media_models WHERE modality = ?')+ .all(SEARCH_MODALITY) as { id: number; platform: string; model_id: string }[];+ for (const c of searchCandidates) {+ if (!SEARCH_ENGINE_PLATFORMS.has(c.platform)) continue;+ if (!inSearchCatalog.has(`${c.platform}:${c.model_id}`)) {+ deleteMedia.run(c.id);+ counts.removed++;+ }+ }+ }+// Prune transcription rows only when the catalog actually carries the// snapshot (mirrors the embeddings rule), scoped to the modality so// image/audio rows are never touched by it.diff --git a/server/src/services/custom-media-register.ts b/server/src/services/custom-media-register.tsindex 72000265..4c165aa0 100644--- a/server/src/services/custom-media-register.ts+++ b/server/src/services/custom-media-register.ts@@ -8,7 +8,9 @@ import { customEndpointKeyIds } from './custom-endpoint.js';// through the SAME upsert, exactly like custom-model-register.ts does for chat// models. This used to live inline in routes/media.ts.-export type CustomMediaModality = 'image' | 'audio' | 'transcription';+// 'search' registers a custom web search relay speaking Tavily's wire shape at+// POST {base_url}/search (#1174); services/search.ts routes it first.+export type CustomMediaModality = 'image' | 'audio' | 'transcription' | 'search';export interface CustomMediaEntry {modelId: string;diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex 7276fe49..93bc8c22 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -213,10 +213,12 @@ export function listMediaModels(modality: MediaModality): MediaModelRow[] {.all(modality) as MediaModelRow[];}-/** All media models (both modalities, including disabled) for the dashboard. */+/** All media models (every media modality, including disabled) for the+ * dashboard. Search engines share the table (modality 'search') but have+ * their own page and API (routes/search.ts), so they are left out here. */export function listAllMediaModels(): MediaModelRow[] {return getDb()- .prepare('SELECT * FROM media_models ORDER BY modality, priority, id')+ .prepare("SELECT * FROM media_models WHERE modality != 'search' ORDER BY modality, priority, id").all() as MediaModelRow[];}diff --git a/server/src/services/search.ts b/server/src/services/search.tsnew file mode 100644index 00000000..d45a7829--- /dev/null+++ b/server/src/services/search.ts@@ -0,0 +1,627 @@+import { getDb, getSetting, setSetting } from '../db/index.js';+import { parseRetryAfterMs } from '../providers/base.js';+import { RetryHintTracker } from '../lib/retry-hint.js';+import { getClientContext } from '../lib/client-context.js';+import { proxyFetch } from '../lib/proxy.js';+import { isSearchPlatform } from '../lib/search-platforms.js';+import { TAVILY_BASE_URL } from '../providers/tavily.js';+import { EXA_BASE_URL } from '../providers/exa.js';+import { FIRECRAWL_BASE_URL } from '../providers/firecrawl.js';+import { LINKUP_BASE_URL } from '../providers/linkup.js';+import { secondsUntilNextMonth } from './key-budget.js';+import { reserveProviderCredential, type ReservedProviderCredential } from './provider-credential.js';+import { isOnCooldown, setCooldown } from './ratelimit.js';++// Web search over the key pool (#1174).+//+// Search engines are media_models rows with modality = 'search' (model_id is+// the engine id, e.g. 'tavily-search'). The catalog's `searchEngines` registry+// maintains them (see catalog-sync); nothing is bundled, so engines reach+// Premium first and Free 30 days later like any catalog row. A user can also+// register a custom endpoint that speaks Tavily's wire shape at POST {base_url}/search (POST /api/media/custom with+// modality 'search'), which binds the row to that endpoint's key.+//+// Routing: custom endpoints first (the operator's explicit relays), then the+// catalog engines in priority order (a local reorder from the dashboard wins+// over the catalog's order), then every healthy enabled key of the engine's+// platform. A rate-limited or out-of-credit key cools down per engine and the+// chain moves on; the first engine that returns hits wins. Every attempt is+// logged to search_requests for the dashboard's Search page and analytics.++export const SEARCH_MODALITY = 'search';++/** settings key holding the dashboard's local engine order: a JSON map of+ * `${platform}:${engineId}` → priority. Kept out of media_models.priority so+ * the next catalog apply (which rewrites that column) cannot undo it. */+const PRIORITY_OVERRIDES_SETTING = 'search_engine_priority';++const FETCH_TIMEOUT_MS = 30_000;+const MAX_RESULTS = 20;+const DEFAULT_RESULTS = 5;+/** Page text per hit for the engines that return full content (Exa). Enough+ * for a model to ground an answer without flooding its context. */+const CONTENT_CHARS = 1_500;+/** Cooldowns, per key and engine. */+const RATE_LIMIT_COOLDOWN_MS = 60_000;+const BAD_KEY_COOLDOWN_MS = 60 * 60_000;+/** Out of credits: free search credits reset on each account's own cycle, not+ * a calendar month, so re-check twice a day instead of benching to month end. */+const NO_CREDIT_COOLDOWN_MS = 12 * 60 * 60_000;++export interface SearchHit {+ title: string;+ url: string;+ content: string;+ score: number;+}++export interface SearchResponse {+ query: string;+ answer?: string;+ results: SearchHit[];+ /** Platform that served the search ('tavily', 'exa', ..., or 'custom'). */+ provider: string;+ /** Engine id that served the search ('tavily-search', ...). */+ engine: string;+}++export class SearchError extends Error {+ status: number;+ code?: string;+ retryAfterMs?: number;+ constructor(message: string, status: number, code?: string, retryAfterMs?: number) {+ super(message);+ this.status = status;+ this.code = code;+ this.retryAfterMs = retryAfterMs;+ }+}++export interface SearchOptions {+ maxResults?: number;+ topic?: 'general' | 'news';+ includeAnswer?: boolean;+ /** Pin one engine by id; omitted or 'auto' walks the whole chain. */+ engine?: string;+ /** Agent the search runs for (e.g. 'claude-code'); defaults to the request's+ * detected client. Recorded on search_requests. */+ clientAgent?: string | null;+ /** The caller's cancellation (a departed client). */+ signal?: AbortSignal;+}++export interface SearchEngineFeatures {+ news?: boolean;+ answer?: boolean;+ fullContent?: boolean;+}++export interface SearchEngineMeta {+ creditsPerQuery?: number | null;+ features?: SearchEngineFeatures;+ premiumSince?: string | null;+}++interface SearchEngineRow {+ id: number;+ platform: string;+ model_id: string;+ display_name: string;+ priority: number;+ enabled: number;+ quota_label: string;+ key_id: number | null;+ meta_json: string | null;+}++export function parseSearchMeta(raw: string | null): SearchEngineMeta {+ if (!raw) return {};+ try {+ const parsed = JSON.parse(raw) as SearchEngineMeta;+ return parsed && typeof parsed === 'object' ? parsed : {};+ } catch {+ return {};+ }+}++// ── Engine order ─────────────────────────────────────────────────────────────++function engineKey(row: Pick<SearchEngineRow, 'platform' | 'model_id'>): string {+ return `${row.platform}:${row.model_id}`;+}++function readPriorityOverrides(): Record<string, number> {+ const raw = getSetting(PRIORITY_OVERRIDES_SETTING);+ if (!raw) return {};+ try {+ const parsed = JSON.parse(raw) as Record<string, unknown>;+ const out: Record<string, number> = {};+ for (const [k, v] of Object.entries(parsed ?? {})) {+ if (typeof v === 'number' && Number.isFinite(v)) out[k] = v;+ }+ return out;+ } catch {+ return {};+ }+}++function allEngineRows(): SearchEngineRow[] {+ return getDb()+ .prepare(`SELECT id, platform, model_id, display_name, priority, enabled, quota_label, key_id, meta_json+ FROM media_models WHERE modality = ? ORDER BY priority, id`)+ .all(SEARCH_MODALITY) as SearchEngineRow[];+}++/** Every search engine row in effective order (local reorder over catalog+ * priority), each carrying its effective priority. */+function orderedEngines(): Array<SearchEngineRow & { effectivePriority: number }> {+ const overrides = readPriorityOverrides();+ return allEngineRows()+ .map(row => ({ ...row, effectivePriority: overrides[engineKey(row)] ?? row.priority }))+ .sort((a, b) => a.effectivePriority - b.effectivePriority || a.id - b.id);+}++// ── Adapters ────────────────────────────────────────────────────────────────++interface AdapterResult {+ answer?: string;+ results: SearchHit[];+}++type Adapter = (cred: ReservedProviderCredential, query: string, opts: SearchOptions, maxResults: number) => Promise<AdapterResult>;++async function upstream(url: string, platform: string, init: RequestInit, signal?: AbortSignal): Promise<unknown> {+ const timeoutSignal = AbortSignal.timeout(FETCH_TIMEOUT_MS);+ const res = await proxyFetch(+ url,+ { ...init, signal: signal ? AbortSignal.any([timeoutSignal, signal]) : timeoutSignal },+ platform,+ 'search',+ FETCH_TIMEOUT_MS,+ );+ if (!res.ok) {+ const body = await res.text().catch(() => '');+ throw new SearchError(+ `${platform} ${res.status}: ${body.slice(0, 200)}`,+ res.status,+ undefined,+ parseRetryAfterMs(res.headers?.get('retry-after') ?? null),+ );+ }+ return res.json();+}++const str = (v: unknown): string => (typeof v === 'string' ? v : '');+const clip = (v: string): string => (v.length > CONTENT_CHARS ? `${v.slice(0, CONTENT_CHARS)}…` : v);+/** Engines that do not score hits keep their own ranking: 1.0 down to ~0. */+const rankScore = (i: number, n: number): number => Number((1 - i / Math.max(n, 1)).toFixed(3));++// Some engines (Linkup) return page titles with their HTML entities intact+// ("Quelle est la capitale de l'Australie"). Decode the common ones so+// every engine hands back plain text.+const NAMED_ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };+export function decodeEntities(v: string): string {+ if (!v.includes('&')) return v;+ return v.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e: string) => {+ if (e[0] === '#') {+ const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;+ }+ return NAMED_ENTITIES[e.toLowerCase()] ?? m;+ });+}++function keepHits(hits: Array<{ title: string; url: string; content: string; score?: number }>): SearchHit[] {+ const valid = hits.filter(h => h.url);+ return valid.map((h, i) => ({+ title: decodeEntities(h.title),+ url: h.url,+ content: clip(decodeEntities(h.content)),+ score: typeof h.score === 'number' && Number.isFinite(h.score) ? h.score : rankScore(i, valid.length),+ }));+}++/** Tavily's wire shape, shared by Tavily itself and custom search relays. */+async function tavilyShaped(url: string, platform: string, cred: ReservedProviderCredential, query: string, opts: SearchOptions, maxResults: number): Promise<AdapterResult> {+ const body: Record<string, unknown> = { query, max_results: maxResults };+ if (opts.topic) body.topic = opts.topic;+ if (opts.includeAnswer !== undefined) body.include_answer = opts.includeAnswer;+ const parsed = await upstream(url, platform, {+ method: 'POST',+ headers: { Authorization: `Bearer ${cred.key}`, 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ }, opts.signal) as { answer?: unknown; results?: Array<Record<string, unknown>> };+ const hits = (Array.isArray(parsed?.results) ? parsed.results : []).map(r => ({+ title: str(r.title),+ url: str(r.url),+ content: str(r.content),+ score: typeof r.score === 'number' ? r.score : undefined,+ }));+ return { answer: typeof parsed?.answer === 'string' ? parsed.answer : undefined, results: keepHits(hits) };+}++const ADAPTERS: Record<string, Adapter> = {+ tavily: (cred, query, opts, n) => tavilyShaped(`${TAVILY_BASE_URL}/search`, 'tavily', cred, query, opts, n),++ custom: (cred, query, opts, n) => {+ if (!cred.baseUrl) throw new SearchError('custom search endpoint has no base URL', 502);+ return tavilyShaped(`${cred.baseUrl}/search`, 'custom', cred, query, opts, n);+ },++ exa: async (cred, query, opts, n) => {+ const body: Record<string, unknown> = {+ query,+ numResults: n,+ type: 'auto',+ contents: { text: { maxCharacters: CONTENT_CHARS } },+ };+ if (opts.topic === 'news') body.category = 'news';+ const parsed = await upstream(`${EXA_BASE_URL}/search`, 'exa', {+ method: 'POST',+ headers: { 'x-api-key': cred.key, 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ }, opts.signal) as { results?: Array<Record<string, unknown>> };+ const hits = (Array.isArray(parsed?.results) ? parsed.results : []).map(r => ({+ title: str(r.title),+ url: str(r.url),+ content: str(r.text) || str(r.summary) || (Array.isArray(r.highlights) ? r.highlights.filter(h => typeof h === 'string').join(' … ') : ''),+ }));+ return { results: keepHits(hits) };+ },++ firecrawl: async (cred, query, opts, n) => {+ const source = opts.topic === 'news' ? 'news' : 'web';+ const parsed = await upstream(`${FIRECRAWL_BASE_URL}/search`, 'firecrawl', {+ method: 'POST',+ headers: { Authorization: `Bearer ${cred.key}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ query, limit: n, sources: [source] }),+ }, opts.signal) as { data?: { web?: Array<Record<string, unknown>>; news?: Array<Record<string, unknown>> } | Array<Record<string, unknown>> };+ // v2 groups hits by source; tolerate the v1 flat array too.+ const data = parsed?.data;+ const rows = Array.isArray(data) ? data : (data?.[source] ?? data?.web ?? []);+ const hits = (Array.isArray(rows) ? rows : []).map(r => ({+ title: str(r.title),+ url: str(r.url),+ content: str(r.description) || str(r.snippet) || str(r.markdown),+ }));+ return { results: keepHits(hits) };+ },++ linkup: async (cred, query, opts, n) => {+ const answer = opts.includeAnswer === true;+ const parsed = await upstream(`${LINKUP_BASE_URL}/search`, 'linkup', {+ method: 'POST',+ headers: { Authorization: `Bearer ${cred.key}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ q: query, depth: 'standard', outputType: answer ? 'sourcedAnswer' : 'searchResults', maxResults: n }),+ }, opts.signal) as { answer?: unknown; sources?: Array<Record<string, unknown>>; results?: Array<Record<string, unknown>> };+ if (answer) {+ const hits = (Array.isArray(parsed?.sources) ? parsed.sources : []).map(r => ({+ title: str(r.name),+ url: str(r.url),+ content: str(r.snippet),+ }));+ return { answer: typeof parsed?.answer === 'string' ? parsed.answer : undefined, results: keepHits(hits) };+ }+ const hits = (Array.isArray(parsed?.results) ? parsed.results : [])+ .filter(r => r.type === undefined || r.type === 'text')+ .map(r => ({ title: str(r.name), url: str(r.url), content: str(r.content) }));+ return { results: keepHits(hits) };+ },+};++/** Platforms with a search adapter. catalog-sync gates searchEngines rows on+ * this, the way VIDEO_PLATFORMS gates video rows. */+export const SEARCH_ENGINE_PLATFORMS = new Set(Object.keys(ADAPTERS).filter(p => p !== 'custom'));++// ── Routing ─────────────────────────────────────────────────────────────────++function logSearch(row: SearchEngineRow, keyId: number | null, status: 'ok' | 'error', latencyMs: number, resultCount: number, clientAgent: string | null, error: string | null): void {+ try {+ getDb()+ .prepare(`INSERT INTO search_requests (engine_id, platform, key_id, status, latency_ms, result_count, client_agent, error)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)+ .run(row.model_id, row.platform, keyId, status, latencyMs, resultCount, clientAgent, error);+ } catch (e) {+ console.error('Failed to log search request:', e);+ }+}++/** Bench this key for this engine according to what the upstream said. */+function coolDown(row: SearchEngineRow, keyId: number, e: SearchError): void {+ if (row.platform === 'custom') {+ if (e.status === 429) setCooldown(row.platform, row.model_id, keyId, e.retryAfterMs ?? RATE_LIMIT_COOLDOWN_MS);+ return;+ }+ if (e.status === 401 || e.status === 403) {+ setCooldown(row.platform, row.model_id, keyId, BAD_KEY_COOLDOWN_MS);+ } else if (e.status === 402 || e.status === 432 || e.status === 433) {+ // 402 (Exa, Firecrawl) and 432/433 (Tavily plan / pay-as-you-go cap):+ // the key's credits are spent.+ setCooldown(row.platform, row.model_id, keyId, NO_CREDIT_COOLDOWN_MS, 'credit');+ } else if (e.status === 429) {+ setCooldown(row.platform, row.model_id, keyId, e.retryAfterMs ?? RATE_LIMIT_COOLDOWN_MS);+ }+}++/** True when at least one enabled engine has a usable key, i.e. a search can+ * be attempted. The agents' web_search integration keys off this. */+export function searchAvailable(): boolean {+ const db = getDb();+ for (const row of orderedEngines()) {+ if (row.enabled !== 1) continue;+ if (row.platform === 'custom') {+ if (row.key_id == null) continue;+ const k = db.prepare("SELECT 1 FROM api_keys WHERE id = ? AND enabled = 1 AND status IN ('healthy', 'unknown')").get(row.key_id);+ if (k) return true;+ continue;+ }+ if (!ADAPTERS[row.platform]) continue;+ const k = db.prepare("SELECT 1 FROM api_keys WHERE platform = ? AND enabled = 1 AND status IN ('healthy', 'unknown') LIMIT 1").get(row.platform);+ if (k) return true;+ }+ return false;+}++function searchChain(engine: string | undefined): SearchEngineRow[] {+ const enabled = orderedEngines().filter(r => r.enabled === 1 && ADAPTERS[r.platform]);+ // Custom relays first, catalog engines after, each group in effective order.+ const chain = [...enabled.filter(r => r.platform === 'custom'), ...enabled.filter(r => r.platform !== 'custom')];+ if (!engine || engine === 'auto') return chain;+ const pinned = chain.filter(r => r.model_id === engine);+ if (pinned.length === 0) {+ const known = orderedEngines().some(r => r.model_id === engine);+ throw new SearchError(+ known+ ? `Search engine '${engine}' is turned off. Turn it on from Models → Search, or use 'auto'.`+ : `Unknown search engine '${engine}'. Use 'auto' or an engine id from GET /v1/search/engines.`,+ 400,+ );+ }+ return pinned;+}++export async function runSearch(query: string, opts: SearchOptions = {}): Promise<SearchResponse> {+ const chain = searchChain(opts.engine);+ const maxResults = Math.min(Math.max(1, Math.floor(opts.maxResults ?? DEFAULT_RESULTS)), MAX_RESULTS);+ const clientAgent = opts.clientAgent !== undefined ? opts.clientAgent : getClientContext().agent;++ let lastError: SearchError | null = null;+ let attempted = 0;+ const hints = new RetryHintTracker();+ for (const row of chain) {+ // Several keys per engine: a benched or failing key passes to the next+ // key of the same engine before the chain moves to the next engine.+ const tried = new Set<number>();+ for (;;) {+ if (opts.signal?.aborted) throw new SearchError('search cancelled by the client', 499);+ const { credential, budgetBlocked } = reserveProviderCredential(+ row,+ 0,+ keyId => tried.has(keyId) || isOnCooldown(row.platform, row.model_id, keyId),+ );+ if (!credential) {+ if (budgetBlocked) {+ lastError = new SearchError('Monthly key budget exhausted', 429, 'quota_exceeded');+ hints.record(429, secondsUntilNextMonth() * 1000);+ }+ break;+ }+ tried.add(credential.id);+ attempted++;+ const started = Date.now();+ try {+ const out = await ADAPTERS[row.platform]!(credential, query, opts, maxResults);+ if (out.results.length === 0) throw new SearchError('upstream returned no valid search hits', 502);+ logSearch(row, credential.id, 'ok', Date.now() - started, out.results.length, clientAgent, null);+ return {+ query,+ ...(out.answer ? { answer: out.answer } : {}),+ results: out.results,+ provider: row.platform,+ engine: row.model_id,+ };+ } catch (err: any) {+ const e = err instanceof SearchError ? err : new SearchError(String(err?.message ?? err), 502);+ logSearch(row, credential.id, 'error', Date.now() - started, 0, clientAgent, e.message.slice(0, 300));+ coolDown(row, credential.id, e);+ lastError = e;+ hints.record(e.status, e.retryAfterMs);+ if (opts.signal?.aborted) throw new SearchError('search cancelled by the client', 499);+ // A query the engine rejected as malformed is the caller's problem,+ // not this key's: try the next engine rather than every key.+ if (e.status === 400) break;+ } finally {+ credential.release();+ }+ }+ }++ if (attempted === 0 && !lastError) {+ // Keys exist but every one is benched (rate limited, out of credits or+ // rejected recently): a retryable condition, not a setup problem.+ if (searchAvailable()) {+ throw new SearchError(+ 'Every search key is cooling down (rate limited or out of credits). Try again later or add another search key.',+ 429,+ 'search_keys_cooling_down',+ );+ }+ throw new SearchError(+ 'No search key configured. Add a Tavily, Exa, Firecrawl or Linkup key on the Keys page.',+ 503,+ 'no_search_keys',+ );+ }+ // Only statuses the caller can act on pass through (see media chainError):+ // an upstream 401 means OUR provider key failed, not the caller's.+ const status = lastError?.status === 429 ? 429 : 502;+ throw new SearchError(+ `All search engines failed${lastError ? ` (last: ${lastError.message.slice(0, 160)})` : ' (no usable keys)'}.`,+ status,+ lastError?.code,+ status === 429 ? hints.retryAfterMs() : undefined,+ );+}++/** Whole seconds the client should wait before retrying: the upstream back-off+ * when the chain was rate limited, else the monthly-budget reset. */+export function searchRetryAfterSec(err: SearchError): number | undefined {+ if (err.retryAfterMs !== undefined) return Math.ceil(err.retryAfterMs / 1000);+ if (err.code === 'quota_exceeded') return secondsUntilNextMonth();+ return undefined;+}++// ── Dashboard: engines ───────────────────────────────────────────────────────++export interface SearchEngineView {+ id: number;+ platform: string;+ engineId: string;+ displayName: string;+ priority: number;+ enabled: boolean;+ quotaLabel: string;+ creditsPerQuery: number | null;+ features: SearchEngineFeatures;+ premiumSince: string | null;+ /** premiumSince + 30 days: when a free install receives the engine. */+ freeFrom: string | null;+ isCustom: boolean;+ keyCount: number;+ healthyKeyCount: number;+ searchesThisMonth: number;+}++const FREE_LAG_MS = 30 * 24 * 60 * 60 * 1000;++export function listSearchEngines(): SearchEngineView[] {+ const db = getDb();+ const keyRows = db.prepare(`+ SELECT id, platform, enabled, status FROM api_keys+ WHERE platform = 'custom' OR platform IN (${[...SEARCH_ENGINE_PLATFORMS].map(() => '?').join(', ')})+ `).all(...SEARCH_ENGINE_PLATFORMS) as { id: number; platform: string; enabled: number; status: string }[];+ const healthy = (k: { enabled: number; status: string }) => k.enabled === 1 && (k.status === 'healthy' || k.status === 'unknown');+ const monthCounts = new Map(+ (db.prepare(`+ SELECT platform, engine_id, COUNT(*) AS n FROM search_requests+ WHERE status = 'ok' AND created_at >= datetime('now', 'start of month')+ GROUP BY platform, engine_id+ `).all() as { platform: string; engine_id: string; n: number }[]).map(r => [`${r.platform}:${r.engine_id}`, r.n]),+ );++ return orderedEngines().map(row => {+ const meta = parseSearchMeta(row.meta_json);+ const keys = row.platform === 'custom'+ ? keyRows.filter(k => k.id === row.key_id)+ : keyRows.filter(k => k.platform === row.platform);+ const premiumSince = typeof meta.premiumSince === 'string' ? meta.premiumSince : null;+ const premiumMs = premiumSince ? Date.parse(premiumSince) : NaN;+ return {+ id: row.id,+ platform: row.platform,+ engineId: row.model_id,+ displayName: row.display_name,+ priority: row.effectivePriority,+ enabled: row.enabled === 1,+ quotaLabel: row.quota_label,+ creditsPerQuery: typeof meta.creditsPerQuery === 'number' ? meta.creditsPerQuery : null,+ features: meta.features ?? {},+ premiumSince,+ freeFrom: Number.isFinite(premiumMs) ? new Date(premiumMs + FREE_LAG_MS).toISOString() : null,+ isCustom: row.platform === 'custom',+ keyCount: keys.length,+ healthyKeyCount: keys.filter(healthy).length,+ searchesThisMonth: monthCounts.get(engineKey(row)) ?? 0,+ };+ });+}++/** Turn an engine on/off and/or move it to `priority` (0 = first/default).+ * A move renumbers every engine 0..n-1 in the new order and stores that as+ * the local order. Returns false when the id is not a search engine. */+export function updateSearchEngine(id: number, patch: { enabled?: boolean; priority?: number }): boolean {+ const db = getDb();+ const ordered = orderedEngines();+ const target = ordered.find(r => r.id === id);+ if (!target) return false;+ if (patch.enabled !== undefined) {+ db.prepare('UPDATE media_models SET enabled = ? WHERE id = ?').run(patch.enabled ? 1 : 0, id);+ }+ if (patch.priority !== undefined) {+ const rest = ordered.filter(r => r.id !== id);+ const index = Math.max(0, Math.min(Math.floor(patch.priority), rest.length));+ rest.splice(index, 0, target);+ const overrides: Record<string, number> = {};+ rest.forEach((r, i) => { overrides[engineKey(r)] = i; });+ setSetting(PRIORITY_OVERRIDES_SETTING, JSON.stringify(overrides));+ }+ return true;+}++// ── Dashboard: analytics ────────────────────────────────────────────────────++export type SearchAnalyticsRange = '24h' | '7d' | '30d' | '90d' | 'all';++export interface SearchAnalytics {+ total: number;+ today: number;+ successRate: number;+ avgLatencyMs: number;+ byEngine: Array<{ engineId: string; displayName: string; count: number }>;+ series: Array<{ date: string; engineId: string; count: number }>;+}++function rangeSince(range: SearchAnalyticsRange): string | null {+ const days = { '24h': 1, '7d': 7, '30d': 30, '90d': 90 } as const;+ if (range === 'all') return null;+ const ms = Date.now() - days[range] * 24 * 60 * 60 * 1000;+ return new Date(ms).toISOString().slice(0, 19).replace('T', ' ');+}++/** Searches over a range: totals count successful searches; successRate and+ * latency are over every attempt (a failed attempt that failed over is+ * still a cost the operator wants to see). */+export function searchAnalytics(range: SearchAnalyticsRange): SearchAnalytics {+ const db = getDb();+ const since = rangeSince(range);+ const where = since ? 'WHERE created_at >= ?' : '';+ const args = since ? [since] : [];++ const totals = db.prepare(`+ SELECT COUNT(*) AS attempts,+ COALESCE(SUM(CASE WHEN status = 'ok' THEN 1 ELSE 0 END), 0) AS ok,+ COALESCE(AVG(latency_ms), 0) AS avg_latency+ FROM search_requests ${where}+ `).get(...args) as { attempts: number; ok: number; avg_latency: number };+ const today = (db.prepare(`+ SELECT COUNT(*) AS n FROM search_requests WHERE status = 'ok' AND created_at >= datetime('now', 'start of day')+ `).get() as { n: number }).n;++ const names = new Map(allEngineRows().map(r => [r.model_id, r.display_name]));+ const byEngine = (db.prepare(`+ SELECT engine_id, COUNT(*) AS n FROM search_requests+ ${where ? `${where} AND` : 'WHERE'} status = 'ok'+ GROUP BY engine_id ORDER BY n DESC, engine_id+ `).all(...args) as { engine_id: string; n: number }[])+ .map(r => ({ engineId: r.engine_id, displayName: names.get(r.engine_id) ?? r.engine_id, count: r.n }));+ const series = (db.prepare(`+ SELECT date(created_at) AS day, engine_id, COUNT(*) AS n FROM search_requests+ ${where ? `${where} AND` : 'WHERE'} status = 'ok'+ GROUP BY day, engine_id ORDER BY day, engine_id+ `).all(...args) as { day: string; engine_id: string; n: number }[])+ .map(r => ({ date: r.day, engineId: r.engine_id, count: r.n }));++ return {+ total: totals.ok,+ today,+ // Percent, 0–100, one decimal: the same scale as the chat summary.+ successRate: totals.attempts > 0 ? Math.round((totals.ok / totals.attempts) * 1000) / 10 : 0,+ avgLatencyMs: Math.round(totals.avg_latency),+ byEngine,+ series,+ };+}++/** Search platforms are not chat providers; re-exported for routes that+ * decorate the provider list. */+export { isSearchPlatform };diff --git a/shared/types.ts b/shared/types.tsindex 3514ce0b..ba99d856 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -126,6 +126,14 @@ export type Platform =| 'openrouter'| 'github'| 'cohere'+ // Web search APIs (#1174), not chat providers. Their keys serve POST+ // /v1/search (and the agents' web_search tools) through the catalog's+ // searchEngines registry; chat calls to them are rejected. See+ // SEARCH_PLATFORMS below.+ | 'tavily'+ | 'exa'+ | 'firecrawl'+ | 'linkup'| 'cloudflare'| 'zhipu'| 'ollama'@@ -250,6 +258,17 @@ export type Platform =// Ollama, any base_url). The endpoint URL lives on the api_keys row; see #117.| 'custom';+/** Platforms whose keys serve web search (POST /v1/search and the agents'+ * web_search tools), never chat. Search engine rows arrive through the+ * catalog's `searchEngines` registry. The server keeps its own runtime copy in+ * server/src/lib/search-platforms.ts (shared is type-only on the server). */+export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup'] as const;+export type SearchPlatform = (typeof SEARCH_PLATFORMS)[number];++export function isSearchPlatform(platform: string): platform is SearchPlatform {+ return (SEARCH_PLATFORMS as readonly string[]).includes(platform);+}+export interface Model {id: number;platform: Platform;