Module: Legion::LLM::Settings

Extended by:
Legion::Logging::Helper
Defined in:
lib/legion/llm/settings.rb

Constant Summary collapse

CLIENT_TOOL_PASSTHROUGH_BLACKLIST_DEFAULT =
[
  'sudo', 'visudo', 'su', 'legion', 'legionio', 'legionio do', 'legionio/legion',
  'computer_use_session', 'computer_use_control', 'computer_use_session_info',
  'computer_use_session_message', 'plugin__aithena__recall', 'plugin__aithena__remember',
  'plugin__aithena__skill_search', 'plugin__aithena__skill_feedback', 'plugin__aithena__memory_stats',
  'plugin__cron__create', 'plugin__cron__list', 'plugin__cron__get', 'plugin__cron__update',
  'plugin__cron__delete', 'plugin__cron__get_history', 'plugin__cron__run_now', 'plugin__cron__stop'
].freeze
CLIENT_TOOL_PASSTHROUGH_WHITELIST_DEFAULT =
[].freeze

Class Method Summary collapse

Class Method Details

.api_defaultsObject



517
518
519
520
521
522
523
524
525
# File 'lib/legion/llm/settings.rb', line 517

def self.api_defaults
  {
    auth: {
      enabled:      false,
      api_keys:     [],
      pass_through: false
    }
  }
end

.arbitrage_defaultsObject



357
358
359
360
361
362
363
364
365
# File 'lib/legion/llm/settings.rb', line 357

def self.arbitrage_defaults
  {
    enabled:            true,
    prefer_cheapest:    true,
    quality_floor:      0.7,
    cost_table_refresh: 86_400,
    cost_table:         {}
  }
end

.batch_defaultsObject



367
368
369
370
371
372
373
374
# File 'lib/legion/llm/settings.rb', line 367

def self.batch_defaults
  {
    enabled:          false,
    window_seconds:   300,
    max_batch_size:   100,
    eligible_intents: %w[batch background low_priority]
  }
end

.budget_defaultsObject



349
350
351
352
353
354
355
# File 'lib/legion/llm/settings.rb', line 349

def self.budget_defaults
  {
    session_max_tokens:  nil,
    session_warn_tokens: nil,
    daily_max_tokens:    nil
  }
end

.claude_cli_defaultsObject



200
201
202
203
204
205
# File 'lib/legion/llm/settings.rb', line 200

def self.claude_cli_defaults
  {
    settings_path: '~/.claude/settings.json',
    config_path:   '~/.claude.json'
  }
end

.compliance_defaultsObject



540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/legion/llm/settings.rb', line 540

def self.compliance_defaults
  {
    classification_scan:   false,
    encrypt_audit:         false,
    phi_block_cloud:       false,
    cloud_providers:       %w[bedrock anthropic openai gemini azure],
    redact_pii:            false,
    redaction_placeholder: '[REDACTED]',
    strict_hipaa:          false,
    standalone_email_pii:  false,
    default_level:         :public
  }
end

.confidence_defaultsObject



231
232
233
234
235
236
237
238
239
240
# File 'lib/legion/llm/settings.rb', line 231

def self.confidence_defaults
  {
    bands: {
      low:       0.3,
      medium:    0.5,
      high:      0.7,
      very_high: 0.9
    }
  }
end

.config_value(config, key, default = nil) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/legion/llm/settings.rb', line 80

def self.config_value(config, key, default = nil)
  return default unless config.respond_to?(:key?)

  string_key = key.to_s
  return config[string_key] if config.key?(string_key)

  symbol_key = key.to_sym if key.respond_to?(:to_sym)
  return config[symbol_key] if symbol_key && config.key?(symbol_key)

  default
end

.context_curation_defaultsObject



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/legion/llm/settings.rb', line 456

