lex-llm 0.8.8 → 0.8.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f21576528494d0876f279ea9a60a61b0ae66b00d6f2cf42edf023fea4e937b55
4
- data.tar.gz: b5b4d3a0b3ac21cf23f94e511c059fab5d5f0bf925a137389ee1cf5254b252f5
3
+ metadata.gz: 8f2265b83c2ffa744455c088acc8bd4d4be3a3abd3b004f9eb547d209e56c2f7
4
+ data.tar.gz: 261c110f9f8d09c307fc75990a34b264407dcf87bef2c492fed398f5ef668b2f
5
5
  SHA512:
6
- metadata.gz: 647f69802e60ee7be7c8d428999f337a24fc2d66f65b315631046cbebf44ffcaf36416076857f0efd3127a7728eb84852a143a603b5fb2e28aa7c55257110c20
7
- data.tar.gz: 575f2293e9a1d8a97135c950d0937b24b42c2e6c14d8c4cb49d69d8001f656e5e8d9d3aecc2b50914cfe6b089b140913bb3382288233446473f98d96e621cf41
6
+ metadata.gz: d3b5f51c3e8902afcb8b7fcc2df3578153f782d3eaba8e32cb457815f0c384f75bdfce56692b561bfd25de8e0b35a40af269f50a672e075db5fc243fce7cfa41
7
+ data.tar.gz: 81055c6036021a50a1105ca6c08cfc8a663efc9d4c25e6ab03d03af07f237349b9bc40d2f3d2aa96439c3370f27cbe9f3746a2f8de83a48376f8437e7a82561c
data/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.12 - 2026-11-23
4
+
5
+ ### Fixed
6
+ - Apply the shared `extensions.llm.ssl.verify` policy to provider catalog discovery and readiness connections. Use the native settings helper at the shared LLM namespace so provider-scoped runner settings cannot select a different policy. Keep the existing verification default and inference behavior unchanged.
7
+ - Cover real HTTPS discovery and readiness with Net::HTTP and Typhoeus, including disabled verification, rejected untrusted certificates, explicitly trusted certificate authorities, and hostname rejection before credentials are sent.
8
+ - Reject non-collection tool controls through the canonical input validator before testing collection contents. Fleet chat, streaming-chat and token-count requests now report these malformed controls as non-retryable contract errors before provider execution, releasing the callable lease. Nil, empty hashes and empty arrays retain their empty-tool semantics.
9
+
10
+ ## 0.8.11 - 2026-11-20
11
+
12
+ ### Fixed
13
+ - Let OpenAI-compatible providers declare their protocol's output-limit wire key through `output_token_limit_key`. The shared payload builder emits one field with the unchanged canonical `Params#max_tokens` value; the default remains `max_tokens`, and protocols can select `max_completion_tokens` without model-name rules or parameter mutation. Cover default and overridden keys through real synchronous and streaming provider HTTP execution, including absent limits.
14
+
15
+ ## 0.8.10 - 2026-11-20
16
+
17
+ ### Fixed
18
+ - Preserve explicit OpenAI-compatible streaming finish reasons through canonical chunk parsing and accumulation, including empty terminal deltas and frames containing final content. The shared streaming wrapper emits exactly one final done with the complete trailing usage; missing or unknown reasons remain unconfirmed instead of fabricating successful completion. Add full provider/HTTP-stream regressions for stop, length, tool calls, content filtering, and trailing usage.
19
+
20
+ ## 0.8.9 - 2026-11-20
21
+
22
+ ### Fixed
23
+ - Rehydrate serialized tools, thinking controls, and sampling parameters at the shared fleet worker boundary before chat, streaming-chat, or token-count dispatch. Remote calls now preserve the same canonical controls as direct calls, while embedding and media parameters keep their existing contracts.
24
+ - Reject malformed serialized controls as non-retryable fleet contract errors before provider execution, releasing the acquired callable lease.
25
+
3
26
  ## 0.8.8 - 2026-11-18
4
27
 
5
28
  ### Fixed
data/README.md CHANGED
@@ -41,7 +41,7 @@ gem 'lex-llm'
41
41
  Provider extensions should declare `lex-llm` as a gemspec dependency:
42
42
 
43
43
  ```ruby
44
- spec.add_dependency 'lex-llm', '>= 0.8.6'
44
+ spec.add_dependency 'lex-llm', '>= 0.8.11'
45
45
  ```
46
46
 
47
47
  For local development across LegionIO repos, prefer a local path override in the app or test `Gemfile`, not a permanent git dependency in the gemspec.
@@ -54,6 +54,10 @@ constructor, including `from_hash`; an image without an explicit source type is
54
54
  contract error. `ContentBlock.image` explicitly defaults to `:base64`.
55
55
  Fleet workers rehydrate serialized messages through these same constructors before
56
56
  calling a provider, preserving media bytes, MIME type, ordering and image detail.
57
+ For chat, streaming-chat, and token-count requests, the worker also rehydrates
58
+ tool definitions, sampling parameters, and thinking controls through
59
+ `Canonical::Request`'s shared normalizers. Headers, schemas, and tool preferences
60
+ keep their existing shapes; embedding and media parameter hashes are unchanged.
57
61
 
58
62
  Fleet publishers require `legion-transport >= 1.4.31`: they encode once, validate
59
63
  the final encrypted byte count, then publish those exact bytes with the matching
@@ -63,6 +67,14 @@ connection boundary and supports Faraday's positional and keyword parser APIs.
63
67
  `Provider::OpenAICompatible` translates canonical text/image blocks into OpenAI
64
68
  `text`/`image_url` parts, never raw canonical media fields. Provider-specific cache
65
69
  controls remain canonical metadata unless the selected provider supports them.
