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, MessageDisplay::CRITICAL_TYPES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from RescueLogging

__log_rescue_impl, log_rescue, #log_rescue

Methods included from MessageDisplay

#display_message, included, #message_display_prompt, #quiet_mode?

Constructor Details

#initialize(configuration, prompt: TTY::Prompt.new, binary_checker: Aidp::Util) ⇒ ProviderManager

Returns a new instance of ProviderManager.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/aidp/harness/provider_manager.rb', line 22

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 Attribute Details

#binary_check_cacheObject (readonly)

Returns the value of attribute binary_check_cache.



20
21
22
# File 'lib/aidp/harness/provider_manager.rb', line 20

def binary_check_cache
  @binary_check_cache
end

#binary_check_ttlObject (readonly)

Returns the value of attribute binary_check_ttl.



20
21
22
# File 'lib/aidp/harness/provider_manager.rb', line 20

def binary_check_ttl
  @binary_check_ttl
end

#current_modelObject

Get current model



77
78
79
# File 'lib/aidp/harness/provider_manager.rb', line 77

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

#load_balancing_enabledObject

Expose state for testability



17
18
19
# File 'lib/aidp/harness/provider_manager.rb', line 17

def load_balancing_enabled
  @load_balancing_enabled
end

#provider_healthObject

Returns the value of attribute provider_health.



19
20
21
# File 'lib/aidp/harness/provider_manager.rb', line 19

def provider_health
  @provider_health
end

#provider_metricsObject

Returns the value of attribute provider_metrics.



19
20
21
# File 'lib/aidp/harness/provider_manager.rb', line 19

def provider_metrics
  @provider_metrics
end

#rate_limit_infoObject

Returns the value of attribute rate_limit_info.



19
20
21
# File 'lib/aidp/harness/provider_manager.rb', line 19

def rate_limit_info
  @rate_limit_info
end

#sticky_sessionsObject

Expose state for testability



17
18
19
# File 'lib/aidp/harness/provider_manager.rb', line 17

def sticky_sessions
  @sticky_sessions
end

Instance Method Details

#all_metricsObject

Get all provider metrics



1102
1103
1104
# File 'lib/aidp/harness/provider_manager.rb', line 1102

def all_metrics
  @provider_metrics.dup
end

#all_model_health_statusObject

Get all model health status



1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
# File 'lib/aidp/harness/provider_manager.rb', line 1375

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



1086
1087
1088
# File 'lib/aidp/harness/provider_manager.rb', line 1086

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

#available_models(provider_name) ⇒ Object

Get available models for a provider



383
384
385
386
387
388
389
390
# File 'lib/aidp/harness/provider_manager.rb', line 383

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)



373
374
375
376
377
378
379
380
# File 'lib/aidp/harness/provider_manager.rb', line 373

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



563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/aidp/harness/provider_manager.rb', line 563

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



461
462
463
464
465
# File 'lib/aidp/harness/provider_manager.rb', line 461

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



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

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



544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/aidp/harness/provider_manager.rb', line 544

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



530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/aidp/harness/provider_manager.rb', line 530

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



1810
1811
1812
1813
1814
# File 'lib/aidp/harness/provider_manager.rb', line 1810

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



647
648
649
650
651
652
653
654
655
656
657
658
# File 'lib/aidp/harness/provider_manager.rb', line 647

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



1804
1805
1806
1807
1808
# File 'lib/aidp/harness/provider_manager.rb', line 1804

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



1851
1852
1853
1854
1855
1856
1857
# File 'lib/aidp/harness/provider_manager.rb', line 1851

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



748
749
750
751
752
# File 'lib/aidp/harness/provider_manager.rb', line 748

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



997
998
999
# File 'lib/aidp/harness/provider_manager.rb', line 997

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



1397
1398
1399
# File 'lib/aidp/harness/provider_manager.rb', line 1397

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



1392
1393
1394
# File 'lib/aidp/harness/provider_manager.rb', line 1392

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

#configured_providersObject

Get configured providers from configuration



87
88
89
90
91
92
93
94
# File 'lib/aidp/harness/provider_manager.rb', line 87

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_providerObject

Get current provider



72
73
74
# File 'lib/aidp/harness/provider_manager.rb', line 72

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

#current_provider_modelObject

Get current provider and model combination



82
83
84
# File 'lib/aidp/harness/provider_manager.rb', line 82

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

#default_flags(provider_name) ⇒ Object

Get default flags for provider



1012
1013
1014
# File 'lib/aidp/harness/provider_manager.rb', line 1012

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

#default_model(provider_name) ⇒ Object

Get default model for provider



433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/aidp/harness/provider_manager.rb', line 433

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)