def self.context_curation_defaults
  {
    enabled:                 true,
    mode:                    'heuristic',
    llm_assisted:            false,
    llm_model:               nil,
    tool_result_max_chars:   2000,
    thinking_eviction:       true,
    exchange_folding:        true,
    superseded_eviction:     true,
    dedup_enabled:           true,
    dedup_threshold:         0.85,
    target_context_tokens:   40_000,
    archive_dropped_turns:   true,
    archive_preserve_recent: 10
  }
end

.conversation_defaultsObject



474
475
476
477
478
479
480
481
# File 'lib/legion/llm/settings.rb', line 474

def self.conversation_defaults
  {
    summarize_threshold: 50_000,
    target_tokens:       20_000,
    preserve_recent:     10,
    auto_compact:        true
  }
end

.current_settingsObject



154
155
156
157
158
159
160
161
162
# File 'lib/legion/llm/settings.rb', line 154

def self.current_settings
  settings = Legion::Settings[:llm]
  return settings if settings.is_a?(Hash)

  {}
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.settings.current_settings')
  {}
end

.daemon_defaultsObject



242
243
244
245
246
247
# File 'lib/legion/llm/settings.rb', line 242

def self.daemon_defaults
  {
    url:     'http://127.0.0.1:4567',
    enabled: true
  }
end

.debate_defaultsObject



504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/legion/llm/settings.rb', line 504

def self.debate_defaults
  {
    enabled:                  false,
    gaia_auto_trigger:        false,
    default_rounds:           1,
    max_rounds:               3,
    advocate_model:           nil,
    challenger_model:         nil,
    judge_model:              nil,
    model_selection_strategy: 'rotate'
  }
end

.defaultObject



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
# File 'lib/legion/llm/settings.rb', line 21

def self.default
  model_override = ENV.fetch('ANTHROPIC_MODEL', nil)
  {
    enabled:                   true,
    connected:                 false,
    pipeline_enabled:          true,
    pipeline_async_post_steps: true,
    max_tool_rounds:           200,
    default_model:             model_override,
    default_provider:          nil,
    system_baseline:           system_baseline_default,
    fleet:                     fleet_defaults,
    routing:                   routing_defaults,
    budget:                    budget_defaults,
    confidence:                confidence_defaults,
    discovery:                 discovery_defaults,
    daemon:                    daemon_defaults,
    prompt_caching:            prompt_caching_defaults,
    arbitrage:                 arbitrage_defaults,
    batch:                     batch_defaults,
    scheduling:                scheduling_defaults,
    rag:                       rag_defaults,
    rag_guard:                 rag_guard_defaults,
    gaia:                      gaia_defaults,
    embedding:                 embedding_defaults,
    conversation:              conversation_defaults,
    telemetry:                 telemetry_defaults,
    metering:                  metering_defaults,
    context_curation:          context_curation_defaults,
    debate:                    debate_defaults,
    provider_layer:            provider_layer_defaults,
    tool_trigger:              tool_trigger_defaults,
    api:                       api_defaults,
    compliance:                compliance_defaults,
    skills:                    skills_defaults,
    claude_cli:                claude_cli_defaults
  }
end

.discovery_defaultsObject



267
268
269
270
271
272
273
# File 'lib/legion/llm/settings.rb', line 267

def self.discovery_defaults
  {
    enabled:         true,
    refresh_seconds: 60,
    memory_floor_mb: 2048
  }
end

.embedding_defaultsObject



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/legion/llm/settings.rb', line 413

def self.embedding_defaults
  {
    dimension:                    1024,
    enforce_dimension:            true,
    provider_fallback:            %w[ollama bedrock openai],
    provider_models:              {
      bedrock:   'amazon.titan-embed-text-v2:0',
      anthropic: nil,
      openai:    'text-embedding-3-small',
      gemini:    'text-embedding-004',
      azure:     'text-embedding-3-small',
      ollama:    'mxbai-embed-large'
    },
    ollama_preferred:             %w[mxbai-embed-large nomic-embed-text bge-large snowflake-arctic-embed],
    ollama_context_chars:         {
      'mxbai-embed-large'      => 1400,
      'bge-large'              => 1400,
      'snowflake-arctic-embed' => 1400,
      'nomic-embed-text'       => 24_000
    },
    ollama_default_context_chars: 1400,
    prefix_registry:              {
      'nomic-embed-text'  => { document: 'search_document: ', query: 'search_query: ' },
      'mxbai-embed-large' => { query: 'Represent this sentence for searching relevant passages: ' }
    }
  }
