All files / src/services ToolAvailability.ts

100% Statements 105/105
90% Branches 45/50
100% Functions 20/20
100% Lines 99/99

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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 55215x   15x 15x                                                                   15x   15x                   15x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   15x                                     9x 9x           8x 3x 3x 3x   5x 5x 5x 4x 4x 4x     1x       7x 7x   7x 21x 21x     21x 14x       7x 6x               7x                   263x 263x     255x 6x     249x             4x 4x   3x   3x 2x 2x 2x         3x             4x 4x   2x   2x 2x 2x       269x     269x 1x 1x     268x 268x   218x 218x 215x 215x 7x   208x       3x 3x   50x       50x 46x     46x     4x 4x         215x       9x 9x 7x           2x       34x   34x 34x 32x   32x 2x     30x 30x 2x     28x 2x     26x   2x               236x           236x 236x   236x       7x       5x 215x 86x       4x 4x 172x 49x      
import { ConnectionManager } from "./ConnectionManager";
import { GitLabTier } from "./GitLabVersionDetector";
import { logDebug, logWarn } from "../logger";
import { parseVersion } from "../utils/version";
 
interface ToolRequirement {
  minVersion: string;
  requiredTier: "free" | "premium" | "ultimate";
  notes?: string;
}
 
/**
 * Action-level tier requirement
 */
interface ActionRequirement {
  tier: "free" | "premium" | "ultimate";
  minVersion: string;
  notes?: string;
}
 
/**
 * Parameter-level tier/version requirement.
 * Same structure as ActionRequirement; aliased for semantic clarity
 * when used in parameterRequirements map.
 */
type ParameterRequirement = ActionRequirement;
 
/**
 * Tool with action-level requirements (for consolidated tools)
 */
interface ToolActionRequirements {
  /** Default requirement when action is not specified */
  default: ActionRequirement;
  /** Action-specific requirements (override default) */
  actions?: Record<string, ActionRequirement>;
}
 
export class ToolAvailability {
  /** Tier hierarchy for comparison: free < premium < ultimate */
  private static readonly TIER_ORDER: Record<string, number> = {
    free: 0,
    premium: 1,
    ultimate: 2,
  };
 
  // ============================================================================
  // Consolidated Tools with Action-Level Requirements
  // ============================================================================
 