70
+ Providers can override `output_token_limit_key` for their protocol's output-limit
71
+ spelling. The default is `:max_tokens`; a protocol using `:max_completion_tokens`
72
+ receives the same canonical `Params#max_tokens` value under that single wire key.
73
+ This hook does not change limits, infer model capabilities, or supply defaults.
74
+ Its stream parser maps explicit finish reasons through the shared stop-reason
75
+ vocabulary, even when the terminal delta is empty. The accumulator retains that
76
+ reason while accepting trailing usage; the streaming wrapper emits exactly one
77
+ final canonical `done`. Missing or unknown reasons remain absent.
66
78
 
67
79
  `Routing::RequestRequirements` is the shared immutable record for operation,
68
80
  capabilities, context/input/output bounds, modality, pins, hint disposition, routing
@@ -519,8 +531,10 @@ Key settings paths:
519
531
 
520
532
  ### TLS verification and custom certificate authorities
521
533
 
522
- Shared provider connections read `extensions.llm.ssl.verify` from `Legion::Settings`
523
- when constructed. The default is `false` for both Typhoeus and Net::HTTP.
534
+ Shared provider inference, catalog discovery, and readiness connections read
535
+ `extensions.llm.ssl.verify` when constructed. Discovery reads the shared LLM
536
+ settings namespace, rather than the including provider runner's settings.
537
+ The default is `false` for both Typhoeus and Net::HTTP.
524
538
  With verification disabled, untrusted and wrong-host certificates are accepted,
525
539
  so credentials can be sent to an unauthenticated peer.
526
540
 
@@ -57,7 +57,7 @@ module Legion
57
57
  # L2: the single tools normalizer, shared by build and from_hash.
58
58
  # Hash<name, ToolDefinition> or Array<ToolDefinition|Hash>; anything else raises.
59
59
  def self.normalize_tools(tools, site)
60
- return {} if tools.nil? || tools.empty?
60
+ return {} if tools.nil?
61
61
 
62
62
  case tools
63
63
  when Hash
@@ -577,6 +577,7 @@ module Legion
577
577
 
578
578
  def build_connection(base_url:, instance_cfg:, timeout:, open_timeout:)
579
579
  Faraday.new(url: base_url) do |f|
580
+ f.ssl.verify = Legion::Extensions::Llm.settings[:ssl][:verify] == true
580
581
  f.options.timeout = timeout
581
582
  f.options.open_timeout = open_timeout
582
583
  f.headers['Accept'] = 'application/json'
@@ -2,10 +2,11 @@
2
2
 
3
3
  require 'concurrent'
4
4
 
5
- require_relative 'protocol'
6
- require_relative 'settings'
7
- require_relative 'token_validator'
8
- require_relative 'fleet_envelope'
5
+ require 'legion/extensions/llm/fleet/protocol'
6
+ require 'legion/extensions/llm/fleet/settings'
7
+ require 'legion/extensions/llm/fleet/token_validator'
8
+ require 'legion/extensions/llm/fleet/fleet_envelope'
9
+ require 'legion/extensions/llm/canonical'
9
10
  require 'legion/extensions/llm/taxonomies'
10
11
  require 'legion/extensions/llm/inventory/errors'
11
12
  require 'legion/extensions/llm/inventory/identity'
@@ -183,7 +184,23 @@ module Legion
183
184
  end
184
185
  end
185
186
 
187
+ # Rehydrate message-operation controls at the same fleet boundary as
188
+ # messages. The canonical constructors own validation; providers see
189
+ # canonical values regardless of whether dispatch was local or remote.
190
+ # Other operation params retain their operation-specific wire contract.
191
+ def rehydrate_wire_controls(params:, **)
192
+ normalized = params.dup
193
+ normalized[:tools] = Legion::Extensions::Llm::Canonical::Request.normalize_tools(params[:tools], name) if params.key?(:tools)
194
+ normalized[:params] = Legion::Extensions::Llm::Canonical::Request.normalize_params!(params[:params], name) if params.key?(:params)
195
+ normalized[:thinking] = Legion::Extensions::Llm::Canonical::Request.normalize_thinking!(params[:thinking], name) if params.key?(:thinking)
196
+ normalized
197
+ rescue ArgumentError => e
198
+ raise Legion::Extensions::Llm::Fleet::ContractError, e.message, cause: e
199
+ end
200
+
186
201
  def dispatch_operation(callable, operation, model, params)
202
+ params = rehydrate_wire_controls(params: params) if %i[chat stream_chat count_tokens].include?(operation)
203
+
187
204
  case operation
188
205
  when :chat
