File size: 7,467 Bytes
157862d
064bfd6
 
 
 
 
933d2c0
064bfd6
 
 
 
 
 
 
 
 
 
 
 
 
c681d98
064bfd6
 
 
c681d98
 
 
064bfd6
 
 
c681d98
 
064bfd6
 
 
 
 
 
 
c681d98
 
 
064bfd6
 
 
c681d98
064bfd6
 
 
 
04fbbc8
09db81c
04fbbc8
c681d98
 
3fcac91
 
c681d98
 
 
 
 
 
 
09db81c
c681d98
 
 
 
 
102a9c0
157862d
c681d98
76e6c36
c681d98
9fb8bdf
 
c681d98
064bfd6
c681d98
064bfd6
09db81c
c681d98
09db81c
 
 
 
 
c681d98
 
 
09db81c
c681d98
 
064bfd6
 
933d2c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fcac91
c681d98
3fcac91
 
c681d98
 
 
 
 
 
 
 
 
 
 
3fcac91
 
 
c681d98
3fcac91
 
c681d98
 
 
 
3fcac91
 
 
c681d98
064bfd6
933d2c0
acf3270
c681d98
064bfd6
 
c681d98
064bfd6
c681d98
064bfd6
09db81c
064bfd6
c681d98
 
064bfd6
 
c681d98
 
064bfd6
 
c681d98
064bfd6
 
 
c681d98
064bfd6
 
 
c681d98
064bfd6
157862d
064bfd6
c681d98
 
714ab7d
 
 
064bfd6
c681d98
064bfd6
 
 
c681d98
064bfd6
 
 
c681d98
064bfd6
 
 
c681d98
 
 
 
064bfd6
 
 
c681d98
 
 
064bfd6
76e6c36
c681d98
 
714ab7d
 
 
 
 
c681d98
 
 
102a9c0
 
c681d98
 
102a9c0
 
064bfd6
933d2c0
 
 
 
c681d98
09db81c
 
 
 
3fcac91
c681d98
 
 
 
 
 
 
 
 
064bfd6
9fb8bdf
 
76e6c36
714ab7d
 
 
 
 
064bfd6
76e6c36
9fb8bdf
 
 
76e6c36
064bfd6
76e6c36
714ab7d
 
 
 
 
064bfd6
 
 
c681d98
064bfd6
157862d
 
 
 
c681d98
157862d
 
c681d98
 
 
714ab7d
c681d98
 
064bfd6
714ab7d
 
c681d98
064bfd6
c681d98
064bfd6
714ab7d
064bfd6
 
c681d98
064bfd6
 
09db81c
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import type { PermissionResult } from '../../utils/permissions/PermissionResult.js'
import { z } from 'zod/v4'
import { buildTool, type ToolDef } from '../../Tool.js'
import { lazySchema } from '../../utils/lazySchema.js'
import { logError } from '../../utils/log.js'
import { getWebSearchPrompt, WEB_SEARCH_TOOL_NAME } from './prompt.js'
import { tavily } from '@tavily/core'
import {
  getToolUseSummary,
  renderToolResultMessage,
  renderToolUseMessage,
  renderToolUseProgressMessage,
} from './UI.js'

const inputSchema = lazySchema(() =>
  z.strictObject({
    query: z.string().min(2).describe('The search query to use'),
  }),
)

type Input = z.infer<ReturnType<typeof inputSchema>>

const searchResultSchema = lazySchema(() => {
  const searchHitSchema = z.object({
    title: z.string(),
    url: z.string(),
    snippet: z.string().optional(),
  })

  return z.object({
    tool_use_id: z.string(),
    content: z.array(searchHitSchema),
  })
})

export type SearchResult = z.infer<ReturnType<typeof searchResultSchema>>

const outputSchema = lazySchema(() =>
  z.object({
    query: z.string(),
    results: z.array(z.union([searchResultSchema(), z.string()])),
    durationSeconds: z.number(),
  }),
)

export type Output = z.infer<ReturnType<typeof outputSchema>>

export type { WebSearchProgress } from '../../types/tools.js'
import type { WebSearchProgress } from '../../types/tools.js'

/**
 * 使用 SearXNG 本地搜索
 */
async function searchSearXNG(
  query: string
): Promise<Array<{ title: string; url: string; snippet?: string }>> {
  try {
    const url = new URL('http://localhost:8080/search')
    url.searchParams.set('q', query)
    url.searchParams.set('format', 'json')

    const controller = new AbortController()
    const timeout = setTimeout(() => controller.abort(), 10000)

    const res = await fetch(url.toString(), {
      signal: controller.signal,
      headers: {
        'User-Agent': 'Mozilla/5.0 (compatible; WebSearchTool/1.0)',
        'Accept': 'application/json',
      },
    })

    clearTimeout(timeout)

    if (!res.ok) {
      const errorText = await res.text()
      throw new Error(`HTTP ${res.status}: ${errorText}`)
    }

    const data = await res.json()

    return (data.results || [])
      .slice(0, 10)
      .map((r: any) => ({
        title: r.title,
        url: r.url,
        snippet: r.content,
      }))
  } catch (error) {
    logError('SearXNG search failed', error)
    throw new Error(
      `SearXNG search failed: ${error instanceof Error ? error.message : String(error)}`
    )
  }
}