  private static actionRequirements: Record<string, ToolActionRequirements> = {
    // Core tools
    browse_projects: {
      default: { tier: "free", minVersion: "8.0" },
    },
    browse_namespaces: {
      default: { tier: "free", minVersion: "9.0" },
    },
    browse_commits: {
      default: { tier: "free", minVersion: "8.0" },
    },
    browse_events: {
      default: { tier: "free", minVersion: "9.0" },
    },
    browse_users: {
      default: { tier: "free", minVersion: "8.0" },
    },
    browse_todos: {
      default: { tier: "free", minVersion: "8.0" },
    },
    browse_iterations: {
      default: { tier: "premium", minVersion: "13.1", notes: "Iterations/Sprints" },
    },
    manage_project: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        create: { tier: "free", minVersion: "8.0" },
        fork: { tier: "free", minVersion: "8.0" },
        update: { tier: "free", minVersion: "8.0" },
        delete: { tier: "free", minVersion: "8.0" },
        archive: { tier: "free", minVersion: "8.0" },
        unarchive: { tier: "free", minVersion: "8.0" },
        transfer: { tier: "free", minVersion: "8.0" },
      },
    },
    manage_namespace: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        create: { tier: "free", minVersion: "8.0" },
        update: { tier: "free", minVersion: "8.0" },
        delete: { tier: "free", minVersion: "8.0" },
      },
    },
 
    // Merge Requests
    browse_merge_requests: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        approvals: { tier: "premium", minVersion: "10.6", notes: "MR approvals" },
      },
    },
    browse_mr_discussions: {
      default: { tier: "free", minVersion: "8.0" },
    },
    manage_merge_request: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        create: { tier: "free", minVersion: "8.0" },
        update: { tier: "free", minVersion: "8.0" },
        merge: { tier: "free", minVersion: "8.0" },
        approve: { tier: "premium", minVersion: "10.6", notes: "MR approvals" },
        unapprove: { tier: "premium", minVersion: "10.6", notes: "MR approvals" },
        get_approval_state: { tier: "premium", minVersion: "13.8", notes: "MR approval state" },
      },
    },
    manage_mr_discussion: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        comment: { tier: "free", minVersion: "8.0" },
        thread: { tier: "free", minVersion: "11.0" },
        reply: { tier: "free", minVersion: "11.0" },
        update: { tier: "free", minVersion: "8.0" },
        apply_suggestion: { tier: "free", minVersion: "13.0" },
        apply_suggestions: { tier: "free", minVersion: "13.0" },
        resolve: { tier: "free", minVersion: "10.0", notes: "Resolve discussion threads" },
        suggest: { tier: "free", minVersion: "10.5", notes: "Code suggestions" },
      },
    },
    manage_draft_notes: {
      default: { tier: "free", minVersion: "13.2" },
    },
 
    // Work Items
    browse_work_items: {
      default: { tier: "free", minVersion: "15.0" },
    },
    manage_work_item: {
      default: { tier: "free", minVersion: "15.0" },
    },
 
    // Labels
    browse_labels: {
      default: { tier: "free", minVersion: "8.0" },
    },
    manage_label: {
      default: { tier: "free", minVersion: "8.0" },
    },
 
    // Wiki
    browse_wiki: {
      default: { tier: "free", minVersion: "9.0" },
    },
    manage_wiki: {
      default: { tier: "free", minVersion: "9.0" },
    },
 
    // Pipelines
    browse_pipelines: {
      default: { tier: "free", minVersion: "9.0" },
    },
    manage_pipeline: {
      default: { tier: "free", minVersion: "9.0" },
    },
    manage_pipeline_job: {
      default: { tier: "free", minVersion: "9.0" },
    },
 
    // Variables
    browse_variables: {
      default: { tier: "free", minVersion: "9.0" },
    },
    manage_variable: {
      default: { tier: "free", minVersion: "9.0" },
    },
 
    // Milestones
    browse_milestones: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        burndown: { tier: "premium", minVersion: "12.0", notes: "Burndown charts" },
      },
    },
    manage_milestone: {
      default: { tier: "free", minVersion: "8.0" },
    },
 
    // Files
    browse_files: {
      default: { tier: "free", minVersion: "8.0" },
    },
    manage_files: {
      default: { tier: "free", minVersion: "8.0" },
    },
 
    // Snippets
    browse_snippets: {
      default: { tier: "free", minVersion: "8.15" },
    },
    manage_snippet: {
      default: { tier: "free", minVersion: "8.15" },
    },
 
    // Webhooks
    browse_webhooks: {
      default: { tier: "free", minVersion: "8.0", notes: "Project webhooks" },
    },
    manage_webhook: {
      default: { tier: "free", minVersion: "8.0", notes: "Project webhooks" },
      actions: {
        create_group: { tier: "premium", minVersion: "10.4", notes: "Group webhooks" },
        update_group: { tier: "premium", minVersion: "10.4", notes: "Group webhooks" },
        delete_group: { tier: "premium", minVersion: "10.4", notes: "Group webhooks" },
      },
    },
 
    // Integrations
    browse_integrations: {
      default: { tier: "free", minVersion: "8.0" },
    },
    manage_integration: {
      default: { tier: "free", minVersion: "8.0" },
    },
 
    // Todos
    manage_todos: {
      default: { tier: "free", minVersion: "8.0" },
    },
 
    // Releases
    browse_releases: {
      default: { tier: "free", minVersion: "11.7" },
    },
    manage_release: {
      default: { tier: "free", minVersion: "11.7" },
    },
 
    // Refs (branches and tags)
    browse_refs: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        list_branches: { tier: "free", minVersion: "8.0" },
        get_branch: { tier: "free", minVersion: "8.0" },
        list_tags: { tier: "free", minVersion: "8.0" },
        get_tag: { tier: "free", minVersion: "8.0" },
        list_protected_branches: { tier: "free", minVersion: "8.11" },
        get_protected_branch: { tier: "free", minVersion: "8.11" },
        list_protected_tags: { tier: "premium", minVersion: "11.3", notes: "Protected tags" },
      },
    },
    manage_ref: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        create_branch: { tier: "free", minVersion: "8.0" },
        delete_branch: { tier: "free", minVersion: "8.0" },
        protect_branch: { tier: "free", minVersion: "8.11" },
        unprotect_branch: { tier: "free", minVersion: "8.11" },
        update_branch_protection: {
          tier: "free",
          minVersion: "11.9",
          notes: "PATCH endpoint; code owners require Premium",
        },
        create_tag: { tier: "free", minVersion: "8.0" },
        delete_tag: { tier: "free", minVersion: "8.0" },
        protect_tag: { tier: "premium", minVersion: "11.3", notes: "Protected tags" },
        unprotect_tag: { tier: "premium", minVersion: "11.3", notes: "Protected tags" },
      },
    },
 
    // Members (team management)
    browse_members: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        list_project: { tier: "free", minVersion: "8.0" },
        list_group: { tier: "free", minVersion: "8.0" },
        get_project: { tier: "free", minVersion: "8.0" },
        get_group: { tier: "free", minVersion: "8.0" },
        list_all_project: { tier: "free", minVersion: "12.4", notes: "Includes inherited members" },
        list_all_group: { tier: "free", minVersion: "12.4", notes: "Includes inherited members" },
      },
    },
    manage_member: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        add_to_project: { tier: "free", minVersion: "8.0" },
        add_to_group: { tier: "free", minVersion: "8.0" },
        remove_from_project: { tier: "free", minVersion: "8.0" },
        remove_from_group: { tier: "free", minVersion: "8.0" },
        update_project: { tier: "free", minVersion: "8.0" },
        update_group: {
          tier: "free",
          minVersion: "8.0",
          notes: "member_role_id requires Ultimate",
        },
      },
    },
 
    // Search (read-only)
    browse_search: {
      default: { tier: "free", minVersion: "8.0" },
      actions: {
        global: { tier: "free", minVersion: "8.0", notes: "Global search across GitLab instance" },
        project: { tier: "free", minVersion: "8.0", notes: "Project-scoped search" },
        group: { tier: "free", minVersion: "10.5", notes: "Group-scoped search" },
      },
    },
  };
 
  // ============================================================================
  // Per-Parameter Tier Requirements
  // ============================================================================
 
  /**
   * Parameter-level requirements for tools with tier-gated parameters.
   * Parameters listed here will be stripped from the JSON Schema when the
   * detected instance tier/version is insufficient.
   */
  private static parameterRequirements: Record<string, Record<string, ParameterRequirement>> = {
    manage_work_item: {
      weight: { tier: "premium", minVersion: "15.0", notes: "Work item weight widget" },
      iterationId: { tier: "premium", minVersion: "15.0", notes: "Iteration widget" },
      healthStatus: { tier: "ultimate", minVersion: "15.0", notes: "Health status widget" },
    },
  };
 
  /**
   * Get list of parameter names that should be REMOVED from the schema
   * for the current instance tier and version.
   *
   * @param toolName - Tool name to check parameter requirements for
   * @returns Array of parameter names that should be stripped from the schema
   */
  public static getRestrictedParameters(
    toolName: string,
    cachedInstanceInfo?: { tier: GitLabTier; version: string }
  ): string[] {
    const paramReqs = this.parameterRequirements[toolName];
    if (!paramReqs) return [];
 
    let instanceTier: GitLabTier;
    let instanceVersion: number;
    let rawVersion: string;
 
    if (cachedInstanceInfo) {
      instanceTier = cachedInstanceInfo.tier;
      rawVersion = cachedInstanceInfo.version;
      instanceVersion = parseVersion(rawVersion);
    } else {
      const connectionManager = ConnectionManager.getInstance();
      try {
        const instanceInfo = connectionManager.getInstanceInfo();
        instanceTier = instanceInfo.tier;
        rawVersion = instanceInfo.version;
        instanceVersion = parseVersion(rawVersion);
      } catch {
        // Connection not initialized - don't restrict anything
        return [];
      }
    }
 
    const restricted: string[] = [];
    const actualTierLevel = this.TIER_ORDER[instanceTier] ?? 0;
 
    for (const [paramName, req] of Object.entries(paramReqs)) {
      const requiredTierLevel = this.TIER_ORDER[req.tier] ?? 0;
      const requiredVersion = parseVersion(req.minVersion);
 
      // Parameter is restricted if tier is insufficient OR version is too low
      if (actualTierLevel < requiredTierLevel || instanceVersion < requiredVersion) {
        restricted.push(paramName);
      }
    }
 
    if (restricted.length > 0) {
      logDebug("Tool restricted parameters", {
        toolName,
        tier: instanceTier,
        version: rawVersion,
        restricted: restricted.join(", "),
      });
    }
 
    return restricted;
  }
 
  /**
   * Get requirement for a tool, optionally with action
   */
  public static getActionRequirement(
    toolName: string,
    action?: string
  ): ActionRequirement | undefined {
    const toolReq = this.actionRequirements[toolName];
    if (!toolReq) return undefined;
 
    // If action specified, check action-specific requirement first
    if (action && toolReq.actions?.[action]) {
      return toolReq.actions[action];
    }
 
    return toolReq.default;
  }
 
  /**
   * Get the highest tier required by any action of a tool
   */
  public static getHighestTier(toolName: string): "free" | "premium" | "ultimate" {
    const toolReq = this.actionRequirements[toolName];
    if (!toolReq) return "free";
 
    let highest = toolReq.default.tier;
 
    if (toolReq.actions) {
      for (const actionReq of Object.values(toolReq.actions)) {
        Eif (this.TIER_ORDER[actionReq.tier] > this.TIER_ORDER[highest]) {
          highest = actionReq.tier;
        }
      }
    }
 
    return highest;
  }
 
  /**
   * Get all actions that require a specific tier or higher
   */
  public static getTierRestrictedActions(toolName: string, tier: "premium" | "ultimate"): string[] {
    const toolReq = this.actionRequirements[toolName];
    if (!toolReq?.actions) return [];
 
    const minLevel = this.TIER_ORDER[tier];
 
    return Object.entries(toolReq.actions)
      .filter(([, req]) => this.TIER_ORDER[req.tier] >= minLevel)
      .map(([action]) => action);
  }
 
  public static isToolAvailable(toolName: string, action?: string): boolean {
    const connectionManager = ConnectionManager.getInstance();
 
    // Add null check as extra safety
    if (!connectionManager) {
      logDebug("Tool availability check: ConnectionManager instance is null", { toolName });
      return false;
    }
 
    try {
      const instanceInfo = connectionManager.getInstanceInfo();
 
      const actionReq = this.getActionRequirement(toolName, action);
      if (actionReq) {
        const version = parseVersion(instanceInfo.version);
        if (version < parseVersion(actionReq.minVersion)) {
          return false;
        }
        return this.isTierSufficient(instanceInfo.tier, actionReq.tier);
      }
 
      // Tool not found in requirements - unknown tool
      logDebug("Tool not found in requirements database", { toolName });
      return parseVersion(instanceInfo.version) >= parseVersion("15.0");
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
 
      // In OAuth mode, introspection is deferred until first authenticated request.
      // Allow all tools initially - they'll be properly filtered on actual use.
      if (errorMessage.includes("Connection not initialized")) {
        logDebug("Tool availability check: instance info not available yet, allowing", {
          toolName,
        });
        return true;
      }
 
      logWarn("Failed to check tool availability", { toolName, error: errorMessage });
      return false;
    }
  }
 
  public static getAvailableTools(): string[] {
    return Object.keys(this.actionRequirements).filter(tool => this.isToolAvailable(tool));
  }
 
  public static getToolRequirement(toolName: string, action?: string): ToolRequirement | undefined {
    const actionReq = this.getActionRequirement(toolName, action);
    if (actionReq) {
      return {
        minVersion: actionReq.minVersion,
        requiredTier: actionReq.tier,
        notes: actionReq.notes,
      };
    }
    return undefined;
  }
 
  public static getUnavailableReason(toolName: string, action?: string): string | null {
    const connectionManager = ConnectionManager.getInstance();
 
    try {
      const instanceInfo = connectionManager.getInstanceInfo();
      const actionReq = this.getActionRequirement(toolName, action);
 
      if (!actionReq) {
        return `Tool '${toolName}' is not recognized`;
      }
 
      const version = parseVersion(instanceInfo.version);
      if (version < parseVersion(actionReq.minVersion)) {
        return `Requires GitLab ${actionReq.minVersion}+, current version is ${instanceInfo.version}`;
      }
 
      if (!this.isTierSufficient(instanceInfo.tier, actionReq.tier)) {
        return `Requires GitLab ${actionReq.tier} tier or higher, current tier is ${instanceInfo.tier}`;
      }
 
      return null; // Tool is available
    } catch {
      return "GitLab connection not initialized";
    }
  }
 
  private static isTierSufficient(
    actualTier: GitLabTier,
    requiredTier: "free" | "premium" | "ultimate"
  ): boolean {
    const tierHierarchy: Record<string, number> = {
      free: 0,
      premium: 1,
      ultimate: 2,
    };
 
    const actualLevel = tierHierarchy[actualTier] ?? 0;
    const requiredLevel = tierHierarchy[requiredTier] ?? 0;
 
    return actualLevel >= requiredLevel;
  }
 
  public static filterToolsByAvailability(tools: string[]): string[] {
    return tools.filter(tool => this.isToolAvailable(tool));
  }
 
  public static getToolsByTier(tier: "free" | "premium" | "ultimate"): string[] {
    return Object.entries(this.actionRequirements)
      .filter(([, req]) => req.default.tier === tier)
      .map(([toolName]) => toolName);
  }
 
  public static getToolsByMinVersion(minVersion: string): string[] {
    const minVer = parseVersion(minVersion);
    return Object.entries(this.actionRequirements)
      .filter(([, req]) => parseVersion(req.default.minVersion) >= minVer)
      .map(([toolName]) => toolName);
  }
}