All files / src registry-manager.ts

96.62% Statements 143/148
98.71% Branches 77/78
93.33% Functions 14/15
96.42% Lines 135/140

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374  2x 2x 2x 2x 2x       2x       2x       2x 2x       2x                         2x 2x               46x     46x 46x 46x     46x     46x     46x 46x 46x       48x 46x   48x               46x     46x 43x     46x 45x     46x 45x     46x 45x     46x 45x     46x 45x     46x 45x     46x 44x                   46x   46x 4x 4x 6x                 6x     6x     6x 5x     6x 5x     6x 5x     6x 5x     6x 5x     6x 5x     6x 5x     6x 5x     6x             406x 406x             48x   48x 421x   2775x 189x 189x       2586x 8x 8x       2578x 1x 1x 1x       2577x 2577x 2577x 5x       5x       2577x       48x                                     12x             3x 3x 1x     2x             2x             11x   8x   8x 234x               11x                 5x     5x 5x         5x 5x 5x 5x 5x 5x 5x 5x     5x     5x     5x 5x 5x 5x 5x 5x 5x 5x     5x   5x 36x   270x 41x       229x 2x       227x 227x 227x           227x       5x             4x             15x   15x       2x  
import { ToolRegistry, EnhancedToolDefinition, ToolDefinition } from "./types";
import { coreToolRegistry, getCoreReadOnlyToolNames } from "./entities/core/registry";
import { labelsToolRegistry, getLabelsReadOnlyToolNames } from "./entities/labels/registry";
import { mrsToolRegistry, getMrsReadOnlyToolNames } from "./entities/mrs/registry";
import { filesToolRegistry, getFilesReadOnlyToolNames } from "./entities/files/registry";
import {
  milestonesToolRegistry,
  getMilestonesReadOnlyToolNames,
} from "./entities/milestones/registry";
import {
  pipelinesToolRegistry,
  getPipelinesReadOnlyToolNames,
} from "./entities/pipelines/registry";
import {
  variablesToolRegistry,
  getVariablesReadOnlyToolNames,
} from "./entities/variables/registry";
import { wikiToolRegistry, getWikiReadOnlyToolNames } from "./entities/wiki/registry";
import {
  workitemsToolRegistry,
  getWorkitemsReadOnlyToolNames,
} from "./entities/workitems/registry";
import {
  GITLAB_READ_ONLY_MODE,
  GITLAB_DENIED_TOOLS_REGEX,
  USE_GITLAB_WIKI,
  USE_MILESTONE,
  USE_PIPELINE,
  USE_WORKITEMS,
  USE_LABELS,
  USE_MRS,
  USE_FILES,
  USE_VARIABLES,
  getToolDescriptionOverrides,
} from "./config";
import { ToolAvailability } from "./services/ToolAvailability";
import { logger } from "./logger";
 
/**
 * Central registry manager that aggregates tools from all entity registries
 * and provides a unified interface for tool discovery and execution
 */
class RegistryManager {
  private static instance: RegistryManager;
  private registries: Map<string, ToolRegistry> = new Map();
 
  // Performance optimization caches
  private toolLookupCache: Map<string, EnhancedToolDefinition> = new Map();
  private toolDefinitionsCache: ToolDefinition[] | null = null;
  private toolNamesCache: string[] | null = null;
 
  // Tool description overrides from environment variables
  private descriptionOverrides: Map<string, string> = new Map();
 
  // Cached read-only tools list built from registries
  private readOnlyToolsCache: string[] | null = null;
 
  private constructor() {
    this.initializeRegistries();
    this.loadDescriptionOverrides();
    this.buildToolLookupCache();
  }
 
  public static getInstance(): RegistryManager {
    if (!RegistryManager.instance) {
      RegistryManager.instance = new RegistryManager();
    }
    return RegistryManager.instance;
  }
 
  /**
   * Initialize all entity registries based on configuration
   */
  private initializeRegistries(): void {
    // Always add core tools
    this.registries.set("core", coreToolRegistry);
 
    // Add tools based on feature flags
    if (USE_LABELS) {
      this.registries.set("labels", labelsToolRegistry);
    }
 
    if (USE_MRS) {
      this.registries.set("mrs", mrsToolRegistry);
    }
 
    if (USE_FILES) {
      this.registries.set("files", filesToolRegistry);
    }
 
    if (USE_MILESTONE) {
      this.registries.set("milestones", milestonesToolRegistry);
    }
 
    if (USE_PIPELINE) {
      this.registries.set("pipelines", pipelinesToolRegistry);
    }
 
    if (USE_VARIABLES) {
      this.registries.set("variables", variablesToolRegistry);
    }
 
    if (USE_GITLAB_WIKI) {
      this.registries.set("wiki", wikiToolRegistry);
    }
 
    if (USE_WORKITEMS) {
      this.registries.set("workitems", workitemsToolRegistry);
    }
 
    // All entity registries have been migrated to the new pattern!
  }
 