/**
 * 使用 Tavily 云搜索
 */
async function searchTavily(
  query: string
): Promise<Array<{ title: string; url: string; snippet?: string }>> {
  try {
    const apiKey = process.env.TAVILY_API_KEY
    if (!apiKey) {
      throw new Error('TAVILY_API_KEY is not set')
    }

    const client = tavily({ apiKey })
    const response = await client.search(query, {
      maxResults: 10,
      searchDepth: 'basic',
      topic: 'general',
    })

    return (response.results || []).map((r: any) => ({
      title: r.title,
      url: r.url,
      snippet: r.content,
    }))
  } catch (error) {
    logError('Tavily search failed', error)
    throw new Error(
      `Tavily search failed: ${error instanceof Error ? error.message : String(error)}`
    )
  }
}

/**
 * 文本清洗
 */
function stripTags(text: string): string {
  return text
    .replace(/<script[\s\S]*?<\/script>/gi, '')
    .replace(/<style[\s\S]*?<\/style>/gi, '')
    .replace(/<[^>]+>/g, '')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&nbsp;/g, ' ')
    .trim()
}

function normalizeText(text: string): string {
  return text.replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim()
}

function cleanSearchResult(result: any) {
  return {
    title: result.title ? normalizeText(stripTags(result.title)) : undefined,
    snippet: result.snippet ? normalizeText(stripTags(result.snippet)) : undefined,
  }
}

export const WebSearchTool = buildTool({
  name: WEB_SEARCH_TOOL_NAME,
  description: 'Search the web using local SearXNG or Tavily (when TAVILY_API_KEY is set)',
  shouldDefer: true,

  getToolUseSummary,
  getActivityDescription(input) {
    return input?.query ? `Searching for "${input.query}"` : 'Searching the web'
  },

  isEnabled() {
    return true
  },

  get inputSchema() {
    return inputSchema()
  },

  get outputSchema() {
    return outputSchema()
  },

  isConcurrencySafe() {
    return true
  },

  isReadOnly() {
    return true
  },

  toAutoClassifierInput(input) {
    return input?.query ?? ''
  },

  async checkPermissions(): Promise<PermissionResult> {
    return {
      behavior: 'allow',
    }
  },

  async prompt() {
    return getWebSearchPrompt()
  },

  renderToolUseMessage,
  renderToolUseProgressMessage,
  renderToolResultMessage,

  extractSearchText() {
    return ''
  },

  async validateInput(input) {
    if (!input?.query) {
      return { result: false, message: 'Missing query', errorCode: 1 }
    }
    return { result: true }
  },

  async call(input, _context, _canUseTool, _parentMessage, onProgress) {
    const start = performance.now()

    try {
      if (!input?.query || input.query.trim() === '') {
        return {
          data: {
            query: input?.query || '',
            results: ['Error: Missing query'],
            durationSeconds: (performance.now() - start) / 1000,
          },
        }
      }

      if (onProgress) {
        onProgress({
          toolUseID: 'search-start',
          data: { type: 'query_update', query: input.query },
        })
      }

      const useTavily = !!process.env.TAVILY_API_KEY
      const results = useTavily
        ? await searchTavily(input.query)
        : await searchSearXNG(input.query)

      const cleaned = results.map(r => ({
        ...r,
        ...cleanSearchResult(r),
      }))

      const output =
        cleaned.length === 0
          ? [`No results for: ${input.query}`]
          : [
              {
                tool_use_id: 'search-1',
                content: cleaned,
              },
            ]

      const duration = (performance.now() - start) / 1000

      return {
        data: {
          query: input.query,
          results: output,
          durationSeconds: duration,
        },
      }
    } catch (error) {
      const duration = (performance.now() - start) / 1000
      const errorMessage = error instanceof Error ? error.message : String(error)

      logError(error)

      return {
        data: {
          query: input?.query || '',
          results: [`Error: ${errorMessage}`],
          durationSeconds: duration,
        },
      }
    }
  },

  mapToolResultToToolResultBlockParam(output, toolUseID) {
    if (!output) {
      return {
        tool_use_id: toolUseID,
        type: 'tool_result',
        content: 'Error',
      }
    }

    let text = `Results for "${output.query}"\n\n`

    for (const r of output.results) {
      if (typeof r === 'string') {
        text += r + '\n\n'
      } else {
        r.content.forEach((item: any, i: number) => {
          text += `${i + 1}. ${item.title}\n${item.url}\n${item.snippet || ''}\n\n`
        })
      }
    }

    return {
      tool_use_id: toolUseID,
      type: 'tool_result',
      content: text,
    }
  },
}) satisfies ToolDef<any, Output, WebSearchProgress>