end

.enterprise_privacy?Boolean

Returns:

  • (Boolean)


143
144
145
146
147
148
149
150
151
152
# File 'lib/legion/llm/settings.rb', line 143

def self.enterprise_privacy?
  if Legion::Settings.respond_to?(:enterprise_privacy?)
    Legion::Settings.enterprise_privacy?
  else
    ENV['LEGION_ENTERPRISE_PRIVACY'] == 'true'
  end
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.settings.enterprise_privacy')
  ENV['LEGION_ENTERPRISE_PRIVACY'] == 'true'
end

.fleet_defaultsObject



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/legion/llm/settings.rb', line 275

def self.fleet_defaults
  {
    dispatch:  {
      enabled:                true,
      exchange:               'llm.fleet',
      routing_style:          :shared_lane,
      mandatory:              true,
      publisher_confirm:      true,
      spool:                  false,
      timeout_seconds:        30,
      timeouts:               { chat: 30, stream: 30, embed: 10, image: 60, default: 30 },
      require_auth:           nil,
      token_ttl_seconds:      180,
      reply_queue_expires_ms: 60_000,
      reply_queue_prefix:     'llm.fleet.reply',
      request_ttl_ms:         120_000
    },
    auth:      {
      require_signed_token:   true,
      issuer:                 'legion-llm',
      audience:               'lex-llm-fleet-worker',
      algorithm:              'HS256',
      accepted_issuers:       ['legion-llm'],
      max_clock_skew_seconds: 30
    },
    responder: {
      enabled:                    true,
      require_auth:               nil,
      require_policy:             false,
      require_idempotency:        true,
      idempotency_ttl_seconds:    600,
      accepted_protocol_version:  2,
      mandatory:                  false,
      publisher_confirm:          false,
      publish_confirm_timeout_ms: 500,
      spool:                      false
    }
  }
end

.gaia_defaultsObject



407
408
409
410
411
# File 'lib/legion/llm/settings.rb', line 407

def self.gaia_defaults
  {
    advisory_enabled: true
  }
end

.global_value(namespace, *keys, default: nil) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/legion/llm/settings.rb', line 100

def self.global_value(namespace, *keys, default: nil)
  if Legion::Settings.respond_to?(:dig) && keys.any?
    direct = Legion::Settings.dig(namespace, *keys)
    return direct unless direct.nil?
  end

  missing = Object.new
  current = self.namespace(namespace)
  keys.each_with_index do |key, index|
    unless current.respond_to?(:key?)
      warn_invalid_path(namespace, keys, index, current)
      return default
    end

    value = config_value(current, key, missing)
    return default if value.equal?(missing)

    current = value
  end
  current
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.settings.global_value', namespace: namespace, keys: keys)
  default
end

.metering_defaultsObject



447
448
449
450
451
452
453
454
# File 'lib/legion/llm/settings.rb', line 447

def self.metering_defaults
  {
    spool: {
      max_events:        10_000,
      flush_batch_sleep: 0.0
    }
  }
end

.namespace(namespace) ⇒ Object



92
93
94
95
96
97
98
# File 'lib/legion/llm/settings.rb', line 92

def self.namespace(namespace)
  settings = Legion::Settings[namespace]
  settings.is_a?(Hash) ? settings : {}
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.settings.namespace', namespace: namespace)
  {}
end

.prompt_caching_defaultsObject



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/legion/llm/settings.rb', line 249

