File size: 9,029 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { getProviderCredentials } from "@/sse/services/auth";
import { recordCost } from "@/domain/costRules";
import * as defaultLog from "@/sse/utils/logger";
import {
  getAllSearchProviders,
  getSearchProvider,
  selectProvider,
  supportsSearchType,
  SEARCH_CREDENTIAL_FALLBACKS,
  SEARCH_PROVIDERS,
  type SearchProviderConfig,
} from "@omniroute/open-sse/config/searchRegistry.ts";
import { handleSearch, type SearchResponse } from "@omniroute/open-sse/handlers/search.ts";
import {
  computeCacheKey,
  getOrCoalesce,
  SEARCH_CACHE_DEFAULT_TTL_MS,
} from "@omniroute/open-sse/services/searchCache.ts";

type SearchLogger = typeof defaultLog;

export interface ExecuteWebSearchInput {
  query: string;
  provider?: string;
  max_results?: number;
  limit?: number;
  search_type?: "web" | "news";
  offset?: number;
  country?: string;
  language?: string;
  time_range?: "any" | "day" | "week" | "month" | "year";
  content?: {
    snippet?: boolean;
    full_page?: boolean;
    format?: "text" | "markdown";
    max_characters?: number;
  };
  filters?: {
    include_domains?: string[];
    exclude_domains?: string[];
    safe_search?: "off" | "moderate" | "strict";
  };
  provider_options?: Record<string, unknown>;
  strict_filters?: boolean;
  apiKeyId?: string | null;
  log?: SearchLogger;
}

export interface ExecuteWebSearchResult {
  cached: boolean;
  data: SearchResponse;
}

export class WebSearchExecutionError extends Error {
  statusCode: number;

  constructor(message: string, statusCode: number) {
    super(message);
    this.statusCode = statusCode;
  }
}

async function resolveSearchCredentials(providerId: string) {
  const creds = await getProviderCredentials(providerId).catch(() => null);
  if (creds) return creds;
  const fallbackId = SEARCH_CREDENTIAL_FALLBACKS[providerId];
  if (fallbackId) return getProviderCredentials(fallbackId).catch(() => null);
  return null;
}

function buildDomainFilter(filters?: {

  include_domains?: string[];

  exclude_domains?: string[];

}): string[] | undefined {
  if (!filters) return undefined;
  const parts: string[] = [];
  if (filters.include_domains?.length) parts.push(...filters.include_domains);
  if (filters.exclude_domains?.length) parts.push(...filters.exclude_domains.map((d) => `-${d}`));
  return parts.length > 0 ? parts : undefined;
}

function normalizeMaxResults(input: ExecuteWebSearchInput, providerConfig: SearchProviderConfig) {
  const fromMaxResults =
    typeof input.max_results === "number"
      ? input.max_results
      : typeof input.max_results === "string"
        ? Number(input.max_results)
        : Number.NaN;
  const fromLimit =
    typeof input.limit === "number"
      ? input.limit
      : typeof input.limit === "string"
        ? Number(input.limit)
        : Number.NaN;
  const requested = Number.isFinite(fromMaxResults)
    ? fromMaxResults
    : Number.isFinite(fromLimit)
      ? fromLimit
      : providerConfig.defaultMaxResults;
  return Math.min(Math.max(1, requested), providerConfig.maxMaxResults);
}

function assertValidSearchInput(input: ExecuteWebSearchInput) {
  if (typeof input.query !== "string" || input.query.trim().length === 0) {
    throw new WebSearchExecutionError("Missing required field: query", 400);
  }
  if (input.query.trim().length > 500) {
    throw new WebSearchExecutionError("Query must be 500 characters or fewer", 400);
  }
  if (input.search_type && input.search_type !== "web" && input.search_type !== "news") {
    throw new WebSearchExecutionError(`Unsupported search_type: ${String(input.search_type)}`, 400);
  }
}