189
206
  callable.chat(rehydrate_wire_messages(require_param!(params, :messages, operation)), model: model,
@@ -12,6 +12,8 @@ module Legion
12
12
  # fields) lives here, at the edge (03 O03a).
13
13
  module OpenAICompatible
14
14
  def stream_usage_supported? = false
15
+ # Provider protocols choose the wire spelling, never a new limit value.
16
+ def output_token_limit_key = :max_tokens
15
17
  def completion_url = '/v1/chat/completions'
16
18
  def stream_url = completion_url
17
19
  def models_url = '/v1/models'
@@ -46,7 +48,7 @@ module Legion
46
48
  return {} unless params
47
49
 
48
50
  {
49
- max_tokens: params.max_tokens,
51
+ output_token_limit_key => params.max_tokens,
50
52
  top_p: params.top_p,
51
53
  top_k: params.top_k,
52
54
  stop: params.stop_sequences,
@@ -246,6 +248,13 @@ module Legion
246
248
  chunks.concat(parse_streaming_tool_calls(delta['tool_calls']))
247
249
  canonical_usage = openai_usage_to_canonical(usage)
248
250
  chunks << Canonical::Chunk.usage_chunk(usage: canonical_usage, request_id: nil) if canonical_usage
251
+ # The accumulator records this reason without emitting the marker.
252
+ # Streaming emits the sole final done after trailing usage arrives.
253
+ if choice['finish_reason']
254
+ chunks << Legion::Extensions::Llm::Canonical::Chunk.done(
255
+ request_id: nil, stop_reason: stop_reason_lookup(choice['finish_reason'])
256
+ )
257
+ end
249
258
 
250
259
  if chunks.empty?
251
260
  nil
@@ -3,7 +3,7 @@
3
3
  module Legion
4
4
  module Extensions
5
5
  module Llm
6
- VERSION = '0.8.8'
6
+ VERSION = '0.8.12'
7
7
  end
8
8
  end
9
9
  end
@@ -9,6 +9,7 @@ require 'faraday/multipart'
9
9
  require 'faraday/retry'
10
10
  require 'legion/json'
11
11
  require 'legion/logging'
12
+ require 'legion/settings/helper'
12
13
  # legion/cache writes DEBUG lines to $stdout on first load; suppress them here
13
14
  # so callers that capture our stdout (e.g. Open3-based integration tests) are unaffected.
14
15
  begin
@@ -29,6 +30,8 @@ module Legion
29
30
  module Extensions
30
31
  # Legion-native namespace for the shared LLM provider framework.
31
32
  module Llm
33
+ extend Legion::Settings::Helper
34
+
32
35
  # ------------------------------------------------------------------ #
33
36
  # Explicit requires (replaces Zeitwerk autoloading). #
34
37
  # Load order: base classes & canonical types first, then anything #
@@ -64,6 +64,22 @@ RSpec.describe Legion::Extensions::Llm::Canonical::Request do
64
64
  end
65
65
 
66
66
  describe 'L2 — tools/params/thinking normalizers shared by both factories' do
67
+ [nil, {}, []].each do |tools|
68
+ it "preserves empty tools #{tools.inspect} through every constructor" do
69
+ expect(described_class.build(tools: tools).tools).to eq({})
70
+ expect(described_class.new(tools: tools).tools).to eq({})
71
+ expect(described_class.from_hash(tools: tools).tools).to eq({})
72
+ end
73
+ end
74
+
75
+ [5, 1.5, false, true, ''].each do |tools|
76
+ it "rejects non-collection tools #{tools.inspect} with the canonical input error" do
77
+ expect { described_class.build(tools: tools) }.to raise_error(ArgumentError, /tools expected/)
78
+ expect { described_class.new(tools: tools) }.to raise_error(ArgumentError, /tools expected/)
79
+ expect { described_class.from_hash(tools: tools) }.to raise_error(ArgumentError, /tools expected/)
80
+ end
81
+ end
82
+
67
83
  it 'normalizes tools to Hash<name, ToolDefinition> (T7)' do
68
84
  via_build = described_class.build(tools: [{ name: 'get_weather', parameters: {} }])
69
85
  via_hash = described_class.from_hash(tools: [{ name: 'get_weather', parameters: {} }])
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'faraday/net_http'
5
+ require 'faraday/typhoeus'
6
+ require 'legion/settings'
7
+ require 'legion/transport'
8
+ require_relative '../../../../support/tls_endpoint'
9
+
10
+ # Load the production module per example to isolate the helper stub.
11
+ RSpec.describe 'Legion::Extensions::Llm::Discovery::Pipeline TLS' do # rubocop:disable RSpec/DescribeClass
12
+ before do
13
+ # TODO: Remove this spec-local helper stub when extension helpers are available without legionio.
14
+ stub_const('Legion::Extensions::Helpers::Lex', Module.new { include Legion::Logging::Helper })
15
+ stub_const('Legion::Extensions::Llm::Discovery::Pipeline', Module.new)
16
+ load File.join(Gem.loaded_specs.fetch('lex-llm').full_gem_path, 'lib/legion/extensions/llm/discovery/pipeline.rb')
17
+ end
18
+
19
+ around do |example|
20
+ saved = Legion::Settings.loader.settings[:extensions]
21
+ Legion::Settings.loader.settings[:extensions] = { llm: Legion::Extensions::Llm.default_settings }
22
+ example.run
23
+ ensure
24
+ if saved.nil?
25
+ Legion::Settings.loader.settings.delete(:extensions)
26
+ else
27
+ Legion::Settings.loader.settings[:extensions] = saved
28
+ end
29
+ end
30
+
31
+ let(:runner) do
32
+ Class.new do
33
+ include Legion::Extensions::Llm::Discovery::Pipeline
34
+
35
+ def provider_family = :tls_probe
36
+ end.new
37
+ end
38
+ let(:endpoint) { SpecSupport::TlsEndpoint.new(body: { data: [{ id: 'catalog-model' }] }) }
39
+ let(:instance_cfg) { { base_url: endpoint.url, credentials: { api_key: 'discovery-fixture' } } }
40
+
41
+ after { endpoint.close }
42
+
43
+ { net_http: Faraday::SSLError, typhoeus: Faraday::ConnectionFailed }.each do |adapter, error_class|
44
+ context "with the #{adapter} adapter" do
45
+ before { allow(Faraday).to receive(:default_adapter).and_return(adapter) }
46
+
47
+ context 'with the shared default verification policy' do
48
+ let(:endpoint) do
49
+ SpecSupport::TlsEndpoint.new(subject_alt_name: 'DNS:wrong.example.test', body: { data: [{ id: 'catalog-model' }] })
50
+ end
51
+
52
+ it 'fetches the actual catalog through an untrusted and wrong-host certificate' do
53
+ expect(runner.fetch_raw_models(instance_cfg: instance_cfg)).to eq([{ id: 'catalog-model' }])
54
+ endpoint.finish
55
+
56
+ expect(endpoint.requests.size).to eq(1)
57
+ expect(endpoint.requests.first).to start_with("GET /v1/models HTTP/1.1\r\n")
58
+ expect(endpoint.requests.first).to match(/^Authorization: Bearer discovery-fixture\r?$/i)
59
+ end
60
+
61
+ it 'uses the same policy for the readiness request' do
62
+ result = runner.check_health(instance_cfg: instance_cfg)
63
+ endpoint.finish
64
+
65
+ expect(result).to be_ready
66
+ expect(endpoint.requests.first).to start_with("GET /health HTTP/1.1\r\n")
67
+ expect(endpoint.requests.first).to match(/^Authorization: Bearer discovery-fixture\r?$/i)
68
+ end
69
+ end
70
+
71
+ context 'with verification enabled in shared settings' do
72
+ before { Legion::Settings.loader.settings[:extensions][:llm][:ssl][:verify] = true }
73
+
74
+ it 'rejects an untrusted catalog peer before transmitting credentials' do
75
+ expect { runner.fetch_raw_models(instance_cfg: instance_cfg) }.to raise_error(error_class)
76
+ endpoint.finish
77
+
78
+ expect(endpoint.requests).to be_empty
79
+ end
80
+
81
+ it 'reports the untrusted readiness peer as not ready without sending credentials' do
82
+ result = runner.check_health(instance_cfg: instance_cfg)
83
+ endpoint.finish
84
+
85
+ expect(result).not_to be_ready
86
+ expect(result.metadata).to include(error_class: error_class.name)
87
+ expect(endpoint.requests).to be_empty
88
+ end
89
+
90
+ it 'accepts a catalog peer through an explicitly trusted matching CA' do
91
+ allow(runner).to receive(:build_connection).and_wrap_original do |original, **args|
92
+ original.call(**args).tap { |connection| connection.ssl.ca_file = endpoint.ca_file.path }
93
+ end
94
+
95
+ expect(runner.fetch_raw_models(instance_cfg: instance_cfg)).to eq([{ id: 'catalog-model' }])
96
+ endpoint.finish
97
+
98
+ expect(endpoint.requests.size).to eq(1)
99
+ end
100
+ end
101
+
102
+ context 'with verification enabled and an explicitly trusted wrong-host certificate' do
103
+ let(:endpoint) { SpecSupport::TlsEndpoint.new(subject_alt_name: 'DNS:wrong.example.test') }
104
+
105
+ before { Legion::Settings.loader.settings[:extensions][:llm][:ssl][:verify] = true }
106
+
107
+ it 'still rejects the catalog peer before transmitting credentials' do
108
+ allow(runner).to receive(:build_connection).and_wrap_original do |original, **args|
109
+ original.call(**args).tap { |connection| connection.ssl.ca_file = endpoint.ca_file.path }
110
+ end
111
+
112
+ expect { runner.fetch_raw_models(instance_cfg: instance_cfg) }.to raise_error(error_class)
113
+ endpoint.finish
114
+
115
+ expect(endpoint.requests).to be_empty
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end
@@ -177,6 +177,52 @@ RSpec.describe Legion::Extensions::Llm::Fleet::ExactOffering do
177
177
  expect(call[:messages][3].content).to eq(content)
178
178
  end
179
179
  end
180
+
181
+ it 'rehydrates tools and controls for token counting through the same canonical constructors' do
182
+ params = {
183
+ messages: [], tools: { lookup: { name: 'lookup', parameters: { type: 'object', properties: {} } } },
184
+ thinking: { enabled: true, effort: 'high' }, params: { max_tokens: 512, temperature: 0.2 }
185
+ }
186
+ wire = Legion::JSON.load(Legion::JSON.dump(exact_envelope(operation: 'count_tokens', params: params)))
187
+
188
+ worker.call(envelope: wire, registry: inventory::Registry)
189
+
190
+ controls = recording_callable.calls.first[:rest]
191
+ expect(controls[:tools][:lookup]).to be_a(Legion::Extensions::Llm::Canonical::ToolDefinition)
192
+ expect(controls[:thinking]).to eq(Legion::Extensions::Llm::Canonical::Thinking::Config.build(effort: 'high'))
193
+ expect(controls[:params]).to eq(Legion::Extensions::Llm::Canonical::Params.build(max_tokens: 512, temperature: 0.2))
194
+ expect(handle_reference_count).to eq(0)
195
+ end
196
+
197
+ it 'preserves canonical control instances already present at the fleet boundary' do
198
+ tool = Legion::Extensions::Llm::Canonical::ToolDefinition.build(name: 'lookup')
199
+ thinking = Legion::Extensions::Llm::Canonical::Thinking::Config.build(enabled: false)
200
+ params = Legion::Extensions::Llm::Canonical::Params.build(max_tokens: 512)
201
+
202
+ worker.call(envelope: exact_envelope(params: { messages: [], tools: { lookup: tool }, thinking: thinking, params: params }),
203
+ registry: inventory::Registry)
204
+
205
+ controls = recording_callable.calls.first[:rest]
206
+ expect(controls[:tools][:lookup]).to equal(tool)
207
+ expect(controls[:thinking]).to equal(thinking)
208
+ expect(controls[:params]).to equal(params)
209
+ end
210
+
211
+ it 'preserves embedding-specific params instead of coercing them into chat sampling controls' do
212
+ embedding_key = instance_key(family: 'vllm', instance: 'embedding')
213
+ claim_and_activate(key: embedding_key, callable: recording_callable, coordinator: probe_coordinator(embedding_key),
214
+ supported: [:embed])
215
+ params = { encoding_format: 'base64', dimensions: 64 }
216
+ envelope = exact_envelope(
217
+ provider_instance: 'embedding', operation: 'embed',
218
+ offering_id: inventory::Registry.snapshot.lanes_for(instance_key: embedding_key).first.lane_id,
219
+ params: { text: 'hello', params: params }
220
+ )
221
+
222
+ worker.call(envelope: envelope, registry: inventory::Registry)
223
+
224
+ expect(recording_callable.calls.first[:rest][:params]).to equal(params)
225
+ end
180
226
  end
181
227
 
182
228
  describe 'TokenValidator exact signed claims' do
@@ -0,0 +1,189 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'legion/extensions/llm/fleet/worker_execution'
5
+ require 'legion/extensions/llm/fleet/provider_responder'
6
+ require 'legion/transport'
7
+ require 'support/ssot_registry_helpers'
8
+
9
+ RSpec.describe Legion::Extensions::Llm::Fleet::WorkerExecution do
10
+ include SsotRegistryHelpers
11
+
12
+ def key = instance_key(family: 'wire_probe', instance: 'primary')
13
+ let(:provider) do
14
+ Class.new(Legion::Extensions::Llm::Provider) do
15
+ include Legion::Extensions::Llm::Provider::OpenAICompatible
16
+
17
+ def self.slug = 'wire_probe'
18
+ def api_base = 'https://provider.example'
19
+ end.new(Legion::Extensions::Llm.config)
20
+ end
21
+ let(:messages) { [Legion::Extensions::Llm::Canonical::Message.build(role: :user, content: 'Check the status')] }
22
+ let(:controls) do
23
+ {
24
+ tools: { lookup: tool },
25
+ thinking: Legion::Extensions::Llm::Canonical::Thinking::Config.build(effort: 'high'),
26
+ params: Legion::Extensions::Llm::Canonical::Params.build(temperature: 0.25, max_tokens: 512,
27
+ top_p: 0.8, stop_sequences: ['END'], seed: 7),
28
+ headers: { 'X-Request-Probe' => 'preserved' }, tool_prefs: { choice: 'lookup' },
29
+ schema: { name: 'status', schema: { type: 'object', properties: { status: { type: 'string' } } } }
30
+ }
31
+ end
32
+ let(:captured) { [] }
33
+ let(:stubs) do
34
+ Faraday::Adapter::Test::Stubs.new do |stub|
35
+ stub.post('/v1/chat/completions') do |env|
36
+ captured << { payload: Legion::JSON.load(env.body), header: env.request_headers['X-Request-Probe'] }
37
+ body = { model: 'deployment', choices: [{ message: { role: 'assistant', content: 'ready' }, finish_reason: 'stop' }] }
38
+ [200, { 'content-type' => 'application/json' }, Legion::JSON.dump(body)]
39
+ end
40
+ end
41
+ end
42
+
43
+ def tool
44
+ Legion::Extensions::Llm::Canonical::ToolDefinition.build(
45
+ name: 'lookup', description: 'Find a status',
46
+ parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] }
47
+ )
48
+ end
49
+
50
+ around do |example|
51
+ original = Legion::Settings[:extensions]
52
+ Legion::Settings.loader.settings[:extensions] = Legion::Extensions::Llm::Utils.deep_merge(
53
+ original || {}, { llm: { fleet: { responder: { require_auth: false, require_policy: false, require_idempotency: false } } } }
54
+ )
55
+ example.run
56
+ ensure
57
+ Legion::Settings.loader.settings[:extensions] = original
58
+ Legion::Extensions::Llm::Inventory::Registry.reset!
59
+ end
60
+
61
+ before do
62
+ Legion::Extensions::Llm::Inventory::Registry.reset!
63
+ claim_and_activate(key: key, callable: provider, coordinator: probe_coordinator(key),
64
+ model: 'deployment', supported: %i[chat stream_chat count_tokens])
65
+ provider.connection.connection.builder.adapter :test, stubs
66
+ end
67
+
68
+ %i[chat stream_chat].each do |operation|
69
+ %i[tools thinking params].each do |control|
70
+ it "preserves serialized #{control} through the real #{operation} provider funnel" do
71
+ selected = controls.slice(control)
72
+ provider.public_send(operation, messages, model: 'deployment', **selected)
73
+ wire = wire_envelope(operation: operation, controls: selected)
74
+ response = described_class.call(envelope: wire, registry: registry)
75
+
76
+ expect(response.text).to eq('ready')
77
+ expect(captured.size).to eq(2)
78
+ expect(captured.last).to eq(captured.first)
79
+ expect(handle_reference_count).to eq(0)
80
+ end
81
+ end
82
+
83
+ it "preserves combined controls and transport fields through #{operation}" do
84
+ provider.public_send(operation, messages, model: 'deployment', **controls)
85
+ wire = wire_envelope(operation: operation, controls: controls)
86
+ original = Legion::JSON.dump(wire)
87
+ described_class.call(envelope: wire, registry: registry)
88
+
89
+ expect(captured.last).to eq(captured.first)
90
+ expect(captured.last[:header]).to eq('preserved')
91
+ expect(captured.last[:payload]).to include(
92
+ reasoning_effort: 'high', max_tokens: 512, temperature: 0.25, top_p: 0.8, stop: ['END'], seed: 7,
93
+ tool_choice: { type: 'function', function: { name: 'lookup' } },
94
+ response_format: { type: 'json_schema', json_schema: controls[:schema] }
95
+ )
96
+ expect(captured.last[:payload][:tools]).to eq(
97
+ [{ type: 'function', function: { name: tool.name, description: tool.description, parameters: tool.parameters } }]
98
+ )
99
+ expect(Legion::JSON.dump(wire)).to eq(original)
100
+ end
101
+ end
102
+
103
+ { tools: { lookup: 42 }, thinking: [], params: [] }.each do |control, value|
104
+ it "rejects malformed #{control} before provider dispatch and releases the lease" do
105
+ wire = wire_envelope(operation: :chat, controls: { control => value })
106
+
107
+ expect { described_class.call(envelope: wire, registry: registry) }
108
+ .to raise_error(Legion::Extensions::Llm::Fleet::ContractError) { |error|
109
+ expect(error.cause).to be_a(ArgumentError)
110
+ expect(Legion::Extensions::Llm::Fleet::ProviderResponder.retryable_error?(error)).to be(false)
111
+ }
112
+ expect(captured).to be_empty
113
+ expect(handle_reference_count).to eq(0)
114
+ end
115
+ end
116
+
117
+ it 'preserves explicit nil controls without inventing provider settings' do
118
+ wire = wire_envelope(operation: :chat, controls: { tools: nil, thinking: nil, params: nil })
119
+
120
+ described_class.call(envelope: wire, registry: registry)
121
+
122
+ expect(captured.first[:payload]).not_to have_key(:tools)
123
+ expect(captured.first[:payload]).not_to have_key(:reasoning_effort)
124
+ expect(captured.first[:payload]).not_to have_key(:max_tokens)
125
+ end
126
+
127
+ %i[chat stream_chat count_tokens].each do |operation|
128
+ [5, false, ''].each do |tools|
129
+ it "rejects #{operation} tools #{tools.inspect} as a terminal fleet contract error" do
130
+ publications = capture_fleet_publications
131
+ channel = instance_double(Bunny::Channel, reject: true, ack: true)
132
+ delivery = instance_double(Bunny::DeliveryInfo, channel: channel, delivery_tag: 7)
133
+ allow(provider).to receive(operation).and_call_original
134
+ payload = wire_envelope(operation: operation, controls: { tools: tools }).merge(
135
+ request_id: 'req-invalid-tools', correlation_id: 'corr-invalid-tools', idempotency_key: 'idem-invalid-tools',
136
+ reply_to: 'reply.queue', message_context: {}, caller: {}, trace_context: {}, signed_token: 'unused',
137
+ timeout_seconds: 30, expires_at: (Time.now.utc + 30).iso8601,
138
+ protocol_version: Legion::Extensions::Llm::Fleet::Protocol::VERSION,
139
+ execution_contract: Legion::Extensions::Llm::Fleet::Protocol::EXACT_EXECUTION_CONTRACT
140
+ )
141
+
142
+ expect do
143
+ Legion::Extensions::Llm::Fleet::ProviderResponder.call(
144
+ payload: Legion::JSON.dump(payload), provider_family: key.provider_family, registry: registry, delivery: delivery
145
+ )
146
+ end.to raise_error(Legion::Extensions::Llm::Fleet::ContractError) { |error|
147
+ expect(error.cause).to be_a(ArgumentError)
148
+ }
149
+
150
+ expect(provider).not_to have_received(operation)
151
+ expect(captured).to be_empty
152
+ expect(handle_reference_count).to eq(0)
153
+ expect(publications.size).to eq(1)
154
+ expect(publications.first).to include(
155
+ code: 'contract_error', retryable: false, error_class: 'Legion::Extensions::Llm::Fleet::ContractError'
156
+ )
157
+ expect(channel).to have_received(:reject).with(7, false)
158
+ expect(channel).not_to have_received(:ack)
159
+ end
160
+ end
161
+ end
162
+
163
+ # Keep the actual envelope construction and serialization; isolate only AMQP
164
+ # publication so malformed requests cannot contact a broker on the red path.
165
+ def capture_fleet_publications
166
+ publications = []
167
+ [Legion::Extensions::Llm::Transport::Messages::FleetError, Legion::Extensions::Llm::Transport::Messages::FleetResponse].each do |message_class|
168
+ allow(message_class).to receive(:new).and_wrap_original do |constructor, **options|
169
+ constructor.call(**options).tap do |message|
170
+ allow(message).to receive(:publish) { publications << Legion::JSON.load(Legion::JSON.dump(message.message)) }
171
+ end
172
+ end
173
+ end
174
+ publications
175
+ end
176
+
177
+ def wire_envelope(operation:, controls:)
178
+ Legion::JSON.load(Legion::JSON.dump({
179
+ provider: key.provider_family, provider_instance: key.instance_id,
180
+ model: 'deployment', operation: operation,
181
+ offering_id: registry.snapshot.lanes_for(instance_key: key).first.lane_id,
182
+ params: { messages: messages }.merge(controls)
183
+ }))
184
+ end
185
+
186
+ def handle_reference_count
187
+ registry.snapshot.instance(instance_key: key).callable_handle.reference_count
188
+ end
189
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ RSpec.describe Legion::Extensions::Llm::Provider::OpenAICompatible do
6
+ def provider_for(output_key:)
7
+ base = Class.new(Legion::Extensions::Llm::Provider) do
8
+ include Legion::Extensions::Llm::Provider::OpenAICompatible
9
+
10
+ def api_base = 'https://compatible.example'
11
+ end
12
+ provider_class = if output_key == :max_tokens
13
+ base
14
+ else
15
+ Class.new(base) { define_method(:output_token_limit_key) { output_key } }
16
+ end
17
+ provider_class.new(Legion::Extensions::Llm.config)
18
+ end
19
+
20
+ def serve_response(env:, stream:)
21
+ unless stream
22
+ body = { model: 'selected-model', choices: [{ message: { content: 'OK' }, finish_reason: 'stop' }],
23
+ usage: { prompt_tokens: 2, completion_tokens: 1 } }
24
+ return [200, { 'content-type' => 'application/json' }, Legion::JSON.dump(body)]
25
+ end
26
+
27
+ env.status = 200
28
+ env.response_headers = { 'content-type' => 'text/event-stream' }
29
+ body = { model: 'selected-model', choices: [{ delta: { content: 'OK' }, finish_reason: 'stop' }],
30
+ usage: { prompt_tokens: 2, completion_tokens: 1 } }
31
+ wire = "data: #{Legion::JSON.dump(body)}\n\ndata: [DONE]\n\n"
32
+ env.request.on_data.call(wire, wire.bytesize, env)
33
+ [200, env.response_headers, '']
34
+ end
35
+
36
+ %i[max_tokens max_completion_tokens].each do |output_key|
37
+ [false, true].each do |stream|
38
+ [128, 64_000, nil, :absent_params].each do |limit|
39
+ it "uses exactly the #{output_key} protocol field for #{limit.inspect}, stream=#{stream}, without changing canonical params" do
40
+ provider = provider_for(output_key: output_key)
41
+ params = (Legion::Extensions::Llm::Canonical::Params.build(max_tokens: limit, temperature: 0, top_p: 0.7) unless limit == :absent_params)
42
+ original = params&.to_h
43
+ expected = limit == :absent_params ? nil : limit
44
+ payloads = []
45
+ stubs = Faraday::Adapter::Test::Stubs.new do |stub|
46
+ stub.post('/v1/chat/completions') do |env|
47
+ payloads << Legion::JSON.load(env.body)
48
+ serve_response(env: env, stream: stream)
49
+ end
50
+ end
51
+ provider.connection.connection.builder.adapter :test, stubs
52
+ messages = [Legion::Extensions::Llm::Canonical::Message.build(role: :user, content: 'Hello.')]
53
+ chunks = []
54
+ response = if stream
55
+ provider.stream_chat(messages, model: 'selected-model', params: params) { |chunk| chunks << chunk }
56
+ else
57
+ provider.chat(messages, model: 'selected-model', params: params)
58
+ end
59
+
60
+ expect(payloads.size).to eq(1)
61
+ payload = payloads.first
62
+ expect(payload.keys & %i[max_tokens max_completion_tokens]).to eq(expected.nil? ? [] : [output_key])
63
+ expect(payload[output_key]).to eq(expected)
64
+ expect(payload).to include(temperature: 0, top_p: 0.7) if params
65
+ expect(params&.to_h).to eq(original)
66
+ expect(response).to have_attributes(text: 'OK', stop_reason: :end_turn)
67
+ expect(chunks.count { |chunk| chunk.type == :done }).to eq(1) if stream
68
+ stubs.verify_stubbed_calls
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ RSpec.describe Legion::Extensions::Llm::Provider::OpenAICompatible do
6
+ let(:canonical) { Legion::Extensions::Llm::Canonical }
7
+ let(:provider_class) do
8
+ Class.new(Legion::Extensions::Llm::Provider) do
9
+ include Legion::Extensions::Llm::Provider::OpenAICompatible
10
+
11
+ def api_base = 'https://compatible.example'
12
+ end
13
+ end
14
+ let(:provider) { provider_class.new(Legion::Extensions::Llm.config) }
15
+ let(:chunks) { [] }
16
+
17
+ def run_http_stream(frames)
18
+ stubs = Faraday::Adapter::Test::Stubs.new do |stub|
19
+ stub.post('/v1/chat/completions') do |env|
20
+ expect(Legion::JSON.load(env.body)).to include(model: 'selected-model', stream: true)
21
+ env.status = 200
22
+ env.response_headers = { 'content-type' => 'text/event-stream' }
23
+ frames.each do |frame|
24
+ wire = "data: #{Legion::JSON.dump(frame)}\n\n"
25
+ # Exercise the real SSE parser across HTTP callback boundaries.
26
+ midpoint = wire.bytesize / 2
27
+ [wire.byteslice(0, midpoint), wire.byteslice(midpoint..)].each do |part|
28
+ env.request.on_data.call(part, part.bytesize, env)
29
+ end
30
+ expect(chunks.count { |chunk| chunk.type == :done }).to eq(0)
31
+ end
32
+ env.request.on_data.call("data: [DONE]\n\n", 14, env)
33
+ [200, env.response_headers, '']
34
+ end
35
+ end
36
+ provider.connection.connection.builder.adapter :test, stubs
37
+ response = provider.stream_chat([canonical::Message.build(role: :user, content: 'Continue.')], model: 'selected-model') do |chunk|
38
+ chunks << chunk
39
+ end
40
+ stubs.verify_stubbed_calls
41
+ response
42
+ end
43
+
44
+ def choice_frame(delta:, finish_reason: nil)
45
+ { model: 'selected-model', choices: [{ index: 0, delta: delta, finish_reason: finish_reason }] }
46
+ end
47
+
48
+ { 'stop' => :end_turn, 'length' => :max_tokens, 'tool_calls' => :tool_use, 'content_filter' => :content_filter }.each do |wire_reason, reason|
49
+ [false, true].each do |terminal_content|
50
+ it "preserves #{wire_reason} with terminal content=#{terminal_content}, trailing usage, and exactly one final done" do
51
+ frames = [choice_frame(delta: { content: 'Hello' })]
52
+ if wire_reason == 'tool_calls'
53
+ frames << choice_frame(delta: { tool_calls: [{ index: 0, id: 'call_lookup',
54
+ function: { name: 'lookup', arguments: '{}' } }] })
55
+ end
56
+ frames << choice_frame(delta: terminal_content ? { content: ' there.' } : {}, finish_reason: wire_reason)
57
+ frames << { choices: [], usage: { prompt_tokens: 11, completion_tokens: 7,
58
+ completion_tokens_details: { reasoning_tokens: 3 } } }
59
+
60
+ response = run_http_stream(frames)
61
+
62
+ expect(response.stop_reason).to eq(reason)
63
+ expect(response.text).to eq(terminal_content ? 'Hello there.' : 'Hello')
64
+ expect(response.usage).to have_attributes(input_tokens: 11, output_tokens: 7, thinking_tokens: 3)
65
+ expect(response.tool_calls.map(&:name)).to eq(wire_reason == 'tool_calls' ? ['lookup'] : [])
66
+ expect(chunks).to all(be_a(canonical::Chunk))
67
+ expect(chunks.select { |chunk| chunk.type == :text_delta }.map(&:delta).join).to eq(response.text)
68
+ expect(chunks.count { |chunk| chunk.type == :done }).to eq(1)
69
+ expect(chunks.last).to have_attributes(type: :done, stop_reason: reason, usage: response.usage)
70
+ end
71
+ end
72
+ end
73
+
74
+ [nil, '', 'unrecognized_reason'].each do |wire_reason|
75
+ it "does not fabricate successful completion for #{wire_reason.inspect}" do
76
+ response = run_http_stream([
77
+ choice_frame(delta: { content: 'Unconfirmed' }),
78
+ choice_frame(delta: {}, finish_reason: wire_reason),
79
+ { choices: [], usage: { prompt_tokens: 2, completion_tokens: 1 } }
80
+ ])
81
+
82
+ expect(response.stop_reason).to be_nil
83
+ expect(response.text).to eq('Unconfirmed')
84
+ expect(chunks.count { |chunk| chunk.type == :done }).to eq(1)
85
+ expect(chunks.last).to have_attributes(type: :done, stop_reason: nil)
86
+ end
87
+ end
88
+ end
@@ -8,9 +8,12 @@ require 'timeout'
8
8
  module SpecSupport
