Class: Aidp::Harness::ProviderManager
- Inherits:
-
Object
- Object
- Aidp::Harness::ProviderManager
- Includes:
- MessageDisplay, RescueLogging
- Defined in:
- lib/aidp/harness/provider_manager.rb
Overview
Manages provider switching and fallback logic
Constant Summary
Constants included from MessageDisplay
Instance Method Summary collapse
-
#all_metrics ⇒ Object
Get all provider metrics.
-
#all_model_health_status ⇒ Object
Get all model health status.
-
#all_model_metrics(provider_name) ⇒ Object
Get all model metrics for provider.
-
#available_models(provider_name) ⇒ Object
Get available models for a provider.
-
#available_providers ⇒ Object
Get available providers (not rate limited, healthy, and circuit breaker closed).
-
#build_default_fallback_chain(provider_name) ⇒ Object
Build default fallback chain.
-
#build_default_model_fallback_chain(provider_name) ⇒ Object
Build default model fallback chain.
-
#calculate_current_usage(provider_name) ⇒ Object
Calculate current usage for provider.
-
#calculate_model_current_usage(provider_name, model_name) ⇒ Object
Calculate current usage for model.
-
#calculate_model_load(provider_name, model_name) ⇒ Object
Calculate model load.
- #calculate_model_reset_time(_provider_name, _model_name) ⇒ Object
-
#calculate_provider_load(provider_name) ⇒ Object
Calculate provider load.
- #calculate_reset_time(_provider_name) ⇒ Object
-
#cleanup_expired_rate_limits ⇒ Object
Clean up expired rate limits from memory.
-
#clear_model_rate_limit(provider_name, model_name) ⇒ Object
Clear rate limit for model.
-
#clear_rate_limit(provider_name) ⇒ Object
Clear rate limit for provider.
-
#configure_model_weights(provider_name, weights) ⇒ Object
Configure model weights for load balancing.
-
#configure_provider_weights(weights) ⇒ Object
Configure provider weights for load balancing.
-
#configured_providers ⇒ Object
Get configured providers from configuration.
-
#current_model ⇒ Object
Get current model.
-
#current_provider ⇒ Object
Get current provider.
-
#current_provider_model ⇒ Object
Get current provider and model combination.
-
#default_flags(provider_name) ⇒ Object
Get default flags for provider.
-
#default_model(provider_name) ⇒ Object
Get default model for provider.
-
#deny_model(provider_name, model_name, error: nil) ⇒ Object
Add a model to the denylist for a provider (e.g., unsupported model errors).
-
#execute_with_provider(provider_type, prompt, options = {}) ⇒ Object
Execute a prompt with a specific provider.
-
#fallback_chain(provider_name) ⇒ Object
Get fallback chain for a provider.
-
#find_any_available_model(provider_name) ⇒ Object
Find any available model for provider.
-
#find_any_available_provider ⇒ Object
Find any available provider.
-
#find_next_healthy_model(model_chain, current_model) ⇒ Object
Find next healthy model in fallback chain.
-
#find_next_healthy_provider(fallback_chain, current_provider) ⇒ Object
Find next healthy provider in fallback chain.
-
#health_dashboard ⇒ Object
Summarize health and metrics for dashboard/CLI display.
-
#initialize(configuration, prompt: TTY::Prompt.new, binary_checker: Aidp::Util) ⇒ ProviderManager
constructor
A new instance of ProviderManager.
-
#is_model_circuit_breaker_open?(provider_name, model_name) ⇒ Boolean
Check if model circuit breaker is open.
-
#is_model_healthy?(provider_name, model_name) ⇒ Boolean
Check if model is healthy.
-
#is_model_rate_limited?(provider_name, model_name) ⇒ Boolean
Check if model is rate limited.
-
#is_provider_available?(provider_name) ⇒ Boolean
Check if provider is available (not rate limited, healthy, circuit breaker closed).
-
#is_provider_circuit_breaker_open?(provider_name) ⇒ Boolean
Check if provider circuit breaker is open.
-
#is_provider_healthy?(provider_name) ⇒ Boolean
Check if provider is healthy.
-
#is_rate_limited?(provider_name) ⇒ Boolean
Check if provider is rate limited.
-
#load_persisted_metrics ⇒ Object
Load persisted metrics from disk.
-
#log_circuit_breaker_event(provider_name, event) ⇒ Object
Log circuit breaker event.
-
#log_model_circuit_breaker_event(provider_name, model_name, event) ⇒ Object
Log model circuit breaker event.
-
#log_model_switch(from_model, to_model, reason, context) ⇒ Object
Log model switch.
-
#log_no_models_available(provider_name, reason, context) ⇒ Object
Log no models available.
-
#log_no_providers_available(reason, context) ⇒ Object
Log no providers available.
-
#log_provider_switch(from_provider, to_provider, reason, context) ⇒ Object
Log provider switch.
-
#mark_model_rate_limited(provider_name, model_name, reset_time = nil) ⇒ Object
Mark model as rate limited.
- #mark_provider_auth_failure(provider_name) ⇒ Object
-
#mark_provider_failure_exhausted(provider_name) ⇒ Object
Mark provider unhealthy specifically due to failure exhaustion (non-auth).
-
#mark_provider_unhealthy(provider_name, reason: "manual", open_circuit: true) ⇒ Object
Mark provider unhealthy (auth or generic) and optionally open circuit breaker.
-
#mark_rate_limited(provider_name, reset_time = nil) ⇒ Object
Mark provider as rate limited.
-
#metrics(provider_name) ⇒ Object
Get provider metrics.
-
#model_available?(provider_name, model_name) ⇒ Boolean
Check if model is available.
-
#model_configured?(provider_name, model_name) ⇒ Boolean
Check if model is configured for provider.
-
#model_denied?(provider_name, model_name) ⇒ Boolean
Check if a model has been denylisted for a provider.
-
#model_fallback_chain(provider_name) ⇒ Object
Get fallback chain for models within a provider.
-
#model_health_status(provider_name) ⇒ Object
Get detailed model health status.
-
#model_history ⇒ Object
Get model history.
-
#model_metrics(provider_name, model_name) ⇒ Object
Get model metrics.
-
#next_reset_time ⇒ Object
Get next reset time for any provider.
-
#open_circuit_breaker(provider_name) ⇒ Object
Open circuit breaker for provider.
-
#open_model_circuit_breaker(provider_name, model_name) ⇒ Object
Open circuit breaker for model.
-
#provider_cli_available?(provider_name) ⇒ Boolean
Attempt to run a provider’s CLI with –version (or no-op) to verify executable health.
-
#provider_config(provider_name) ⇒ Object
Get provider configuration.
-
#provider_health_status ⇒ Object
Get detailed provider health status.
-
#provider_history ⇒ Object
Get provider history.
-
#provider_installed?(provider_name) ⇒ Boolean
Determine whether a provider CLI/binary appears installed.
-
#provider_models(provider_name) ⇒ Object
Get models for a provider.
-
#provider_type(provider_name) ⇒ Object
Get provider type.
-
#record_metrics(provider_name, success:, duration:, tokens_used: nil, error: nil) ⇒ Object
Record provider metrics.
-
#record_model_metrics(provider_name, model_name, success:, duration:, tokens_used: nil, error: nil) ⇒ Object
Record model metrics.
-
#reset ⇒ Object
Reset all provider state.
-
#reset_circuit_breaker(provider_name) ⇒ Object
Reset circuit breaker for provider.
-
#reset_model_circuit_breaker(provider_name, model_name) ⇒ Object
Reset circuit breaker for model.
-
#save_persisted_metrics ⇒ Object
Save persisted metrics to disk.
-
#save_persisted_rate_limits ⇒ Object
Save persisted rate limits to disk.
-
#select_model_by_load_balancing(provider_name) ⇒ Object
Select model by load balancing.
-
#select_model_by_weight(provider_name, available_models) ⇒ Object
Select model by weight.
-
#select_provider_by_load_balancing ⇒ Object
Select provider by load balancing.
-
#select_provider_by_weight(available_providers) ⇒ Object
Select provider by weight.
-
#set_current_model(model_name, reason = "manual_switch", context = {}) ⇒ Object
Set current model with enhanced validation.
-
#set_current_provider(provider_name, reason = "manual_switch", context = {}) ⇒ Object
Set current provider with enhanced validation.
-
#set_load_balancing(enabled) ⇒ Object
Enable/disable load balancing.
-
#set_model_switching(enabled) ⇒ Object
Enable/disable model switching.
-
#status ⇒ Object
Get status summary.
-
#sticky_session_provider(session_id) ⇒ Object
Get sticky session provider.
-
#switch_model(reason = "manual_switch", context = {}) ⇒ Object
Switch to next available model within current provider.
-
#switch_model_for_error(error_type, error_details = {}) ⇒ Object
Switch model for specific error type.
-
#switch_model_with_retry(reason = "retry", max_retries = @max_retries) ⇒ Object
Switch model with retry logic.
-
#switch_provider(reason = "manual_switch", context = {}) ⇒ Object
Switch to next available provider with sophisticated fallback logic.
-
#switch_provider_for_error(error_type, error_details = {}) ⇒ Object
Switch provider for specific error type.
-
#switch_provider_with_retry(reason = "retry", max_retries = @max_retries) ⇒ Object
Switch provider with retry logic.
-
#update_model_health(provider_name, model_name, event, _details = {}) ⇒ Object
Update model health.
-
#update_provider_health(provider_name, event, _details = {}) ⇒ Object
Update provider health.
-
#update_sticky_session(provider_name) ⇒ Object
Update sticky session.
Methods included from RescueLogging
__log_rescue_impl, log_rescue, #log_rescue
Methods included from MessageDisplay
#display_message, included, #message_display_prompt
Constructor Details
#initialize(configuration, prompt: TTY::Prompt.new, binary_checker: Aidp::Util) ⇒ ProviderManager
Returns a new instance of ProviderManager.
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 |
# File 'lib/aidp/harness/provider_manager.rb', line 16 def initialize(configuration, prompt: TTY::Prompt.new, binary_checker: Aidp::Util) @configuration = configuration @prompt = prompt @binary_checker = binary_checker @current_provider = nil @current_model = nil @provider_history = [] @rate_limit_info = {} @provider_metrics = {} @fallback_chains = {} @provider_health = {} @retry_counts = {} @max_retries = 3 @circuit_breaker_threshold = 5 @circuit_breaker_timeout = 300 # 5 minutes @provider_weights = {} @load_balancing_enabled = true @sticky_sessions = {} @session_timeout = 1800 # 30 minutes @model_configs = {} @model_health = {} @model_metrics = {} @model_fallback_chains = {} @model_switching_enabled = true @model_weights = {} @model_denylist = Hash.new { |h, k| h[k] = [] } @unavailable_cache = {} @binary_check_cache = {} @binary_check_ttl = 300 # seconds # Initialize persistence project_dir = if configuration.respond_to?(:project_dir) configuration.project_dir elsif configuration.respond_to?(:root_dir) configuration.root_dir else Dir.pwd end @metrics_persistence = ProviderMetrics.new(project_dir) # Load persisted metrics load_persisted_metrics initialize_fallback_chains initialize_provider_health initialize_model_configs initialize_model_health end |
Instance Method Details
#all_metrics ⇒ Object
Get all provider metrics
1096 1097 1098 |
# File 'lib/aidp/harness/provider_manager.rb', line 1096 def all_metrics @provider_metrics.dup end |
#all_model_health_status ⇒ Object
Get all model health status
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 |
# File 'lib/aidp/harness/provider_manager.rb', line 1364 def all_model_health_status @model_health.transform_values do |provider_models| provider_models.transform_values do |health| { status: health[:status], error_count: health[:error_count], success_count: health[:success_count], circuit_breaker_open: health[:circuit_breaker_open], last_updated: health[:last_updated], last_used: health[:last_used], last_rate_limited: health[:last_rate_limited] } end end end |
#all_model_metrics(provider_name) ⇒ Object
Get all model metrics for provider
1080 1081 1082 |
# File 'lib/aidp/harness/provider_manager.rb', line 1080 def all_model_metrics(provider_name) @model_metrics[provider_name] || {} end |
#available_models(provider_name) ⇒ Object
Get available models for a provider
377 378 379 380 381 382 383 384 |
# File 'lib/aidp/harness/provider_manager.rb', line 377 def available_models(provider_name) models = provider_models(provider_name) models.select do |model| model_available?(provider_name, model) && is_model_healthy?(provider_name, model) && !is_model_circuit_breaker_open?(provider_name, model) end end |
#available_providers ⇒ Object
Get available providers (not rate limited, healthy, and circuit breaker closed)
367 368 369 370 371 372 373 374 |
# File 'lib/aidp/harness/provider_manager.rb', line 367 def available_providers all_providers = configured_providers all_providers.select do |provider| !is_rate_limited?(provider) && is_provider_healthy?(provider) && !is_provider_circuit_breaker_open?(provider) end end |
#build_default_fallback_chain(provider_name) ⇒ Object
Build default fallback chain
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 |
# File 'lib/aidp/harness/provider_manager.rb', line 557 def build_default_fallback_chain(provider_name) all_providers = configured_providers # Harness-defined explicit ordering has priority harness_fallbacks = if @configuration.respond_to?(:fallback_providers) Array(@configuration.fallback_providers).map(&:to_s) else [] end # Construct ordered chain: # 1. current provider first # 2. harness fallback providers (excluding current and de-duplicated) # 3. any remaining configured providers not already listed ordered = [provider_name] ordered += harness_fallbacks.reject { |p| p == provider_name || ordered.include?(p) } ordered += all_providers.reject { |p| ordered.include?(p) } @fallback_chains[provider_name] = ordered ordered end |
#build_default_model_fallback_chain(provider_name) ⇒ Object
Build default model fallback chain
455 456 457 458 459 |
# File 'lib/aidp/harness/provider_manager.rb', line 455 def build_default_model_fallback_chain(provider_name) models = provider_models(provider_name) @model_fallback_chains[provider_name] = models.dup models end |
#calculate_current_usage(provider_name) ⇒ Object
Calculate current usage for provider
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
# File 'lib/aidp/harness/provider_manager.rb', line 655 def calculate_current_usage(provider_name) # Simple usage calculation based on recent activity provider_metrics = metrics(provider_name) return 0 if provider_metrics.empty? last_used = provider_metrics[:last_used] return 0 unless last_used # Higher usage if used recently time_since_last_use = Time.now - last_used if time_since_last_use < 60 # Used within last minute 10 elsif time_since_last_use < 300 # Used within last 5 minutes 5 else 0 end end |
#calculate_model_current_usage(provider_name, model_name) ⇒ Object
Calculate current usage for model
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 |
# File 'lib/aidp/harness/provider_manager.rb', line 538 def calculate_model_current_usage(provider_name, model_name) metrics = model_metrics(provider_name, model_name) return 0 if metrics.empty? last_used = metrics[:last_used] return 0 unless last_used # Higher usage if used recently time_since_last_use = Time.now - last_used if time_since_last_use < 60 # Used within last minute 10 elsif time_since_last_use < 300 # Used within last 5 minutes 5 else 0 end end |
#calculate_model_load(provider_name, model_name) ⇒ Object
Calculate model load
524 525 526 527 528 529 530 531 532 533 534 535 |
# File 'lib/aidp/harness/provider_manager.rb', line 524 def calculate_model_load(provider_name, model_name) metrics = model_metrics(provider_name, model_name) return 0 if metrics.empty? # Calculate load based on success rate, response time, and current usage success_rate = metrics[:successful_requests].to_f / [metrics[:total_requests], 1].max avg_response_time = metrics[:total_duration] / [metrics[:successful_requests], 1].max current_usage = calculate_model_current_usage(provider_name, model_name) # Load formula: higher is worse (1 - success_rate) * 100 + avg_response_time + current_usage end |
#calculate_model_reset_time(_provider_name, _model_name) ⇒ Object
1716 1717 1718 1719 1720 |
# File 'lib/aidp/harness/provider_manager.rb', line 1716 def calculate_model_reset_time(_provider_name, _model_name) # Default reset time calculation for models # Most models reset rate limits every hour Time.now + (60 * 60) end |
#calculate_provider_load(provider_name) ⇒ Object
Calculate provider load
641 642 643 644 645 646 647 648 649 650 651 652 |
# File 'lib/aidp/harness/provider_manager.rb', line 641 def calculate_provider_load(provider_name) provider_metrics = metrics(provider_name) return 0 if provider_metrics.empty? # Calculate load based on success rate, response time, and current usage success_rate = provider_metrics[:successful_requests].to_f / [provider_metrics[:total_requests], 1].max avg_response_time = provider_metrics[:total_duration] / [provider_metrics[:successful_requests], 1].max current_usage = calculate_current_usage(provider_name) # Load formula: higher is worse (1 - success_rate) * 100 + avg_response_time + current_usage end |
#calculate_reset_time(_provider_name) ⇒ Object
1710 1711 1712 1713 1714 |
# File 'lib/aidp/harness/provider_manager.rb', line 1710 def calculate_reset_time(_provider_name) # Default reset time calculation # Most providers reset rate limits every hour Time.now + (60 * 60) end |
#cleanup_expired_rate_limits ⇒ Object
Clean up expired rate limits from memory
1757 1758 1759 1760 1761 1762 1763 |
# File 'lib/aidp/harness/provider_manager.rb', line 1757 def cleanup_expired_rate_limits now = Time.now @rate_limit_info.delete_if do |_provider, info| reset_time = info[:reset_time] reset_time && now >= reset_time end end |
#clear_model_rate_limit(provider_name, model_name) ⇒ Object
Clear rate limit for model
742 743 744 745 746 |
# File 'lib/aidp/harness/provider_manager.rb', line 742 def clear_model_rate_limit(provider_name, model_name) @model_rate_limit_info ||= {} model_key = "#{provider_name}:#{model_name}" @model_rate_limit_info.delete(model_key) end |
#clear_rate_limit(provider_name) ⇒ Object
Clear rate limit for provider
991 992 993 |
# File 'lib/aidp/harness/provider_manager.rb', line 991 def clear_rate_limit(provider_name) @rate_limit_info.delete(provider_name) end |
#configure_model_weights(provider_name, weights) ⇒ Object
Configure model weights for load balancing
1386 1387 1388 |
# File 'lib/aidp/harness/provider_manager.rb', line 1386 def configure_model_weights(provider_name, weights) @model_weights[provider_name] = weights.dup end |
#configure_provider_weights(weights) ⇒ Object
Configure provider weights for load balancing
1381 1382 1383 |
# File 'lib/aidp/harness/provider_manager.rb', line 1381 def configure_provider_weights(weights) @provider_weights = weights.dup end |
#configured_providers ⇒ Object
Get configured providers from configuration
81 82 83 84 85 86 87 88 |
# File 'lib/aidp/harness/provider_manager.rb', line 81 def configured_providers # Handle both Configuration and ConfigManager instances if @configuration.respond_to?(:configured_providers) @configuration.configured_providers else @configuration.provider_names end end |
#current_model ⇒ Object
Get current model
71 72 73 |
# File 'lib/aidp/harness/provider_manager.rb', line 71 def current_model @current_model ||= default_model(current_provider) end |
#current_provider ⇒ Object
Get current provider
66 67 68 |
# File 'lib/aidp/harness/provider_manager.rb', line 66 def current_provider @current_provider ||= @configuration.default_provider end |
#current_provider_model ⇒ Object
Get current provider and model combination
76 77 78 |
# File 'lib/aidp/harness/provider_manager.rb', line 76 def current_provider_model "#{current_provider}:#{current_model}" end |
#default_flags(provider_name) ⇒ Object
Get default flags for provider
1006 1007 1008 |
# File 'lib/aidp/harness/provider_manager.rb', line 1006 def default_flags(provider_name) @configuration.default_flags(provider_name) end |
#default_model(provider_name) ⇒ Object
Get default model for provider
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 |
# File 'lib/aidp/harness/provider_manager.rb', line 427 def default_model(provider_name) models = provider_models(provider_name) return models.first if models.any? # Fallback to provider-specific defaults case provider_name when "claude" "claude-3-5-sonnet-20241022" when "gemini" "gemini-1.5-pro" when "cursor" "cursor-default" else "default" end end |
#deny_model(provider_name, model_name, error: nil) ⇒ Object
Add a model to the denylist for a provider (e.g., unsupported model errors)
404 405 406 407 408 409 410 411 412 413 |
# File 'lib/aidp/harness/provider_manager.rb', line 404 def deny_model(provider_name, model_name, error: nil) return if provider_name.nil? || model_name.nil? return if model_denied?(provider_name, model_name) @model_denylist[provider_name] << model_name Aidp.log_debug("provider_manager", "model_denylisted", provider: provider_name, model: model_name, error: error&.) end |
#execute_with_provider(provider_type, prompt, options = {}) ⇒ Object
Execute a prompt with a specific provider
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 |
# File 'lib/aidp/harness/provider_manager.rb', line 1418 def execute_with_provider(provider_type, prompt, = {}) # Extract model from options if provided model_name = .delete(:model) retry_on_rate_limit = .delete(:retry_on_rate_limit) != false # Default true # Create provider factory instance provider_factory = ProviderFactory.new # Add model to provider options if specified = .dup [:model] = model_name if model_name # Create provider instance provider = provider_factory.create_provider(provider_type, ) # Set current provider and model @current_provider = provider_type @current_model = model_name if model_name Aidp.logger.debug("provider_manager", "Executing with provider", provider: provider_type, model: model_name, prompt_length: prompt.length) # Execute the prompt with the provider result = provider.(prompt: prompt, session: nil) # Return structured result { status: "completed", provider: provider_type, model: model_name, output: result, metadata: { provider_type: provider_type, model: model_name, prompt_length: prompt.length, timestamp: Time.now.strftime("%Y-%m-%dT%H:%M:%S.%3N%z") } } rescue => e log_rescue(e, component: "provider_manager", action: "execute_with_provider", fallback: "error_result", provider: provider_type, model: model_name, prompt_length: prompt.length) if unsupported_model_error?(e, model_name) deny_model(provider_type, model_name, error: e) end # Detect rate limit / quota errors and attempt fallback = e..to_s.downcase is_rate_limit = .include?("rate limit") || .include?("quota") || .include?("limit reached") || .include?("resource exhausted") || .include?("too many requests") if is_rate_limit && retry_on_rate_limit Aidp.logger.warn("provider_manager", "Rate limit detected, attempting fallback", provider: provider_type, model: model_name, error: e.) # Attempt to switch to fallback provider fallback_provider = switch_provider_for_error("rate_limit", { original_provider: provider_type, model: model_name, error_message: e. }) if fallback_provider && fallback_provider != provider_type Aidp.logger.info("provider_manager", "Retrying with fallback provider", original: provider_type, fallback: fallback_provider) # Retry with fallback provider (disable retry to prevent infinite loop) return execute_with_provider(fallback_provider, prompt, .merge(retry_on_rate_limit: false)) end end # Return error result { status: "error", provider: provider_type, error: e., metadata: { provider_type: provider_type, error_class: e.class.name, timestamp: Time.now.strftime("%Y-%m-%dT%H:%M:%S.%3N%z") } } end |
#fallback_chain(provider_name) ⇒ Object
Get fallback chain for a provider
445 446 447 |
# File 'lib/aidp/harness/provider_manager.rb', line 445 def fallback_chain(provider_name) @fallback_chains[provider_name] || build_default_fallback_chain(provider_name) end |
#find_any_available_model(provider_name) ⇒ Object
Find any available model for provider
477 478 479 480 481 482 483 484 485 486 487 488 |
# File 'lib/aidp/harness/provider_manager.rb', line 477 def find_any_available_model(provider_name) available_models = available_models(provider_name) return nil if available_models.empty? # Use weighted selection if weights are configured if @model_weights[provider_name]&.any? select_model_by_weight(provider_name, available_models) else # Simple round-robin selection available_models.first end end |
#find_any_available_provider ⇒ Object
Find any available provider
595 596 597 598 599 600 601 602 603 604 605 606 |
# File 'lib/aidp/harness/provider_manager.rb', line 595 def find_any_available_provider provider_list = available_providers return nil if provider_list.empty? # Use weighted selection if weights are configured if @provider_weights.any? select_provider_by_weight(provider_list) else # Simple round-robin selection provider_list.first end end |
#find_next_healthy_model(model_chain, current_model) ⇒ Object
Find next healthy model in fallback chain
462 463 464 465 466 467 468 469 470 471 472 473 474 |
# File 'lib/aidp/harness/provider_manager.rb', line 462 def find_next_healthy_model(model_chain, current_model) current_index = model_chain.index(current_model) || -1 # Start from next model in chain (current_index + 1...model_chain.size).each do |index| model = model_chain[index] if model_available?(current_provider, model) return model end end nil end |
#find_next_healthy_provider(fallback_chain, current_provider) ⇒ Object
Find next healthy provider in fallback chain
580 581 582 583 584 585 586 587 588 589 590 591 592 |
# File 'lib/aidp/harness/provider_manager.rb', line 580 def find_next_healthy_provider(fallback_chain, current_provider) current_index = fallback_chain.index(current_provider) || -1 # Start from next provider in chain (current_index + 1...fallback_chain.size).each do |index| provider = fallback_chain[index] if is_provider_available?(provider) return provider end end nil end |
#health_dashboard ⇒ Object
Summarize health and metrics for dashboard/CLI display
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 |
# File 'lib/aidp/harness/provider_manager.rb', line 1207 def health_dashboard now = Time.now statuses = provider_health_status metrics = all_metrics configured = configured_providers rows_by_normalized = {} configured.each do |prov| # Temporarily hide macos provider until it's user-configurable next if prov == "macos" normalized = normalize_provider_name(prov) cli_ok_prefetch, cli_reason_prefetch = provider_cli_available?(prov) h = statuses[prov] || {} m = metrics[prov] || {} rl = @rate_limit_info[prov] reset_in = (rl && rl[:reset_time]) ? [(rl[:reset_time] - now).to_i, 0].max : nil cb_remaining = if h[:circuit_breaker_open] && h[:circuit_breaker_opened_at] elapsed = now - h[:circuit_breaker_opened_at] rem = @circuit_breaker_timeout - elapsed rem.positive? ? rem.to_i : 0 end row = { provider: normalized, installed: provider_installed?(prov), status: h[:status] || (provider_installed?(prov) ? "unknown" : "uninstalled"), unhealthy_reason: h[:unhealthy_reason], available: false, # will set true below only if all checks pass circuit_breaker: h[:circuit_breaker_open] ? "open" : "closed", circuit_breaker_remaining: cb_remaining, rate_limited: !!rl, rate_limit_reset_in: reset_in, total_requests: m[:total_requests] || 0, failed_requests: m[:failed_requests] || 0, success_requests: m[:successful_requests] || 0, total_tokens: m[:total_tokens] || 0, last_used: m[:last_used] } # Incorporate CLI check outcome into reason/availability if failing unless cli_ok_prefetch row[:available] = false row[:unhealthy_reason] ||= cli_reason_prefetch row[:status] = "unhealthy" if row[:status] == "healthy" || row[:status] == "healthy_auth" end if cli_ok_prefetch && is_provider_available?(prov) row[:available] = true end if (existing = rows_by_normalized[normalized]) # Merge metrics: sum counts/tokens, keep most severe status, earliest unhealthy reason if any existing[:total_requests] += row[:total_requests] existing[:failed_requests] += row[:failed_requests] existing[:success_requests] += row[:success_requests] existing[:total_tokens] += row[:total_tokens] # If either unavailable then mark unavailable existing[:available] &&= row[:available] # Prefer an unhealthy or circuit breaker status over healthy existing[:status] = merge_status_priority(existing[:status], row[:status]) existing[:unhealthy_reason] ||= row[:unhealthy_reason] # Circuit breaker open takes precedence if row[:circuit_breaker] == "open" existing[:circuit_breaker] = "open" existing[:circuit_breaker_remaining] = [existing[:circuit_breaker_remaining].to_i, row[:circuit_breaker_remaining].to_i].max end # Rate limited if any underlying if row[:rate_limited] existing[:rate_limited] = true existing[:rate_limit_reset_in] = [existing[:rate_limit_reset_in].to_i, row[:rate_limit_reset_in].to_i].max end # Keep most recent last_used if row[:last_used] && (!existing[:last_used] || row[:last_used] > existing[:last_used]) existing[:last_used] = row[:last_used] end else rows_by_normalized[normalized] = row end end rows_by_normalized.values end |
#is_model_circuit_breaker_open?(provider_name, model_name) ⇒ Boolean
Check if model circuit breaker is open
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 |
# File 'lib/aidp/harness/provider_manager.rb', line 757 def is_model_circuit_breaker_open?(provider_name, model_name) health = @model_health[provider_name]&.dig(model_name) return false unless health if health[:circuit_breaker_open] # Check if timeout has passed if health[:circuit_breaker_opened_at] && Time.now - health[:circuit_breaker_opened_at] > @circuit_breaker_timeout # Reset circuit breaker reset_model_circuit_breaker(provider_name, model_name) return false end return true end false end |
#is_model_healthy?(provider_name, model_name) ⇒ Boolean
Check if model is healthy
749 750 751 752 753 754 |
# File 'lib/aidp/harness/provider_manager.rb', line 749 def is_model_healthy?(provider_name, model_name) health = @model_health[provider_name]&.dig(model_name) return true unless health # Default to healthy if no health info health[:status] == "healthy" end |
#is_model_rate_limited?(provider_name, model_name) ⇒ Boolean
Check if model is rate limited
712 713 714 715 716 717 718 719 720 |
# File 'lib/aidp/harness/provider_manager.rb', line 712 def is_model_rate_limited?(provider_name, model_name) info = @model_rate_limit_info ||= {} model_key = "#{provider_name}:#{model_name}" rate_limit_info = info[model_key] return false unless rate_limit_info reset_time = rate_limit_info[:reset_time] reset_time && Time.now < reset_time end |
#is_provider_available?(provider_name) ⇒ Boolean
Check if provider is available (not rate limited, healthy, circuit breaker closed)
675 676 677 678 679 680 681 682 |
# File 'lib/aidp/harness/provider_manager.rb', line 675 def is_provider_available?(provider_name) cli_ok, _reason = provider_cli_available?(provider_name) return false unless cli_ok return false if is_rate_limited?(provider_name) return false unless is_provider_healthy?(provider_name) return false if is_provider_circuit_breaker_open?(provider_name) true end |
#is_provider_circuit_breaker_open?(provider_name) ⇒ Boolean
Check if provider circuit breaker is open
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 |
# File 'lib/aidp/harness/provider_manager.rb', line 868 def is_provider_circuit_breaker_open?(provider_name) health = @provider_health[provider_name] return false unless health if health[:circuit_breaker_open] # Check if timeout has passed if health[:circuit_breaker_opened_at] && Time.now - health[:circuit_breaker_opened_at] > @circuit_breaker_timeout # Reset circuit breaker reset_circuit_breaker(provider_name) return false end return true end false end |
#is_provider_healthy?(provider_name) ⇒ Boolean
Check if provider is healthy
860 861 862 863 864 865 |
# File 'lib/aidp/harness/provider_manager.rb', line 860 def is_provider_healthy?(provider_name) health = @provider_health[provider_name] return true unless health # Default to healthy if no health info health[:status] == "healthy" end |
#is_rate_limited?(provider_name) ⇒ Boolean
Check if provider is rate limited
851 852 853 854 855 856 857 |
# File 'lib/aidp/harness/provider_manager.rb', line 851 def is_rate_limited?(provider_name) info = @rate_limit_info[provider_name] return false unless info reset_time = info[:reset_time] reset_time && Time.now < reset_time end |
#load_persisted_metrics ⇒ Object
Load persisted metrics from disk
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 |
# File 'lib/aidp/harness/provider_manager.rb', line 1723 def load_persisted_metrics return unless @metrics_persistence # Load provider metrics persisted_metrics = @metrics_persistence.load_metrics @provider_metrics.merge!(persisted_metrics) if persisted_metrics.is_a?(Hash) # Load rate limit info persisted_rate_limits = @metrics_persistence.load_rate_limits @rate_limit_info.merge!(persisted_rate_limits) if persisted_rate_limits.is_a?(Hash) # Clean up expired rate limits cleanup_expired_rate_limits rescue => e log_rescue(e, component: "provider_manager", action: "load_persisted_metrics", fallback: nil) end |
#log_circuit_breaker_event(provider_name, event) ⇒ Object
Log circuit breaker event
1674 1675 1676 1677 1678 1679 1680 1681 |
# File 'lib/aidp/harness/provider_manager.rb', line 1674 def log_circuit_breaker_event(provider_name, event) case event when "opened" ("🔴 Circuit breaker opened for provider: #{provider_name}", type: :error) when "reset" ("🟢 Circuit breaker reset for provider: #{provider_name}", type: :success) end end |
#log_model_circuit_breaker_event(provider_name, model_name, event) ⇒ Object
Log model circuit breaker event
1701 1702 1703 1704 1705 1706 1707 1708 |
# File 'lib/aidp/harness/provider_manager.rb', line 1701 def log_model_circuit_breaker_event(provider_name, model_name, event) case event when "opened" ("🔴 Circuit breaker opened for model: #{provider_name}:#{model_name}", type: :error) when "reset" ("🟢 Circuit breaker reset for model: #{provider_name}:#{model_name}", type: :success) end end |
#log_model_switch(from_model, to_model, reason, context) ⇒ Object
Log model switch
1684 1685 1686 1687 1688 1689 |
# File 'lib/aidp/harness/provider_manager.rb', line 1684 def log_model_switch(from_model, to_model, reason, context) ("🔄 Model switch: #{from_model} → #{to_model} (#{reason})", type: :info) if context.any? (" Context: #{context.inspect}", type: :muted) end end |
#log_no_models_available(provider_name, reason, context) ⇒ Object
Log no models available
1692 1693 1694 1695 1696 1697 1698 |
# File 'lib/aidp/harness/provider_manager.rb', line 1692 def log_no_models_available(provider_name, reason, context) ("❌ No models available for provider #{provider_name} (#{reason})", type: :error) (" All models are rate limited, unhealthy, or circuit breaker open", type: :warning) if context.any? (" Context: #{context.inspect}", type: :muted) end end |
#log_no_providers_available(reason, context) ⇒ Object
Log no providers available
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 |
# File 'lib/aidp/harness/provider_manager.rb', line 1641 def log_no_providers_available(reason, context) ("❌ No providers available for switching (#{reason})", type: :error) # Check if we have any fallback providers configured harness_fallbacks = if @configuration.respond_to?(:fallback_providers) Array(@configuration.fallback_providers).compact else [] end all_providers = configured_providers if harness_fallbacks.empty? && all_providers.size <= 1 (" No fallback providers configured in aidp.yml", type: :warning) (" 💡 Add fallback providers to enable automatic failover:", type: :info) (" harness:", type: :muted) (" fallback_providers:", type: :muted) (" - anthropic", type: :muted) (" - gemini", type: :muted) (" Run 'aidp config --interactive' to configure providers", type: :info) else (" All providers are rate limited, unhealthy, or circuit breaker open", type: :warning) if harness_fallbacks.any? (" Configured fallbacks: #{harness_fallbacks.join(", ")}", type: :muted) end end if context.any? (" Context: #{context.inspect}", type: :muted) end end |
#log_provider_switch(from_provider, to_provider, reason, context) ⇒ Object
Log provider switch
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 |
# File 'lib/aidp/harness/provider_manager.rb', line 1627 def log_provider_switch(from_provider, to_provider, reason, context) if from_provider == to_provider # Same provider - this indicates no fallback was possible ("⚠️ Provider switch failed: #{from_provider} → #{to_provider} (#{reason})", type: :warning) (" No alternative providers available", type: :warning) else ("🔄 Provider switch: #{from_provider} → #{to_provider} (#{reason})", type: :info) end if context.any? (" Context: #{context.inspect}", type: :muted) end end |
#mark_model_rate_limited(provider_name, model_name, reset_time = nil) ⇒ Object
Mark model as rate limited
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 |
# File 'lib/aidp/harness/provider_manager.rb', line 723 def mark_model_rate_limited(provider_name, model_name, reset_time = nil) @model_rate_limit_info ||= {} model_key = "#{provider_name}:#{model_name}" @model_rate_limit_info[model_key] = { rate_limited_at: Time.now, reset_time: reset_time || calculate_model_reset_time(provider_name, model_name), error_count: (@model_rate_limit_info[model_key]&.dig(:error_count) || 0) + 1 } # Update model health update_model_health(provider_name, model_name, "rate_limited") # Switch to next model if current one is rate limited if provider_name == current_provider && model_name == current_model switch_model("rate_limit", {provider: provider_name, model: model_name}) end end |
#mark_provider_auth_failure(provider_name) ⇒ Object
698 699 700 |
# File 'lib/aidp/harness/provider_manager.rb', line 698 def mark_provider_auth_failure(provider_name) mark_provider_unhealthy(provider_name, reason: "auth", open_circuit: true) end |
#mark_provider_failure_exhausted(provider_name) ⇒ Object
Mark provider unhealthy specifically due to failure exhaustion (non-auth)
703 704 705 706 707 708 709 |
# File 'lib/aidp/harness/provider_manager.rb', line 703 def mark_provider_failure_exhausted(provider_name) return unless @provider_health[provider_name] health = @provider_health[provider_name] # Don't override more critical states (auth or circuit already open) return if health[:unhealthy_reason] == "auth" mark_provider_unhealthy(provider_name, reason: "fail_exhausted", open_circuit: true) end |
#mark_provider_unhealthy(provider_name, reason: "manual", open_circuit: true) ⇒ Object
Mark provider unhealthy (auth or generic) and optionally open circuit breaker
685 686 687 688 689 690 691 692 693 694 695 696 |
# File 'lib/aidp/harness/provider_manager.rb', line 685 def mark_provider_unhealthy(provider_name, reason: "manual", open_circuit: true) return unless @provider_health[provider_name] health = @provider_health[provider_name] health[:status] = (reason == "auth") ? "unhealthy_auth" : "unhealthy" health[:last_updated] = Time.now health[:unhealthy_reason] = reason if open_circuit health[:circuit_breaker_open] = true health[:circuit_breaker_opened_at] = Time.now log_circuit_breaker_event(provider_name, "opened") end end |
#mark_rate_limited(provider_name, reset_time = nil) ⇒ Object
Mark provider as rate limited
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 |
# File 'lib/aidp/harness/provider_manager.rb', line 961 def mark_rate_limited(provider_name, reset_time = nil) @rate_limit_info[provider_name] = { rate_limited_at: Time.now, reset_time: reset_time || calculate_reset_time(provider_name), error_count: (@rate_limit_info[provider_name]&.dig(:error_count) || 0) + 1 } # Update provider health update_provider_health(provider_name, "rate_limited") # Persist rate limit info to disk save_persisted_rate_limits # Switch to next provider if current one is rate limited if provider_name == current_provider switch_provider("rate_limit", {provider: provider_name}) end end |
#metrics(provider_name) ⇒ Object
Get provider metrics
1091 1092 1093 |
# File 'lib/aidp/harness/provider_manager.rb', line 1091 def metrics(provider_name) @provider_metrics[provider_name] || {} end |
#model_available?(provider_name, model_name) ⇒ Boolean
Check if model is available
387 388 389 390 391 392 393 394 395 396 |
# File 'lib/aidp/harness/provider_manager.rb', line 387 def model_available?(provider_name, model_name) # Check if model is configured for provider return false unless model_configured?(provider_name, model_name) # Skip models that were explicitly denied (e.g., unsupported by provider) return false if model_denied?(provider_name, model_name) # Check if model is not rate limited !is_model_rate_limited?(provider_name, model_name) end |
#model_configured?(provider_name, model_name) ⇒ Boolean
Check if model is configured for provider
416 417 418 419 |
# File 'lib/aidp/harness/provider_manager.rb', line 416 def model_configured?(provider_name, model_name) models = provider_models(provider_name) models.include?(model_name) end |
#model_denied?(provider_name, model_name) ⇒ Boolean
Check if a model has been denylisted for a provider
399 400 401 |
# File 'lib/aidp/harness/provider_manager.rb', line 399 def model_denied?(provider_name, model_name) @model_denylist[provider_name]&.include?(model_name) end |
#model_fallback_chain(provider_name) ⇒ Object
Get fallback chain for models within a provider
450 451 452 |
# File 'lib/aidp/harness/provider_manager.rb', line 450 def model_fallback_chain(provider_name) @model_fallback_chains[provider_name] || build_default_model_fallback_chain(provider_name) end |
#model_health_status(provider_name) ⇒ Object
Get detailed model health status
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 |
# File 'lib/aidp/harness/provider_manager.rb', line 1349 def model_health_status(provider_name) @model_health[provider_name]&.transform_values do |health| { status: health[:status], error_count: health[:error_count], success_count: health[:success_count], circuit_breaker_open: health[:circuit_breaker_open], last_updated: health[:last_updated], last_used: health[:last_used], last_rate_limited: health[:last_rate_limited] } end || {} end |
#model_history ⇒ Object
Get model history
1085 1086 1087 1088 |
# File 'lib/aidp/harness/provider_manager.rb', line 1085 def model_history @model_history ||= [] @model_history.dup end |
#model_metrics(provider_name, model_name) ⇒ Object
Get model metrics
1075 1076 1077 |
# File 'lib/aidp/harness/provider_manager.rb', line 1075 def model_metrics(provider_name, model_name) @model_metrics[provider_name]&.dig(model_name) || {} end |
#next_reset_time ⇒ Object
Get next reset time for any provider
981 982 983 984 985 986 987 988 |
# File 'lib/aidp/harness/provider_manager.rb', line 981 def next_reset_time reset_times = @rate_limit_info.values .map { |info| info[:reset_time] } .compact .select { |time| time > Time.now } reset_times.min end |
#open_circuit_breaker(provider_name) ⇒ Object
Open circuit breaker for provider
935 936 937 938 939 940 941 942 943 944 |
# File 'lib/aidp/harness/provider_manager.rb', line 935 def open_circuit_breaker(provider_name) health = @provider_health[provider_name] return unless health health[:circuit_breaker_open] = true health[:circuit_breaker_opened_at] = Time.now health[:status] = "circuit_breaker_open" log_circuit_breaker_event(provider_name, "opened") end |
#open_model_circuit_breaker(provider_name, model_name) ⇒ Object
Open circuit breaker for model
825 826 827 828 829 830 831 832 833 834 |
# File 'lib/aidp/harness/provider_manager.rb', line 825 def open_model_circuit_breaker(provider_name, model_name) health = @model_health[provider_name]&.dig(model_name) return unless health health[:circuit_breaker_open] = true health[:circuit_breaker_opened_at] = Time.now health[:status] = "circuit_breaker_open" log_model_circuit_breaker_event(provider_name, model_name, "opened") end |
#provider_cli_available?(provider_name) ⇒ Boolean
Attempt to run a provider’s CLI with –version (or no-op) to verify executable health
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 |
# File 'lib/aidp/harness/provider_manager.rb', line 1126 def provider_cli_available?(provider_name) normalized = normalize_provider_name(provider_name) cache_key = "#{provider_name}:#{normalized}" cached = @binary_check_cache[cache_key] if cached && (Time.now - cached[:checked_at] < @binary_check_ttl) return [cached[:ok], cached[:reason]] end # Map normalized provider -> binary binary = case normalized when "claude" then "claude" when "cursor" then "cursor" when "gemini" then "gemini" when "macos" then nil # passthrough; no direct binary expected end unless binary @binary_check_cache[cache_key] = {ok: true, reason: nil, checked_at: Time.now} return [true, nil] end path = begin @binary_checker.which(binary) rescue => e log_rescue(e, component: "provider_manager", action: "locate_binary", fallback: nil, binary: binary) nil end unless path @binary_check_cache[cache_key] = {ok: false, reason: "binary_missing", checked_at: Time.now} return [false, "binary_missing"] end # Light command execution to ensure it responds quickly ok = true reason = nil begin # Use IO.popen to avoid shell injection and impose a short timeout r, w = IO.pipe pid = Process.spawn(binary, "--version", out: w, err: w) w.close # Wait for process to exit with timeout begin Aidp::Concurrency::Wait.for_process_exit(pid, timeout: 3, interval: 0.05) rescue Aidp::Concurrency::TimeoutError # Timeout -> kill process begin Process.kill("TERM", pid) rescue => e log_rescue(e, component: "provider_manager", action: "kill_timeout_process_term", fallback: nil, binary: binary, pid: pid) nil end # Brief wait for TERM to take effect begin Aidp::Concurrency::Wait.for_process_exit(pid, timeout: 0.1, interval: 0.02) rescue Aidp::Concurrency::TimeoutError # TERM didn't work, use KILL begin Process.kill("KILL", pid) rescue => e log_rescue(e, component: "provider_manager", action: "kill_timeout_process_kill", fallback: nil, binary: binary, pid: pid) nil end end ok = false reason = "binary_timeout" end output = r.read.to_s r.close if ok && output.strip.empty? # Some CLIs require just calling without args; treat empty as still OK ok = true end rescue => e log_rescue(e, component: "provider_manager", action: "verify_binary_health", fallback: "binary_error", binary: binary) ok = false reason = e.class.name.downcase.include?("enoent") ? "binary_missing" : "binary_error" end @binary_check_cache[cache_key] = {ok: ok, reason: reason, checked_at: Time.now} [ok, reason] end |
#provider_config(provider_name) ⇒ Object
Get provider configuration
996 997 998 |
# File 'lib/aidp/harness/provider_manager.rb', line 996 def provider_config(provider_name) @configuration.provider_config(provider_name) end |
#provider_health_status ⇒ Object
Get detailed provider health status
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 |
# File 'lib/aidp/harness/provider_manager.rb', line 1332 def provider_health_status @provider_health.transform_values do |health| { status: health[:status], error_count: health[:error_count], success_count: health[:success_count], circuit_breaker_open: health[:circuit_breaker_open], last_updated: health[:last_updated], last_used: health[:last_used], last_rate_limited: health[:last_rate_limited], circuit_breaker_opened_at: health[:circuit_breaker_opened_at], unhealthy_reason: health[:unhealthy_reason] } end end |
#provider_history ⇒ Object
Get provider history
1285 1286 1287 |
# File 'lib/aidp/harness/provider_manager.rb', line 1285 def provider_history @provider_history.dup end |
#provider_installed?(provider_name) ⇒ Boolean
Determine whether a provider CLI/binary appears installed
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 |
# File 'lib/aidp/harness/provider_manager.rb', line 1101 def provider_installed?(provider_name) return @unavailable_cache[provider_name] unless @unavailable_cache[provider_name].nil? installed = true begin case provider_name when "anthropic", "claude" # Prefer direct binary probe instead of Anthropic.available? (which uses which internally) path = begin Aidp::Util.which("claude") rescue nil end installed = !path.nil? when "cursor" require_relative "../providers/cursor" installed = Aidp::Providers::Cursor.available? end rescue LoadError => e log_rescue(e, component: "provider_manager", action: "check_provider_availability", fallback: false, provider: provider_name) installed = false end @unavailable_cache[provider_name] = installed end |
#provider_models(provider_name) ⇒ Object
Get models for a provider
422 423 424 |
# File 'lib/aidp/harness/provider_manager.rb', line 422 def provider_models(provider_name) @model_configs[provider_name] || [] end |
#provider_type(provider_name) ⇒ Object
Get provider type
1001 1002 1003 |
# File 'lib/aidp/harness/provider_manager.rb', line 1001 def provider_type(provider_name) @configuration.provider_type(provider_name) end |
#record_metrics(provider_name, success:, duration:, tokens_used: nil, error: nil) ⇒ Object
Record provider metrics
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 |
# File 'lib/aidp/harness/provider_manager.rb', line 1011 def record_metrics(provider_name, success:, duration:, tokens_used: nil, error: nil) @provider_metrics[provider_name] ||= { total_requests: 0, successful_requests: 0, failed_requests: 0, total_duration: 0.0, total_tokens: 0, last_used: nil, last_error: nil, last_error_time: nil } metrics = @provider_metrics[provider_name] metrics[:total_requests] += 1 metrics[:last_used] = Time.now if success metrics[:successful_requests] += 1 metrics[:total_duration] += duration metrics[:total_tokens] += tokens_used if tokens_used update_provider_health(provider_name, "success") else metrics[:failed_requests] += 1 metrics[:last_error] = error&. || "Unknown error" metrics[:last_error_time] = Time.now update_provider_health(provider_name, "error", {error: error}) end # Persist metrics to disk save_persisted_metrics end |
#record_model_metrics(provider_name, model_name, success:, duration:, tokens_used: nil, error: nil) ⇒ Object
Record model metrics
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 |
# File 'lib/aidp/harness/provider_manager.rb', line 1044 def record_model_metrics(provider_name, model_name, success:, duration:, tokens_used: nil, error: nil) @model_metrics[provider_name] ||= {} @model_metrics[provider_name][model_name] ||= { total_requests: 0, successful_requests: 0, failed_requests: 0, total_duration: 0.0, total_tokens: 0, last_used: nil, last_error: nil, last_error_time: nil } metrics = @model_metrics[provider_name][model_name] metrics[:total_requests] += 1 metrics[:last_used] = Time.now if success metrics[:successful_requests] += 1 metrics[:total_duration] += duration metrics[:total_tokens] += tokens_used if tokens_used update_model_health(provider_name, model_name, "success") else metrics[:failed_requests] += 1 metrics[:last_error] = error&. || "Unknown error" metrics[:last_error_time] = Time.now update_model_health(provider_name, model_name, "error", {error: error}) end end |
#reset ⇒ Object
Reset all provider state
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 |
# File 'lib/aidp/harness/provider_manager.rb', line 1290 def reset @current_provider = nil @current_model = nil @provider_history.clear @rate_limit_info.clear @provider_metrics.clear @provider_health.clear @retry_counts.clear @sticky_sessions.clear @model_configs.clear @model_health.clear @model_metrics.clear @model_fallback_chains.clear @model_denylist.clear @model_rate_limit_info&.clear @model_history&.clear initialize_fallback_chains initialize_provider_health initialize_model_configs initialize_model_health end |
#reset_circuit_breaker(provider_name) ⇒ Object
Reset circuit breaker for provider
947 948 949 950 951 952 953 954 955 956 957 958 |
# File 'lib/aidp/harness/provider_manager.rb', line 947 def reset_circuit_breaker(provider_name) health = @provider_health[provider_name] return unless health was_open = health[:circuit_breaker_open] health[:circuit_breaker_open] = false health[:circuit_breaker_opened_at] = nil health[:error_count] = 0 health[:status] = "healthy" log_circuit_breaker_event(provider_name, "reset") if was_open end |
#reset_model_circuit_breaker(provider_name, model_name) ⇒ Object
Reset circuit breaker for model
837 838 839 840 841 842 843 844 845 846 847 848 |
# File 'lib/aidp/harness/provider_manager.rb', line 837 def reset_model_circuit_breaker(provider_name, model_name) health = @model_health[provider_name]&.dig(model_name) return unless health was_open = health[:circuit_breaker_open] health[:circuit_breaker_open] = false health[:circuit_breaker_opened_at] = nil health[:error_count] = 0 health[:status] = "healthy" log_model_circuit_breaker_event(provider_name, model_name, "reset") if was_open end |
#save_persisted_metrics ⇒ Object
Save persisted metrics to disk
1741 1742 1743 1744 1745 1746 |
# File 'lib/aidp/harness/provider_manager.rb', line 1741 def save_persisted_metrics return unless @metrics_persistence @metrics_persistence.save_metrics(@provider_metrics) rescue => e log_rescue(e, component: "provider_manager", action: "save_persisted_metrics", fallback: nil) end |
#save_persisted_rate_limits ⇒ Object
Save persisted rate limits to disk
1749 1750 1751 1752 1753 1754 |
# File 'lib/aidp/harness/provider_manager.rb', line 1749 def save_persisted_rate_limits return unless @metrics_persistence @metrics_persistence.save_rate_limits(@rate_limit_info) rescue => e log_rescue(e, component: "provider_manager", action: "save_persisted_rate_limits", fallback: nil) end |
#select_model_by_load_balancing(provider_name) ⇒ Object
Select model by load balancing
491 492 493 494 495 496 497 498 499 500 501 502 503 |
# File 'lib/aidp/harness/provider_manager.rb', line 491 def select_model_by_load_balancing(provider_name) available_models = available_models(provider_name) return nil if available_models.empty? # Calculate load for each model model_loads = available_models.map do |model| load = calculate_model_load(provider_name, model) [model, load] end # Select model with lowest load model_loads.min_by { |_, load| load }&.first end |
#select_model_by_weight(provider_name, available_models) ⇒ Object
Select model by weight
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'lib/aidp/harness/provider_manager.rb', line 506 def select_model_by_weight(provider_name, available_models) weights = @model_weights[provider_name] || {} total_weight = available_models.sum { |model| weights[model] || 1 } return available_models.first if total_weight == 0 random_value = rand(total_weight) current_weight = 0 available_models.each do |model| weight = weights[model] || 1 current_weight += weight return model if random_value < current_weight end available_models.last end |
#select_provider_by_load_balancing ⇒ Object
Select provider by load balancing
609 610 611 612 613 614 615 616 617 618 619 620 621 |
# File 'lib/aidp/harness/provider_manager.rb', line 609 def select_provider_by_load_balancing provider_list = available_providers return nil if provider_list.empty? # Calculate load for each provider provider_loads = provider_list.map do |provider| load = calculate_provider_load(provider) [provider, load] end # Select provider with lowest load provider_loads.min_by { |_, load| load }&.first end |
#select_provider_by_weight(available_providers) ⇒ Object
Select provider by weight
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
# File 'lib/aidp/harness/provider_manager.rb', line 624 def select_provider_by_weight(available_providers) total_weight = available_providers.sum { |provider| @provider_weights[provider] || 1 } return available_providers.first if total_weight == 0 random_value = rand(total_weight) current_weight = 0 available_providers.each do |provider| weight = @provider_weights[provider] || 1 current_weight += weight return provider if random_value < current_weight end available_providers.last end |
#set_current_model(model_name, reason = "manual_switch", context = {}) ⇒ Object
Set current model with enhanced validation
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
# File 'lib/aidp/harness/provider_manager.rb', line 296 def set_current_model(model_name, reason = "manual_switch", context = {}) return false unless model_available?(current_provider, model_name) return false unless is_model_healthy?(current_provider, model_name) return false if is_model_circuit_breaker_open?(current_provider, model_name) # Update model health update_model_health(current_provider, model_name, "switched_to") # Record model switch @model_history ||= [] @model_history << { provider: current_provider, model: model_name, switched_at: Time.now, reason: reason, context: context, previous_model: @current_model } @current_model = model_name true end |
#set_current_provider(provider_name, reason = "manual_switch", context = {}) ⇒ Object
Set current provider with enhanced validation
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 |
# File 'lib/aidp/harness/provider_manager.rb', line 320 def set_current_provider(provider_name, reason = "manual_switch", context = {}) # Use provider_config for ConfigManager, provider_configured? for legacy Configuration config_exists = if @configuration.respond_to?(:provider_config) @configuration.provider_config(provider_name) else @configuration.provider_configured?(provider_name) end unless config_exists Aidp.logger.warn("provider_manager", "Provider not configured", provider: provider_name) return false end unless is_provider_healthy?(provider_name) Aidp.logger.warn("provider_manager", "Provider not healthy", provider: provider_name) return false end if is_provider_circuit_breaker_open?(provider_name) Aidp.logger.warn("provider_manager", "Provider circuit breaker open", provider: provider_name) return false end # Update provider health update_provider_health(provider_name, "switched_to") # Record provider switch @provider_history << { provider: provider_name, switched_at: Time.now, reason: reason, context: context, previous_provider: @current_provider } # Update sticky session if enabled update_sticky_session(provider_name) if context[:session_id] # Reset current model when switching providers @current_model = default_model(provider_name) @current_provider = provider_name Aidp.logger.info("provider_manager", "Provider activated", provider: provider_name, reason: reason) true end |
#set_load_balancing(enabled) ⇒ Object
Enable/disable load balancing
1391 1392 1393 |
# File 'lib/aidp/harness/provider_manager.rb', line 1391 def set_load_balancing(enabled) @load_balancing_enabled = enabled end |
#set_model_switching(enabled) ⇒ Object
Enable/disable model switching
1396 1397 1398 |
# File 'lib/aidp/harness/provider_manager.rb', line 1396 def set_model_switching(enabled) @model_switching_enabled = enabled end |
#status ⇒ Object
Get status summary
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 |
# File 'lib/aidp/harness/provider_manager.rb', line 1313 def status { current_provider: current_provider, current_model: current_model, current_provider_model: current_provider_model, available_providers: available_providers, rate_limited_providers: @rate_limit_info.keys, unhealthy_providers: @provider_health.select { |_, health| health[:status] != "healthy" }.keys, circuit_breaker_open: @provider_health.select { |_, health| health[:circuit_breaker_open] }.keys, next_reset_time: next_reset_time, total_switches: @provider_history.size, load_balancing_enabled: @load_balancing_enabled, provider_weights: @provider_weights, model_switching_enabled: @model_switching_enabled, model_weights: @model_weights } end |
#sticky_session_provider(session_id) ⇒ Object
Get sticky session provider
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 |
# File 'lib/aidp/harness/provider_manager.rb', line 1406 def sticky_session_provider(session_id) return nil unless session_id # Find provider with recent session activity recent_sessions = @sticky_sessions.select do |_, time| Time.now - time < @session_timeout end recent_sessions.max_by { |_, time| time }&.first end |
#switch_model(reason = "manual_switch", context = {}) ⇒ Object
Switch to next available model within current provider
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 |
# File 'lib/aidp/harness/provider_manager.rb', line 205 def switch_model(reason = "manual_switch", context = {}) return nil unless @model_switching_enabled # Get fallback chain for current provider's models model_chain = model_fallback_chain(current_provider) # Find next healthy model in fallback chain next_model = find_next_healthy_model(model_chain, current_model) if next_model success = set_current_model(next_model, reason, context) if success log_model_switch(current_model, next_model, reason, context) return next_model end end # If no model in fallback chain, try load balancing if @load_balancing_enabled next_model = select_model_by_load_balancing(current_provider) if next_model success = set_current_model(next_model, reason, context) if success log_model_switch(current_model, next_model, reason, context) return next_model end end end # Last resort: try any available model next_model = find_any_available_model(current_provider) if next_model success = set_current_model(next_model, reason, context) if success log_model_switch(current_model, next_model, reason, context) return next_model end end # No models available log_no_models_available(current_provider, reason, context) nil end |
#switch_model_for_error(error_type, error_details = {}) ⇒ Object
Switch model for specific error type
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/aidp/harness/provider_manager.rb', line 250 def switch_model_for_error(error_type, error_details = {}) return nil unless @model_switching_enabled case error_type when "rate_limit" switch_model("rate_limit", error_details) when "model_unavailable" switch_model("model_unavailable", error_details) when "model_error" switch_model("model_error", error_details) when "timeout" switch_model("timeout", error_details) else switch_model("error", {error_type: error_type}.merge(error_details)) end end |
#switch_model_with_retry(reason = "retry", max_retries = @max_retries) ⇒ Object
Switch model with retry logic
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 |
# File 'lib/aidp/harness/provider_manager.rb', line 268 def switch_model_with_retry(reason = "retry", max_retries = @max_retries) return nil unless @model_switching_enabled attempt_count = 0 Aidp::Concurrency::Backoff.retry( max_attempts: max_retries, base: 0.5, strategy: :exponential, jitter: 0.2, on: [StandardError] ) do attempt_count += 1 next_model = switch_model(reason, {retry_count: attempt_count - 1}) if next_model return next_model else # Raise to trigger retry raise "Model switch failed on attempt #{attempt_count}" end end rescue Aidp::Concurrency::MaxAttemptsError # All retries exhausted nil end |
#switch_provider(reason = "manual_switch", context = {}) ⇒ Object
Switch to next available provider with sophisticated fallback logic
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 |
# File 'lib/aidp/harness/provider_manager.rb', line 91 def switch_provider(reason = "manual_switch", context = {}) old_provider = current_provider Aidp.logger.info("provider_manager", "Attempting provider switch", reason: reason, current: old_provider, **context) # Get fallback chain for current provider provider_fallback_chain = fallback_chain(old_provider) # Find next healthy provider in fallback chain next_provider = find_next_healthy_provider(provider_fallback_chain, old_provider) if next_provider success = set_current_provider(next_provider, reason, context) if success log_provider_switch(old_provider, next_provider, reason, context) Aidp.logger.info("provider_manager", "Provider switched successfully", from: old_provider, to: next_provider, reason: reason) return next_provider else Aidp.logger.warn("provider_manager", "Failed to switch to provider", provider: next_provider, reason: reason) end end # If no provider in fallback chain, try load balancing if @load_balancing_enabled next_provider = select_provider_by_load_balancing if next_provider success = set_current_provider(next_provider, reason, context) if success log_provider_switch(old_provider, next_provider, reason, context) return next_provider end end end # Last resort: try any available provider next_provider = find_any_available_provider if next_provider # Only attempt switch if it's actually a different provider if next_provider != old_provider success = set_current_provider(next_provider, reason, context) if success log_provider_switch(old_provider, next_provider, reason, context) return next_provider end else # Same provider - no switch possible Aidp.logger.debug("provider_manager", "Only provider available is current provider", provider: next_provider) end end # No providers available log_no_providers_available(reason, context) Aidp.logger.error("provider_manager", "No providers available for fallback", reason: reason, provider: old_provider) nil end |
#switch_provider_for_error(error_type, error_details = {}) ⇒ Object
Switch provider for specific error type
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 |
# File 'lib/aidp/harness/provider_manager.rb', line 147 def switch_provider_for_error(error_type, error_details = {}) Aidp.logger.warn("provider_manager", "Error triggered provider switch", error_type: error_type, **error_details) case error_type when "rate_limit" switch_provider("rate_limit", error_details) when "resource_exhausted", "quota_exceeded" # Treat capacity/resource exhaustion like rate limit for fallback purposes Aidp.logger.warn("provider_manager", "Resource/quota exhaustion detected", classified_from: error_type) switch_provider("rate_limit", error_details.merge(classified_from: error_type)) when "empty_response" # Empty response indicates provider failure, try next provider Aidp.logger.warn("provider_manager", "Empty response from provider", classified_from: error_type) switch_provider("provider_failure", error_details.merge(classified_from: error_type)) when "provider_error" # Generic provider error, try next provider Aidp.logger.warn("provider_manager", "Provider error detected", classified_from: error_type) switch_provider("provider_failure", error_details.merge(classified_from: error_type)) when "authentication" switch_provider("authentication_error", error_details) when "network" switch_provider("network_error", error_details) when "server_error" switch_provider("server_error", error_details) when "timeout" switch_provider("timeout", error_details) else switch_provider("error", {error_type: error_type}.merge(error_details)) end end |
#switch_provider_with_retry(reason = "retry", max_retries = @max_retries) ⇒ Object
Switch provider with retry logic
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/aidp/harness/provider_manager.rb', line 179 def switch_provider_with_retry(reason = "retry", max_retries = @max_retries) attempt_count = 0 Aidp::Concurrency::Backoff.retry( max_attempts: max_retries, base: 0.5, strategy: :exponential, jitter: 0.2, on: [StandardError] ) do attempt_count += 1 next_provider = switch_provider(reason, {retry_count: attempt_count - 1}) if next_provider return next_provider else # Raise to trigger retry raise "Provider switch failed on attempt #{attempt_count}" end end rescue Aidp::Concurrency::MaxAttemptsError # All retries exhausted nil end |
#update_model_health(provider_name, model_name, event, _details = {}) ⇒ Object
Update model health
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 |
# File 'lib/aidp/harness/provider_manager.rb', line 776 def update_model_health(provider_name, model_name, event, _details = {}) @model_health[provider_name] ||= {} @model_health[provider_name][model_name] ||= { status: "healthy", last_updated: Time.now, error_count: 0, success_count: 0, circuit_breaker_open: false, circuit_breaker_opened_at: nil } health = @model_health[provider_name][model_name] health[:last_updated] = Time.now case event when "success" health[:success_count] += 1 health[:error_count] = [health[:error_count] - 1, 0].max # Decay errors health[:status] = "healthy" # Reset circuit breaker on success if health[:circuit_breaker_open] reset_model_circuit_breaker(provider_name, model_name) end when "error" health[:error_count] += 1 # Check if circuit breaker should open if health[:error_count] >= @circuit_breaker_threshold open_model_circuit_breaker(provider_name, model_name) end # Mark as unhealthy if too many errors if health[:error_count] > @circuit_breaker_threshold * 2 health[:status] = "unhealthy" end when "switched_to" # Model was selected, update last used health[:last_used] = Time.now when "rate_limited" # Rate limiting doesn't affect health status health[:last_rate_limited] = Time.now end end |
#update_provider_health(provider_name, event, _details = {}) ⇒ Object
Update provider health
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 |
# File 'lib/aidp/harness/provider_manager.rb', line 887 def update_provider_health(provider_name, event, _details = {}) @provider_health[provider_name] ||= { status: "healthy", last_updated: Time.now, error_count: 0, success_count: 0, circuit_breaker_open: false, circuit_breaker_opened_at: nil } health = @provider_health[provider_name] health[:last_updated] = Time.now case event when "success" health[:success_count] += 1 health[:error_count] = [health[:error_count] - 1, 0].max # Decay errors health[:status] = "healthy" # Reset circuit breaker on success if health[:circuit_breaker_open] reset_circuit_breaker(provider_name) end when "error" health[:error_count] += 1 # Check if circuit breaker should open if health[:error_count] >= @circuit_breaker_threshold open_circuit_breaker(provider_name) end # Mark as unhealthy if too many errors if health[:error_count] > @circuit_breaker_threshold * 2 health[:status] = "unhealthy" end when "switched_to" # Provider was selected, update last used health[:last_used] = Time.now when "rate_limited" # Rate limiting doesn't affect health status health[:last_rate_limited] = Time.now end end |
#update_sticky_session(provider_name) ⇒ Object
Update sticky session
1401 1402 1403 |
# File 'lib/aidp/harness/provider_manager.rb', line 1401 def update_sticky_session(provider_name) @sticky_sessions[provider_name] = Time.now end |