@arabold/docs-mcp-server 3.3.0 → 3.4.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.
@@ -1,2 +0,0 @@
1
- import { a as getGlobalOptions, c as resolveEmbeddingContext, d as validatePort, f as validateResumeFlag, i as getEventBus, l as resolveProtocol, n as createAppServerConfig, o as handleEmbeddingModelChange, r as ensurePlaywrightBrowsersInstalled, s as parseHeaders, t as checkAuthForProtocol, u as validateHost } from "./utils-DXo1A54z.js";
2
- export { checkAuthForProtocol, createAppServerConfig, ensurePlaywrightBrowsersInstalled, getEventBus, getGlobalOptions, handleEmbeddingModelChange, parseHeaders, resolveEmbeddingContext, resolveProtocol, validateHost, validatePort, validateResumeFlag };
@@ -1,675 +0,0 @@
1
- import { t as normalizeEnvValue } from "./env-DONvEfR5.js";
2
- import { r as logger } from "./logger-BBxstTD7.js";
3
- import fs, { existsSync } from "node:fs";
4
- import path from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import envPaths from "env-paths";
7
- import { chromium } from "playwright";
8
- import { execSync } from "node:child_process";
9
- import { createInterface } from "node:readline";
10
- //#region src/store/embeddings/EmbeddingConfig.ts
11
- /**
12
- * Shared embedding model configuration service.
13
- * Provides synchronous parsing of embedding model configuration and known dimensions lookup.
14
- * Eliminates code duplication between DocumentStore and telemetry systems.
15
- *
16
- * All model lookups are case-insensitive to handle variations in model name capitalization.
17
- * Uses class-based approach to avoid mutable global state and improve testability.
18
- */
19
- /**
20
- * The complete set of provider prefixes recognized in a model specification.
21
- * Anything else before the first colon is part of the model name itself.
22
- *
23
- * This list is normative rather than descriptive: it decides which prefixes claim
24
- * the provider slot, so adding an entry changes how existing specifications parse.
25
- * A model literally named `<new-provider>:<tag>` served by an OpenAI-compatible
26
- * endpoint would start resolving to the new provider, breaking that configuration
27
- * on upgrade. Call provider additions out in the release notes.
28
- *
29
- * `EmbeddingProvider` is derived from this array so the two cannot drift apart.
30
- */
31
- var SUPPORTED_PROVIDERS = [
32
- "openai",
33
- "vertex",
34
- "gemini",
35
- "aws",
36
- "microsoft"
37
- ];
38
- /**
39
- * Split a model specification into its provider prefix and model name.
40
- *
41
- * Only a prefix that names a supported provider is treated as a provider, matched
42
- * case-insensitively and resolved to its canonical lowercase form. Every other
43
- * specification is an OpenAI-compatible model name, which keeps names that carry a
44
- * tag or quantization suffix intact (e.g. "nomic-embed-text:latest" or
45
- * "second-state/jina-embeddings-v3-GGUF:Q4_K_M").
46
- *
47
- * @param spec The full model specification.
48
- * @returns The resolved provider and model name.
49
- */
50
- function splitModelSpec(spec) {
51
- const colonIndex = spec.indexOf(":");
52
- const prefix = spec.substring(0, colonIndex).toLowerCase();
53
- const provider = colonIndex === -1 ? void 0 : SUPPORTED_PROVIDERS.find((name) => name === prefix);
54
- return provider ? {
55
- provider,
56
- model: spec.substring(colonIndex + 1)
57
- } : {
58
- provider: "openai",
59
- model: spec
60
- };
61
- }
62
- /**
63
- * Embedding configuration manager that handles model parsing and dimension caching.
64
- * Encapsulates state to avoid global variable issues and improve testability.
65
- */
66
- var EmbeddingConfig = class EmbeddingConfig {
67
- static instance = null;
68
- /**
69
- * Get the singleton instance of EmbeddingConfig.
70
- * Creates the instance if it doesn't exist.
71
- */
72
- static getInstance() {
73
- if (EmbeddingConfig.instance === null) EmbeddingConfig.instance = new EmbeddingConfig();
74
- return EmbeddingConfig.instance;
75
- }
76
- /**
77
- * Reset the singleton instance (useful for testing).
78
- */
79
- static resetInstance() {
80
- EmbeddingConfig.instance = null;
81
- }
82
- /**
83
- * Known dimensions for common embedding models.
84
- * This avoids expensive API calls for dimension detection in telemetry.
85
- *
86
- * Note: The "openai" provider also supports OpenAI-compatible APIs like:
87
- * - Ollama (local models)
88
- * - LMStudio (local models)
89
- * - Any service implementing OpenAI's embedding API
90
- */
91
- knownModelDimensions = {
92
- "text-embedding-3-small": 1536,
93
- "text-embedding-3-large": 3072,
94
- "text-embedding-ada-002": 1536,
95
- "text-embedding-004": 768,
96
- "text-embedding-005": 768,
97
- "textembedding-gecko@003": 768,
98
- "textembedding-gecko@002": 768,
99
- "textembedding-gecko@001": 768,
100
- "text-embedding-preview-0409": 768,
101
- "embedding-001": 768,
102
- "gemini-embedding-2-preview": 3072,
103
- "amazon.titan-embed-text-v1": 1536,
104
- "amazon.titan-embed-text-v2:0": 1024,
105
- "amazon.titan-embed-image-v1": 1024,
106
- "cohere.embed-english-v3": 1024,
107
- "cohere.embed-multilingual-v3": 1024,
108
- "Cohere/Cohere-embed-v4.0": 1536,
109
- "embed-v4.0": 1536,
110
- "intfloat/multilingual-e5-large": 1024,
111
- "multilingual-e5-large": 1024,
112
- "text-embedding-multilingual-e5-large": 1024,
113
- "sentence-transformers/all-MiniLM-L6-v2": 384,
114
- "gemini-embedding-001": 3072,
115
- "Qwen/Qwen3-Embedding-8B": 4096,
116
- "Qwen/Qwen3-Embedding-4B": 2560,
117
- "Qwen/Qwen3-Embedding-0.6B": 1024,
118
- "Linq-AI-Research/Linq-Embed-Mistral": 4096,
119
- "Alibaba-NLP/gte-Qwen2-7B-instruct": 3584,
120
- "intfloat/multilingual-e5-large-instruct": 1024,
121
- "Salesforce/SFR-Embedding-Mistral": 4096,
122
- "text-multilingual-embedding-002": 768,
123
- "GritLM/GritLM-7B": 4096,
124
- "GritLM/GritLM-8x7B": 4096,
125
- "intfloat/e5-mistral-7b-instruct": 4096,
126
- "Cohere/Cohere-embed-multilingual-v3.0": 1024,
127
- "Alibaba-NLP/gte-Qwen2-1.5B-instruct": 8960,
128
- "Lajavaness/bilingual-embedding-large": 1024,
129
- "Salesforce/SFR-Embedding-2_R": 4096,
130
- "NovaSearch/stella_en_1.5B_v5": 8960,
131
- "NovaSearch/jasper_en_vision_language_v1": 8960,
132
- "nvidia/NV-Embed-v2": 4096,
133
- "OrdalieTech/Solon-embeddings-large-0.1": 1024,
134
- "BAAI/bge-m3": 1024,
135
- "HIT-TMG/KaLM-embedding-multilingual-mini-v1": 896,
136
- "jinaai/jina-embeddings-v3": 1024,
137
- "Alibaba-NLP/gte-multilingual-base": 768,
138
- "Lajavaness/bilingual-embedding-base": 768,
139
- "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1": 896,
140
- "nvidia/NV-Embed-v1": 4096,
141
- "Cohere/Cohere-embed-multilingual-light-v3.0": 384,
142
- "manu/bge-m3-custom-fr": 1024,
143
- "Lajavaness/bilingual-embedding-small": 384,
144
- "Snowflake/snowflake-arctic-embed-l-v2.0": 1024,
145
- "intfloat/multilingual-e5-base": 768,
146
- "voyage-3-lite": 512,
147
- "voyage-3": 1024,
148
- "voyage-3-large": 1024,
149
- "voyage-3.5": 1024,
150
- "voyage-4": 1024,
151
- "voyage-4-large": 1024,
152
- "voyage-4-lite": 1024,
153
- "voyage-code-3": 1024,
154
- "intfloat/multilingual-e5-small": 384,
155
- "Alibaba-NLP/gte-Qwen1.5-7B-instruct": 4096,
156
- "Snowflake/snowflake-arctic-embed-m-v2.0": 768,
157
- "deepvk/USER-bge-m3": 1024,
158
- "Cohere/Cohere-embed-english-v3.0": 1024,
159
- "Omartificial-Intelligence-Space/Arabic-labse-Matryoshka": 768,
160
- "ibm-granite/granite-embedding-278m-multilingual": 768,
161
- "NovaSearch/stella_en_400M_v5": 4096,
162
- "omarelshehy/arabic-english-sts-matryoshka": 1024,
163
- "sentence-transformers/paraphrase-multilingual-mpnet-base-v2": 768,
164
- "Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka": 768,
165
- "Haon-Chen/speed-embedding-7b-instruct": 4096,
166
- "sentence-transformers/LaBSE": 768,
167
- "WhereIsAI/UAE-Large-V1": 1024,
168
- "ibm-granite/granite-embedding-107m-multilingual": 384,
169
- "mixedbread-ai/mxbai-embed-large-v1": 1024,
170
- "intfloat/e5-large-v2": 1024,
171
- "avsolatorio/GIST-large-Embedding-v0": 1024,
172
- "sdadas/mmlw-e5-large": 1024,
173
- "nomic-ai/nomic-embed-text-v1": 768,
174
- "nomic-embed-text-v1": 768,
175
- "nomic-ai/nomic-embed-text-v1-ablated": 768,
176
- "nomic-ai/nomic-embed-text-v2-moe": 768,
177
- "nomic-ai/modernbert-embed-base": 768,
178
- "nomic-ai/nomic-embed-code": 3584,
179
- "intfloat/e5-base-v2": 768,
180
- "BAAI/bge-large-en-v1.5": 1024,
181
- "intfloat/e5-large": 1024,
182
- "Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet": 384,
183
- "Cohere/Cohere-embed-english-light-v3.0": 384,
184
- "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2": 768,
185
- "Gameselo/STS-multilingual-mpnet-base-v2": 768,
186
- "thenlper/gte-large": 1024,
187
- "avsolatorio/GIST-Embedding-v0": 768,
188
- "nomic-ai/nomic-embed-text-v1-unsupervised": 768,
189
- "infgrad/stella-base-en-v2": 768,
190
- "avsolatorio/NoInstruct-small-Embedding-v0": 384,
191
- "dwzhu/e5-base-4k": 768,
192
- "sdadas/mmlw-e5-base": 768,
193
- "voyage-multilingual-2": 1024,
194
- "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised": 4096,
195
- "BAAI/bge-base-en-v1.5": 768,
196
- "avsolatorio/GIST-small-Embedding-v0": 384,
197
- "sdadas/mmlw-roberta-large": 1024,
198
- "nomic-ai/nomic-embed-text-v1.5": 768,
199
- "nomic-embed-text-v1.5": 768,
200
- "text-embedding-nomic-embed-text-v1.5": 768,
201
- "minishlab/potion-multilingual-128M": 256,
202
- "shibing624/text2vec-base-multilingual": 384,
203
- "thenlper/gte-base": 768,
204
- "intfloat/e5-small-v2": 384,
205
- "intfloat/e5-base": 768,
206
- "sentence-transformers/static-similarity-mrl-multilingual-v1": 1024,
207
- "manu/sentence_croissant_alpha_v0.3": 2048,
208
- "BAAI/bge-small-en-v1.5": 512,
209
- "thenlper/gte-small": 384,
210
- "sdadas/mmlw-e5-small": 384,
211
- "manu/sentence_croissant_alpha_v0.4": 2048,
212
- "manu/sentence_croissant_alpha_v0.2": 2048,
213
- "abhinand/MedEmbed-small-v0.1": 384,
214
- "ibm-granite/granite-embedding-125m-english": 768,
215
- "intfloat/e5-small": 384,
216
- "voyage-large-2-instruct": 1024,
217
- "sdadas/mmlw-roberta-base": 768,
218
- "Snowflake/snowflake-arctic-embed-l": 1024,
219
- "Mihaiii/Ivysaur": 384,
220
- "Snowflake/snowflake-arctic-embed-m-long": 768,
221
- "bigscience/sgpt-bloom-7b1-msmarco": 4096,
222
- "avsolatorio/GIST-all-MiniLM-L6-v2": 384,
223
- "sergeyzh/LaBSE-ru-turbo": 768,
224
- "sentence-transformers/all-mpnet-base-v2": 768,
225
- "Snowflake/snowflake-arctic-embed-m": 768,
226
- "Snowflake/snowflake-arctic-embed-s": 384,
227
- "sentence-transformers/all-MiniLM-L12-v2": 384,
228
- "Mihaiii/gte-micro-v4": 384,
229
- "Snowflake/snowflake-arctic-embed-m-v1.5": 768,
230
- "cointegrated/LaBSE-en-ru": 768,
231
- "Mihaiii/Bulbasaur": 384,
232
- "ibm-granite/granite-embedding-30m-english": 384,
233
- "deepfile/embedder-100p": 768,
234
- "Jaume/gemma-2b-embeddings": 2048,
235
- "OrlikB/KartonBERT-USE-base-v1": 768,
236
- "izhx/udever-bloom-7b1": 4096,
237
- "izhx/udever-bloom-1b1": 1024,
238
- "brahmairesearch/slx-v0.1": 384,
239
- "Mihaiii/Wartortle": 384,
240
- "izhx/udever-bloom-3b": 2048,
241
- "deepvk/USER-base": 768,
242
- "ai-forever/ru-en-RoSBERTa": 1024,
243
- "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse": 4096,
244
- "Mihaiii/Venusaur": 384,
245
- "Snowflake/snowflake-arctic-embed-xs": 384,
246
- "jinaai/jina-embedding-b-en-v1": 768,
247
- "Mihaiii/gte-micro": 384,
248
- "aari1995/German_Semantic_STS_V2": 1024,
249
- "Mihaiii/Squirtle": 384,
250
- "OrlikB/st-polish-kartonberta-base-alpha-v1": 768,
251
- "sergeyzh/rubert-tiny-turbo": 312,
252
- "minishlab/potion-base-8M": 256,
253
- "minishlab/M2V_base_glove_subword": 256,
254
- "jinaai/jina-embedding-s-en-v1": 512,
255
- "minishlab/potion-base-4M": 128,
256
- "minishlab/M2V_base_output": 256,
257
- "DeepPavlov/rubert-base-cased-sentence": 768,
258
- "jinaai/jina-embeddings-v2-small-en": 512,
259
- "cointegrated/rubert-tiny2": 312,
260
- "minishlab/M2V_base_glove": 256,
261
- "cointegrated/rubert-tiny": 312,
262
- "silma-ai/silma-embeddding-matryoshka-v0.1": 768,
263
- "DeepPavlov/rubert-base-cased": 768,
264
- "Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet": 768,
265
- "izhx/udever-bloom-560m": 1024,
266
- "minishlab/potion-base-2M": 64,
267
- "DeepPavlov/distilrubert-small-cased-conversational": 768,
268
- "consciousAI/cai-lunaris-text-embeddings": 1024,
269
- "deepvk/deberta-v1-base": 768,
270
- "Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka": 768,
271
- "Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka": 768,
272
- "ai-forever/sbert_large_mt_nlu_ru": 1024,
273
- "ai-forever/sbert_large_nlu_ru": 1024,
274
- "malenia1/ternary-weight-embedding": 1024,
275
- "jinaai/jina-embeddings-v2-base-en": 768,
276
- "VPLabs/SearchMap_Preview": 4096,
277
- "Hum-Works/lodestone-base-4096-v1": 768,
278
- "jinaai/jina-embeddings-v4": 2048
279
- };
280
- runtimeDetectedDimensionModels = /* @__PURE__ */ new Set([
281
- "novasearch/stella_en_1.5b_v5",
282
- "stella_en_1.5b_v5",
283
- "novasearch/stella_en_400m_v5",
284
- "dunzhang/stella_en_400m_v5",
285
- "stella_en_400m_v5",
286
- "novasearch/jasper_en_vision_language_v1",
287
- "jasper_en_vision_language_v1"
288
- ]);
289
- /**
290
- * Lowercase lookup map for case-insensitive model dimension queries.
291
- * Built lazily from knownModelDimensions to ensure consistency.
292
- */
293
- modelLookup;
294
- constructor() {
295
- this.modelLookup = /* @__PURE__ */ new Map();
296
- for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) this.modelLookup.set(model.toLowerCase(), dimensions);
297
- }
298
- /**
299
- * Build the lookup keys to try for a model name, most specific first:
300
- * the name itself, then with the namespace dropped, the tag dropped, and both.
301
- *
302
- * Dropping a trailing tag lets a quantized or tagged variant reuse the base
303
- * model's dimensions (e.g. "nomic-ai/nomic-embed-text-v2-moe:latest"), which
304
- * quantization does not change. Exact matches are tried first, so names whose
305
- * own identifier contains a colon (e.g. "amazon.titan-embed-text-v2:0") still
306
- * resolve to their own entry.
307
- */
308
- dimensionLookupKeys(normalized) {
309
- const slashIndex = normalized.lastIndexOf("/");
310
- const withoutNamespace = slashIndex > -1 ? normalized.substring(slashIndex + 1) : void 0;
311
- const bases = withoutNamespace ? [normalized, withoutNamespace] : [normalized];
312
- const withoutTag = (key) => {
313
- const colonIndex = key.lastIndexOf(":");
314
- return colonIndex > 0 ? [key.substring(0, colonIndex)] : [];
315
- };
316
- return [...bases, ...bases.flatMap(withoutTag)];
317
- }
318
- findKnownDimension(model) {
319
- for (const key of this.dimensionLookupKeys(model.toLowerCase())) {
320
- if (this.runtimeDetectedDimensionModels.has(key)) return null;
321
- const dimensions = this.modelLookup?.get(key);
322
- if (dimensions !== void 0) return dimensions;
323
- }
324
- return null;
325
- }
326
- /**
327
- * Parse embedding model configuration from a provided model specification.
328
- * This is a synchronous operation that extracts provider, model, and known dimensions.
329
- *
330
- * Supports various providers:
331
- * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)
332
- * - vertex: Google Cloud Vertex AI
333
- * - gemini: Google Generative AI
334
- * - aws: AWS Bedrock models
335
- * - microsoft: Azure OpenAI
336
- *
337
- * @param modelSpec Model specification (e.g., "openai:text-embedding-3-small"), defaults to "text-embedding-3-small"
338
- * @returns Parsed embedding model configuration
339
- */
340
- parse(modelSpec) {
341
- const spec = normalizeEnvValue(modelSpec || "text-embedding-3-small");
342
- const { provider, model } = splitModelSpec(spec);
343
- return {
344
- provider,
345
- model,
346
- dimensions: this.findKnownDimension(model),
347
- modelSpec: spec
348
- };
349
- }
350
- /**
351
- * Get the known dimensions for a specific model.
352
- * Returns null if the model dimensions are not known.
353
- * Uses case-insensitive lookup.
354
- *
355
- * @param model The model name (e.g., "text-embedding-3-small")
356
- * @returns Known dimensions or null
357
- */
358
- getKnownDimensions(model) {
359
- return this.findKnownDimension(model);
360
- }
361
- /**
362
- * Add or update known dimensions for a model.
363
- * This can be used to cache discovered dimensions.
364
- * Stores both original case and lowercase for consistent lookup.
365
- *
366
- * @param model The model name
367
- * @param dimensions The dimensions to cache
368
- */
369
- setKnownDimensions(model, dimensions) {
370
- this.knownModelDimensions[model] = dimensions;
371
- if (this.modelLookup) this.modelLookup.set(model.toLowerCase(), dimensions);
372
- }
373
- /**
374
- * Static method to parse embedding model configuration using the singleton instance.
375
- * This maintains backward compatibility while using the class-based approach.
376
- */
377
- static parseEmbeddingConfig(modelSpec) {
378
- return EmbeddingConfig.getInstance().parse(modelSpec);
379
- }
380
- /**
381
- * Static method to get known model dimensions using the singleton instance.
382
- * This maintains backward compatibility while using the class-based approach.
383
- */
384
- static getKnownModelDimensions(model) {
385
- return EmbeddingConfig.getInstance().getKnownDimensions(model);
386
- }
387
- /**
388
- * Static method to set known model dimensions using the singleton instance.
389
- * This maintains backward compatibility while using the class-based approach.
390
- */
391
- static setKnownModelDimensions(model, dimensions) {
392
- EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);
393
- }
394
- };
395
- //#endregion
396
- //#region src/utils/paths.ts
397
- var projectRoot = null;
398
- /**
399
- * Finds the project root directory by searching upwards from the current file
400
- * for a directory containing 'package.json'. Caches the result.
401
- *
402
- * @returns {string} The absolute path to the project root.
403
- * @throws {Error} If package.json cannot be found.
404
- */
405
- function getProjectRoot() {
406
- if (projectRoot) return projectRoot;
407
- const currentFilePath = fileURLToPath(import.meta.url);
408
- let currentDir = path.dirname(currentFilePath);
409
- while (true) {
410
- const packageJsonPath = path.join(currentDir, "package.json");
411
- if (fs.existsSync(packageJsonPath)) {
412
- projectRoot = currentDir;
413
- return currentDir;
414
- }
415
- const parentDir = path.dirname(currentDir);
416
- if (parentDir === currentDir) throw new Error("Could not find project root containing package.json.");
417
- currentDir = parentDir;
418
- }
419
- }
420
- /**
421
- * Resolves the data storage path using the following priority:
422
- * 1. Provided storePath parameter
423
- * 2. Legacy .store directory in project root (if exists)
424
- * 3. Standard system data directory using env-paths
425
- *
426
- * @param storePath Optional custom storage path
427
- * @returns Resolved absolute path for data storage
428
- */
429
- function resolveStorePath(storePath) {
430
- let dbDir;
431
- if (storePath) dbDir = path.resolve(storePath);
432
- else {
433
- const projectRoot = getProjectRoot();
434
- const oldDbDir = path.join(projectRoot, ".store");
435
- const oldDbPath = path.join(oldDbDir, "documents.db");
436
- if (fs.existsSync(oldDbPath)) dbDir = oldDbDir;
437
- else dbDir = envPaths("docs-mcp-server", { suffix: "" }).data;
438
- }
439
- try {
440
- fs.mkdirSync(dbDir, { recursive: true });
441
- } catch (error) {
442
- logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);
443
- }
444
- return dbDir;
445
- }
446
- //#endregion
447
- //#region src/cli/utils.ts
448
- /**
449
- * Shared CLI utilities and helper functions.
450
- */
451
- /**
452
- * Retrieves the global EventBusService from the arguments context.
453
- * @param argv The parsed arguments context.
454
- * @returns The global EventBusService.
455
- * @throws Error if EventBusService is not initialized.
456
- */
457
- function getEventBus(argv) {
458
- const eventBus = argv._eventBus;
459
- if (!eventBus) throw new Error("EventBusService not initialized");
460
- return eventBus;
461
- }
462
- /**
463
- * Helper to extract GlobalOptions from the argv.
464
- * In Yargs, all options are in argv, so we just cast/pick.
465
- */
466
- function getGlobalOptions(argv) {
467
- return argv;
468
- }
469
- /**
470
- * Ensures that the Playwright browsers are installed, unless a system Chromium path is set.
471
- */
472
- function ensurePlaywrightBrowsersInstalled() {
473
- if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === "1") {
474
- logger.debug("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.");
475
- return;
476
- }
477
- const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
478
- if (chromiumEnvPath && existsSync(chromiumEnvPath)) {
479
- logger.debug(`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`);
480
- return;
481
- }
482
- try {
483
- const chromiumPath = chromium.executablePath();
484
- if (!chromiumPath || !existsSync(chromiumPath)) throw new Error("Playwright Chromium browser not found");
485
- } catch (error) {
486
- logger.debug(String(error));
487
- try {
488
- logger.info("🌐 Installing Playwright Chromium browser... (this may take a moment)");
489
- execSync("npm exec -y playwright install --no-shell --with-deps chromium", {
490
- stdio: "ignore",
491
- cwd: getProjectRoot()
492
- });
493
- } catch (_installErr) {
494
- logger.error("❌ Failed to install Playwright browsers automatically. Please run:\n npx playwright install --no-shell --with-deps chromium\nand try again.");
495
- process.exit(1);
496
- }
497
- }
498
- }
499
- /**
500
- * Resolves the protocol based on auto-detection or explicit specification.
501
- * Auto-detection uses TTY status to determine appropriate protocol.
502
- */
503
- function resolveProtocol(protocol) {
504
- if (protocol === "auto") {
505
- if (!process.stdin.isTTY && !process.stdout.isTTY) return "stdio";
506
- return "http";
507
- }
508
- if (protocol === "stdio" || protocol === "http") return protocol;
509
- throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);
510
- }
511
- /**
512
- * Validates that --resume flag is only used with in-process workers.
513
- */
514
- function validateResumeFlag(resume, serverUrl) {
515
- if (resume && serverUrl) throw new Error("--resume flag is incompatible with --server-url. External workers handle their own job recovery.");
516
- }
517
- /**
518
- * Validates and parses port number
519
- */
520
- function validatePort(portString) {
521
- const port = Number.parseInt(portString, 10);
522
- if (Number.isNaN(port) || port < 1 || port > 65535) throw new Error("Invalid port number");
523
- return port;
524
- }
525
- /**
526
- * Validates host string for basic format checking
527
- */
528
- function validateHost(hostString) {
529
- const trimmed = hostString.trim();
530
- if (!trimmed) throw new Error("Host cannot be empty");
531
- if (trimmed.includes(" ") || trimmed.includes(" ") || trimmed.includes("\n")) throw new Error("Host cannot contain whitespace");
532
- return trimmed;
533
- }
534
- /**
535
- * Creates AppServerConfig based on service requirements.
536
- *
537
- * AppConfig is the source of truth for host/auth/telemetry/read-only settings.
538
- * AppServerConfig only selects which services to run and which port to bind to.
539
- * Whether the server runs jobs itself or uses a worker follows from the backend.
540
- *
541
- * @param options Which services to run, the port, and startup details.
542
- * @returns The server configuration.
543
- */
544
- function createAppServerConfig(options) {
545
- return {
546
- enableWebInterface: options.enableWebInterface ?? false,
547
- enableMcpServer: options.enableMcpServer ?? true,
548
- enableApiServer: options.enableApiServer ?? false,
549
- port: options.port,
550
- showLogo: options.showLogo ?? true,
551
- startupContext: options.startupContext
552
- };
553
- }
554
- /**
555
- * Parses custom headers from CLI options
556
- */
557
- function parseHeaders(headerOptions) {
558
- const headers = {};
559
- if (Array.isArray(headerOptions)) for (const entry of headerOptions) {
560
- const idx = entry.indexOf(":");
561
- if (idx > 0) {
562
- const name = entry.slice(0, idx).trim();
563
- const value = entry.slice(idx + 1).trim();
564
- if (name) headers[name] = value;
565
- }
566
- }
567
- return headers;
568
- }
569
- /**
570
- * Check the auth settings for the transport a command serves. Authentication
571
- * applies to MCP over HTTP only. Over stdio the host launching the process is
572
- * the trust boundary, so auth settings are ignored with a warning on stderr,
573
- * which never carries protocol data.
574
- * @param auth - The loaded auth settings.
575
- * @param protocol - The resolved transport.
576
- * @param port - The HTTP port, for the plain-HTTP warning.
577
- * @throws Error when an auth setting over HTTP is malformed.
578
- */
579
- function checkAuthForProtocol(auth, protocol, port) {
580
- if (!auth.enabled) return;
581
- if (protocol === "stdio") {
582
- console.error("⚠️ Authentication does not apply to MCP over stdio; auth settings are ignored.");
583
- return;
584
- }
585
- validateAuthConfig(auth);
586
- warnHttpUsage(port);
587
- }
588
- /**
589
- * Validates the format of auth settings that are present. Whether a setting
590
- * is required depends on what the process serves, so the server checks that
591
- * at startup.
592
- */
593
- function validateAuthConfig(authConfig) {
594
- const errors = [];
595
- if (authConfig.issuerUrl) try {
596
- if (new URL(authConfig.issuerUrl).protocol !== "https:") errors.push("Issuer URL must use HTTPS protocol");
597
- } catch {
598
- errors.push("Issuer URL must be a valid URL");
599
- }
600
- if (authConfig.audience) try {
601
- const url = new URL(authConfig.audience);
602
- if (url.protocol === "http:" && url.hostname !== "localhost") logger.warn("⚠️ Audience uses HTTP protocol - consider using HTTPS for production");
603
- if (url.hash) errors.push("Audience must not contain URL fragments");
604
- } catch {
605
- if (authConfig.audience.startsWith("urn:")) {
606
- const urnParts = authConfig.audience.split(":");
607
- if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) errors.push("URN audience must follow format: urn:namespace:specific-string");
608
- } else errors.push("Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)");
609
- }
610
- if (errors.length > 0) throw new Error(`Auth configuration validation failed:\n${errors.join("\n")}`);
611
- }
612
- /**
613
- * Warns about HTTP usage in production when auth is enabled.
614
- */
615
- function warnHttpUsage(port) {
616
- if (!(process.env.NODE_ENV !== "production" || port === 6280 || process.env.HOSTNAME?.includes("localhost"))) logger.warn("⚠️ Authentication is enabled but running over HTTP in production. Consider using HTTPS for security.");
617
- }
618
- /**
619
- * Resolves embedding configuration from the provided model specification.
620
- * This function centralizes the logic for determining the embedding model.
621
- *
622
- * @param embeddingModel The embedding model specification string.
623
- * @returns Embedding configuration or null if config is unavailable.
624
- */
625
- function resolveEmbeddingContext(embeddingModel) {
626
- try {
627
- const modelSpec = embeddingModel;
628
- if (!modelSpec) {
629
- logger.debug("No embedding model specified. Embeddings are disabled.");
630
- return null;
631
- }
632
- logger.debug(`Resolving embedding configuration for model: ${modelSpec}`);
633
- return EmbeddingConfig.parseEmbeddingConfig(modelSpec);
634
- } catch (error) {
635
- logger.debug(`Failed to resolve embedding configuration: ${error}`);
636
- return null;
637
- }
638
- }
639
- /**
640
- * Prompts the user interactively to confirm an embedding model change.
641
- * Returns true if the user confirms (y/Y), false otherwise.
642
- */
643
- function promptModelChangeConfirmation(previousModel, previousDimension, currentModel, currentDimension) {
644
- return new Promise((resolve) => {
645
- console.error(`\n⚠️ Embedding model change detected:\n Previous: ${previousModel} (${previousDimension} dimensions)\n Current: ${currentModel} (${currentDimension} dimensions)\n\n All existing embedding vectors will be invalidated.\n Libraries must be re-scraped to restore vector search.\n Full-text search will continue working for all existing documents.\n`);
646
- const rl = createInterface({
647
- input: process.stdin,
648
- output: process.stderr
649
- });
650
- rl.question(" Proceed with model change? (y/N) ", (answer) => {
651
- rl.close();
652
- resolve(answer.trim().toLowerCase() === "y");
653
- });
654
- });
655
- }
656
- /**
657
- * Handles EmbeddingModelChangedError during service initialization.
658
- *
659
- * - In non-interactive mode (no TTY): re-throws the error to fail startup.
660
- * - In interactive mode (TTY): prompts the user for confirmation, then either
661
- * resolves the model change (invalidates vectors) or exits.
662
- *
663
- * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()
664
- * @param service The DocumentManagementService instance (already partially initialized)
665
- * @throws Re-throws the error in non-interactive mode or if the user rejects the change
666
- */
667
- async function handleEmbeddingModelChange(error, service) {
668
- if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
669
- if (!await promptModelChangeConfirmation(error.previousModel, error.previousDimension, error.currentModel, error.currentDimension)) throw new Error("Embedding model change rejected. Startup aborted.\nRestore the previous embedding model configuration to continue without changes.");
670
- await service.resolveModelChange();
671
- }
672
- //#endregion
673
- export { splitModelSpec as _, getGlobalOptions as a, resolveEmbeddingContext as c, validatePort as d, validateResumeFlag as f, SUPPORTED_PROVIDERS as g, EmbeddingConfig as h, getEventBus as i, resolveProtocol as l, resolveStorePath as m, createAppServerConfig as n, handleEmbeddingModelChange as o, getProjectRoot as p, ensurePlaywrightBrowsersInstalled as r, parseHeaders as s, checkAuthForProtocol as t, validateHost as u };
674
-
675
- //# sourceMappingURL=utils-DXo1A54z.js.map