  /**
   * Load tool description overrides from environment variables
   */
  private loadDescriptionOverrides(): void {
    this.descriptionOverrides = getToolDescriptionOverrides();
 
    if (this.descriptionOverrides.size > 0) {
      logger.debug(`Loaded ${this.descriptionOverrides.size} tool description overrides`);
      for (const [toolName, description] of this.descriptionOverrides) {
        logger.debug(`Tool description override: ${toolName} -> "${description}"`);
      }
    }
  }
 
  /**
   * Build read-only tools list from registries based on configuration
   */
  private buildReadOnlyToolsList(): string[] {
    const readOnlyTools: string[] = [];
 
    // Always add core read-only tools
    readOnlyTools.push(...getCoreReadOnlyToolNames());
 
    // Add read-only tools from enabled entities
    if (USE_LABELS) {
      readOnlyTools.push(...getLabelsReadOnlyToolNames());
    }
 
    if (USE_MRS) {
      readOnlyTools.push(...getMrsReadOnlyToolNames());
    }
 
    if (USE_FILES) {
      readOnlyTools.push(...getFilesReadOnlyToolNames());
    }
 
    if (USE_GITLAB_WIKI) {
      readOnlyTools.push(...getWikiReadOnlyToolNames());
    }
 
    if (USE_MILESTONE) {
      readOnlyTools.push(...getMilestonesReadOnlyToolNames());
    }
 
    if (USE_PIPELINE) {
      readOnlyTools.push(...getPipelinesReadOnlyToolNames());
    }
 
    if (USE_WORKITEMS) {
      readOnlyTools.push(...getWorkitemsReadOnlyToolNames());
    }
 
    if (USE_VARIABLES) {
      readOnlyTools.push(...getVariablesReadOnlyToolNames());
    }
 
    return readOnlyTools;
  }
 
  /**
   * Get read-only tools list (cached for performance)
   */
  private getReadOnlyTools(): string[] {
    this.readOnlyToolsCache ??= this.buildReadOnlyToolsList();
    return this.readOnlyToolsCache;
  }
 
  /**
   * Build unified tool lookup cache for O(1) tool access with filtering applied
   */
  private buildToolLookupCache(): void {
    this.toolLookupCache.clear();
 
    for (const registry of this.registries.values()) {
      for (const [toolName, tool] of registry) {
        // Apply GITLAB_READ_ONLY_MODE filtering at registry level
        if (GITLAB_READ_ONLY_MODE && !this.getReadOnlyTools().includes(toolName)) {
          logger.debug(`Tool '${toolName}' filtered out: read-only mode`);
          continue;
        }
 
        // Apply GITLAB_DENIED_TOOLS_REGEX filtering at registry level
        if (GITLAB_DENIED_TOOLS_REGEX?.test(toolName)) {
          logger.debug(`Tool '${toolName}' filtered out: matches denied regex`);
          continue;
        }
 
        // Apply GitLab version/tier filtering at registry level
        if (!ToolAvailability.isToolAvailable(toolName)) {
          const reason = ToolAvailability.getUnavailableReason(toolName);
          logger.debug(`Tool '${toolName}' filtered out: ${reason}`);
          continue;
        }
 
        // Tool passes all filters - apply description override if available
        let finalTool = tool;
        const customDescription = this.descriptionOverrides.get(toolName);
        if (customDescription) {
          finalTool = {
            ...tool,
            description: customDescription,
          };
          logger.debug(`Applied description override for '${toolName}': "${customDescription}"`);
        }
 
        // Add to cache
        this.toolLookupCache.set(toolName, finalTool);
      }
    }
 
    logger.debug(
      `Registry manager built cache with ${this.toolLookupCache.size} tools after filtering`
    );
  }
 
  /**
   * Invalidate all caches - call when registries change
   */
  private invalidateCaches(): void {
    this.toolDefinitionsCache = null;
    this.toolNamesCache = null;
    this.readOnlyToolsCache = null;
    this.buildToolLookupCache();
  }
 
  /**
   * Get a tool by name from any registry - O(1) lookup using cache
   */
  public getTool(toolName: string): EnhancedToolDefinition | null {
    return this.toolLookupCache.get(toolName) ?? null;
  }
 
