@arabold/docs-mcp-server 2.4.2 → 2.4.4

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.
Files changed (34) hide show
  1. package/db/migrations/002-normalize-library-table.sql +5 -0
  2. package/db/migrations/003-normalize-vector-table.sql +5 -0
  3. package/db/migrations/004-complete-normalization.sql +7 -0
  4. package/db/migrations/007-dedupe-unversioned-versions.sql +5 -0
  5. package/db/migrations/009-add-pages-table.sql +10 -0
  6. package/db/migrations/014-rebuild-vector-partition-keys.sql +56 -0
  7. package/dist/HtmlDefuddleMiddleware-Cm0vQDqD.js +148 -0
  8. package/dist/HtmlDefuddleMiddleware-Cm0vQDqD.js.map +1 -0
  9. package/dist/assets/main.css +3 -1
  10. package/dist/assets/main.js +7845 -8777
  11. package/dist/assets/main.js.map +1 -1
  12. package/dist/env-DONvEfR5.js +30 -0
  13. package/dist/env-DONvEfR5.js.map +1 -0
  14. package/dist/index.js +10 -8
  15. package/dist/index.js.map +1 -1
  16. package/dist/logger-BBxstTD7.js +82 -0
  17. package/dist/logger-BBxstTD7.js.map +1 -0
  18. package/dist/main-Bq5EqYvY.js +18646 -0
  19. package/dist/main-Bq5EqYvY.js.map +1 -0
  20. package/dist/utils-B-zX5sgp.js +1113 -0
  21. package/dist/utils-B-zX5sgp.js.map +1 -0
  22. package/dist/utils-LjYa0nIu.js +2 -0
  23. package/package.json +61 -61
  24. package/public/assets/main.css +3 -1
  25. package/public/assets/main.js +7845 -8777
  26. package/public/assets/main.js.map +1 -1
  27. package/dist/HtmlDefuddleMiddleware-DjhdN_D2.js +0 -152
  28. package/dist/HtmlDefuddleMiddleware-DjhdN_D2.js.map +0 -1
  29. package/dist/logger-CLtABTNb.js +0 -99
  30. package/dist/logger-CLtABTNb.js.map +0 -1
  31. package/dist/main-WZKPkgC6.js +0 -20454
  32. package/dist/main-WZKPkgC6.js.map +0 -1
  33. package/dist/utils-CJgh41os.js +0 -1152
  34. package/dist/utils-CJgh41os.js.map +0 -1
