Class: Aidp::Harness::ProviderManager

Inherits:
Object
  • Object
show all
Includes:
MessageDisplay, RescueLogging
Defined in:
lib/aidp/harness/provider_manager.rb

Overview

Manages provider switching and fallback logic

Constant Summary

Constants included from MessageDisplay

MessageDisplay::COLOR_MAP

Instance Method Summary collapse

Methods included from RescueLogging

__log_rescue_impl, log_rescue, #log_rescue

Methods included from MessageDisplay

#display_message, #in_test_environment?, included, #message_display_prompt, #suppress_display_message?

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
# 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 = {}
  @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_metricsObject

Get all provider metrics



1075
1076
1077
# File 'lib/aidp/harness/provider_manager.rb', line 1075

def all_metrics
  @provider_metrics.dup
end

#all_model_health_statusObject

Get all model health status



1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
# File 'lib/aidp/harness/provider_manager.rb', line 1342

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



1059
1060
1061
# File 'lib/aidp/harness/provider_manager.rb', line 1059

def all_model_metrics(provider_name)
  @model_metrics[provider_name] || {}
end

#available_models(provider_name) ⇒ Object

Get available models for a provider



376
377
378
379
380
381
382
383
# File 'lib/aidp/harness/provider_manager.rb', line 376

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_providersObject

Get available providers (not rate limited, healthy, and circuit breaker closed)



366
367
368
369
370
371
372
373
# File 'lib/aidp/harness/provider_manager.rb', line 366

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



536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/aidp/harness/provider_manager.rb', line 536

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



434
435
436
437
438
# File 'lib/aidp/harness/provider_manager.rb', line 434

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



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
# File 'lib/aidp/harness/provider_manager.rb', line 634

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



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/aidp/harness/provider_manager.rb', line 517

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



503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/aidp/harness/provider_manager.rb', line 503

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



1645
1646
1647
1648
1649
# File 'lib/aidp/harness/provider_manager.rb', line 1645

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



620
621
622
623
624
625
626
627
628
629
630
631
# File 'lib/aidp/harness/provider_manager.rb', line 620

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



1639
1640
1641
1642
1643
# File 'lib/aidp/harness/provider_manager.rb', line 1639

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_limitsObject

Clean up expired rate limits from memory



1686
1687
1688
1689
1690
1691
1692
# File 'lib/aidp/harness/provider_manager.rb', line 1686

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



721
722
723
724
725
# File 'lib/aidp/harness/provider_manager.rb', line 721

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



970
971
972
# File 'lib/aidp/harness/provider_manager.rb', line 970

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



1364
1365
1366
# File 'lib/aidp/harness/provider_manager.rb', line 1364

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



1359
1360
1361
# File 'lib/aidp/harness/provider_manager.rb', line 1359

def configure_provider_weights(weights)
  @provider_weights = weights.dup
end

#configured_providersObject

Get configured providers from configuration



80
81
82
83
84
85
86
87
# File 'lib/aidp/harness/provider_manager.rb', line 80

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_modelObject

Get current model



70
71
72
# File 'lib/aidp/harness/provider_manager.rb', line 70

def current_model
  @current_model ||= default_model(current_provider)
end

#current_providerObject

Get current provider



65
66
67
# File 'lib/aidp/harness/provider_manager.rb', line 65

def current_provider
  @current_provider ||= @configuration.default_provider
end

#current_provider_modelObject

Get current provider and model combination



75
76
77
# File 'lib/aidp/harness/provider_manager.rb', line 75

def current_provider_model
  "#{current_provider}:#{current_model}"
end

#default_flags(provider_name) ⇒ Object

Get default flags for provider



985
986
987
# File 'lib/aidp/harness/provider_manager.rb', line 985

def default_flags(provider_name)
  @configuration.default_flags(provider_name)
end

#default_model(provider_name) ⇒ Object

Get default model for provider



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/aidp/harness/provider_manager.rb', line 406

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

#execute_with_provider(provider_type, prompt, options = {}) ⇒ Object