410
411
412
413
414
415
416
417
418
419
# File 'lib/aidp/harness/provider_manager.rb', line 410

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&.message)
end

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

Execute a prompt with a specific provider



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
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
# File 'lib/aidp/harness/provider_manager.rb', line 1429

def execute_with_provider(provider_type, prompt, options = {})
  options = options.dup

  # Extract model from options if provided
  model_name = options.delete(:model)
  retry_on_rate_limit = if options.key?(:retry_on_rate_limit)
    options.delete(:retry_on_rate_limit) != false
  else
    true
  end
  retry_on_unsupported = if options.key?(:retry_on_unsupported)
    options.delete(:retry_on_unsupported) != false
  else
    true
  end
  tier = options[:tier]
  base_options = options.dup

  if model_name && model_denied?(provider_type, model_name)
    alternate_model = select_alternate_model(provider_type, tier: tier, current_model: model_name)
    if alternate_model
      Aidp.logger.warn("provider_manager", "Model is denylisted, selecting alternate",
        provider: provider_type,
        model: model_name,
        alternate_model: alternate_model,
        tier: tier)

      return execute_with_provider(
        provider_type,
        prompt,
        base_options.merge(
          model: alternate_model,
          retry_on_rate_limit: retry_on_rate_limit,
          retry_on_unsupported: false
        )
      )
    end
  end

  # 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, options: options)

  # 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)

    if retry_on_unsupported
      alternate_model = select_alternate_model(provider_type, tier: tier, current_model: model_name)

      if alternate_model
        Aidp.logger.info("provider_manager", "Retrying with alternate model after unsupported model error",
          provider: provider_type,
          original_model: model_name,
          alternate_model: alternate_model,
          tier: tier)

        return execute_with_provider(
          provider_type,
          prompt,
          base_options.merge(
            model: alternate_model,
            retry_on_rate_limit: retry_on_rate_limit,
            retry_on_unsupported: false
          )
        )
      end
    end
  end

  # Detect rate limit / quota errors and attempt fallback
  error_message = e.message.to_s.downcase
  is_rate_limit = error_message.include?("rate limit") ||
    error_message.include?("quota") ||
    error_message.include?("limit reached") ||
    error_message.include?("resource exhausted") ||
    error_message.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.message)

    # Attempt to switch to fallback provider
    fallback_provider = switch_provider_for_error("rate_limit", {
      original_provider: provider_type,
      model: model_name,
      error_message: e.message
    })

    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, options.merge(retry_on_rate_limit: false))
    end
  end

  # 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



451
452
453
# File 'lib/aidp/harness/provider_manager.rb', line 451

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



483
484
485
486
487
488
489
490
491
492
493
494
# File 'lib/aidp/harness/provider_manager.rb', line 483

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



601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/aidp/harness/provider_manager.rb', line 601

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



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

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



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

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



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
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
# File 'lib/aidp/harness/provider_manager.rb', line 1213

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]
    }

    # Set reason if currently rate limited (for display in Reason column)
    if rl && reset_in && reset_in > 0
      row[:unhealthy_reason] ||= "rate_limited"
    end
    # 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)


763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
# File 'lib/aidp/harness/provider_manager.rb', line 763

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)


755
756
757
758
759
760
# File 'lib/aidp/harness/provider_manager.rb', line 755

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)


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

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)


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

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)


874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
# File 'lib/aidp/harness/provider_manager.rb', line 874

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)


866
867
868
869
870
871
# File 'lib/aidp/harness/provider_manager.rb', line 866

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)


857
858
859
860
861
862
863
# File 'lib/aidp/harness/provider_manager.rb', line 857

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



1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
# File 'lib/aidp/harness/provider_manager.rb', line 1817

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



1768
1769
1770
1771
1772
1773
1774
1775
# File 'lib/aidp/harness/provider_manager.rb', line 1768

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



1795
1796
1797
1798
1799
1800
1801
1802
# File 'lib/aidp/harness/provider_manager.rb', line 1795

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



1778
1779
1780
1781
1782
1783
# File 'lib/aidp/harness/provider_manager.rb', line 1778

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



1786
1787
1788
1789
1790
1791
1792
# File 'lib/aidp/harness/provider_manager.rb', line 1786

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



1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
# File 'lib/aidp/harness/provider_manager.rb', line 1735

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



1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
# File 'lib/aidp/harness/provider_manager.rb', line 1721

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



729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# File 'lib/aidp/harness/provider_manager.rb', line 729

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



704
705
706
# File 'lib/aidp/harness/provider_manager.rb', line 704

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)



709
710
711
712
713
714
715
# File 'lib/aidp/harness/provider_manager.rb', line 709

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



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

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



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
# File 'lib/aidp/harness/provider_manager.rb', line 967

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



