(args: z.infer<typeof SemanticSearchArgs>, ctx: ToolContext)
| 42 | argsSchema = SemanticSearchArgs; |
| 43 | |
| 44 | async execute(args: z.infer<typeof SemanticSearchArgs>, ctx: ToolContext): Promise<ToolResult> { |
| 45 | const root = args.path ? path.join(ctx.cwd, args.path) : ctx.cwd; |
| 46 | const topK = args.top_k ?? 10; |
| 47 | const model = args.embedding_model ?? 'nomic-embed-text'; |
| 48 | const maxFiles = args.max_files ?? 5000; |
| 49 | const baseUrl = process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434'; |
| 50 | |
| 51 | // Verify Ollama is reachable |
| 52 | try { |
| 53 | const r = await fetch(`${baseUrl}/api/tags`, { signal: ctx.signal }); |
| 54 | if (!r.ok) throw new Error(`Ollama returned HTTP ${r.status}`); |
| 55 | } catch (e: any) { |
| 56 | return { |
| 57 | content: `[SEMANTIC_SEARCH_ERROR] Ollama not reachable at ${baseUrl}: ${e?.message}\n\nInstall: https://ollama.com\nPull embed model: ollama pull nomic-embed-text`, |
| 58 | isError: true, |
| 59 | }; |
| 60 | } |
| 61 | |
| 62 | // Load or build index |
| 63 | const idxPath = indexPath(root, model); |
| 64 | let idx: Index | null = args.rebuild_index ? null : await loadIndex(idxPath); |
| 65 | |
| 66 | // Re-index if file count changed significantly (heuristic). |
| 67 | if (idx && !args.rebuild_index) { |
| 68 | const currentFiles = await walkSource(root, maxFiles); |
| 69 | const currentChunkCount = currentFiles.reduce((a, f) => a + Math.ceil(f.content.split('\n').length / 25), 0); |
| 70 | if (Math.abs(currentChunkCount - idx.chunks.length) > idx.chunks.length * 0.15) { |
| 71 | logger.info('Semantic search index stale (file count drifted >15%); rebuilding'); |
| 72 | idx = null; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | const buildMessages: string[] = []; |
| 77 | if (!idx) { |
| 78 | try { |
| 79 | idx = await buildIndex(root, model, baseUrl, maxFiles, ctx.signal, (msg) => buildMessages.push(msg)); |
| 80 | await persistIndex(root, model, idx); |
| 81 | } catch (e: any) { |
| 82 | return { |
| 83 | content: `[SEMANTIC_SEARCH_ERROR] Index build failed: ${e?.message}\n\nIf the error mentions "model not found", run:\n ollama pull ${model}`, |
| 84 | isError: true, |
| 85 | }; |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | // Embed query |
| 90 | let queryEmbedding: number[]; |
| 91 | try { |
| 92 | const [e] = await ollamaEmbed(baseUrl, model, [args.query], ctx.signal); |
| 93 | queryEmbedding = e!; |
| 94 | } catch (e: any) { |
| 95 | return { content: `[SEMANTIC_SEARCH_ERROR] Query embed failed: ${e?.message}`, isError: true }; |
| 96 | } |
| 97 | |
| 98 | // Hybrid (BM25 + semantic) ranking over the persisted index (SQLite preferred), |
| 99 | // unless the caller explicitly opts into semantic-only. |
| 100 | const scored = await searchPersisted(root, model, args.query, queryEmbedding, topK, idx, !!args.semantic_only); |
| 101 |
nothing calls this directly
no test coverage detected