Execute a prompt with a specific provider



1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
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
# File 'lib/aidp/harness/provider_manager.rb', line 1396

def execute_with_provider(provider_type, prompt, options = {})
  # Extract model from options if provided
  model_name = options.delete(:model)

  # Create provider factory instance
  provider_factory = ProviderFactory.new

  # Add model to provider options if specified
  provider_options = options.dup
  provider_options[:model] = model_name if model_name

  # Create provider instance
  provider = provider_factory.create_provider(provider_type, provider_options)

  # 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.send_message(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)
  # Return error result
  {
    status: "error",
    provider: provider_type,
    error: e.message,
    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



424
425
426
# File 'lib/aidp/harness/provider_manager.rb', line 424

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



456
457
458
459
460
461
462
463
464
465
466
467
# File 'lib/aidp/harness/provider_manager.rb', line 456

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_providerObject

Find any available provider



574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/aidp/harness/provider_manager.rb', line 574

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



441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/aidp/harness/provider_manager.rb', line 441

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



559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/aidp/harness/provider_manager.rb', line 559

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_dashboardObject

Summarize health and metrics for dashboard/CLI display



1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
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
# File 'lib/aidp/harness/provider_manager.rb', line 1186

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

Returns:

  • (Boolean)


736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
# File 'lib/aidp/harness/provider_manager.rb', line 736

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

Returns:

  • (Boolean)


728
729
730
731
732
733
# File 'lib/aidp/harness/provider_manager.rb', line 728

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

Returns:

  • (Boolean)


691
692
693
694
695
696
697
698
699
# File 'lib/aidp/harness/provider_manager.rb', line 691

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)

Returns:

  • (Boolean)


654
655
656
657
658
659
660
661
# File 'lib/aidp/harness/provider_manager.rb', line 654

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

Returns:

  • (Boolean)


847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
# File 'lib/aidp/harness/provider_manager.rb', line 847

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

Returns:

  • (Boolean)


839
840
841
842
843
844
# File 'lib/aidp/harness/provider_manager.rb', line 839

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

Returns:

  • (Boolean)


830
831
832
833
834
835
836
# File 'lib/aidp/harness/provider_manager.rb', line 830

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_metricsObject

Load persisted metrics from disk



1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
# File 'lib/aidp/harness/provider_manager.rb', line 1652

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



1603
1604
1605
1606
1607
1608
1609
1610
# File 'lib/aidp/harness/provider_manager.rb', line 1603