9
9
  # One real HTTPS exchange, using a fresh private CA rather than external trust.
10
10
  class TlsEndpoint
11
+ include Legion::Logging::Helper
12
+
11
13
  attr_reader :url, :ca_file, :requests
12
14
 
13
- def initialize(subject_alt_name: 'IP:127.0.0.1')
15
+ def initialize(subject_alt_name: 'IP:127.0.0.1', body: { status: 'ok' })
16
+ @body = Legion::JSON.dump(body)
14
17
  ca_key = OpenSSL::PKey::EC.generate('prime256v1')
15
18
  ca = certificate(key: ca_key, name: 'lex-llm test CA')
16
19
  ca_extensions = OpenSSL::X509::ExtensionFactory.new
@@ -81,10 +84,9 @@ module SpecSupport
81
84
  return if request.empty?
82
85
 
83
86
  @requests << request
84
- body = '{"status":"ok"}'
85
- socket.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: #{body.bytesize}\r\nConnection: close\r\n\r\n#{body}")
87
+ socket.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: #{@body.bytesize}\r\nConnection: close\r\n\r\n#{@body}")
86
88
  rescue OpenSSL::SSL::SSLError, Errno::ECONNRESET => e
87
- Legion::Logging.debug("TLS fixture peer rejected the connection: #{e.class}")
89
+ handle_exception(e, level: :warn, operation: :tls_fixture_peer_rejection)
88
90
  ensure