def self.prompt_caching_defaults
  {
    enabled:             true,
    min_tokens:          1024,
    scope:               'ephemeral',
    cache_system_prompt: true,
    cache_tools:         true,
    cache_conversation:  true,
    sort_tools:          true,
    response_cache:      {
      enabled:               true,
      ttl_seconds:           300,
      spool_dir:             '~/.legionio/data/spool/llm_responses',
      spool_threshold_bytes: 8 * 1024 * 1024
    }
  }
end

.provider_layer_defaultsObject



483
484
485
486
487
488
489
490
491
# File 'lib/legion/llm/settings.rb', line 483

def self.provider_layer_defaults
  {
    mode:             'auto',
    native_providers: %w[
      ollama vllm anthropic openai gemini mlx
      bedrock azure_foundry vertex
    ]
  }
end

.rag_defaultsObject



385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/legion/llm/settings.rb', line 385

def self.rag_defaults
  {
    enabled:                       true,
    full_limit:                    10,
    compact_limit:                 5,
    min_confidence:                0.85,
    utilization_compact_threshold: 0.7,
    utilization_skip_threshold:    0.9,
    conversation_history_enabled:  false,
    trivial_max_chars:             20,
    trivial_patterns:              %w[hello hi hey ping pong test ok okay yes no thanks thank],
    exclude_source_agents:         %w[teams-api-ingest unknown teams-entity-extractor legion-interlink]
  }
end

.rag_guard_defaultsObject



400
401
402
403
404
405
# File 'lib/legion/llm/settings.rb', line 400

def self.rag_guard_defaults
  {
    threshold:        0.7,
    block_on_failure: true
  }
end

.register_defaults!Object



164
165
166
167
168
169
# File 'lib/legion/llm/settings.rb', line 164

def self.register_defaults!
  return unless Legion::Settings.respond_to?(:register_library)

  log.debug '[llm][settings] action=register_defaults'
  Legion::Settings.register_library(:llm, default)
end

.routing_defaultsObject



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/legion/llm/settings.rb', line 315

def self.routing_defaults
  {
    enabled:        true,
    tier_priority:  %w[local direct fleet openai_compat cloud frontier],
    default_intent: { privacy: 'normal', capability: 'moderate', cost: 'normal' },
    tiers:          {
      local:         { provider: 'ollama' },
      fleet:         {
        queue:           'llm.fleet',
        routing_style:   :shared_lane,
        timeout_seconds: 30,
        timeouts:        { embed: 10, chat: 30, generate: 30, default: 30 }
      },
      openai_compat: {},
      cloud:         { providers: %w[bedrock azure gemini] },
      frontier:      { providers: %w[anthropic openai] }
    },
    health:         {
      window_seconds:               300,
      circuit_breaker:              { failure_threshold: 3, cooldown_seconds: 60 },
      latency_penalty_threshold_ms: 5000,
      budget:                       { daily_limit_usd: nil, monthly_limit_usd: nil }
    },
    escalation:     {
      enabled:           true,
      pipeline_enabled:  true,
      max_attempts:      3,
      quality_threshold: 0
    },
    rules:          [],
    tier_mappings:  []
  }
end

.scheduling_defaultsObject



376
377
378
379
380
381
382
383
# File 'lib/legion/llm/settings.rb', line 376

def self.scheduling_defaults
  {
    enabled:         false,
    peak_hours_utc:  '14-22',
    defer_intents:   %w[batch background],
    max_defer_hours: 8
  }
end

.set_value(*keys, value:) ⇒ Object



125
126
127
128
129
130
131
132
133
134
# File 'lib/legion/llm/settings.rb', line 125

def self.set_value(*keys, value:)
  target = current_settings
  return value unless target.is_a?(Hash)

  assign_value(target, keys, value)
  value
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.settings.set_value', keys: keys)
  value
end

.skills_defaultsObject



527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/legion/llm/settings.rb', line 527