1097
1098
1099
# File 'lib/aidp/harness/provider_manager.rb', line 1097

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

#model_available?(provider_name, model_name) ⇒ Boolean

Check if model is available

Returns:

  • (Boolean)


393
394
395
396
397
398
399
400
401
402
# File 'lib/aidp/harness/provider_manager.rb', line 393

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

Returns:

  • (Boolean)


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

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

Returns:

  • (Boolean)


405
406
407
# File 'lib/aidp/harness/provider_manager.rb', line 405

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



456
457
458
# File 'lib/aidp/harness/provider_manager.rb', line 456

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



1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
# File 'lib/aidp/harness/provider_manager.rb', line 1360

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



1091
1092
1093
1094
# File 'lib/aidp/harness/provider_manager.rb', line 1091

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

#model_metrics(provider_name, model_name) ⇒ Object

Get model metrics



1081
1082
1083
# File 'lib/aidp/harness/provider_manager.rb', line 1081

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



987
988
989
990
991
992
993
994
# File 'lib/aidp/harness/provider_manager.rb', line 987

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



941
942
943
944
945
946
947
948
949
950
# File 'lib/aidp/harness/provider_manager.rb', line 941

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



831
832
833
834
835
836
837
838
839
840
# File 'lib/aidp/harness/provider_manager.rb', line 831

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)


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
1205
1206
1207
1208
1209
1210
# File 'lib/aidp/harness/provider_manager.rb', line 1132

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



1002
1003
1004
# File 'lib/aidp/harness/provider_manager.rb', line 1002

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

#provider_health_statusObject

Get detailed provider health status



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

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



1296
1297
1298
# File 'lib/aidp/harness/provider_manager.rb', line 1296

def provider_history
  @provider_history.dup
end

#provider_installed?(provider_name) ⇒ Boolean

Determine whether a provider CLI/binary appears installed

Returns:

  • (Boolean)


1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
# File 'lib/aidp/harness/provider_manager.rb', line 1107

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



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

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

#provider_type(provider_name) ⇒ Object

Get provider type



1007
1008
1009
# File 'lib/aidp/harness/provider_manager.rb', line 1007

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



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
1042
1043
1044
1045
1046
1047
# File 'lib/aidp/harness/provider_manager.rb', line 1017

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



1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
# File 'lib/aidp/harness/provider_manager.rb', line 1050

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



1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
# File 'lib/aidp/harness/provider_manager.rb', line 1301

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



953
954
955
956
957
958
959
960
961
962
963
964
# File 'lib/aidp/harness/provider_manager.rb', line 953

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



843
844
845
846
847
848
849
850
851
852
853
854
# File 'lib/aidp/harness/provider_manager.rb', line 843

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



1835
1836
1837
1838
1839
1840
# File 'lib/aidp/harness/provider_manager.rb', line 1835

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



1843
1844
1845
1846
1847
1848
# File 'lib/aidp/harness/provider_manager.rb', line 1843

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



497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/aidp/harness/provider_manager.rb', line 497

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



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/aidp/harness/provider_manager.rb', line 512

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



615
616
617
618
619
620
621
622
623
624
625
626
627
# File 'lib/aidp/harness/provider_manager.rb', line 615

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



630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/aidp/harness/provider_manager.rb', line 630

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



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/aidp/harness/provider_manager.rb', line 302

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



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/aidp/harness/provider_manager.rb', line 326

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



1402
1403
1404
# File 'lib/aidp/harness/provider_manager.rb', line 1402

def set_load_balancing(enabled)
  @load_balancing_enabled = enabled
end

#set_model_switching(enabled) ⇒ Object

Enable/disable model switching



1407
1408
1409
# File 'lib/aidp/harness/provider_manager.rb', line 1407

def set_model_switching(enabled)
  @model_switching_enabled = enabled
end

#statusObject

Get status summary



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

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



1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
# File 'lib/aidp/harness/provider_manager.rb', line 1417

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



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/aidp/harness/provider_manager.rb', line 211

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



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/aidp/harness/provider_manager.rb', line 256

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



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/aidp/harness/provider_manager.rb', line 274

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



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/aidp/harness/provider_manager.rb', line 97

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



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/aidp/harness/provider_manager.rb', line 153

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



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/aidp/harness/provider_manager.rb', line 185

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



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
823
824
825
826
827
828
# File 'lib/aidp/harness/provider_manager.rb', line 782

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



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
933
934
935
936
937
938
# File 'lib/aidp/harness/provider_manager.rb', line 893

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



1412
1413
1414
# File 'lib/aidp/harness/provider_manager.rb', line 1412

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