spectrawl 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spectrawl",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "The unified web layer for AI agents. Search (6 engines), stealth browse (Camoufox + Playwright), auth (cookies, multi-account), act (24 adapters, 30+ platforms), proxy rotation. Self-hosted, free.",
5
5
  "main": "src/index.js",
6
6
  "types": "index.d.ts",
@@ -0,0 +1,90 @@
1
+ const https = require('https')
2
+
3
+ /**
4
+ * Gemini Grounded Search — uses Google's Gemini API with built-in Google Search.
5
+ * Free tier: 1,500 req/day for Flash.
6
+ * Returns both an AI answer AND the search results it found.
7
+ *
8
+ * This is basically free Google search + AI summarization in one call.
9
+ */
10
+ async function geminiGroundedSearch(query, config = {}) {
11
+ const apiKey = config.apiKey || process.env.GEMINI_API_KEY
12
+ if (!apiKey) throw new Error('GEMINI_API_KEY required for grounded search')
13
+
14
+ const model = config.model || 'gemini-2.0-flash'
15
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`
16
+
17
+ const body = JSON.stringify({
18
+ contents: [{
19
+ parts: [{ text: `Search the web and provide relevant results for: ${query}` }]
20
+ }],
21
+ tools: [{ google_search: {} }],
22
+ generationConfig: {
23
+ temperature: 0.1,
24
+ maxOutputTokens: 1000
25
+ }
26
+ })
27
+
28
+ const data = await post(url, body)
29
+
30
+ if (data.error) {
31
+ throw new Error(`Gemini grounded search: ${data.error.message}`)
32
+ }
33
+
34
+ // Extract grounding metadata (search results)
35
+ const candidate = data.candidates?.[0]
36
+ const grounding = candidate?.groundingMetadata
37
+ const chunks = grounding?.groundingChunks || []
38
+ const answer = candidate?.content?.parts?.map(p => p.text).filter(Boolean).join('\n') || ''
39
+
40
+ // Convert grounding chunks to standard search result format
41
+ const results = chunks.map((chunk, i) => ({
42
+ title: chunk.web?.title || `Result ${i + 1}`,
43
+ url: chunk.web?.uri || '',
44
+ snippet: '', // Gemini doesn't give per-result snippets
45
+ source: 'gemini-grounded'
46
+ })).filter(r => r.url)
47
+
48
+ // Also try to extract URLs from grounding support
49
+ const supports = grounding?.groundingSupports || []
50
+ for (const support of supports) {
51
+ const indices = support.groundingChunkIndices || []
52
+ // Already captured above
53
+ }
54
+
55
+ // Attach the AI answer as metadata
56
+ if (results.length > 0) {
57
+ results._groundedAnswer = answer
58
+ }
59
+
60
+ return results
61
+ }
62
+
63
+ function post(url, body) {
64
+ return new Promise((resolve, reject) => {
65
+ const urlObj = new URL(url)
66
+ const opts = {
67
+ hostname: urlObj.hostname,
68
+ path: urlObj.pathname + urlObj.search,
69
+ method: 'POST',
70
+ headers: {
71
+ 'Content-Type': 'application/json',
72
+ 'Content-Length': Buffer.byteLength(body)
73
+ }
74
+ }
75
+ const req = https.request(opts, res => {
76
+ let data = ''
77
+ res.on('data', c => data += c)
78
+ res.on('end', () => {
79
+ try { resolve(JSON.parse(data)) }
80
+ catch (e) { reject(new Error(`Invalid Gemini response: ${data.slice(0, 200)}`)) }
81
+ })
82
+ })
83
+ req.on('error', reject)
84
+ req.setTimeout(15000, () => { req.destroy(); reject(new Error('Gemini grounded search timeout')) })
85
+ req.write(body)
86
+ req.end()
87
+ })
88
+ }
89
+
90
+ module.exports = { geminiGroundedSearch }
@@ -4,6 +4,7 @@ const { serperSearch } = require('./engines/serper')
4
4
  const { searxngSearch } = require('./engines/searxng')
5
5
  const { googleCseSearch } = require('./engines/google-cse')
6
6
  const { jinaSearch } = require('./engines/jina')
7
+ const { geminiGroundedSearch } = require('./engines/gemini-grounded')
7
8
  const { scrapeUrls } = require('./scraper')
8
9
  const { Summarizer } = require('./summarizer')
9
10
  const { Reranker } = require('./reranker')
@@ -15,7 +16,9 @@ const ENGINES = {
15
16
  brave: braveSearch,
16
17
  serper: serperSearch,
17
18
  'google-cse': googleCseSearch,
18
- jina: jinaSearch
19
+ jina: jinaSearch,
20
+ 'gemini-grounded': geminiGroundedSearch,
21
+ gemini: geminiGroundedSearch
19
22
  }
20
23
 
21
24
  class SearchEngine {
@@ -109,9 +112,10 @@ class SearchEngine {
109
112
  const cached = this.cache?.get('search', cacheKey)
110
113
  if (cached) return { ...cached, cached: true }
111
114
 
112
- // Step 1: Query expansion
115
+ // Step 1: Query expansion (skip if using Gemini grounded — it searches Google natively)
113
116
  let queries = [query]
114
- if (this.expander && opts.expand !== false) {
117
+ const usesGrounded = this.cascade.includes('gemini-grounded') || this.cascade.includes('gemini')
118
+ if (this.expander && opts.expand !== false && !usesGrounded) {
115
119
  queries = await this.expander.expand(query)
116
120
  }
117
121
 
@@ -16,17 +16,20 @@ async function scrapeUrls(urls, opts = {}) {
16
16
  const concurrent = opts.concurrent || 3
17
17
  const engine = opts.engine || 'auto' // 'jina', 'readability', 'auto'
18
18
 
19
- for (let i = 0; i < urls.length; i += concurrent) {
20
- const batch = urls.slice(i, i + concurrent)
21
- const promises = batch.map(url => scrapeUrl(url, { timeout, engine }).catch(() => null))
22
- const batchResults = await Promise.all(promises)
23
-
24
- batch.forEach((url, idx) => {
25
- if (batchResults[idx]) {
26
- results[url] = batchResults[idx]
27
- }
28
- })
29
- }
19
+ // All URLs in parallel (with per-URL timeout)
20
+ const promises = urls.map(url => {
21
+ const p = scrapeUrl(url, { timeout, engine }).catch(() => null)
22
+ // Hard timeout per URL
23
+ const timer = new Promise(resolve => setTimeout(() => resolve(null), timeout + 1000))
24
+ return Promise.race([p, timer])
25
+ })
26
+ const allResults = await Promise.all(promises)
27
+
28
+ urls.forEach((url, idx) => {
29
+ if (allResults[idx]) {
30
+ results[url] = allResults[idx]
31
+ }
32
+ })
30
33
 
31
34
  return results
32
35
  }