obsidian-hybrid-search 0.2.0 → 0.2.2

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/README.md CHANGED
@@ -40,8 +40,11 @@ export OBSIDIAN_VAULT_PATH="/path/to/your/vault"
40
40
 
41
41
  # Optional — only needed if using a remote embedding API instead of local model
42
42
  export OPENAI_API_KEY="sk-..."
43
- export OPENAI_BASE_URL="https://openrouter.ai/api/v1"
44
- export OPENAI_EMBEDDING_MODEL="openai/text-embedding-3-small"
43
+ # Default API base is https://api.openai.com/v1 — override for other providers:
44
+ # export OPENAI_BASE_URL="https://openrouter.ai/api/v1" # OpenRouter
45
+ # export OPENAI_BASE_URL="http://localhost:11434/v1" # Ollama (no key needed)
46
+ # export OPENAI_BASE_URL="http://localhost:1234/v1" # LM Studio (no key needed)
47
+ export OPENAI_EMBEDDING_MODEL="text-embedding-3-small"
45
48
  ```
46
49
 
47
50
  Without `OPENAI_API_KEY` the local `Xenova/all-MiniLM-L6-v2` model is used automatically (no API key needed, ~50 MB download on first run).
@@ -144,8 +147,7 @@ Add to your Claude MCP config (`.mcp.json` or `claude_desktop_config.json`):
144
147
  "OBSIDIAN_VAULT_PATH": "/path/to/your/vault",
145
148
  "OBSIDIAN_IGNORE_PATTERNS": ".obsidian/**,templates/**,*.canvas",
146
149
  "OPENAI_API_KEY": "sk-...",
147
- "OPENAI_BASE_URL": "https://openrouter.ai/api/v1",
148
- "OPENAI_EMBEDDING_MODEL": "openai/text-embedding-3-small"
150
+ "OPENAI_EMBEDDING_MODEL": "text-embedding-3-small"
149
151
  }
150
152
  }
151
153
  }
@@ -170,9 +172,9 @@ The server exposes three tools:
170
172
  |----------------------|---------|-------------|
171
173
  | `OBSIDIAN_VAULT_PATH` | *(required)* | Absolute path to your vault |
172
174
  | `OBSIDIAN_IGNORE_PATTERNS` | `.obsidian/**,templates/**,*.canvas` | Comma-separated ignore patterns |
173
- | `OPENAI_API_KEY` | — | API key (omit for local embeddings) |
174
- | `OPENAI_BASE_URL` | `https://openrouter.ai/api/v1` | API base URL |
175
- | `OPENAI_EMBEDDING_MODEL` | `openai/text-embedding-3-small` | Embedding model name |
175
+ | `OPENAI_API_KEY` | — | API key; omit to use local Xenova embeddings or keyless servers (Ollama, LM Studio) |
176
+ | `OPENAI_BASE_URL` | `https://api.openai.com/v1` | API base URL |
177
+ | `OPENAI_EMBEDDING_MODEL` | `text-embedding-3-small` | Embedding model name |
176
178
 
177
179
  ### Ignore patterns
178
180
 
package/dist/src/cli.js CHANGED
@@ -164,7 +164,7 @@ program
164
164
  indexed: stats.indexed,
165
165
  pending: stats.pending,
166
166
  last_indexed: stats.lastIndexed,
167
- model: config.apiKey ? config.apiModel : 'Xenova/all-MiniLM-L6-v2 (local)',
167
+ model: (config.apiKey || process.env.OPENAI_BASE_URL) ? config.apiModel : 'Xenova/all-MiniLM-L6-v2 (local)',
168
168
  context_length: contextLength,
169
169
  }, null, 2));
170
170
  });
@@ -16,10 +16,10 @@ export const config = {
16
16
  return process.env.OPENAI_API_KEY;
17
17
  },
18
18
  get apiBaseUrl() {
19
- return process.env.OPENAI_BASE_URL ?? 'https://openrouter.ai/api/v1';
19
+ return process.env.OPENAI_BASE_URL ?? 'https://api.openai.com/v1';
20
20
  },
21
21
  get apiModel() {
22
- return process.env.OPENAI_EMBEDDING_MODEL ?? 'openai/text-embedding-3-small';
22
+ return process.env.OPENAI_EMBEDDING_MODEL ?? 'text-embedding-3-small';
23
23
  },
24
24
  get dbPath() {
25
25
  const v = process.env.OBSIDIAN_VAULT_PATH;
@@ -89,14 +89,17 @@ const KNOWN_CONTEXT_LENGTHS = {
89
89
  export async function getContextLength() {
90
90
  if (cachedContextLength !== null)
91
91
  return cachedContextLength;
92
- if (config.apiKey) {
93
- // Check known models first
92
+ if (useApiMode()) {
93
+ // Check known models first — avoids an API roundtrip
94
94
  if (KNOWN_CONTEXT_LENGTHS[config.apiModel]) {
95
95
  cachedContextLength = KNOWN_CONTEXT_LENGTHS[config.apiModel];
96
96
  return cachedContextLength;
97
97
  }
98
98
  try {
99
- const res = await fetch(`${config.apiBaseUrl}/models/${config.apiModel}`, { headers: { Authorization: `Bearer ${config.apiKey}` } });
99
+ const headers = {};
100
+ if (config.apiKey)
101
+ headers['Authorization'] = `Bearer ${config.apiKey}`;
102
+ const res = await fetch(`${config.apiBaseUrl}/models/${config.apiModel}`, { headers });
100
103
  const data = await res.json();
101
104
  cachedContextLength = data.context_length ?? config.chunkContextFallback;
102
105
  return cachedContextLength;
@@ -136,28 +139,42 @@ async function getLocalPipeline() {
136
139
  }
137
140
  return localPipeline;
138
141
  }
142
+ // Ollama queues requests internally — parallel batches don't help and can crash
143
+ // buggy versions (v0.12.5+ bug: requests >2KB crash the server).
144
+ function isOllamaEndpoint() {
145
+ const url = config.apiBaseUrl.toLowerCase();
146
+ return url.includes('11434') || url.includes('ollama');
147
+ }
148
+ // Use API mode when an API key is set OR when a custom base URL is configured
149
+ // (e.g. Ollama, LM Studio, local OpenAI-compatible servers — no key required)
150
+ function useApiMode() {
151
+ return !!(config.apiKey || process.env.OPENAI_BASE_URL);
152
+ }
139
153
  export async function embed(texts) {
140
- if (config.apiKey) {
154
+ if (useApiMode()) {
141
155
  return embedViaApi(texts);
142
156
  }
143
157
  return embedLocal(texts);
144
158
  }
145
159
  async function embedViaApi(texts) {
146
160
  const results = [];
147
- for (let i = 0; i < texts.length; i += config.batchSize) {
148
- const batch = texts.slice(i, i + config.batchSize);
161
+ // Ollama: send one at a time to avoid the >2KB crash bug in v0.12.5+
162
+ // and because Ollama queues internally anyway (batching gives no speedup)
163
+ const batchSize = isOllamaEndpoint() ? 1 : config.batchSize;
164
+ for (let i = 0; i < texts.length; i += batchSize) {
165
+ const batch = texts.slice(i, i + batchSize);
149
166
  const batchResults = await embedApiBatchWithFallback(batch);
150
167
  results.push(...batchResults);
151
168
  }
152
169
  return results;
153
170
  }
154
171
  async function embedApiBatch(texts) {
172
+ const headers = { 'Content-Type': 'application/json' };
173
+ if (config.apiKey)
174
+ headers['Authorization'] = `Bearer ${config.apiKey}`;
155
175
  const res = await fetch(`${config.apiBaseUrl}/embeddings`, {
156
176
  method: 'POST',
157
- headers: {
158
- Authorization: `Bearer ${config.apiKey}`,
159
- 'Content-Type': 'application/json',
160
- },
177
+ headers,
161
178
  body: JSON.stringify({ model: config.apiModel, input: texts }),
162
179
  });
163
180
  if (!res.ok) {
@@ -87,7 +87,10 @@ export async function indexFile(fullPath, contextLength, force = false) {
87
87
  if (chunks.length === 0) {
88
88
  return 'skipped';
89
89
  }
90
- const embeddings = await embed(chunks.map(c => c.text));
90
+ // Prepend title to first chunk — improves semantic recall for the note as a whole
91
+ // (idea from obsidian-similar-notes plugin)
92
+ const textsToEmbed = chunks.map((c, i) => i === 0 && title ? `${title}\n${c.text}` : c.text);
93
+ const embeddings = await embed(textsToEmbed);
91
94
  upsertNote({
92
95
  path: relPath,
93
96
  title,
@@ -188,11 +188,50 @@ function rrfFusion(lists, k = 60) {
188
188
  .sort((a, b) => b.rrfScore - a.rrfScore)
189
189
  .map(({ rrfScore, result }) => ({ ...result, score: rrfScore / maxPossibleScore }));
190
190
  }
191
+ // ─── LRU cache ───────────────────────────────────────────
192
+ // Avoids redundant searches when the same query is repeated (common in MCP usage).
193
+ // Path-based lookups are cached by path:mtime so stale entries auto-invalidate.
194
+ class LRUCache {
195
+ maxSize;
196
+ map = new Map();
197
+ constructor(maxSize) {
198
+ this.maxSize = maxSize;
199
+ }
200
+ get(key) {
201
+ const val = this.map.get(key);
202
+ if (val !== undefined) {
203
+ this.map.delete(key);
204
+ this.map.set(key, val);
205
+ }
206
+ return val;
207
+ }
208
+ set(key, val) {
209
+ if (this.map.has(key))
210
+ this.map.delete(key);
211
+ else if (this.map.size >= this.maxSize)
212
+ this.map.delete(this.map.keys().next().value);
213
+ this.map.set(key, val);
214
+ }
215
+ }
216
+ const searchCache = new LRUCache(20);
217
+ function cacheKey(input, options) {
218
+ return `${input}\0${options.mode ?? ''}\0${options.scope ?? ''}\0${options.limit ?? ''}\0${options.threshold ?? ''}\0${options.tag ?? ''}`;
219
+ }
191
220
  export async function search(input, options = {}) {
192
221
  const mode = options.mode ?? 'hybrid';
193
222
  const limit = options.limit ?? 10;
194
223
  const threshold = options.threshold ?? 0.0;
195
224
  const isPathLookup = input.includes('/') || input.endsWith('.md');
225
+ // For path lookups, include mtime in cache key so stale entries auto-invalidate
226
+ let key = cacheKey(input, options);
227
+ if (isPathLookup) {
228
+ const note = getNoteByPath(input.normalize('NFD'));
229
+ if (note)
230
+ key += `\0${note.mtime}`;
231
+ }
232
+ const cached = searchCache.get(key);
233
+ if (cached)
234
+ return cached;
196
235
  let results;
197
236
  if (isPathLookup) {
198
237
  results = await searchSimilar(input, limit);
@@ -207,11 +246,13 @@ export async function search(input, options = {}) {
207
246
  results = results.slice(0, limit);
208
247
  const paths = results.map(r => r.path);
209
248
  const { links, backlinks } = getLinksForPaths(paths);
210
- return results.map(r => ({
249
+ const final = results.map(r => ({
211
250
  ...toSearchResult(r),
212
251
  links: links.get(r.path) ?? [],
213
252
  backlinks: backlinks.get(r.path) ?? [],
214
253
  }));
254
+ searchCache.set(key, final);
255
+ return final;
215
256
  }
216
257
  async function searchByQuery(query, mode, limit) {
217
258
  if (mode === 'fulltext') {
@@ -18,7 +18,7 @@ async function main() {
18
18
  ignorePatternsCsv: config.ignorePatterns.join(','),
19
19
  });
20
20
  // Check if model changed — wipes DB if so, forces full reindex
21
- const modelName = config.apiKey ? config.apiModel : 'local:Xenova/all-MiniLM-L6-v2';
21
+ const modelName = (config.apiKey || process.env.OPENAI_BASE_URL) ? config.apiModel : 'local:Xenova/all-MiniLM-L6-v2';
22
22
  const modelChanged = checkModelChanged(modelName);
23
23
  if (modelChanged) {
24
24
  console.error('[server] embedding model changed — database cleared, full reindex will run');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "obsidian-hybrid-search",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "obsidian-hybrid-search": "./dist/src/cli.js",