  /**
   * Execute a tool by name
   */
  public async executeTool(toolName: string, args: unknown): Promise<unknown> {
    const tool = this.getTool(toolName);
    if (!tool) {
      throw new Error(`Tool '${toolName}' not found in any registry`);
    }
 
    return await tool.handler(args);
  }
 
  /**
   * Clear all caches and rebuild
   */
  public refreshCache(): void {
    this.buildToolLookupCache();
  }
 
  /**
   * Get all tool definitions (for backward compatibility with tools.ts) - cached for performance
   */
  public getAllToolDefinitions(): ToolDefinition[] {
    if (this.toolDefinitionsCache === null) {
      // Build cache
      this.toolDefinitionsCache = [];
 
      for (const tool of this.toolLookupCache.values()) {
        this.toolDefinitionsCache.push({
          name: tool.name,
          description: tool.description,
          inputSchema: tool.inputSchema,
        });
      }
    }
 
    return this.toolDefinitionsCache;
  }
 
  /**
   * Get tool definitions without GitLab tier/version filtering (for CLI tools, documentation, etc.)
   * Dynamically checks environment filters at runtime to respect CLI-time environment variables
   * but bypasses ToolAvailability tier/version checks since no GitLab connection exists
   */
  public getAllToolDefinitionsTierless(): EnhancedToolDefinition[] {
    const allTools: EnhancedToolDefinition[] = [];
 
    // Dynamically check environment variables at runtime
    const isReadOnly = process.env.GITLAB_READ_ONLY_MODE === "true";
    const deniedRegex = process.env.GITLAB_DENIED_TOOLS_REGEX
      ? new RegExp(process.env.GITLAB_DENIED_TOOLS_REGEX)
      : undefined;
 
    // Dynamically check USE_* flags at runtime
    const useLabels = process.env.USE_LABELS !== "false";
    const useMrs = process.env.USE_MRS !== "false";
    const useFiles = process.env.USE_FILES !== "false";
    const useMilestone = process.env.USE_MILESTONE !== "false";
    const usePipeline = process.env.USE_PIPELINE !== "false";
    const useVariables = process.env.USE_VARIABLES !== "false";
    const useWiki = process.env.USE_GITLAB_WIKI !== "false";
    const useWorkitems = process.env.USE_WORKITEMS !== "false";
 
    // Build registries map based on dynamic feature flags
    const registriesToUse = new Map<string, ToolRegistry>();
 
    // Always add core tools
    registriesToUse.set("core", coreToolRegistry);
 
    // Add tools based on dynamically checked feature flags
    if (useLabels) registriesToUse.set("labels", labelsToolRegistry);
    if (useMrs) registriesToUse.set("mrs", mrsToolRegistry);
    if (useFiles) registriesToUse.set("files", filesToolRegistry);
    if (useMilestone) registriesToUse.set("milestones", milestonesToolRegistry);
    if (usePipeline) registriesToUse.set("pipelines", pipelinesToolRegistry);
    if (useVariables) registriesToUse.set("variables", variablesToolRegistry);
    if (useWiki) registriesToUse.set("wiki", wikiToolRegistry);
    if (useWorkitems) registriesToUse.set("workitems", workitemsToolRegistry);
 
    // Dynamically load description overrides
    const descOverrides = getToolDescriptionOverrides();
 
    for (const registry of registriesToUse.values()) {
      for (const [toolName, tool] of registry) {
        // Apply dynamically checked GITLAB_READ_ONLY_MODE filtering
        if (isReadOnly && !this.getReadOnlyTools().includes(toolName)) {
          continue;
        }
 
        // Apply dynamically checked GITLAB_DENIED_TOOLS_REGEX filtering
        if (deniedRegex?.test(toolName)) {
          continue;
        }
 
        // Apply dynamically loaded description override if available
        let finalTool = tool;
        const customDescription = descOverrides.get(toolName);
        Iif (customDescription) {
          finalTool = {
            ...tool,
            description: customDescription,
          };
        }
        allTools.push(finalTool);
      }
    }
 
    return allTools;
  }
 
  /**
   * Check if a tool exists in any registry - O(1) lookup using cache
   */
  public hasToolHandler(toolName: string): boolean {
    return this.toolLookupCache.has(toolName);
  }
 
  /**
   * Get all available tool names - cached for performance
   */
  public getAvailableToolNames(): string[] {
    this.toolNamesCache ??= Array.from(this.toolLookupCache.keys());
 
    return this.toolNamesCache;
  }
}
 
export { RegistryManager };