def log_circuit_breaker_event(provider_name, event)
  case event
  when "opened"
    display_message("🔴 Circuit breaker opened for provider: #{provider_name}", type: :error)
  when "reset"
    display_message("🟢 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



1630
1631
1632
1633
1634
1635
1636
1637
# File 'lib/aidp/harness/provider_manager.rb', line 1630

def log_model_circuit_breaker_event(provider_name, model_name, event)
  case event
  when "opened"
    display_message("🔴 Circuit breaker opened for model: #{provider_name}:#{model_name}", type: :error)
  when "reset"
    display_message("🟢 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



1613
1614
1615
1616
1617
1618
# File 'lib/aidp/harness/provider_manager.rb', line 1613

def log_model_switch(from_model, to_model, reason, context)
  display_message("🔄 Model switch: #{from_model}#{to_model} (#{reason})", type: :info)
  if context.any?
    display_message("   Context: #{context.inspect}", type: :muted)
  end
end

#log_no_models_available(provider_name, reason, context) ⇒ Object

Log no models available



1621
1622
1623
1624
1625
1626
1627
# File 'lib/aidp/harness/provider_manager.rb', line 1621

def log_no_models_available(provider_name, reason, context)
  display_message("❌ No models available for provider #{provider_name} (#{reason})", type: :error)
  display_message("   All models are rate limited, unhealthy, or circuit breaker open", type: :warning)
  if context.any?
    display_message("   Context: #{context.inspect}", type: :muted)
  end
end

#log_no_providers_available(reason, context) ⇒ Object

Log no providers available



1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
# File 'lib/aidp/harness/provider_manager.rb', line 1570

def log_no_providers_available(reason, context)
  display_message("❌ 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
    display_message("   No fallback providers configured in aidp.yml", type: :warning)
    display_message("   💡 Add fallback providers to enable automatic failover:", type: :info)
    display_message("      harness:", type: :muted)
    display_message("        fallback_providers:", type: :muted)
    display_message("          - anthropic", type: :muted)
    display_message("          - gemini", type: :muted)
    display_message("   Run 'aidp config --interactive' to configure providers", type: :info)
  else
    display_message("   All providers are rate limited, unhealthy, or circuit breaker open", type: :warning)
    if harness_fallbacks.any?
      display_message("   Configured fallbacks: #{harness_fallbacks.join(", ")}", type: :muted)
    end
  end

  if context.any?
    display_message("   Context: #{context.inspect}", type: :muted)
  end
end

#log_provider_switch(from_provider, to_provider, reason, context) ⇒ Object

Log provider switch



1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
# File 'lib/aidp/harness/provider_manager.rb', line 1556

def log_provider_switch(from_provider, to_provider, reason, context)
  if from_provider == to_provider
    # Same provider - this indicates no fallback was possible
    display_message("⚠️  Provider switch failed: #{from_provider}#{to_provider} (#{reason})", type: :warning)
    display_message("   No alternative providers available", type: :warning)
  else
    display_message("🔄 Provider switch: #{from_provider}#{to_provider} (#{reason})", type: :info)
  end
  if context.any?
    display_message("   Context: #{context.inspect}", type: :muted)
  end
end

#mark_model_rate_limited(provider_name, model_name, reset_time = nil) ⇒ Object

Mark model as rate limited



702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/aidp/harness/provider_manager.rb', line 702

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



677
678
679
# File 'lib/aidp/harness/provider_manager.rb', line 677

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)



682
683
684
685
686
687
688
# File 'lib/aidp/harness/provider_manager.rb', line 682

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



664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/aidp/harness/provider_manager.rb', line 664

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



940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
# File 'lib/aidp/harness/provider_manager.rb', line 940

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



1070
1071
1072
# File 'lib/aidp/harness/provider_manager.rb', line 1070

def metrics(provider_name)
  @provider_metrics[provider_name] || {}
end

#model_available?(provider_name, model_name) ⇒ Boolean

Check if model is available

Returns:

  • (Boolean)


386
387
388
389
390
391
392
# File 'lib/aidp/harness/provider_manager.rb', line 386

def model_available?(provider_name, model_name)
  # Check if model is configured for provider
  return false unless model_configured?(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

Returns:

  • (Boolean)


395
396
397
398
# File 'lib/aidp/harness/provider_manager.rb', line 395

def model_configured?(provider_name, model_name)
  models = provider_models(provider_name)
  models.include?(model_name)
end

#model_fallback_chain(provider_name) ⇒ Object

Get fallback chain for models within a provider



429
430
431
# File 'lib/aidp/harness/provider_manager.rb', line 429

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



1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
# File 'lib/aidp/harness/provider_manager.rb', line 1327

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_historyObject

Get model history



1064
1065
1066
1067
# File 'lib/aidp/harness/provider_manager.rb', line 1064

def model_history
  @model_history ||= []
  @model_history.dup
end

#model_metrics(provider_name, model_name) ⇒ Object

Get model metrics



1054
1055
1056
# File 'lib/aidp/harness/provider_manager.rb', line 1054

def model_metrics(provider_name, model_name)
  @model_metrics[provider_name]&.dig(model_name) || {}
end

#next_reset_timeObject

Get next reset time for any provider



960
961
962
963
964
965
966
967
# File 'lib/aidp/harness/provider_manager.rb', line 960

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



914
915
916
917
918
919
920
921
922
923
# File 'lib/aidp/harness/provider_manager.rb', line 914

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



804
805
806
807
808
809
810
811
812
813
# File 'lib/aidp/harness/provider_manager.rb', line 804

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

Returns:

  • (Boolean)


1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
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
# File 'lib/aidp/harness/provider_manager.rb', line 1105

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



975
976
977
# File 'lib/aidp/harness/provider_manager.rb', line 975

def provider_config(provider_name)
  @configuration.provider_config(provider_name)
end

#provider_health_statusObject

Get detailed provider health status



1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
# File 'lib/aidp/harness/provider_manager.rb', line 1310

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_historyObject

Get provider history



1264
1265
1266
# File 'lib/aidp/harness/provider_manager.rb', line 1264

def provider_history
  @provider_history.dup
end

#provider_installed?(provider_name) ⇒ Boolean

Determine whether a provider CLI/binary appears installed

Returns:

  • (Boolean)


1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
# File 'lib/aidp/harness/provider_manager.rb', line 1080

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



401
402
403
# File 'lib/aidp/harness/provider_manager.rb', line 401

def provider_models(provider_name)
  @model_configs[provider_name] || []
end

#provider_type(provider_name) ⇒ Object

Get provider type



980
981
982
# File 'lib/aidp/harness/provider_manager.rb', line 980

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



990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
# File 'lib/aidp/harness/provider_manager.rb', line 990

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&.message || "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



1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
# File 'lib/aidp/harness/provider_manager.rb', line 1023

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&.message || "Unknown error"
    metrics[:last_error_time] = Time.now
    update_model_health(provider_name, model_name, "error", {error: error})
  end
end

#resetObject

Reset all provider state



1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
# File 'lib/aidp/harness/provider_manager.rb', line 1269

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_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



926
927
928
929
930
931
932
933
934
935
936
937
# File 'lib/aidp/harness/provider_manager.rb', line 926

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



816
817
818
819
820
821
822
823
824
825
826
827
# File 'lib/aidp/harness/provider_manager.rb', line 816

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_metricsObject

Save persisted metrics to disk



1670
1671
1672
1673
1674
1675
# File 'lib/aidp/harness/provider_manager.rb', line 1670

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_limitsObject

Save persisted rate limits to disk



1678
1679
1680
1681
1682
1683
# File 'lib/aidp/harness/provider_manager.rb', line 1678

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



470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/aidp/harness/provider_manager.rb', line 470

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



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/aidp/harness/provider_manager.rb', line 485

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_balancingObject

Select provider by load balancing



588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'lib/aidp/harness/provider_manager.rb', line 588

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



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'lib/aidp/harness/provider_manager.rb', line 603

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



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/aidp/harness/provider_manager.rb', line 295

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



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
# File 'lib/aidp/harness/provider_manager.rb', line 319

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



1369
1370
1371
# File 'lib/aidp/harness/provider_manager.rb', line 1369

def set_load_balancing(enabled)
  @load_balancing_enabled = enabled
end

#set_model_switching(enabled) ⇒ Object

Enable/disable model switching



1374
1375
1376
# File 'lib/aidp/harness/provider_manager.rb', line 1374

def set_model_switching(enabled)
  @model_switching_enabled = enabled
end

#statusObject

Get status summary



1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'lib/aidp/harness/provider_manager.rb', line 1291

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



1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
# File 'lib/aidp/harness/provider_manager.rb', line 1384

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



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
# File 'lib/aidp/harness/provider_manager.rb', line 204

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



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/aidp/harness/provider_manager.rb', line 249

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



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
# File 'lib/aidp/harness/provider_manager.rb', line 267

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



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
# File 'lib/aidp/harness/provider_manager.rb', line 90

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



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
# File 'lib/aidp/harness/provider_manager.rb', line 146

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



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/aidp/harness/provider_manager.rb', line 178

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



755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
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
# File 'lib/aidp/harness/provider_manager.rb', line 755

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



866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
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
# File 'lib/aidp/harness/provider_manager.rb', line 866

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



1379
1380
1381
# File 'lib/aidp/harness/provider_manager.rb', line 1379

def update_sticky_session(provider_name)
  @sticky_sessions[provider_name] = Time.now
end