okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-agent2 c7b65c7f7 (/loop, /goal, /time-skip, keyless search, system-browser tool, Settings Tools, Plan refuses connected tools) into f-split-intea2d565e6

main
3.8 KiB66 linesraw
1/**
2 * Search through a service the person has their own key for: Exa or Perplexity (the Harness ships both as separate packages the app's
3 * bundle leaves out, so these are the same two small calls written here; DeepSeek's provider is in the bundle and is used as it is).
4 * Shapes follow the Harness's providers (packages/web/web-search-exa and web-search-perplexity at the pinned commit).
5 */
6import { SearchUnavailable } from './web-search-ddg.mjs';
7
8const abortError = e => e?.name === 'AbortError';
9
10async function call(service, url, options, signal) {
11  let res;
12  try { res = await fetch(url, { ...options, redirect: 'error', ...(signal ? { signal } : {}) }); }
13  catch (error) {
14    if (abortError(error)) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error });
15    throw new SearchUnavailable(`The search could not reach ${service}. Check the internet connection and try again.`, 'WEB_PROVIDER_ERROR', { cause: error });
16  }
17  if (!res.ok) {
18    let detail = '';
19    try { const body = await res.json(); detail = typeof body.error === 'string' ? body.error : body.error?.message ?? body.message ?? ''; } catch { /* not JSON */ }
20    if (res.status === 401 || res.status === 403) throw new SearchUnavailable(`${service} did not accept the key. Check it in Settings, Tools.`, 'WEB_PROVIDER_ERROR');
21    if (res.status === 429) throw new SearchUnavailable(`${service} says there have been too many searches. Try again in a minute.`, 'WEB_RATE_LIMITED');
22    throw new SearchUnavailable(`${service} could not search (error ${res.status}).${detail ? ' ' + String(detail).slice(0, 200) : ''}`, 'WEB_PROVIDER_ERROR');
23  }
24  try { return await res.json(); }
25  catch (error) { throw new SearchUnavailable(`${service} sent an answer that could not be read.`, 'WEB_PROVIDER_ERROR', { cause: error }); }
26}
27
28export function createExaSearch({ key }) {
29  return {
30    id: 'exa',
31    available: () => typeof key === 'function' ? !!key() : !!key,
32    async search(request, signal) {
33      const apiKey = typeof key === 'function' ? key() : key;
34      const body = await call('Exa', 'https://api.exa.ai/search', {
35        method: 'POST',
36        headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json', accept: 'application/json' },
37        body: JSON.stringify({ query: request.query, type: 'auto', contents: { highlights: { highlightsPerUrl: 1 } }, ...(request.maxResults ? { numResults: request.maxResults } : {}) }),
38      }, signal);
39      const sources = (body.results ?? []).flatMap(r => {
40        const snippet = (r.highlights ?? []).find(h => String(h).trim());
41        return snippet === undefined ? [] : [{ url: r.url, ...(r.title ? { title: r.title } : {}), snippet, ...(r.publishedDate ? { publishedAt: r.publishedDate } : {}) }];
42      });
43      return { sources, truncated: false };
44    },
45  };
46}
47
48export function createPerplexitySearch({ key }) {
49  return {
50    id: 'perplexity',
51    available: () => typeof key === 'function' ? !!key() : !!key,
52    async search(request, signal) {
53      const apiKey = typeof key === 'function' ? key() : key;
54      const body = await call('Perplexity', 'https://api.perplexity.ai/chat/completions', {
55        method: 'POST',
56        headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json', accept: 'application/json' },
57        body: JSON.stringify({ model: 'sonar', max_tokens: 1024, messages: [{ role: 'user', content: request.query }] }),
58      }, signal);
59      const content = body.choices?.[0]?.message?.content;
60      const sources = body.search_results !== undefined
61        ? body.search_results.map(r => ({ url: r.url, ...(r.title ? { title: r.title } : {}), ...(r.snippet ? { snippet: r.snippet } : {}), ...(r.date ? { publishedAt: r.date } : {}) }))
62        : (body.citations ?? []).map(url => ({ url }));
63      return { ...(content ? { content } : {}), sources, truncated: false };
64    },
65  };
66}