def self.skills_defaults
  {
    enabled:           true,
    auto_inject:       true,
    on_demand:         true,
    max_active_skills: 1,
    directories:       ['.legion/skills', '~/.legionio/skills'],
    auto_discover:     { claude: false, codex: false },
    enabled_skills:    [],
    disabled_skills:   []
  }
end

.system_baseline_defaultObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/legion/llm/settings.rb', line 207

def self.system_baseline_default
  <<~PROMPT.strip
    You are Legion, an agentic AI partner running on the LegionIO framework.

    LegionIO is a governed, production-oriented cognitive task and orchestration platform.
    Your role is to help the user accomplish real work quickly, directly, and safely.

    Core behavior:
    - Honor user intent and constraints.
    - Prefer execution over prompt ceremony: do the task when possible, don't just describe it.
    - Be concise by default; expand only when the user asks for depth.
    - Be transparent: never claim you ran something you did not run, and never hide uncertainty.
    - Minimize blast radius: make the smallest effective change and preserve existing behavior unless asked otherwise.
    - Do not YOLO risky actions. For destructive, irreversible, security-sensitive, or high-impact actions, pause and get explicit confirmation.
    - When risk or ambiguity is high, ask focused clarifying questions before acting.
    - Validate outcomes when practical, and report what changed and why.
    - Prefer solving work directly in-session; only produce handoff artifacts (including prompts for other AI tools) when the user explicitly asks for that format.

    Trust model:
    - Trust is earned through reliable outcomes, clarity, and safe execution.
    - Speed matters, but never at the expense of integrity or user trust.
  PROMPT
end

.telemetry_defaultsObject



441
442
443
444
445
# File 'lib/legion/llm/settings.rb', line 441

def self.telemetry_defaults
  {
    pipeline_spans: true
  }
end

.tool_trigger_defaultsObject



493
494
495
496
497
498
499
500
501
502
# File 'lib/legion/llm/settings.rb', line 493

def self.tool_trigger_defaults
  {
    scan_depth:                        10,
    tool_limit:                        25,
    local_tool_limit:                  100,
    client_tool_passthrough:           false,
    client_tool_passthrough_whitelist: CLIENT_TOOL_PASSTHROUGH_WHITELIST_DEFAULT.dup,
    client_tool_passthrough_blacklist: CLIENT_TOOL_PASSTHROUGH_BLACKLIST_DEFAULT.dup
  }
end

.transport_connected?Boolean

Returns:

  • (Boolean)


136
137
138
139
140
141
# File 'lib/legion/llm/settings.rb', line 136

def self.transport_connected?
  return true if global_value(:transport, :connected) == true

  transport = namespace(:transport)
  config_value(transport, :connected) == true
end

.validate!(settings) ⇒ Object

Raises:

  • (ArgumentError)


171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/legion/llm/settings.rb', line 171

def self.validate!(settings)
  raise ArgumentError, 'llm.gateway has been removed; configure provider instances instead' if config_key?(settings, :gateway)

  routing = config_value(settings, :routing, {})
  if routing.is_a?(Hash)
    raise ArgumentError, 'routing.use_fleet has been removed; configure fleet.dispatch.enabled instead' if config_key?(routing, :use_fleet)

    openai_compat = config_value(config_value(routing, :tiers, {}), :openai_compat, {})
    if openai_compat.is_a?(Hash) && config_key?(openai_compat, :gateways)
      raise ArgumentError, 'routing.tiers.openai_compat.gateways has been removed; configure lex-llm-openai provider instances instead'
    end
  end

  settings
end

.value(*keys, default: nil) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/legion/llm/settings.rb', line 60

def self.value(*keys, default: nil)
  missing = Object.new
  current = current_settings
  keys.each_with_index do |key, index|
    unless current.respond_to?(:key?)
      warn_invalid_path(nil, keys, index, current)
      return default
    end

    value = config_value(current, key, missing)
    return default if value.equal?(missing)

    current = value
  end
  current
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.settings.value')
  default
end