File size: 1,732 Bytes
289c704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export async function withSearchContext(text) {
  const now = new Date();
  const dateStr = now.toLocaleDateString("en-US", {
    weekday: "long", year: "numeric", month: "long", day: "numeric",
  });
  const timeStr = now.toLocaleTimeString("en-US", {
    hour: "2-digit", minute: "2-digit",
  });

  let context = `[Current date and time: ${dateStr} at ${timeStr}]`;

  try {
    // Step 1: Search
    const searchResp = await fetch(`/api/web/search?q=${encodeURIComponent(text)}`);
    if (!searchResp.ok) return `${context}\n\n${text}`;
    const searchData = await searchResp.json();
    if (!searchData.results || searchData.results.length === 0) return `${context}\n\n${text}`;

    // Step 2: Build context from search results with detailed content
    const topResults = searchData.results.slice(0, 3);
    context += `\n\n[Real-time web search results (${dateStr}):`;

    for (let i = 0; i < topResults.length; i++) {
      const r = topResults[i];
      context += `\n--- Result ${i + 1}: ${r.title} ---\n${r.snippet}`;

      // Step 3: Try to fetch full article content from each result URL
      if (r.url) {
        try {
          const contentResp = await fetch(`/api/web/content?url=${encodeURIComponent(r.url)}`);
          if (contentResp.ok) {
            const contentData = await contentResp.json();
            if (contentData.content && contentData.content.length > r.snippet.length) {
              context += `\n[Full article excerpt:]\n${contentData.content}`;
            }
          }
        } catch {
          // Content fetch failed, snippet is enough
        }
      }
    }
    context += `]`;
  } catch (e) {
    console.warn("auto-search failed:", e);
  }

  return `${context}\n\n${text}`;
}