export async function executeWebSearch(

  input: ExecuteWebSearchInput

): Promise<ExecuteWebSearchResult> {
  assertValidSearchInput(input);

  const log = input.log || defaultLog;
  const searchType = input.search_type || "web";

  if (input.provider) {
    const explicitProvider = getSearchProvider(input.provider);
    if (!explicitProvider) {
      throw new WebSearchExecutionError(`Unknown search provider: ${input.provider}`, 400);
    }
    if (!supportsSearchType(explicitProvider, searchType)) {
      throw new WebSearchExecutionError(
        `Search provider ${input.provider} does not support search_type: ${searchType}`,
        400
      );
    }
  }

  let providerConfig = selectProvider(input.provider, searchType);
  if (!providerConfig) {
    throw new WebSearchExecutionError(
      input.provider
        ? `Unknown search provider: ${input.provider}`
        : `No search providers available. Add an API key for a search provider (${getAllSearchProviders()

            .map((provider) => provider.id)

            .join(", ")}) in the dashboard.`,
      400
    );
  }

  let credentials: Record<string, any> | null = null;
  let alternateProviderId: string | undefined;
  let alternateCredentials: Record<string, any> | null = null;

  if (input.provider) {
    credentials = await resolveSearchCredentials(providerConfig.id);
    if (
      !credentials &&
      providerConfig.authType === "none" &&
      typeof input.provider_options?.baseUrl === "string" &&
      input.provider_options.baseUrl.trim().length > 0
    ) {
      credentials = {
        providerSpecificData: { baseUrl: input.provider_options.baseUrl.trim() },
      };
    }
    if (!credentials) {
      throw new WebSearchExecutionError(
        providerConfig.authType === "none"
          ? `Search provider ${providerConfig.id} is not configured. Set its base URL in the dashboard or pass provider_options.baseUrl.`
          : `No credentials configured for search provider: ${providerConfig.id}. Add an API key for "${providerConfig.id}" in the dashboard.`,
        400
      );
    }
  } else {
    credentials = await resolveSearchCredentials(providerConfig.id);

    if (!credentials) {
      const sortedIds = Object.values(SEARCH_PROVIDERS)
        .filter((provider) => supportsSearchType(provider, searchType))
        .sort((a, b) => a.costPerQuery - b.costPerQuery)
        .map((provider) => provider.id);

      for (const providerId of sortedIds) {
        if (providerId === providerConfig.id) continue;
        const altConfig = getSearchProvider(providerId);
        const altCreds = await resolveSearchCredentials(providerId);
        if (altConfig && altCreds) {
          providerConfig = altConfig;
          credentials = altCreds;
          break;
        }
      }
    }

    if (!credentials) {
      throw new WebSearchExecutionError(
        `No credentials configured for any search provider. Add an API key for a search provider (${Object.keys(

          SEARCH_PROVIDERS

        ).join(", ")}) in the dashboard.`,
        400
      );
    }

    const otherIds = Object.values(SEARCH_PROVIDERS)
      .filter((provider) => supportsSearchType(provider, searchType))
      .sort((a, b) => a.costPerQuery - b.costPerQuery)
      .map((provider) => provider.id)
      .filter((providerId) => providerId !== providerConfig.id);

    for (const providerId of otherIds) {
      const creds = await resolveSearchCredentials(providerId);
      if (creds) {
        alternateProviderId = providerId;
        alternateCredentials = creds;
        break;
      }
    }
  }

  const clampedMaxResults = normalizeMaxResults(input, providerConfig);
  const cacheKey = computeCacheKey(
    input.query.trim(),
    providerConfig.id,
    searchType,
    clampedMaxResults,
    input.country,
    input.language,
    {
      filters: input.filters,
      offset: input.offset,
      time_range: input.time_range,
    }
  );
  const ttl = providerConfig.cacheTTLMs ?? SEARCH_CACHE_DEFAULT_TTL_MS;

  const { data, cached } = await getOrCoalesce(cacheKey, ttl, async () => {
    const result = await handleSearch({
      query: input.query.trim(),
      provider: providerConfig.id,
      maxResults: clampedMaxResults,
      searchType,
      country: input.country,
      language: input.language,
      timeRange: input.time_range,
      offset: input.offset,
      domainFilter: buildDomainFilter(input.filters),
      contentOptions: input.content,
      strictFilters: input.strict_filters,
      providerOptions: input.provider_options,
      credentials,
      alternateProvider: alternateProviderId,
      alternateCredentials,
      log,
    });

    if (!result.success || !result.data) {
      throw new WebSearchExecutionError(result.error || "Search failed", result.status || 502);
    }

    return result.data;
  });

  if (!cached && input.apiKeyId && input.apiKeyId !== "local" && data.usage?.search_cost_usd > 0) {
    try {
      recordCost(input.apiKeyId, data.usage.search_cost_usd);
    } catch (error: any) {
      log.warn("SEARCH", `Cost recording failed: ${error?.message || String(error)}`);
    }
  }

  return { data, cached };
}