89
91
  socket&.close
90
92
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lex-llm
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.8
4
+ version: 0.8.12
5
5
  platform: ruby
6
6
  authors:
7
7
  - LegionIO
@@ -391,11 +391,13 @@ files:
391
391
  - spec/legion/extensions/llm/connection_retry_spec.rb
392
392
  - spec/legion/extensions/llm/connection_tls_spec.rb
393
393
  - spec/legion/extensions/llm/credential_sources_spec.rb
394
+ - spec/legion/extensions/llm/discovery/pipeline_tls_spec.rb
394
395
  - spec/legion/extensions/llm/error_middleware_spec.rb
395
396
  - spec/legion/extensions/llm/error_spec.rb
396
397
  - spec/legion/extensions/llm/fleet/exact_offering_spec.rb
397
398
  - spec/legion/extensions/llm/fleet/provider_responder_spec.rb
398
399
  - spec/legion/extensions/llm/fleet/token_validator_spec.rb
400
+ - spec/legion/extensions/llm/fleet/worker_execution_controls_spec.rb
399
401
  - spec/legion/extensions/llm/fleet/worker_execution_spec.rb
400
402
  - spec/legion/extensions/llm/fleet_messages_spec.rb
401
403
  - spec/legion/extensions/llm/gemspec_spec.rb
@@ -415,7 +417,9 @@ files:
415
417
  - spec/legion/extensions/llm/inventory/snapshot_spec.rb
416
418
  - spec/legion/extensions/llm/inventory/weight_reconciler_spec.rb
417
419
  - spec/legion/extensions/llm/inventory/weight_schema_spec.rb
420
+ - spec/legion/extensions/llm/provider/open_ai_compatible_output_limit_spec.rb
418
421
  - spec/legion/extensions/llm/provider/open_ai_compatible_spec.rb
422
+ - spec/legion/extensions/llm/provider/open_ai_compatible_stream_terminal_spec.rb
419
423
  - spec/legion/extensions/llm/provider/open_ai_compatible_tool_calls_array_spec.rb
420
424
  - spec/legion/extensions/llm/provider_contract_spec.rb
421
425
  - spec/legion/extensions/llm/provider_settings_spec.rb