@@ -0,0 +1,1113 @@
1
+ import { t as normalizeEnvValue } from "./env-DONvEfR5.js";
2
+ import { r as logger } from "./logger-BBxstTD7.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import fs, { existsSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import envPaths from "env-paths";
8
+ import { PostHog } from "posthog-node";
9
+ import EventEmitter from "node:events";
10
+ import { chromium } from "playwright";
11
+ import { execSync } from "node:child_process";
12
+ import { createInterface } from "node:readline";
13
+ //#region src/utils/paths.ts
14
+ var projectRoot = null;
15
+ /**
16
+ * Finds the project root directory by searching upwards from the current file
17
+ * for a directory containing 'package.json'. Caches the result.
18
+ *
19
+ * @returns {string} The absolute path to the project root.
20
+ * @throws {Error} If package.json cannot be found.
21
+ */
22
+ function getProjectRoot() {
23
+ if (projectRoot) return projectRoot;
24
+ const currentFilePath = fileURLToPath(import.meta.url);
25
+ let currentDir = path.dirname(currentFilePath);
26
+ while (true) {
27
+ const packageJsonPath = path.join(currentDir, "package.json");
28
+ if (fs.existsSync(packageJsonPath)) {
29
+ projectRoot = currentDir;
30
+ return currentDir;
31
+ }
32
+ const parentDir = path.dirname(currentDir);
33
+ if (parentDir === currentDir) throw new Error("Could not find project root containing package.json.");
34
+ currentDir = parentDir;
35
+ }
36
+ }
37
+ /**
38
+ * Resolves the data storage path using the following priority:
39
+ * 1. Provided storePath parameter
40
+ * 2. Legacy .store directory in project root (if exists)
41
+ * 3. Standard system data directory using env-paths
42
+ *
43
+ * @param storePath Optional custom storage path
44
+ * @returns Resolved absolute path for data storage
45
+ */
46
+ function resolveStorePath(storePath) {
47
+ let dbDir;
48
+ if (storePath) dbDir = path.resolve(storePath);
49
+ else {
50
+ const projectRoot = getProjectRoot();
51
+ const oldDbDir = path.join(projectRoot, ".store");
52
+ const oldDbPath = path.join(oldDbDir, "documents.db");
53
+ if (fs.existsSync(oldDbPath)) dbDir = oldDbDir;
54
+ else dbDir = envPaths("docs-mcp-server", { suffix: "" }).data;
55
+ }
56
+ try {
57
+ fs.mkdirSync(dbDir, { recursive: true });
58
+ } catch (error) {
59
+ logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);
60
+ }
61
+ return dbDir;
62
+ }
63
+ //#endregion
64
+ //#region src/telemetry/TelemetryConfig.ts
65
+ /**
66
+ * Telemetry configuration management for enabling/disabling analytics collection.
67
+ * Handles CLI flags, environment variables, and default settings.
68
+ */
69
+ var TelemetryConfig = class TelemetryConfig {
70
+ static instance;
71
+ enabled = true;
72
+ constructor() {}
73
+ isEnabled() {
74
+ return this.enabled;
75
+ }
76
+ setEnabled(enabled) {
77
+ this.enabled = enabled;
78
+ }
79
+ static getInstance() {
80
+ if (!TelemetryConfig.instance) TelemetryConfig.instance = new TelemetryConfig();
81
+ return TelemetryConfig.instance;
82
+ }
83
+ };
84
+ /**
85
+ * Generate or retrieve a persistent installation identifier.
86
+ * Creates a UUID and stores it in a file in the user data directory.
87
+ * Supports custom store path override for Docker deployments.
88
+ * This ensures truly unique identification that persists across runs.
89
+ */
90
+ function generateInstallationId(storePath) {
91
+ try {
92
+ const dataDir = resolveStorePath(storePath);
93
+ const installationIdPath = path.join(dataDir, "installation.id");
94
+ if (fs.existsSync(installationIdPath)) {
95
+ const existingId = fs.readFileSync(installationIdPath, "utf8").trim();
96
+ if (existingId) return existingId;
97
+ }
98
+ const newId = randomUUID();
99
+ fs.mkdirSync(dataDir, { recursive: true });
100
+ fs.writeFileSync(installationIdPath, newId, "utf8");
101
+ return newId;
102
+ } catch {
103
+ return randomUUID();
104
+ }
105
+ }
106
+ /**
107
+ * Check if telemetry should be enabled based on environment and CLI flags.
108
+ */
109
+ function shouldEnableTelemetry() {
110
+ return TelemetryConfig.getInstance().isEnabled();
111
+ }
112
+ //#endregion
113
+ //#region src/events/types.ts
114
+ /**
115
+ * Event type enum used by the EventBusService.
116
+ * These are the internal event identifiers.
117
+ */
118
+ var EventType = /* @__PURE__ */ function(EventType) {
119
+ EventType["JOB_STATUS_CHANGE"] = "JOB_STATUS_CHANGE";
120
+ EventType["JOB_PROGRESS"] = "JOB_PROGRESS";
121
+ EventType["LIBRARY_CHANGE"] = "LIBRARY_CHANGE";
122
+ EventType["JOB_LIST_CHANGE"] = "JOB_LIST_CHANGE";
123
+ return EventType;
124
+ }({});
125
+ /**
126
+ * Server-side event names used in SSE messages.
127
+ * These match the event names expected by the frontend EventClient.
128
+ */
129
+ var ServerEventName = {
130
+ ["JOB_STATUS_CHANGE"]: "job-status-change",
131
+ ["JOB_PROGRESS"]: "job-progress",
132
+ ["LIBRARY_CHANGE"]: "library-change",
133
+ ["JOB_LIST_CHANGE"]: "job-list-change"
134
+ };
135
+ //#endregion
136
+ //#region src/pipeline/types.ts
137
+ /**
138
+ * Represents the possible states of a pipeline job.
139
+ */
140
+ var PipelineJobStatus = /* @__PURE__ */ function(PipelineJobStatus) {
141
+ PipelineJobStatus["QUEUED"] = "queued";
142
+ PipelineJobStatus["RUNNING"] = "running";
143
+ PipelineJobStatus["COMPLETED"] = "completed";
144
+ PipelineJobStatus["FAILED"] = "failed";
145
+ PipelineJobStatus["CANCELLING"] = "cancelling";
146
+ PipelineJobStatus["CANCELLED"] = "cancelled";
147
+ return PipelineJobStatus;
148
+ }({});
149
+ //#endregion
150
+ //#region src/telemetry/postHogClient.ts
151
+ /**
152
+ * PostHog client wrapper for telemetry events.
153
+ * Handles PostHog SDK integration and event capture with privacy-first configuration.
154
+ * Automatically converts camelCase property names to snake_case for PostHog compatibility.
155
+ */
156
+ /**
157
+ * Convert camelCase string to snake_case
158
+ * Specifically designed for PostHog property name conversion
159
+ */
160
+ function camelToSnakeCase(str) {
161
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
162
+ }
163
+ /**
164
+ * Recursively convert object keys from camelCase to snake_case
165
+ * Handles nested objects and arrays while preserving values
166
+ */
167
+ function convertPropertiesToSnakeCase(obj) {
168
+ const result = {};
169
+ for (const [key, value] of Object.entries(obj)) {
170
+ const snakeKey = camelToSnakeCase(key);
171
+ if (value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date)) result[snakeKey] = convertPropertiesToSnakeCase(value);
172
+ else if (Array.isArray(value)) result[snakeKey] = value.map((item) => item && typeof item === "object" && !(item instanceof Date) ? convertPropertiesToSnakeCase(item) : item);
173
+ else result[snakeKey] = value;
174
+ }
175
+ return result;
176
+ }
177
+ /**
178
+ * Add PostHog standard properties and remove duplicates
179
+ * Maps our properties to PostHog's expected property names
180
+ */
181
+ function addPostHogStandardProperties(properties) {
182
+ const result = { ...properties };
183
+ if (properties.sessionId) {
184
+ result.$session_id = properties.sessionId;
185
+ delete result.sessionId;
186
+ }
187
+ if (properties.startTime) {
188
+ result.$start_timestamp = properties.startTime.toISOString();
189
+ delete result.startTime;
190
+ }
191
+ if (properties.appVersion) {
192
+ result.$app_version = properties.appVersion;
193
+ delete result.appVersion;
194
+ }
195
+ return result;
196
+ }
197
+ /**
198
+ * PostHog client wrapper for telemetry events
199
+ */
200
+ var PostHogClient = class PostHogClient {
201
+ client;
202
+ enabled;
203
+ static CONFIG = {
204
+ host: "https://app.posthog.com",
205
+ flushAt: 20,
206
+ flushInterval: 1e4,
207
+ disableGeoip: true,
208
+ disableSessionRecording: true,
209
+ disableSurveys: true,
210
+ persistence: "memory"
211
+ };
212
+ constructor(enabled) {
213
+ this.enabled = enabled;
214
+ if (!this.enabled) return;
215
+ try {
216
+ this.client = new PostHog("phc_g7pXZZdUiAQXdnwUANjloQWMvO0amEDTBaeDSWgXgrQ", {
217
+ host: PostHogClient.CONFIG.host,
218
+ flushAt: PostHogClient.CONFIG.flushAt,
219
+ flushInterval: PostHogClient.CONFIG.flushInterval,
220
+ disableGeoip: PostHogClient.CONFIG.disableGeoip
221
+ });
222
+ logger.debug("PostHog client initialized");
223
+ } catch (error) {
224
+ logger.debug(`PostHog initialization failed: ${error instanceof Error ? error.message : "Unknown error"}`);
225
+ this.enabled = false;
226
+ }
227
+ }
228
+ /**
229
+ * Send event to PostHog
230
+ */
231
+ capture(distinctId, event, properties) {
232
+ if (!this.enabled || !this.client) return;
233
+ try {
234
+ const snakeCaseProperties = convertPropertiesToSnakeCase(addPostHogStandardProperties(properties));
235
+ this.client.capture({
236
+ distinctId,
237
+ event,
238
+ properties: snakeCaseProperties
239
+ });
240
+ logger.debug(`PostHog event captured: ${event}`);
241
+ } catch (error) {
242
+ logger.debug(`PostHog capture error: ${error instanceof Error ? error.message : "Unknown error"}`);
243
+ }
244
+ }
245
+ /**
246
+ * Capture exception using PostHog's native error tracking
247
+ */
248
+ captureException(distinctId, error, properties) {
249
+ if (!this.enabled || !this.client) return;
250
+ try {
251
+ const snakeCaseProperties = convertPropertiesToSnakeCase(addPostHogStandardProperties(properties || {}));
252
+ this.client.captureException({
253
+ error,
254
+ distinctId,
255
+ properties: snakeCaseProperties
256
+ });
257
+ logger.debug(`PostHog exception captured: ${error.constructor.name}`);
258
+ } catch (captureError) {
259
+ logger.debug(`PostHog captureException error: ${captureError instanceof Error ? captureError.message : "Unknown error"}`);
260
+ }
261
+ }
262
+ /**
263
+ * Graceful shutdown with event flushing
264
+ */
265
+ async shutdown() {
266
+ if (this.client) try {
267
+ await this.client.shutdown();
268
+ logger.debug("PostHog client shutdown complete");
269
+ } catch (error) {
270
+ logger.debug(`PostHog shutdown error: ${error instanceof Error ? error.message : "Unknown error"}`);
271
+ }
272
+ }
273
+ /**
274
+ * Check if client is enabled and ready
275
+ */
276
+ isEnabled() {
277
+ return this.enabled && !!this.client;
278
+ }
279
+ };
280
+ //#endregion
281
+ //#region src/telemetry/telemetry.ts
282
+ /**
283
+ * Telemtry wrapper for privacy-first telemetry using PostHog.
284
+ * Provides global context and automatic data sanitization.
285
+ *
286
+ * Architecture:
287
+ * - PostHogClient: Handles PostHog SDK integration and event capture
288
+ * - Telemtry: High-level coordinator providing public API with global context
289
+ */
290
+ /**
291
+ * Event types for structured telemetry tracking
292
+ */
293
+ var TelemetryEvent = /* @__PURE__ */ function(TelemetryEvent) {
294
+ TelemetryEvent["APP_STARTED"] = "app_started";
295
+ TelemetryEvent["APP_SHUTDOWN"] = "app_shutdown";
296
+ TelemetryEvent["CLI_COMMAND"] = "cli_command";
297
+ TelemetryEvent["TOOL_USED"] = "tool_used";
298
+ TelemetryEvent["PIPELINE_JOB_STARTED"] = "pipeline_job_started";
299
+ TelemetryEvent["PIPELINE_JOB_COMPLETED"] = "pipeline_job_completed";
300
+ TelemetryEvent["PIPELINE_JOB_FAILED"] = "pipeline_job_failed";
301
+ return TelemetryEvent;
302
+ }({});
303
+ /**
304
+ * Main telemetry class providing privacy-first telemetry
305
+ */
306
+ var Telemetry = class Telemetry {
307
+ postHogClient;
308
+ enabled;
309
+ distinctId;
310
+ globalContext = {};
311
+ /**
312
+ * Create a new Telemetry instance with proper initialization
313
+ * This is the recommended way to create Telemetry instances
314
+ */
315
+ static create() {
316
+ const config = TelemetryConfig.getInstance();
317
+ const shouldEnable = config.isEnabled() && true;
318
+ const telemetry = new Telemetry(shouldEnable);
319
+ if (telemetry.isEnabled()) logger.debug("Telemetry enabled");
320
+ else if (!config.isEnabled()) logger.debug("Telemetry disabled (user preference)");
321
+ else logger.debug("Telemetry disabled");
322
+ return telemetry;
323
+ }
324
+ /**
325
+ * Private constructor - use Telemetry.create() instead
326
+ */
327
+ constructor(enabled = true) {
328
+ this.enabled = enabled;
329
+ this.distinctId = generateInstallationId();
330
+ this.postHogClient = new PostHogClient(this.enabled);
331
+ }
332
+ /**
333
+ * Set global application context that will be included in all events
334
+ */
335
+ setGlobalContext(context) {
336
+ this.globalContext = { ...context };
337
+ }
338
+ /**
339
+ * Get current global context
340
+ */
341
+ getGlobalContext() {
342
+ return { ...this.globalContext };
343
+ }
344
+ track(event, properties = {}) {
345
+ if (!this.enabled) return;
346
+ const enrichedProperties = {
347
+ ...this.globalContext,
348
+ ...properties,
349
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
350
+ };
351
+ logger.debug(`Tracking event: ${event}`);
352
+ this.postHogClient.capture(this.distinctId, event, enrichedProperties);
353
+ }
354
+ /**
355
+ * Capture exception using PostHog's native error tracking with global context
356
+ */
357
+ captureException(error, properties = {}) {
358
+ if (!this.enabled) return;
359
+ const enrichedProperties = {
360
+ ...this.globalContext,
361
+ ...properties,
362
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
363
+ };
364
+ logger.debug(`Capturing exception: ${error instanceof Error ? error.message : String(error)}`);
365
+ this.postHogClient.captureException(this.distinctId, error instanceof Error ? error : new Error(String(error)), enrichedProperties);
366
+ }
367
+ /**
368
+ * Graceful shutdown with event flushing
369
+ */
370
+ async shutdown() {
371
+ if (!this.enabled) return;
372
+ await this.postHogClient.shutdown();
373
+ }
374
+ /**
375
+ * Check if telemetry is enabled
376
+ */
377
+ isEnabled() {
378
+ return this.enabled;
379
+ }
380
+ };
381
+ /**
382
+ * Global telemetry instance - initialized lazily
383
+ */
384
+ var telemetryInstance = null;
385
+ /**
386
+ * Get the global telemetry instance, initializing it if needed
387
+ */
388
+ function getTelemetryInstance() {
389
+ if (!telemetryInstance) telemetryInstance = Telemetry.create();
390
+ return telemetryInstance;
391
+ }
392
+ /**
393
+ * Initialize telemetry system with proper configuration.
394
+ * This should be called once at application startup.
395
+ */
396
+ function initTelemetry(options) {
397
+ TelemetryConfig.getInstance().setEnabled(options.enabled);
398
+ generateInstallationId(options.storePath);
399
+ telemetryInstance = Telemetry.create();
400
+ }
401
+ var telemetry = new Proxy({}, { get(_target, prop) {
402
+ const instance = getTelemetryInstance();
403
+ const value = instance[prop];
404
+ if (typeof value === "function") return value.bind(instance);
405
+ return value;
406
+ } });
407
+ //#endregion
408
+ //#region src/telemetry/TelemetryService.ts
409
+ var TelemetryService = class {
410
+ eventBus;
411
+ unsubscribers = [];
412
+ constructor(eventBus) {
413
+ this.eventBus = eventBus;
414
+ this.setupEventListeners();
415
+ }
416
+ /**
417
+ * Sets up event listeners for pipeline events.
418
+ */
419
+ setupEventListeners() {
420
+ const unsubStatusChange = this.eventBus.on(EventType.JOB_STATUS_CHANGE, this.handleJobStatusChange.bind(this));
421
+ const unsubProgress = this.eventBus.on(EventType.JOB_PROGRESS, this.handleJobProgress.bind(this));
422
+ this.unsubscribers.push(unsubStatusChange, unsubProgress);
423
+ logger.debug("TelemetryService initialized and listening to events");
424
+ }
425
+ /**
426
+ * Handles job status change events and tracks them to analytics.
427
+ * Only tracks events for meaningful state transitions: started, completed, and failed.
428
+ */
429
+ handleJobStatusChange(job) {
430
+ const duration = job.startedAt ? Date.now() - job.startedAt.getTime() : null;
431
+ const queueWaitTime = job.startedAt && job.createdAt ? job.startedAt.getTime() - job.createdAt.getTime() : null;
432
+ switch (job.status) {
433
+ case PipelineJobStatus.RUNNING:
434
+ telemetry.track(TelemetryEvent.PIPELINE_JOB_STARTED, {
435
+ jobId: job.id,
436
+ library: job.library,
437
+ hasVersion: !!job.version,
438
+ maxPagesConfigured: job.progressMaxPages || 0,
439
+ queueWaitTimeMs: queueWaitTime
440
+ });
441
+ break;
442
+ case PipelineJobStatus.COMPLETED:
443
+ telemetry.track(TelemetryEvent.PIPELINE_JOB_COMPLETED, {
444
+ jobId: job.id,
445
+ library: job.library,
446
+ durationMs: duration,
447
+ pagesProcessed: job.progressPages || 0,
448
+ maxPagesConfigured: job.progressMaxPages || 0,
449
+ hasVersion: !!job.version,
450
+ throughputPagesPerSecond: duration && job.progressPages ? Math.round(job.progressPages / duration * 1e3) : 0
451
+ });
452
+ break;
453
+ case PipelineJobStatus.FAILED:
454
+ telemetry.track(TelemetryEvent.PIPELINE_JOB_FAILED, {
455
+ jobId: job.id,
456
+ library: job.library,
457
+ durationMs: duration,
458
+ pagesProcessed: job.progressPages || 0,
459
+ maxPagesConfigured: job.progressMaxPages || 0,
460
+ hasVersion: !!job.version,
461
+ hasError: !!job.error,
462
+ errorMessage: job.error?.message
463
+ });
464
+ break;
465
+ default: break;
466
+ }
467
+ }
468
+ /**
469
+ * Handles job progress events. Currently a no-op but can be extended
470
+ * for progress-specific telemetry tracking.
471
+ */
472
+ handleJobProgress(_event) {}
473
+ /**
474
+ * Cleans up event listeners.
475
+ */
476
+ shutdown() {
477
+ for (const unsubscribe of this.unsubscribers) unsubscribe();
478
+ this.unsubscribers = [];
479
+ logger.debug("TelemetryService shut down");
480
+ }
481
+ };
482
+ //#endregion
483
+ //#region src/events/EventBusService.ts
484
+ /**
485
+ * Central event bus service for application-wide event distribution.
486
+ *
487
+ * This service provides a pub/sub mechanism that can be used by any service
488
+ * to emit and listen for events. Events emitted here can be:
489
+ * - Consumed locally by in-process subscribers
490
+ * - Broadcast to remote processes via tRPC subscriptions
491
+ * - Forwarded to SSE clients via the web service
492
+ *
493
+ * This decouples event producers (like DocumentManagementService) from
494
+ * consumers (like the Web UI), enabling a clean, scalable architecture.
495
+ */
496
+ /**
497
+ * Central event bus for application-wide events.
498
+ */
499
+ var EventBusService = class {
500
+ emitter;
501
+ constructor() {
502
+ this.emitter = new EventEmitter();
503
+ this.emitter.setMaxListeners(100);
504
+ }
505
+ /**
506
+ * Emit an event to all subscribers.
507
+ */
508
+ emit(eventType, payload) {
509
+ logger.debug(`Event emitted: ${eventType}`);
510
+ this.emitter.emit(eventType, payload);
511
+ }
512
+ /**
513
+ * Subscribe to events of a specific type.
514
+ * Returns an unsubscribe function.
515
+ */
516
+ on(eventType, listener) {
517
+ this.emitter.on(eventType, listener);
518
+ return () => this.emitter.off(eventType, listener);
519
+ }
520
+ /**
521
+ * Subscribe to events once (auto-unsubscribes after first event).
522
+ */
523
+ once(eventType, listener) {
524
+ this.emitter.once(eventType, listener);
525
+ }
526
+ /**
527
+ * Remove a specific listener.
528
+ */
529
+ off(eventType, listener) {
530
+ this.emitter.off(eventType, listener);
531
+ }
532
+ /**
533
+ * Remove all listeners for a specific event type, or all listeners if no type specified.
534
+ */
535
+ removeAllListeners(eventType) {
536
+ if (eventType === void 0) this.emitter.removeAllListeners();
537
+ else this.emitter.removeAllListeners(eventType);
538
+ }
539
+ /**
540
+ * Get the count of listeners for a specific event type.
541
+ */
542
+ listenerCount(eventType) {
543
+ return this.emitter.listenerCount(eventType);
544
+ }
545
+ };
546
+ //#endregion
547
+ //#region src/store/embeddings/EmbeddingConfig.ts
548
+ /**
549
+ * Embedding configuration manager that handles model parsing and dimension caching.
550
+ * Encapsulates state to avoid global variable issues and improve testability.
551
+ */
552
+ var EmbeddingConfig = class EmbeddingConfig {
553
+ static instance = null;
554
+ /**
555
+ * Get the singleton instance of EmbeddingConfig.
556
+ * Creates the instance if it doesn't exist.
557
+ */
558
+ static getInstance() {
559
+ if (EmbeddingConfig.instance === null) EmbeddingConfig.instance = new EmbeddingConfig();
560
+ return EmbeddingConfig.instance;
561
+ }
562
+ /**
563
+ * Reset the singleton instance (useful for testing).
564
+ */
565
+ static resetInstance() {
566
+ EmbeddingConfig.instance = null;
567
+ }
568
+ /**
569
+ * Known dimensions for common embedding models.
570
+ * This avoids expensive API calls for dimension detection in telemetry.
571
+ *
572
+ * Note: The "openai" provider also supports OpenAI-compatible APIs like:
573
+ * - Ollama (local models)
574
+ * - LMStudio (local models)
575
+ * - Any service implementing OpenAI's embedding API
576
+ */
577
+ knownModelDimensions = {
578
+ "text-embedding-3-small": 1536,
579
+ "text-embedding-3-large": 3072,
580
+ "text-embedding-ada-002": 1536,
581
+ "text-embedding-004": 768,
582
+ "text-embedding-005": 768,
583
+ "textembedding-gecko@003": 768,
584
+ "textembedding-gecko@002": 768,
585
+ "textembedding-gecko@001": 768,
586
+ "text-embedding-preview-0409": 768,
587
+ "embedding-001": 768,
588
+ "gemini-embedding-2-preview": 3072,
589
+ "amazon.titan-embed-text-v1": 1536,
590
+ "amazon.titan-embed-text-v2:0": 1024,
591
+ "amazon.titan-embed-image-v1": 1024,
592
+ "cohere.embed-english-v3": 1024,
593
+ "cohere.embed-multilingual-v3": 1024,
594
+ "Cohere/Cohere-embed-v4.0": 1536,
595
+ "embed-v4.0": 1536,
596
+ "intfloat/multilingual-e5-large": 1024,
597
+ "multilingual-e5-large": 1024,
598
+ "text-embedding-multilingual-e5-large": 1024,
599
+ "sentence-transformers/all-MiniLM-L6-v2": 384,
600
+ "gemini-embedding-001": 3072,
601
+ "Qwen/Qwen3-Embedding-8B": 4096,
602
+ "Qwen/Qwen3-Embedding-4B": 2560,
603
+ "Qwen/Qwen3-Embedding-0.6B": 1024,
604
+ "Linq-AI-Research/Linq-Embed-Mistral": 4096,
605
+ "Alibaba-NLP/gte-Qwen2-7B-instruct": 3584,
606
+ "intfloat/multilingual-e5-large-instruct": 1024,
607
+ "Salesforce/SFR-Embedding-Mistral": 4096,
608
+ "text-multilingual-embedding-002": 768,
609
+ "GritLM/GritLM-7B": 4096,
610
+ "GritLM/GritLM-8x7B": 4096,
611
+ "intfloat/e5-mistral-7b-instruct": 4096,
612
+ "Cohere/Cohere-embed-multilingual-v3.0": 1024,
613
+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct": 8960,
614
+ "Lajavaness/bilingual-embedding-large": 1024,
615
+ "Salesforce/SFR-Embedding-2_R": 4096,
616
+ "NovaSearch/stella_en_1.5B_v5": 8960,
617
+ "NovaSearch/jasper_en_vision_language_v1": 8960,
618
+ "nvidia/NV-Embed-v2": 4096,
619
+ "OrdalieTech/Solon-embeddings-large-0.1": 1024,
620
+ "BAAI/bge-m3": 1024,
621
+ "HIT-TMG/KaLM-embedding-multilingual-mini-v1": 896,
622
+ "jinaai/jina-embeddings-v3": 1024,
623
+ "Alibaba-NLP/gte-multilingual-base": 768,
624
+ "Lajavaness/bilingual-embedding-base": 768,
625
+ "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1": 896,
626
+ "nvidia/NV-Embed-v1": 4096,
627
+ "Cohere/Cohere-embed-multilingual-light-v3.0": 384,
628
+ "manu/bge-m3-custom-fr": 1024,
629
+ "Lajavaness/bilingual-embedding-small": 384,
630
+ "Snowflake/snowflake-arctic-embed-l-v2.0": 1024,
631
+ "intfloat/multilingual-e5-base": 768,
632
+ "voyage-3-lite": 512,
633
+ "voyage-3": 1024,
634
+ "voyage-3-large": 1024,
635
+ "voyage-3.5": 1024,
636
+ "voyage-4": 1024,
637
+ "voyage-4-large": 1024,
638
+ "voyage-4-lite": 1024,
639
+ "voyage-code-3": 1024,
640
+ "intfloat/multilingual-e5-small": 384,
641
+ "Alibaba-NLP/gte-Qwen1.5-7B-instruct": 4096,
642
+ "Snowflake/snowflake-arctic-embed-m-v2.0": 768,
643
+ "deepvk/USER-bge-m3": 1024,
644
+ "Cohere/Cohere-embed-english-v3.0": 1024,
645
+ "Omartificial-Intelligence-Space/Arabic-labse-Matryoshka": 768,
646
+ "ibm-granite/granite-embedding-278m-multilingual": 768,
647
+ "NovaSearch/stella_en_400M_v5": 4096,
648
+ "omarelshehy/arabic-english-sts-matryoshka": 1024,
649
+ "sentence-transformers/paraphrase-multilingual-mpnet-base-v2": 768,
650
+ "Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka": 768,
651
+ "Haon-Chen/speed-embedding-7b-instruct": 4096,
652
+ "sentence-transformers/LaBSE": 768,
653
+ "WhereIsAI/UAE-Large-V1": 1024,
654
+ "ibm-granite/granite-embedding-107m-multilingual": 384,
655
+ "mixedbread-ai/mxbai-embed-large-v1": 1024,
656
+ "intfloat/e5-large-v2": 1024,
657
+ "avsolatorio/GIST-large-Embedding-v0": 1024,
658
+ "sdadas/mmlw-e5-large": 1024,
659
+ "nomic-ai/nomic-embed-text-v1": 768,
660
+ "nomic-embed-text-v1": 768,
661
+ "nomic-ai/nomic-embed-text-v1-ablated": 768,
662
+ "nomic-ai/nomic-embed-text-v2-moe": 768,
663
+ "nomic-ai/modernbert-embed-base": 768,
664
+ "nomic-ai/nomic-embed-code": 3584,
665
+ "intfloat/e5-base-v2": 768,
666
+ "BAAI/bge-large-en-v1.5": 1024,
667
+ "intfloat/e5-large": 1024,
668
+ "Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet": 384,
669
+ "Cohere/Cohere-embed-english-light-v3.0": 384,
670
+ "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2": 768,
671
+ "Gameselo/STS-multilingual-mpnet-base-v2": 768,
672
+ "thenlper/gte-large": 1024,
673
+ "avsolatorio/GIST-Embedding-v0": 768,
674
+ "nomic-ai/nomic-embed-text-v1-unsupervised": 768,
675
+ "infgrad/stella-base-en-v2": 768,
676
+ "avsolatorio/NoInstruct-small-Embedding-v0": 384,
677
+ "dwzhu/e5-base-4k": 768,
678
+ "sdadas/mmlw-e5-base": 768,
679
+ "voyage-multilingual-2": 1024,
680
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised": 4096,
681
+ "BAAI/bge-base-en-v1.5": 768,
682
+ "avsolatorio/GIST-small-Embedding-v0": 384,
683
+ "sdadas/mmlw-roberta-large": 1024,
684
+ "nomic-ai/nomic-embed-text-v1.5": 768,
685
+ "nomic-embed-text-v1.5": 768,
686
+ "text-embedding-nomic-embed-text-v1.5": 768,
687
+ "minishlab/potion-multilingual-128M": 256,
688
+ "shibing624/text2vec-base-multilingual": 384,
689
+ "thenlper/gte-base": 768,
690
+ "intfloat/e5-small-v2": 384,
691
+ "intfloat/e5-base": 768,
692
+ "sentence-transformers/static-similarity-mrl-multilingual-v1": 1024,
693
+ "manu/sentence_croissant_alpha_v0.3": 2048,
694
+ "BAAI/bge-small-en-v1.5": 512,
695
+ "thenlper/gte-small": 384,
696
+ "sdadas/mmlw-e5-small": 384,
697
+ "manu/sentence_croissant_alpha_v0.4": 2048,
698
+ "manu/sentence_croissant_alpha_v0.2": 2048,
699
+ "abhinand/MedEmbed-small-v0.1": 384,
700
+ "ibm-granite/granite-embedding-125m-english": 768,
701
+ "intfloat/e5-small": 384,
702
+ "voyage-large-2-instruct": 1024,
703
+ "sdadas/mmlw-roberta-base": 768,
704
+ "Snowflake/snowflake-arctic-embed-l": 1024,
705
+ "Mihaiii/Ivysaur": 384,
706
+ "Snowflake/snowflake-arctic-embed-m-long": 768,
707
+ "bigscience/sgpt-bloom-7b1-msmarco": 4096,
708
+ "avsolatorio/GIST-all-MiniLM-L6-v2": 384,
709
+ "sergeyzh/LaBSE-ru-turbo": 768,
710
+ "sentence-transformers/all-mpnet-base-v2": 768,
711
+ "Snowflake/snowflake-arctic-embed-m": 768,
712
+ "Snowflake/snowflake-arctic-embed-s": 384,
713
+ "sentence-transformers/all-MiniLM-L12-v2": 384,
714
+ "Mihaiii/gte-micro-v4": 384,
715
+ "Snowflake/snowflake-arctic-embed-m-v1.5": 768,
716
+ "cointegrated/LaBSE-en-ru": 768,
717
+ "Mihaiii/Bulbasaur": 384,
718
+ "ibm-granite/granite-embedding-30m-english": 384,
719
+ "deepfile/embedder-100p": 768,
720
+ "Jaume/gemma-2b-embeddings": 2048,
721
+ "OrlikB/KartonBERT-USE-base-v1": 768,
722
+ "izhx/udever-bloom-7b1": 4096,
723
+ "izhx/udever-bloom-1b1": 1024,
724
+ "brahmairesearch/slx-v0.1": 384,
725
+ "Mihaiii/Wartortle": 384,
726
+ "izhx/udever-bloom-3b": 2048,
727
+ "deepvk/USER-base": 768,
728
+ "ai-forever/ru-en-RoSBERTa": 1024,
729
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse": 4096,
730
+ "Mihaiii/Venusaur": 384,
731
+ "Snowflake/snowflake-arctic-embed-xs": 384,
732
+ "jinaai/jina-embedding-b-en-v1": 768,
733
+ "Mihaiii/gte-micro": 384,
734
+ "aari1995/German_Semantic_STS_V2": 1024,
735
+ "Mihaiii/Squirtle": 384,
736
+ "OrlikB/st-polish-kartonberta-base-alpha-v1": 768,
737
+ "sergeyzh/rubert-tiny-turbo": 312,
738
+ "minishlab/potion-base-8M": 256,
739
+ "minishlab/M2V_base_glove_subword": 256,
740
+ "jinaai/jina-embedding-s-en-v1": 512,
741
+ "minishlab/potion-base-4M": 128,
742
+ "minishlab/M2V_base_output": 256,
743
+ "DeepPavlov/rubert-base-cased-sentence": 768,
744
+ "jinaai/jina-embeddings-v2-small-en": 512,
745
+ "cointegrated/rubert-tiny2": 312,
746
+ "minishlab/M2V_base_glove": 256,
747
+ "cointegrated/rubert-tiny": 312,
748
+ "silma-ai/silma-embeddding-matryoshka-v0.1": 768,
749
+ "DeepPavlov/rubert-base-cased": 768,
750
+ "Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet": 768,
751
+ "izhx/udever-bloom-560m": 1024,
752
+ "minishlab/potion-base-2M": 64,
753
+ "DeepPavlov/distilrubert-small-cased-conversational": 768,
754
+ "consciousAI/cai-lunaris-text-embeddings": 1024,
755
+ "deepvk/deberta-v1-base": 768,
756
+ "Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka": 768,
757
+ "Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka": 768,
758
+ "ai-forever/sbert_large_mt_nlu_ru": 1024,
759
+ "ai-forever/sbert_large_nlu_ru": 1024,
760
+ "malenia1/ternary-weight-embedding": 1024,
761
+ "jinaai/jina-embeddings-v2-base-en": 768,
762
+ "VPLabs/SearchMap_Preview": 4096,
763
+ "Hum-Works/lodestone-base-4096-v1": 768,
764
+ "jinaai/jina-embeddings-v4": 2048
765
+ };
766
+ runtimeDetectedDimensionModels = /* @__PURE__ */ new Set([
767
+ "novasearch/stella_en_1.5b_v5",
768
+ "stella_en_1.5b_v5",
769
+ "novasearch/stella_en_400m_v5",
770
+ "dunzhang/stella_en_400m_v5",
771
+ "stella_en_400m_v5",
772
+ "novasearch/jasper_en_vision_language_v1",
773
+ "jasper_en_vision_language_v1"
774
+ ]);
775
+ /**
776
+ * Lowercase lookup map for case-insensitive model dimension queries.
777
+ * Built lazily from knownModelDimensions to ensure consistency.
778
+ */
779
+ modelLookup;
780
+ constructor() {
781
+ this.modelLookup = /* @__PURE__ */ new Map();
782
+ for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) this.modelLookup.set(model.toLowerCase(), dimensions);
783
+ }
784
+ findKnownDimension(model) {
785
+ const normalized = model.toLowerCase();
786
+ if (this.runtimeDetectedDimensionModels.has(normalized)) return null;
787
+ const exact = this.modelLookup?.get(normalized);
788
+ if (exact !== void 0) return exact;
789
+ const slashIndex = normalized.lastIndexOf("/");
790
+ if (slashIndex !== -1) {
791
+ const suffix = normalized.substring(slashIndex + 1);
792
+ if (this.runtimeDetectedDimensionModels.has(suffix)) return null;
793
+ return this.modelLookup?.get(suffix) ?? null;
794
+ }
795
+ return null;
796
+ }
797
+ /**
798
+ * Parse embedding model configuration from a provided model specification.
799
+ * This is a synchronous operation that extracts provider, model, and known dimensions.
800
+ *
801
+ * Supports various providers:
802
+ * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)
803
+ * - vertex: Google Cloud Vertex AI
804
+ * - gemini: Google Generative AI
805
+ * - aws: AWS Bedrock models
806
+ * - microsoft: Azure OpenAI
807
+ * - sagemaker: AWS SageMaker hosted models
808
+ *
809
+ * @param modelSpec Model specification (e.g., "openai:text-embedding-3-small"), defaults to "text-embedding-3-small"
810
+ * @returns Parsed embedding model configuration
811
+ */
812
+ parse(modelSpec) {
813
+ const spec = normalizeEnvValue(modelSpec || "text-embedding-3-small");
814
+ const colonIndex = spec.indexOf(":");
815
+ let provider;
816
+ let model;
817
+ if (colonIndex === -1) {
818
+ provider = "openai";
819
+ model = spec;
820
+ } else {
821
+ provider = spec.substring(0, colonIndex);
822
+ model = spec.substring(colonIndex + 1);
823
+ }
824
+ const dimensions = this.findKnownDimension(model);
825
+ return {
826
+ provider,
827
+ model,
828
+ dimensions,
829
+ modelSpec: spec
830
+ };
831
+ }
832
+ /**
833
+ * Get the known dimensions for a specific model.
834
+ * Returns null if the model dimensions are not known.
835
+ * Uses case-insensitive lookup.
836
+ *
837
+ * @param model The model name (e.g., "text-embedding-3-small")
838
+ * @returns Known dimensions or null
839
+ */
840
+ getKnownDimensions(model) {
841
+ return this.findKnownDimension(model);
842
+ }
843
+ /**
844
+ * Add or update known dimensions for a model.
845
+ * This can be used to cache discovered dimensions.
846
+ * Stores both original case and lowercase for consistent lookup.
847
+ *
848
+ * @param model The model name
849
+ * @param dimensions The dimensions to cache
850
+ */
851
+ setKnownDimensions(model, dimensions) {
852
+ this.knownModelDimensions[model] = dimensions;
853
+ if (this.modelLookup) this.modelLookup.set(model.toLowerCase(), dimensions);
854
+ }
855
+ /**
856
+ * Static method to parse embedding model configuration using the singleton instance.
857
+ * This maintains backward compatibility while using the class-based approach.
858
+ */
859
+ static parseEmbeddingConfig(modelSpec) {
860
+ return EmbeddingConfig.getInstance().parse(modelSpec);
861
+ }
862
+ /**
863
+ * Static method to get known model dimensions using the singleton instance.
864
+ * This maintains backward compatibility while using the class-based approach.
865
+ */
866
+ static getKnownModelDimensions(model) {
867
+ return EmbeddingConfig.getInstance().getKnownDimensions(model);
868
+ }
869
+ /**
870
+ * Static method to set known model dimensions using the singleton instance.
871
+ * This maintains backward compatibility while using the class-based approach.
872
+ */
873
+ static setKnownModelDimensions(model, dimensions) {
874
+ EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);
875
+ }
876
+ };
877
+ //#endregion
878
+ //#region src/cli/utils.ts
879
+ /**
880
+ * Shared CLI utilities and helper functions.
881
+ */
882
+ /**
883
+ * Retrieves the global EventBusService from the arguments context.
884
+ * @param argv The parsed arguments context.
885
+ * @returns The global EventBusService.
886
+ * @throws Error if EventBusService is not initialized.
887
+ */
888
+ function getEventBus(argv) {
889
+ const eventBus = argv._eventBus;
890
+ if (!eventBus) throw new Error("EventBusService not initialized");
891
+ return eventBus;
892
+ }
893
+ /**
894
+ * Helper to extract GlobalOptions from the argv.
895
+ * In Yargs, all options are in argv, so we just cast/pick.
896
+ */
897
+ function getGlobalOptions(argv) {
898
+ return argv;
899
+ }
900
+ /**
901
+ * Ensures that the Playwright browsers are installed, unless a system Chromium path is set.
902
+ */
903
+ function ensurePlaywrightBrowsersInstalled() {
904
+ if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === "1") {
905
+ logger.debug("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.");
906
+ return;
907
+ }
908
+ const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
909
+ if (chromiumEnvPath && existsSync(chromiumEnvPath)) {
910
+ logger.debug(`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`);
911
+ return;
912
+ }
913
+ try {
914
+ const chromiumPath = chromium.executablePath();
915
+ if (!chromiumPath || !existsSync(chromiumPath)) throw new Error("Playwright Chromium browser not found");
916
+ } catch (error) {
917
+ logger.debug(String(error));
918
+ try {
919
+ logger.info("🌐 Installing Playwright Chromium browser... (this may take a moment)");
920
+ execSync("npm exec -y playwright install --no-shell --with-deps chromium", {
921
+ stdio: "ignore",
922
+ cwd: getProjectRoot()
923
+ });
924
+ } catch (_installErr) {
925
+ logger.error("❌ Failed to install Playwright browsers automatically. Please run:\n npx playwright install --no-shell --with-deps chromium\nand try again.");
926
+ process.exit(1);
927
+ }
928
+ }
929
+ }
930
+ /**
931
+ * Resolves the protocol based on auto-detection or explicit specification.
932
+ * Auto-detection uses TTY status to determine appropriate protocol.
933
+ */
934
+ function resolveProtocol(protocol) {
935
+ if (protocol === "auto") {
936
+ if (!process.stdin.isTTY && !process.stdout.isTTY) return "stdio";
937
+ return "http";
938
+ }
939
+ if (protocol === "stdio" || protocol === "http") return protocol;
940
+ throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);
941
+ }
942
+ /**
943
+ * Validates that --resume flag is only used with in-process workers.
944
+ */
945
+ function validateResumeFlag(resume, serverUrl) {
946
+ if (resume && serverUrl) throw new Error("--resume flag is incompatible with --server-url. External workers handle their own job recovery.");
947
+ }
948
+ /**
949
+ * Validates and parses port number
950
+ */
951
+ function validatePort(portString) {
952
+ const port = Number.parseInt(portString, 10);
953
+ if (Number.isNaN(port) || port < 1 || port > 65535) throw new Error("Invalid port number");
954
+ return port;
955
+ }
956
+ /**
957
+ * Validates host string for basic format checking
958
+ */
959
+ function validateHost(hostString) {
960
+ const trimmed = hostString.trim();
961
+ if (!trimmed) throw new Error("Host cannot be empty");
962
+ if (trimmed.includes(" ") || trimmed.includes(" ") || trimmed.includes("\n")) throw new Error("Host cannot contain whitespace");
963
+ return trimmed;
964
+ }
965
+ /**
966
+ * Creates AppServerConfig based on service requirements.
967
+ *
968
+ * AppConfig is the source of truth for host/auth/telemetry/read-only settings.
969
+ * AppServerConfig only selects which services to run and which port to bind to.
970
+ */
971
+ function createAppServerConfig(options) {
972
+ return {
973
+ enableWebInterface: options.enableWebInterface ?? false,
974
+ enableMcpServer: options.enableMcpServer ?? true,
975
+ enableApiServer: options.enableApiServer ?? false,
976
+ enableWorker: options.enableWorker ?? true,
977
+ port: options.port,
978
+ externalWorkerUrl: options.externalWorkerUrl,
979
+ showLogo: options.showLogo ?? true,
980
+ startupContext: options.startupContext
981
+ };
982
+ }
983
+ /**
984
+ * Parses custom headers from CLI options
985
+ */
986
+ function parseHeaders(headerOptions) {
987
+ const headers = {};
988
+ if (Array.isArray(headerOptions)) for (const entry of headerOptions) {
989
+ const idx = entry.indexOf(":");
990
+ if (idx > 0) {
991
+ const name = entry.slice(0, idx).trim();
992
+ const value = entry.slice(idx + 1).trim();
993
+ if (name) headers[name] = value;
994
+ }
995
+ }
996
+ return headers;
997
+ }
998
+ /**
999
+ * Parses auth configuration from CLI options.
1000
+ * Environment variables are handled by createOptionWithEnv in command definitions.
1001
+ * Precedence: CLI flags > env vars (handled by commander) > defaults
1002
+ */
1003
+ function parseAuthConfig(options) {
1004
+ if (!options.authEnabled) return;
1005
+ return {
1006
+ enabled: true,
1007
+ issuerUrl: options.authIssuerUrl,
1008
+ audience: options.authAudience,
1009
+ scopes: ["openid", "profile"]
1010
+ };
1011
+ }
1012
+ /**
1013
+ * Validates auth configuration when auth is enabled.
1014
+ */
1015
+ function validateAuthConfig(authConfig) {
1016
+ if (!authConfig.enabled) return;
1017
+ const errors = [];
1018
+ if (!authConfig.issuerUrl) errors.push("--auth-issuer-url is required when auth is enabled");
1019
+ else try {
1020
+ if (new URL(authConfig.issuerUrl).protocol !== "https:") errors.push("Issuer URL must use HTTPS protocol");
1021
+ } catch {
1022
+ errors.push("Issuer URL must be a valid URL");
1023
+ }
1024
+ if (!authConfig.audience) errors.push("--auth-audience is required when auth is enabled");
1025
+ else try {
1026
+ const url = new URL(authConfig.audience);
1027
+ if (url.protocol === "http:" && url.hostname !== "localhost") logger.warn("⚠️ Audience uses HTTP protocol - consider using HTTPS for production");
1028
+ if (url.hash) errors.push("Audience must not contain URL fragments");
1029
+ } catch {
1030
+ if (authConfig.audience.startsWith("urn:")) {
1031
+ const urnParts = authConfig.audience.split(":");
1032
+ if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) errors.push("URN audience must follow format: urn:namespace:specific-string");
1033
+ } else errors.push("Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)");
1034
+ }
1035
+ if (errors.length > 0) throw new Error(`Auth configuration validation failed:\n${errors.join("\n")}`);
1036
+ }
1037
+ /**
1038
+ * Warns about HTTP usage in production when auth is enabled.
1039
+ */
1040
+ function warnHttpUsage(authConfig, port) {
1041
+ if (!authConfig?.enabled) return;
1042
+ 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.");
1043
+ }
1044
+ /**
1045
+ * Creates EventBusService and TelemetryService together.
1046
+ * The TelemetryService automatically subscribes to events from the EventBusService.
1047
+ * @returns Object containing both services
1048
+ */
1049
+ function createEventServices() {
1050
+ const eventBus = new EventBusService();
1051
+ return {
1052
+ eventBus,
1053
+ telemetryService: new TelemetryService(eventBus)
1054
+ };
1055
+ }
1056
+ /**
1057
+ * Resolves embedding configuration from the provided model specification.
1058
+ * This function centralizes the logic for determining the embedding model.
1059
+ *
1060
+ * @param embeddingModel The embedding model specification string.
1061
+ * @returns Embedding configuration or null if config is unavailable.
1062
+ */
1063
+ function resolveEmbeddingContext(embeddingModel) {
1064
+ try {
1065
+ const modelSpec = embeddingModel;
1066
+ if (!modelSpec) {
1067
+ logger.debug("No embedding model specified. Embeddings are disabled.");
1068
+ return null;
1069
+ }
1070
+ logger.debug(`Resolving embedding configuration for model: ${modelSpec}`);
1071
+ return EmbeddingConfig.parseEmbeddingConfig(modelSpec);
1072
+ } catch (error) {
1073
+ logger.debug(`Failed to resolve embedding configuration: ${error}`);
1074
+ return null;
1075
+ }
1076
+ }
1077
+ /**
1078
+ * Prompts the user interactively to confirm an embedding model change.
1079
+ * Returns true if the user confirms (y/Y), false otherwise.
1080
+ */
1081
+ function promptModelChangeConfirmation(previousModel, previousDimension, currentModel, currentDimension) {
1082
+ return new Promise((resolve) => {
1083
+ 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`);
1084
+ const rl = createInterface({
1085
+ input: process.stdin,
1086
+ output: process.stderr
1087
+ });
1088
+ rl.question(" Proceed with model change? (y/N) ", (answer) => {
1089
+ rl.close();
1090
+ resolve(answer.trim().toLowerCase() === "y");
1091
+ });
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Handles EmbeddingModelChangedError during service initialization.
1096
+ *
1097
+ * - In non-interactive mode (no TTY): re-throws the error to fail startup.
1098
+ * - In interactive mode (TTY): prompts the user for confirmation, then either
1099
+ * resolves the model change (invalidates vectors) or exits.
1100
+ *
1101
+ * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()
1102
+ * @param service The DocumentManagementService instance (already partially initialized)
1103
+ * @throws Re-throws the error in non-interactive mode or if the user rejects the change
1104
+ */
1105
+ async function handleEmbeddingModelChange(error, service) {
1106
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
1107
+ 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.");
1108
+ await service.resolveModelChange();
1109
+ }
1110
+ //#endregion
1111
+ export { EventType as C, resolveStorePath as D, getProjectRoot as E, PipelineJobStatus as S, shouldEnableTelemetry as T, EventBusService as _, getGlobalOptions as a, initTelemetry as b, parseHeaders as c, validateAuthConfig as d, validateHost as f, EmbeddingConfig as g, warnHttpUsage as h, getEventBus as i, resolveEmbeddingContext as l, validateResumeFlag as m, createEventServices as n, handleEmbeddingModelChange as o, validatePort as p, ensurePlaywrightBrowsersInstalled as r, parseAuthConfig as s, createAppServerConfig as t, resolveProtocol as u, TelemetryService as v, ServerEventName as w, telemetry as x, TelemetryEvent as y };
1112
+
1113
+ //# sourceMappingURL=utils-B-zX5sgp.js.map