activeagent 1.9.8 → 1.9.10

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: 560139e6515a8b3568aabc383ec0ae4219764a2d8ca91b14b4defc4fdec3439d
4
- data.tar.gz: b1d8651cb0a058b8922e579374720efd42c3babcadfddc3c123c5b7c6c2afd8b
3
+ metadata.gz: 74cdf346c2238da0eda25a4c53a047f56b5557ca991520558cfc88e56290d6e4
4
+ data.tar.gz: 563d490b5800e9735f9ef9ec765ee15799d7bbd431773d5bde2623ccff5c441d
5
5
  SHA512:
6
- metadata.gz: 722dcbfe0e8bc2254871264f42ddf5394eb4f26acfc47f53ce17f2c9b382db627248d90ded1c9164a30bd176f908ee4510db11332e26bd6e25c91d485b251fde
7
- data.tar.gz: e97465f43ad9dfee0eecfa0e3b3207b7c3a67dc620a1fa656c451800b9e49ca89259a75dd7ce7ad7066f05bfeece5d719fdf869e30a3cf89ae11f6e6f9de42dd
6
+ metadata.gz: cd95ef40bf18ed3d6920530c4e7500f17a4cc24a9c9e8c575b7fe6cb6fd245be7b8707e32ddee8d5d90fda58a1fdad7650e184bedfa66e8040b538d86e57ceae
7
+ data.tar.gz: a81a674b55407298ad5935f3e20beece07669944792f4a27c5d7c81bacc2293055ad79cc32f44bdd93db93d0476fe7067120136424c7af95c8e975ad94e7eb6c
data/CHANGELOG.md CHANGED
@@ -5,6 +5,247 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.9.10] - 2026-12-02
9
+
10
+ The dashboard takes OpenTelemetry: an application in any language can
11
+ report traces with its own OTLP exporter. An agent run whose worker died
12
+ is now failed as lost instead of staying "running" forever. The rest is
13
+ provider fixes, most of them from the community: the OpenAI providers
14
+ load the `openai` gem 1.x, Anthropic keeps `cache_control` on a
15
+ single-block system prompt (prompt caching was silently lost), OpenRouter
16
+ sends `tool_choice: "required"`, Ollama honours `format` and `options` and
17
+ keeps parallel tool results apart, Azure and OpenRouter serve embeddings,
18
+ and the RubyLLM provider passes `tool_choice`, array instructions, a
19
+ tool's `input_schema` and cache and embedding token counts through.
20
+
21
+ Upgrading: one dashboard migration, 036 `add_agent_run_execution_leases`:
22
+ run `bin/rails generate action_agent:install --skip` and `bin/rails
23
+ db:migrate`. It is numbered after 1.9.9's 034 and 035 so that a new
24
+ install and an upgraded one run the three in the same order; 033 stays
25
+ unused. Until it runs, agent runs take no leases and a run whose
26
+ worker dies stays running as before; once it has, a run that makes no
27
+ progress for 30 minutes is failed as lost. `activeagent` now requires
28
+ activeagents-telemetry 0.4 or later (it allowed 0.1 and up), which OTLP
29
+ ingest needs: `bundle update activeagent` brings it in. Schema tools now return an error for a
30
+ range filter that cannot apply (an empty range, an unreadable bound, a
31
+ comparison on a string or boolean column) where they used to answer with
32
+ a count of 0. `usage.total_tokens` for a RubyLLM agent rises on cached
33
+ prompts, since cache reads and writes are now counted.
34
+
35
+ ### Added
36
+
37
+ - **OpenTelemetry ingest** (`actionagent`). The trace ingest endpoint
38
+ (`POST <mount>/api/traces`, and `<mount>/api/otlp/v1/traces` for exporters
39
+ given a base endpoint) reads OTLP over HTTP, protobuf or JSON, gzipped or
40
+ not, so an application in any language can report to the dashboard with
41
+ its OpenTelemetry exporter. Spans following the OpenTelemetry GenAI
42
+ semantic conventions become the dashboard's `llm`, `tool` and agent
43
+ spans; other spans are dropped. Because an exporter sends spans as they
44
+ end, a trace is stored with its first span and takes the rest as they
45
+ arrive. activeagents-telemetry 0.4, which `activeagent` now requires,
46
+ does the decoding. The native format is unchanged.
47
+
48
+ - **OpenRouter embeddings** (`activeagent`). `OpenRouterProvider#embed`
49
+ raised `NotImplementedError`, though OpenRouter serves an
50
+ OpenAI-compatible `/embeddings` endpoint. The provider now sends
51
+ embedding requests there, as the Requesty provider does.
52
+ - **Azure OpenAI embeddings** (`activeagent`). `AzureProvider#embed` built
53
+ the request and then raised `NotImplementedError`. It now calls the
54
+ deployment's `/embeddings` endpoint. The Azure client's `auth_headers`
55
+ also accepts the options newer `openai` gem versions pass to it.
56
+
57
+ ### Fixed
58
+
59
+ - **Ollama `format` and `options` take effect** (`activeagent`). Requests
60
+ go to Ollama's OpenAI-compatible endpoint, which ignores the native
61
+ `format` and `options` fields, so `format: "json"`, a JSON schema and
62
+ `options: { num_predict: }` did nothing. They are now also sent as
63
+ `response_format`, `max_tokens` and the matching sampling parameters. A
64
+ value given at the top level wins.
65
+ - **OpenRouter accepts a custom base URL** (`activeagent`). `base_url` was
66
+ read-only on the OpenRouter options, so passing it (or `uri_base`)
67
+ raised `ArgumentError`. The default endpoint is unchanged.
68
+ - **RubyLLM embeddings report token usage** (`activeagent`).
69
+ `response.usage` was nil after an embedding even when the provider
70
+ reported prompt tokens. The input tokens are now summed across the
71
+ inputs. ruby_llm 1.x reports zero for an omitted count, so only positive
72
+ counts are kept there.
73
+ - **OpenAI Chat cache writes are reported** (`activeagent`).
74
+ `prompt_tokens_details.cache_write_tokens` is now mapped to
75
+ `usage.cache_creation_tokens`, as the Anthropic provider already maps
76
+ its own field.
77
+ - **Sampling parameters are dropped for prefixed model ids**
78
+ (`activeagent`). Model capability rules matched only a bare model name,
79
+ so a Bedrock id such as `eu.anthropic.claude-sonnet-5-v1:0` or a routed
80
+ `openai/gpt-5` kept `temperature` and `top_p` for a model that rejects
81
+ them. The region or vendor prefix and the `-vN:M` suffix are now ignored
82
+ when matching.
83
+ - **The OpenAI providers load the `openai` gem 1.x** (`activeagent`).
84
+ The `openai` loader pinned the client gem to `~> 0.34`, so a bundle
85
+ holding openai 1.0 or later raised `LoadError` the moment any
86
+ OpenAI-family provider (OpenAI, OpenRouter, Ollama and the other
87
+ OpenAI-compatible providers) loaded. The loader and the gemspec's
88
+ development dependency now accept openai 0.34 through 1.x, and CI runs
89
+ the OpenAI, Azure, OpenRouter and Ollama provider tests against 1.3.
90
+ - **Required tool choice works with OpenRouter** (`activeagent`). The
91
+ adapter now sends `tool_choice: "required"` and clears it after the
92
+ first tool call so the model can finish its response.
93
+ - **RubyLLM keeps a tool's `input_schema`** (`activeagent`). A tool
94
+ defined with `input_schema` instead of `parameters` reached ruby_llm with
95
+ an empty schema, so the model was told the tool takes no arguments. The
96
+ provider now accepts either key, as the OpenAI providers do.
97
+ - **Array instructions work with RubyLLM** (`activeagent`). An agent whose
98
+ `instructions` were an array raised `ArgumentError: Message content must
99
+ be a String` before any request. Each entry is now sent as its own system
100
+ message.
101
+ - **Anthropic tool choice** (`activeagent`). The common `tool_choice: "none"`
102
+ option now disables tool use without a conversion error.
103
+ - **Ollama keeps parallel tool results apart** (`activeagent`). Before a
104
+ request, consecutive same-role messages were merged, and parallel tool
105
+ calls append one `tool` message per call, so their results were
106
+ concatenated into a single message holding only the first
107
+ `tool_call_id`. Tool results and assistant messages with `tool_calls` are
108
+ no longer merged.
109
+
110
+ - **RubyLLM totals count cached tokens** (`activeagent`). ruby_llm reports
111
+ input apart from cache reads and writes, and the provider's
112
+ `usage.total_tokens` fell back to input plus output, so a prompt that
113
+ read or wrote the cache was undercounted. The total is now input, output,
114
+ cache reads and cache writes, as the Anthropic provider already counts
115
+ it, and a stream totals after its chunks are merged. `total_tokens` for
116
+ a RubyLLM agent rises on cached prompts; `input_tokens`,
117
+ `cached_tokens` and `cache_creation_tokens` are unchanged.
118
+ - **`tool_choice` reaches RubyLLM** (`activeagent`). The adapter read
119
+ `tool_choice` only to clear it between turns and never sent it, so
120
+ `tool_choice: "required"` or a named tool was ignored and a generation
121
+ could finish without calling a tool. It is now passed as RubyLLM's
122
+ `tool_prefs`, and still cleared once the tool has been used.
123
+ - **A streamed Mock prompt reports why it stopped** (`activeagent`). The
124
+ mock emitted `end_turn` in its stream but never recorded it, so
125
+ `response.finish_reason` was `nil` after a streamed prompt, as it was not
126
+ for the real providers. The mock now records it like they do.
127
+ - **A Symbol `tool_choice` is cleared under RubyLLM** (`activeagent`). The
128
+ provider sends `tool_choice: :required` or `{ name: :get_weather }` to
129
+ RubyLLM, but the checks that clear a forced choice once the tool has run
130
+ compared Strings, so a Symbol choice forced every turn into another tool
131
+ call until `max_tool_turns` stopped it. Both forms are now cleared after
132
+ the tool is used, as the String forms already were.
133
+ - **Anthropic keeps `cache_control` on a single text block** (`activeagent`).
134
+ A system prompt or message holding one text block was sent as a bare
135
+ string, which dropped the block's `cache_control` (or `citations`), so a
136
+ prompt marked for caching was never cached. Only a block holding nothing
137
+ but its text is shortened now.
138
+ - **A catalog set run against a project keeps its selection** (`actionagent`).
139
+ Running a set with `project_id` stored the requested `keys` and `models`,
140
+ but `ProjectEvaluationJob` did not pass them on, so the run replayed every
141
+ enabled scenario under the agent's own model. It now replays the ones
142
+ asked for.
143
+ - **Schema tools refuse a range filter that cannot apply** (`activeagent`).
144
+ A bound the column cannot read (`{"before" => "yesterday"}`,
145
+ `{"gt" => "thirty"}`, a blank or `nil` bound), an empty range object, and
146
+ a comparison on a string or boolean column were each answered as if they
147
+ had filtered: zero rows, every row, or a comparison with 0. Each now
148
+ returns the tool's error, as an unknown comparison already did.
149
+ - **A run whose worker died is failed as lost instead of running forever**
150
+ (`actionagent`). Since a run is claimed once, a worker that died after
151
+ its claim left the run `running` for good: a redelivered job leaves a
152
+ running run alone. Each claim (the execution job's, the resume job's,
153
+ `Agent#test_execute`'s) now takes a lease (migration 036,
154
+ `config.run_lease_duration`, 30 minutes by default) that each LLM or
155
+ tool call renews. A running run whose lease ran out is failed with
156
+ `error_class` `ActionAgent::AgentRun::WorkerLost` when its page or the
157
+ run list is read, or when `ActionAgent::AgentRunExpiryJob` runs (not
158
+ scheduled by default). Nothing is executed again: the run's provider and
159
+ tool calls may already have taken effect. A worker that was only slow
160
+ has its result discarded, as a cancelled run's is, and a result now
161
+ only lands while the run holds its worker's lease, so whatever ended
162
+ the run first is kept. `test_execute` records its result the same way,
163
+ so a cancel during a synchronous test run is no longer overwritten. A
164
+ run with no lease, such as one running when the migration is installed,
165
+ is never failed as lost.
166
+
167
+ ## [1.9.9] - 2026-11-18
168
+
169
+ Schema tools can ask whether a column is set: a filter takes
170
+ `{"present": false}` (IS NULL) or `{"present": true}` (IS NOT NULL), so a
171
+ model can find the tickets with no assignee without a sentinel range in
172
+ the instructions. Around that, fixes to evaluations and providers: an
173
+ evaluation run and a fanned-out replay are each claimed before they
174
+ execute, so a job delivered twice no longer replays the suite or calls
175
+ the provider twice; a catalog document safe loading refuses is a 422
176
+ instead of a 500; a run of only ungated groups no longer reads as "every
177
+ gate met"; and the RubyLLM provider refuses media it would drop.
178
+
179
+ Upgrading: no migrations. The RubyLLM provider now raises
180
+ `ActiveAgent::Providers::Errors::InvalidRequest` for a message carrying an
181
+ image, audio or a file, where it used to send the text alone; route such
182
+ messages to a provider that takes media.
183
+
184
+ ### Added
185
+
186
+ - **Schema tools can ask whether a column is set** (`activeagent`). A
187
+ filter value of `null` means "no filter", so a model had no way to ask
188
+ for the tickets with no assignee or the requests not yet approved, and
189
+ hosts wrote sentinel ranges such as `{"after": "2000-01-01"}` into their
190
+ instructions instead. A filter now takes `{"present": false}` (IS NULL)
191
+ or `{"present": true}` (IS NOT NULL) on any filterable column, alone or
192
+ beside a range bound. The tool schema offers it in the range object of
193
+ nullable date, time and number columns, so foreign keys get it too, and
194
+ an enum accepts it though it takes no comparison. Anything but true or
195
+ false is rejected rather than guessed.
196
+
197
+ ### Fixed
198
+
199
+ - **An evaluation run is executed by one job** (`actionagent`). The run job
200
+ read a run's status, then the scenario runner wrote `running`, as two
201
+ steps, so a job delivered twice, or two workers that both loaded the run
202
+ as pending, each replayed the whole suite, or with
203
+ `scenario_evaluation_fan_out` on each enqueued a full set of replay jobs.
204
+ The runner now moves the run from pending to running in one conditional
205
+ update, as the execution job claims an agent run, and replays nothing
206
+ unless it was the one to do so; this covers `ProjectEvaluationJob` too.
207
+ The claim comes before the selection is read, so a selection that cannot
208
+ be resolved (an unsupported provider in a re-run's models) now fails the
209
+ run instead of leaving it pending forever.
210
+ - **A fanned-out replay is claimed before the agent runs** (`actionagent`).
211
+ `EvaluationReplayJob` checked for a stored result, replayed, and only
212
+ then took the run's lock to store, so two deliveries of one replay job
213
+ both called the provider (and the agent's tools) and the second answer
214
+ was dropped. A delivery that failed after another had stored the pair's
215
+ replay also marked that good result errored. The replay now takes a
216
+ claim, kept with the run's fan-out bookkeeping (no migration), before
217
+ the agent runs. A delivery that finds the pair claimed comes back when
218
+ the claim expires (30 minutes) and replays only if nothing was stored,
219
+ so a worker that stopped mid-replay is still covered. A failure is
220
+ stored only over the delivery's own pair. A worker that stops after the
221
+ provider answered and before the result is stored is still replayed
222
+ again: this is one active replay per pair, not exactly once.
223
+ - **A catalog document YAML refuses to load is an invalid document**
224
+ (`activeagent`, `actionagent`). `Catalog.parse` turned only a syntax
225
+ error into `Catalog::InvalidDocument`, while safe loading refuses a tag
226
+ naming a Ruby class (`!ruby/object:...`) or an alias to an undefined
227
+ anchor with other `Psych` errors. Those escaped the dashboard's catalog
228
+ import and preview as a 500, and the `catalogs_import` and
229
+ `catalogs_preview` tools as an internal error. They are now refused like
230
+ any other invalid catalog: 422 with "the catalog is not valid YAML: ...".
231
+ What safe loading permits is unchanged.
232
+ - **A run of only ungated groups no longer reads as "every gate met"**
233
+ (`activeagent`). An ungated group's row is met without being held to a
234
+ bar, so a report whose every result sat in ungated groups said "every
235
+ pass gate met" (`GateCheck`, `assert_meets_pass_gates`, the RSpec
236
+ matcher) and `evals run --wait` printed `Gates: every gate met`, even
237
+ when every answer had failed. The verdict is unchanged, since an ungated
238
+ group never fails the run, but the message now says that every group
239
+ covered is ungated and nothing was held to a bar.
240
+ - **The RubyLLM provider refuses media it would drop** (`activeagent`). It
241
+ sends RubyLLM the text of each message and silently left out every other
242
+ content block, so a message with an image (`image_url`, `image`,
243
+ `input_image`), audio or a file reached the model as its text alone, or
244
+ as an empty message, and the model answered as if it had seen it. Such
245
+ a message now raises `ActiveAgent::Providers::Errors::InvalidRequest`,
246
+ naming the block types, before any provider call. Blocks that are not
247
+ media (an earlier turn's reasoning) are still left out, as before.
248
+
8
249
  ## [1.9.8] - 2026-11-12
9
250
 
10
251
  The dashboard holds a run to its catalog's pass bars: a product's and a
@@ -247,7 +247,13 @@ module ActiveAgent
247
247
  def print_gates(gates, missed)
248
248
  unmet = gates.reject { |gate| gate["met"] == true }
249
249
  unless missed
250
- @out.puts "Gates: every gate met (#{gates.size})."
250
+ # Ungated rows are met without being held to a bar, so a run that
251
+ # reached only those says so rather than "every gate met".
252
+ if gates.none? { |gate| gate["gated"] != false }
253
+ @out.puts "Gates: every group reached is ungated (#{gates.size}); nothing was held to a bar."
254
+ else
255
+ @out.puts "Gates: every gate met (#{gates.size})."
256
+ end
251
257
  return
252
258
  end
253
259
 
@@ -81,13 +81,16 @@ module ActiveAgent
81
81
  end
82
82
 
83
83
  # Parses YAML text. Raises InvalidDocument for YAML that is not a
84
- # document (a list, a scalar) or that YAML cannot read.
84
+ # document (a list, a scalar) or that YAML cannot read: a syntax error,
85
+ # and what safe loading refuses — a tag naming a Ruby class other than
86
+ # Symbol (Psych::DisallowedClass) or an alias to an undefined anchor
87
+ # (Psych::BadAlias), which are not Psych::SyntaxError.
85
88
  def self.parse(text, name: nil)
86
89
  document = YAML.safe_load(text.to_s, aliases: true, permitted_classes: [ Symbol ])
87
90
  raise InvalidDocument, "a scenario catalog is a YAML mapping" unless document.is_a?(Hash)
88
91
 
89
92
  new([ document ], name: name)
90
- rescue Psych::SyntaxError => e
93
+ rescue Psych::Exception => e
91
94
  raise InvalidDocument, "the catalog is not valid YAML: #{e.message}"
92
95
  end
93
96
 
@@ -45,7 +45,9 @@ module ActiveAgent
45
45
  end
46
46
 
47
47
  # The text a failing assertion prints. The first line counts the gates
48
- # not met, or is the one line "every pass gate met" when none is; then
48
+ # not met, or is the one line "every pass gate met" when none is (a
49
+ # report whose every row is an ungated group's says that instead: its
50
+ # rows are met because nothing held them to a bar); then
49
51
  # each unmet gate as Gate#to_s; then, after a blank line, the failures
50
52
  # to read: for each group with an unmet gate, in gates order, "<group>
51
53
  # failures:" over Report#failures_markdown for that group. An unmet All
@@ -59,6 +61,7 @@ module ActiveAgent
59
61
  return "no result reached a pass gate; the run evaluated nothing" if all.empty?
60
62
 
61
63
  unmet = all.reject(&:met?)
64
+ return "every group the run covered is ungated; no answer was held to a bar" if all.none?(&:gated)
62
65
  return "every pass gate met" if unmet.empty?
63
66
 
64
67
  lines = [ "#{unmet.size} of #{all.size} pass gates not met", *unmet.map { |gate| "- #{gate}" } ]
@@ -29,6 +29,11 @@ module ActiveAgent
29
29
  { pattern: /\Agpt-5/, unsupported: SAMPLING_PARAMS }
30
30
  ].freeze
31
31
 
32
+ # Cloud-hosted ids wrap the bare model name, e.g. Bedrock's
33
+ # "eu.anthropic.claude-sonnet-5-v1:0" or "anthropic.claude-opus-5-v1:0".
34
+ PROVIDER_PREFIX = /\A(?:[a-z]{2,6}\.)?(?:anthropic|openai)[.\/]/
35
+ VERSION_SUFFIX = /-v\d+(?::\d+)?\z/
36
+
32
37
  class << self
33
38
  # Master switch; on by default. Set false to send parameters through
34
39
  # untouched (the vendor then enforces its own rules).
@@ -61,12 +66,21 @@ module ActiveAgent
61
66
  def unsupported_params(model)
62
67
  return [] if model.nil?
63
68
 
69
+ name = model.to_s
70
+ bare = normalize_model(name)
71
+
64
72
  (custom_rules + BUILTIN_RULES).each do |rule|
65
- return rule[:unsupported] if model.to_s.match?(rule[:pattern])
73
+ return rule[:unsupported] if name.match?(rule[:pattern]) || bare.match?(rule[:pattern])
66
74
  end
67
75
  []
68
76
  end
69
77
 
78
+ # Strips the region/provider prefix and "-vN:M" suffix that Bedrock-style
79
+ # ids add around the bare model name.
80
+ def normalize_model(name)
81
+ name.sub(PROVIDER_PREFIX, "").sub(VERSION_SUFFIX, "")
82
+ end
83
+
70
84
  def sampling_supported?(model)
71
85
  (unsupported_params(model) & SAMPLING_PARAMS).empty?
72
86
  end
@@ -11,7 +11,7 @@ require_relative "concerns/tool_choice_clearing"
11
11
  # @private
12
12
  GEM_LOADERS = {
13
13
  anthropic: [ "anthropic", [ ">= 1.12", "< 3" ], "anthropic" ],
14
- openai: [ "openai", "~> 0.34", "openai" ],
14
+ openai: [ "openai", [ ">= 0.34", "< 2" ], "openai" ],
15
15
  # Keep a tested floor: 1.2 lacks the provider APIs this adapter uses.
16
16
  ruby_llm: [ "ruby_llm", [ ">= 1.16", "< 3" ], "ruby_llm" ]
17
17
  }
@@ -187,6 +187,7 @@ module ActiveAgent
187
187
  # Maps:
188
188
  # - "required" → ToolChoiceAny (force tool use)
189
189
  # - "auto" → ToolChoiceAuto (let model decide)
190
+ # - "none" → ToolChoiceNone (disable tool use)
190
191
  # - { name: "..." } → ToolChoiceTool with name
191
192
  #
192
193
  # @param tool_choice [String, Hash, Object]
@@ -205,6 +206,8 @@ module ActiveAgent
205
206
  when "auto"
206
207
  # Create ToolChoiceAuto model for letting model decide
207
208
  ::Anthropic::Models::ToolChoiceAuto.new(type: :auto)
209
+ when "none"
210
+ ::Anthropic::Models::ToolChoiceNone.new(type: :none)
208
211
  when Hash
209
212
  choice_hash = tool_choice.deep_symbolize_keys
210
213
 
@@ -567,6 +570,10 @@ module ActiveAgent
567
570
  #
568
571
  # `[{type: "text", text: "hello"}]` → `"hello"`
569
572
  #
573
+ # A block that carries anything besides its text, such as
574
+ # cache_control or citations, stays a block: the string form has
575
+ # nowhere to keep it.
576
+ #
570
577
  # @param msg [Hash] message with :content key
571
578
  # @return [void]
572
579
  def compress_message_content!(msg)
@@ -574,7 +581,7 @@ module ActiveAgent
574
581
  return unless content.is_a?(Array)
575
582
 
576
583
  # Single text block → string shorthand
577
- if content.one? && content.first.is_a?(Hash) && content.first[:type] == "text"
584
+ if content.one? && plain_text_block?(content.first)
578
585
  msg[:content] = content.first[:text]
579
586
  end
580
587
  end
@@ -639,12 +646,20 @@ module ActiveAgent
639
646
  return system unless system.is_a?(Array)
640
647
 
641
648
  # Single text block → string shorthand
642
- if system.one? && system.first.is_a?(Hash) && system.first[:type] == "text"
649
+ if system.one? && plain_text_block?(system.first)
643
650
  system.first[:text]
644
651
  else
645
652
  system
646
653
  end
647
654
  end
655
+
656
+ # True for a text block holding nothing but its text.
657
+ #
658
+ # @param block [Object]
659
+ # @return [Boolean]
660
+ def plain_text_block?(block)
661
+ block.is_a?(Hash) && block[:type] == "text" && block.except(:type, :text).compact.empty?
662
+ end
648
663
  end
649
664
  end
650
665
  end
@@ -60,6 +60,17 @@ module ActiveAgent
60
60
  )
61
61
  end
62
62
 
63
+ protected
64
+
65
+ # Executes an embedding request against the Azure deployment's
66
+ # +/embeddings+ endpoint.
67
+ #
68
+ # @param parameters [Hash]
69
+ # @return [Hash] symbolized API response
70
+ def api_embed_execute(parameters)
71
+ client.embeddings.create(**parameters).as_json.deep_symbolize_keys
72
+ end
73
+
63
74
  # Custom OpenAI client for Azure OpenAI Service.
64
75
  #
65
76
  # Azure uses different authentication headers (api-key instead of Authorization: Bearer)
@@ -103,7 +114,8 @@ module ActiveAgent
103
114
  # Azure uses api-key header instead of Authorization: Bearer.
104
115
  #
105
116
  # @return [Hash{String=>String}]
106
- def auth_headers
117
+ # Newer OpenAI SDK versions pass security options to this hook.
118
+ def auth_headers(**)
107
119
  return {} if @api_key.nil?
108
120
 
109
121
  { "api-key" => @api_key }
@@ -183,6 +183,7 @@ module ActiveAgent
183
183
  input_tokens: usage[:prompt_tokens] || 0,
184
184
  output_tokens: usage[:completion_tokens] || 0,
185
185
  cached_tokens: prompt_details[:cached_tokens],
186
+ cache_creation_tokens: prompt_details[:cache_write_tokens],
186
187
  reasoning_tokens: completion_details[:reasoning_tokens],
187
188
  audio_tokens: audio_sum > 0 ? audio_sum : nil,
188
189
  provider_details: usage.slice(:prompt_tokens_details, :completion_tokens_details).compact
@@ -142,6 +142,7 @@ module ActiveAgent
142
142
  when :message_delta
143
143
  delta = api_response_chunk[:delta]
144
144
  message_stack.last[:stop_reason] = delta[:stop_reason] if delta[:stop_reason]
145
+ self.stream_finish_reason = delta[:stop_reason] if delta[:stop_reason]
145
146
 
146
147
  when :message_stop
147
148
  # Stream complete
@@ -98,13 +98,54 @@ module ActiveAgent
98
98
  cleaned[key] = value
99
99
  end
100
100
 
101
+ map_to_openai_compatible_params(cleaned)
102
+ end
103
+
104
+ # Option keys with a direct equivalent on Ollama's /v1/chat/completions
105
+ OPENAI_COMPATIBLE_OPTIONS = {
106
+ num_predict: :max_tokens,
107
+ temperature: :temperature,
108
+ top_p: :top_p,
109
+ seed: :seed,
110
+ stop: :stop,
111
+ frequency_penalty: :frequency_penalty,
112
+ presence_penalty: :presence_penalty
113
+ }.freeze
114
+
115
+ # Copies format/options into their OpenAI-compatible fields
116
+ #
117
+ # Requests go to Ollama's OpenAI-compatible endpoint, which ignores the
118
+ # native top-level format/options fields. Explicit top-level params win.
119
+ #
120
+ # @param cleaned [Hash] cleaned request hash
121
+ # @return [Hash] request hash with OpenAI-compatible equivalents added
122
+ def map_to_openai_compatible_params(cleaned)
123
+ format = cleaned[:format]
124
+ if format && !cleaned.key?(:response_format)
125
+ if format.is_a?(Hash)
126
+ cleaned[:response_format] = { type: "json_schema", json_schema: { name: "response", schema: format } }
127
+ elsif format.to_s == "json"
128
+ cleaned[:response_format] = { type: "json_object" }
129
+ end
130
+ end
131
+
132
+ if cleaned[:options].is_a?(Hash)
133
+ cleaned[:options].symbolize_keys.each do |key, value|
134
+ target = OPENAI_COMPATIBLE_OPTIONS[key]
135
+ cleaned[target] = value if target && !value.nil? && !cleaned.key?(target)
136
+ end
137
+ end
138
+
101
139
  cleaned
102
140
  end
103
141
 
104
142
  # Groups consecutive same-role messages for Ollama
105
143
  #
106
144
  # Ollama requires consecutive messages with the same role to be merged
107
- # by concatenating their content.
145
+ # by concatenating their content. Tool results and assistant messages
146
+ # carrying tool calls are never merged: each tool result is tied to
147
+ # its own tool_call_id (parallel calls produce consecutive tool
148
+ # messages), and merging would drop ids and calls.
108
149
  #
109
150
  # @param messages [Array<Hash>] array of message hashes
110
151
  # @return [Array<Hash>] grouped messages
@@ -113,7 +154,8 @@ module ActiveAgent
113
154
 
114
155
  grouped = []
115
156
  messages.each do |message|
116
- if grouped.empty? || grouped.last[:role] != message[:role]
157
+ if grouped.empty? || grouped.last[:role] != message[:role] ||
158
+ tool_message?(grouped.last) || tool_message?(message)
117
159
  grouped << message.deep_dup
118
160
  else
119
161
  # Concatenate content for same-role messages
@@ -133,6 +175,12 @@ module ActiveAgent
133
175
 
134
176
  grouped
135
177
  end
178
+
179
+ # @param message [Hash]
180
+ # @return [Boolean] true for tool results and assistant tool calls
181
+ def tool_message?(message)
182
+ message[:role].to_s == "tool" || message[:tool_calls].present? || message.key?(:tool_call_id)
183
+ end
136
184
  end
137
185
  end
138
186
  end
@@ -30,7 +30,7 @@ module ActiveAgent
30
30
  class Options < ActiveAgent::Providers::OpenAI::Options
31
31
  # @!attribute base_url
32
32
  # @return [String] API endpoint (default: "https://openrouter.ai/api/v1")
33
- attribute :base_url, :string, as: "https://openrouter.ai/api/v1"
33
+ attribute :base_url, :string, fallback: "https://openrouter.ai/api/v1"
34
34
 
35
35
  # @!attribute app_name
36
36
  # @return [String] application name for X-Title header (default: "ActiveAgent" or Rails app name)
@@ -150,7 +150,7 @@ module ActiveAgent
150
150
 
151
151
  # Gets tool_choice bypassing gem validation
152
152
  #
153
- # OpenRouter supports "any" which isn't valid in OpenAI gem types.
153
+ # Read the raw value so a cleared tool choice can be read as nil.
154
154
  #
155
155
  # @return [String, Hash, nil]
156
156
  def tool_choice
@@ -159,8 +159,7 @@ module ActiveAgent
159
159
 
160
160
  # Sets tool_choice bypassing gem validation
161
161
  #
162
- # OpenRouter supports "any" which isn't valid in OpenAI gem types,
163
- # so we bypass the gem's type validation by setting @data directly.
162
+ # Write the raw value so the tool loop can clear it with nil.
164
163
  #
165
164
  # @param value [String, Hash, nil]
166
165
  # @return [void]
@@ -62,11 +62,6 @@ module ActiveAgent
62
62
  # Use OpenAI transforms for the base parameters
63
63
  openai_params = OpenAI::Chat::Transforms.normalize_params(params)
64
64
 
65
- # Override tool_choice normalization for OpenRouter's "any" vs "required" difference
66
- if openai_params[:tool_choice]
67
- openai_params[:tool_choice] = normalize_tool_choice(openai_params[:tool_choice])
68
- end
69
-
70
65
  [ openai_params, openrouter_params ]
71
66
  end
72
67
 
@@ -78,23 +73,6 @@ module ActiveAgent
78
73
  OpenAI::Chat::Transforms.normalize_tools(tools)
79
74
  end
80
75
 
81
- # Normalizes tool_choice for OpenRouter API differences
82
- #
83
- # OpenRouter uses "any" instead of OpenAI's "required" for forcing tool use.
84
- # Converts common format to OpenRouter-specific format:
85
- # - "required" (common) → "any" (OpenRouter)
86
- # - Everything else delegates to OpenAI transforms
87
- #
88
- # @param tool_choice [String, Hash, Symbol]
89
- # @return [String, Hash, Symbol]
90
- def normalize_tool_choice(tool_choice)
91
- # Convert "required" to OpenRouter's "any"
92
- return "any" if tool_choice.to_s == "required"
93
-
94
- # For everything else, use OpenAI transforms
95
- OpenAI::Chat::Transforms.normalize_tool_choice(tool_choice)
96
- end
97
-
98
76
  # Normalizes messages using OpenAI transforms
99
77
  #
100
78
  # @param messages [Array, String, Hash, nil]
@@ -31,8 +31,21 @@ module ActiveAgent
31
31
  namespace::RequestType.new
32
32
  end
33
33
 
34
+ # @return [ActiveModel::Type::Value]
35
+ def self.embed_request_type
36
+ OpenAI::Embedding::RequestType.new
37
+ end
38
+
34
39
  protected
35
40
 
41
+ # Executes an embedding request via OpenRouter's OpenAI-compatible API.
42
+ #
43
+ # @param parameters [Hash]
44
+ # @return [Hash] symbolized API response
45
+ def api_embed_execute(parameters)
46
+ client.embeddings.create(**parameters).as_json.deep_symbolize_keys
47
+ end
48
+
36
49
  # @see BaseProvider#prepare_prompt_request
37
50
  # @return [Request]
38
51
  def prepare_prompt_request
@@ -40,11 +53,11 @@ module ActiveAgent
40
53
  super
41
54
  end
42
55
 
43
- # Returns true if tool_choice == "any" (OpenRouter's equivalent of "required").
56
+ # Returns true if tool_choice == "required".
44
57
  #
45
58
  # @return [Boolean]
46
59
  def tool_choice_forces_required?
47
- request.tool_choice == "any"
60
+ request.tool_choice == "required"
48
61
  end
49
62
 
50
63
  # Merges streaming delta into the message with role cleanup.
@@ -62,6 +62,9 @@ module ActiveAgent
62
62
  schema = ruby_llm_schema(parameters[:response_format])
63
63
  kwargs[:schema] = schema if schema
64
64
 
65
+ tool_prefs = ruby_llm_tool_prefs(tools)
66
+ kwargs[:tool_prefs] = tool_prefs if tool_prefs
67
+
65
68
  # RubyLLM 2 renamed params: and exposes a provider-neutral token limit.
66
69
  max_tokens = parameters[:max_tokens] || options.max_tokens
67
70
  if max_tokens
@@ -106,10 +109,18 @@ module ActiveAgent
106
109
 
107
110
  input = parameters[:input]
108
111
  inputs = input.is_a?(Array) ? input : [ input ]
112
+ input_tokens = nil
109
113
 
110
114
  data = inputs.map.with_index do |text, index|
111
115
  embedding_model = ruby_llm_v2? ? @ruby_llm_model : model_id
112
116
  embedding = @ruby_llm_provider.embed(text, model: embedding_model, dimensions: parameters[:dimensions])
117
+ count = if ruby_llm_v2?
118
+ embedding.tokens&.input
119
+ else
120
+ # RubyLLM 1.x also uses zero when the provider omitted usage.
121
+ embedding.input_tokens if embedding.input_tokens&.positive?
122
+ end
123
+ input_tokens = (input_tokens || 0) + count if count
113
124
 
114
125
  {
115
126
  object: "embedding",
@@ -118,11 +129,13 @@ module ActiveAgent
118
129
  }
119
130
  end
120
131
 
121
- {
132
+ response = {
122
133
  object: :list,
123
134
  data: data,
124
135
  model: model_id
125
136
  }
137
+ response[:usage] = { input_tokens: input_tokens, total_tokens: input_tokens } if input_tokens
138
+ response
126
139
  end
127
140
 
128
141
  # Processes streaming chunks from RubyLLM.
@@ -185,13 +198,17 @@ module ActiveAgent
185
198
 
186
199
  # Counts arrive in separate chunks (Anthropic sends input at the start
187
200
  # and output at the end). They are cumulative for this turn, so merge
188
- # reported fields rather than adding each chunk's counts.
201
+ # reported fields rather than adding each chunk's counts. The total is
202
+ # stamped after the merge: a later chunk often carries only output, and
203
+ # its own total would drop the cache already counted.
189
204
  if (usage = ruby_llm_usage(chunk))
190
- (@stream_response[:usage] ||= {}).merge!(usage) do |field, previous, current|
205
+ merged = (@stream_response[:usage] ||= {})
206
+ merged.merge!(usage) do |field, previous, current|
191
207
  # Chat Completions synthesizes zero when cache writes are omitted.
192
208
  # That cannot erase writes already counted in this turn.
193
209
  field == :cache_creation_tokens && current == 0 ? previous : current
194
210
  end
211
+ merged[:total_tokens] = ruby_llm_total_tokens(merged)
195
212
  end
196
213
  if chunk.respond_to?(:finish_reason) && chunk.finish_reason
197
214
  @stream_response[:stop_reason] = ruby_llm_stop_reason(chunk, tool_calls: message[:tool_calls])
@@ -258,19 +275,21 @@ module ActiveAgent
258
275
 
259
276
  # Returns true if tool_choice forces any tool to be used.
260
277
  #
261
- # Handles both string ("required") and hash ({name: "..."}) formats.
278
+ # Accepts "required" or :required, as ruby_llm_tool_prefs does.
262
279
  #
263
280
  # @return [Boolean]
264
281
  def tool_choice_forces_required?
265
- request.tool_choice == "required"
282
+ request.tool_choice.to_s == "required"
266
283
  end
267
284
 
268
- # Returns [true, name] if tool_choice forces a specific tool.
285
+ # Returns [true, name] if tool_choice forces a specific tool. The name
286
+ # is a String, like the names extract_used_function_names returns,
287
+ # whether the choice gave it as a String or a Symbol.
269
288
  #
270
289
  # @return [Array<Boolean, String|nil>]
271
290
  def tool_choice_forces_specific?
272
291
  if request.tool_choice.is_a?(Hash)
273
- [ true, request.tool_choice[:name] ]
292
+ [ true, request.tool_choice[:name]&.to_s ]
274
293
  else
275
294
  [ false, nil ]
276
295
  end
@@ -305,6 +324,23 @@ module ActiveAgent
305
324
 
306
325
  private
307
326
 
327
+ # Maps the request's tool_choice to RubyLLM's tool_prefs. Without it
328
+ # the model is free to answer without calling a tool even when the
329
+ # caller requires one. Nil once ToolChoiceClearing has cleared it, so
330
+ # a follow-up turn is not forced into another call.
331
+ #
332
+ # @param tools [Hash, nil] RubyLLM tools sent with this request
333
+ # @return [Hash, nil]
334
+ def ruby_llm_tool_prefs(tools)
335
+ return nil if tools.blank?
336
+
337
+ choice = request.tool_choice
338
+ choice = (choice[:name] || choice["name"]) if choice.is_a?(Hash)
339
+ return nil if choice.blank?
340
+
341
+ { choice: choice.to_sym }
342
+ end
343
+
308
344
  def ruby_llm_v2?
309
345
  Gem.loaded_specs.fetch("ruby_llm").version.segments.first >= 2
310
346
  end
@@ -341,11 +377,12 @@ module ActiveAgent
341
377
  def build_ruby_llm_messages(parameters)
342
378
  messages = []
343
379
 
344
- # Add system instructions
345
- if parameters[:instructions].present?
380
+ # Add system instructions, one message each: RubyLLM takes only a
381
+ # String as content, and instructions may be an Array
382
+ Array(parameters[:instructions]).compact_blank.each do |instruction|
346
383
  messages << ::RubyLLM::Message.new(
347
384
  role: :system,
348
- content: parameters[:instructions]
385
+ content: instruction
349
386
  )
350
387
  end
351
388
 
@@ -381,6 +418,7 @@ module ActiveAgent
381
418
  when String
382
419
  content
383
420
  when Array
421
+ refuse_media_blocks!(content)
384
422
  content.select { |block| block.is_a?(Hash) && block[:type] == "text" }
385
423
  .map { |block| block[:text] }
386
424
  .join("\n")
@@ -389,6 +427,26 @@ module ActiveAgent
389
427
  end
390
428
  end
391
429
 
430
+ # Content block types that carry media rather than text, in the shapes
431
+ # the OpenAI (Chat and Responses) and Anthropic transforms write.
432
+ MEDIA_BLOCK_TYPES = %w[image image_url input_image audio input_audio file input_file document video].freeze
433
+
434
+ # This provider sends RubyLLM text only, so an image, audio clip or
435
+ # file would be dropped while the model answered as if it had seen
436
+ # it. Such a request is refused before any provider call. Other
437
+ # blocks that are not text (an earlier turn's reasoning) are still
438
+ # left out.
439
+ def refuse_media_blocks!(content)
440
+ types = content.filter_map { |block| block[:type].to_s if block.is_a?(Hash) && MEDIA_BLOCK_TYPES.include?(block[:type].to_s) }.uniq
441
+ return if types.empty?
442
+
443
+ raise Errors::InvalidRequest.new(
444
+ "The RubyLLM provider sends text only; this message has #{types.join(', ')} content, which it would drop. " \
445
+ "Send it through a provider that accepts it, or as text.",
446
+ provider_tag: "RubyLLM"
447
+ )
448
+ end
449
+
392
450
  # Converts ActiveAgent tool_calls to RubyLLM's ToolCall format.
393
451
  #
394
452
  # @param tool_calls [Array<Hash>] ActiveAgent format tool calls
@@ -474,7 +532,7 @@ module ActiveAgent
474
532
  proxy = RubyLLM::ToolProxy.new(
475
533
  name: func[:name],
476
534
  description: func[:description] || "",
477
- parameters: func[:parameters] || {}
535
+ parameters: func[:parameters] || func[:input_schema] || {}
478
536
  )
479
537
  hash[proxy.name] = proxy
480
538
  end
@@ -517,7 +575,10 @@ module ActiveAgent
517
575
  end
518
576
 
519
577
  usage = ruby_llm_usage(response)
520
- hash[:usage] = usage if usage
578
+ if usage
579
+ usage[:total_tokens] = ruby_llm_total_tokens(usage)
580
+ hash[:usage] = usage
581
+ end
521
582
 
522
583
  hash[:model] = model_id if model_id
523
584
 
@@ -592,7 +653,8 @@ module ActiveAgent
592
653
  # none: the message has no Tokens then in ruby_llm 1.x. RubyLLM counts
593
654
  # cached tokens apart from the input, so input_tokens leaves them out.
594
655
  # A count the provider left out is left out here too, and Usage reads it
595
- # as zero.
656
+ # as zero. Total is not set here: a stream merges these hashes field by
657
+ # field and stamps the total once the merge is done.
596
658
  #
597
659
  # @param response [RubyLLM::Message]
598
660
  # @return [Hash, nil] Common::Usage attributes
@@ -619,6 +681,18 @@ module ActiveAgent
619
681
  }.compact
620
682
  end
621
683
  end
684
+
685
+ # Every token the response processed. ruby_llm's input excludes cache
686
+ # reads and writes: OpenAI and Gemini subtract them from the prompt
687
+ # count, and Anthropic already reports them apart from input_tokens.
688
+ # Output already includes thinking when that is billed as output, so
689
+ # reasoning_tokens is not added again.
690
+ #
691
+ # @param usage [Hash] fields from {#ruby_llm_usage}, after a stream merge
692
+ # @return [Integer]
693
+ def ruby_llm_total_tokens(usage)
694
+ %i[input_tokens output_tokens cached_tokens cache_creation_tokens].sum { |key| usage[key] || 0 }
695
+ end
622
696
  end
623
697
  end
624
698
  end
@@ -73,6 +73,11 @@ module ActiveAgent
73
73
  # question nobody asked.
74
74
  RANGE_FILTERABLE_TYPES = %i[date datetime time integer float decimal].freeze
75
75
 
76
+ # The range-filterable types whose bound must be a number, and the
77
+ # strings accepted as one ("42", "-3.5").
78
+ NUMERIC_TYPES = %i[integer float decimal].freeze
79
+ NUMERIC_BOUND = /\A-?\d+(?:\.\d+)?\z/
80
+
76
81
  # The comparison operators a range filter may use, mapped to the Arel
77
82
  # predicate that builds them. Names are the ones models reach for
78
83
  # unprompted (`before`/`after` for dates, `lt`/`gte` for numbers), so a
@@ -83,6 +88,13 @@ module ActiveAgent
83
88
  "on_or_before" => :lteq, "on_or_after" => :gteq
84
89
  }.freeze
85
90
 
91
+ # Asks whether a column holds a value at all: `{ "present" => false }` is
92
+ # IS NULL, `{ "present" => true }` IS NOT NULL. A nil filter value cannot
93
+ # ask it, because nil means "no filter" (models send null for the
94
+ # optional parameters they leave out), so without this "tickets with no
95
+ # assignee" or "requests not yet approved" has no filter that says so.
96
+ PRESENCE_OPERATOR = "present"
97
+
86
98
  # Column names that look like they hold a credential. The schema tools
87
99
  # generator never suggests one, and the dashboard never lets one be
88
100
  # chosen: reading one back would hand a model a credential, and
@@ -329,7 +341,8 @@ module ActiveAgent
329
341
  #
330
342
  # A filter value is normally matched for equality. A Hash value instead
331
343
  # declares a range — `{ "before" => "2026-01-01" }`, `{ "gte" => 10 }` —
332
- # and may carry two bounds at once to express a window.
344
+ # and may carry two bounds at once to express a window, or asks whether
345
+ # the column is set at all (`{ "present" => false }`).
333
346
  #
334
347
  # @api private
335
348
  # @raise [UnpermittedAttribute] if any key is not declared filterable,
@@ -380,23 +393,83 @@ module ActiveAgent
380
393
  # Rails silently turns `where(col: { "before" => x })` into `col = NULL`,
381
394
  # which matches nothing and reports zero rather than failing — the worst
382
395
  # outcome for an agent, which reads it as a truthful empty answer. So an
383
- # unknown operator is rejected loudly here instead.
396
+ # unknown operator is rejected loudly here instead, and so is anything
397
+ # else that would answer without filtering as asked: an empty object
398
+ # (no condition at all), a comparison on a column not offered the range
399
+ # form, and a bound the column's type cannot read.
384
400
  #
385
401
  # @api private
386
- # @raise [UnpermittedAttribute] on an unknown operator
402
+ # @raise [UnpermittedAttribute] on an empty range, an unknown operator,
403
+ # a column that is not range-filterable, or an unreadable bound
387
404
  def range_predicates!(column, value)
405
+ if value.empty?
406
+ raise UnpermittedAttribute,
407
+ "The range object for `#{column}` names no comparison. " \
408
+ "Use one of: #{[ *RANGE_OPERATORS.keys, PRESENCE_OPERATOR ].join(", ")}"
409
+ end
410
+
388
411
  arel = @model.arel_table[column]
389
412
  type = @model.type_for_attribute(column)
390
413
 
391
414
  value.map do |operator, operand|
415
+ next presence_predicate!(column, arel, operand) if operator.to_s == PRESENCE_OPERATOR
416
+
392
417
  predicate = RANGE_OPERATORS[operator.to_s]
393
418
  unless predicate
394
419
  raise UnpermittedAttribute,
395
420
  "`#{operator}` is not a valid comparison for `#{column}`. " \
396
- "Allowed comparisons: #{RANGE_OPERATORS.keys.join(", ")}"
421
+ "Allowed comparisons: #{[ *RANGE_OPERATORS.keys, PRESENCE_OPERATOR ].join(", ")}"
397
422
  end
398
423
 
399
- arel.public_send(predicate, type.cast(operand))
424
+ unless range_filterable?(column)
425
+ raise UnpermittedAttribute,
426
+ "`#{column}` cannot be compared as a range. " \
427
+ "Match it by an exact value, or ask {\"#{PRESENCE_OPERATOR}\": true|false}"
428
+ end
429
+
430
+ arel.public_send(predicate, range_bound!(column, type, operand))
431
+ end
432
+ end
433
+
434
+ # Casts a range bound to the column's type, refusing one it cannot read.
435
+ #
436
+ # ActiveModel casts what it cannot read to nil for a date or time
437
+ # (`published_at < NULL`, which matches nothing) and to 0 for a number
438
+ # ("thirty".to_i), so either would answer a question the model did
439
+ # not ask. A number column therefore takes only a number or a numeric
440
+ # string.
441
+ #
442
+ # @api private
443
+ # @raise [UnpermittedAttribute] on a bound the column's type cannot read
444
+ def range_bound!(column, type, operand)
445
+ bound = type.cast(operand)
446
+ readable = NUMERIC_TYPES.include?(type.type) ? numeric_bound?(operand) : !bound.nil?
447
+ return bound if readable
448
+
449
+ raise UnpermittedAttribute,
450
+ "#{operand.inspect} is not a valid `#{column}` to compare against"
451
+ end
452
+
453
+ # @api private
454
+ def numeric_bound?(operand)
455
+ operand.is_a?(Numeric) || (operand.is_a?(String) && operand.match?(NUMERIC_BOUND))
456
+ end
457
+
458
+ # Builds IS NULL / IS NOT NULL for `{ "present" => ... }`.
459
+ #
460
+ # Only true and false (or their strings) are accepted: anything else
461
+ # would have to be guessed into one of the two, and a wrong guess
462
+ # answers the opposite question.
463
+ #
464
+ # @api private
465
+ # @raise [UnpermittedAttribute] on any other operand
466
+ def presence_predicate!(column, arel, operand)
467
+ case operand.to_s
468
+ when "true" then arel.not_eq(nil)
469
+ when "false" then arel.eq(nil)
470
+ else
471
+ raise UnpermittedAttribute,
472
+ "`#{PRESENCE_OPERATOR}` for `#{column}` takes true or false, not #{operand.inspect}"
400
473
  end
401
474
  end
402
475
 
@@ -415,9 +488,12 @@ module ActiveAgent
415
488
  return if values.blank?
416
489
 
417
490
  if value.is_a?(Hash)
491
+ # Whether it is set at all is a question an enum can answer.
492
+ return if value.keys.map(&:to_s) == [ PRESENCE_OPERATOR ]
493
+
418
494
  raise UnpermittedAttribute,
419
495
  "`#{column}` is an enum and cannot be compared as a range. " \
420
- "Allowed values: #{values.keys.join(", ")}"
496
+ "Allowed values: #{values.keys.join(", ")}, or {\"#{PRESENCE_OPERATOR}\": true|false}"
421
497
  end
422
498
 
423
499
  # An Array is an IN filter, which `where` silently narrows to its
@@ -550,20 +626,28 @@ module ActiveAgent
550
626
  # only `{type: "string", format: "date"}` has no way to know it may ask
551
627
  # for `before`, and answers date questions with an equality match or no
552
628
  # filter at all.
629
+ #
630
+ # A nullable column's range object also takes `present`, so "has no
631
+ # due date" is asked in the same shape as "due before Friday". It is
632
+ # offered only here, on the columns that already carry an object form,
633
+ # rather than wrapping every nullable string and enum in one; a call
634
+ # may still send it for any filterable column.
553
635
  def with_range_form(column, scalar)
554
636
  operand = scalar.slice(:type, :format)
555
- description = scalar[:description]
637
+ nullable = @model.columns_hash[column.to_s]&.null
638
+ properties = RANGE_OPERATORS.keys.index_with { operand.dup }
639
+ properties[PRESENCE_OPERATOR] = { type: "boolean" } if nullable
640
+
641
+ description = [ scalar[:description], "Accepts an exact value, or a range object such as " \
642
+ "{\"before\": ...} / {\"gte\": ...} (#{RANGE_OPERATORS.keys.join(", ")})." ]
643
+ description << "{\"#{PRESENCE_OPERATOR}\": false} matches records where it is empty (null), " \
644
+ "{\"#{PRESENCE_OPERATOR}\": true} where it is set." if nullable
556
645
 
557
646
  {
558
- description: [ description, "Accepts an exact value, or a range object such as " \
559
- "{\"before\": ...} / {\"gte\": ...} (#{RANGE_OPERATORS.keys.join(", ")})." ].compact.join(" "),
647
+ description: description.compact.join(" "),
560
648
  anyOf: [
561
649
  scalar.except(:description),
562
- {
563
- type: "object",
564
- properties: RANGE_OPERATORS.keys.index_with { operand.dup },
565
- additionalProperties: false
566
- }
650
+ { type: "object", properties: properties, additionalProperties: false }
567
651
  ]
568
652
  }
569
653
  end
@@ -1,3 +1,3 @@
1
1
  module ActiveAgent
2
- VERSION = "1.9.8"
2
+ VERSION = "1.9.10"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: activeagent
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.9.8
4
+ version: 1.9.10
5
5
  platform: ruby
6
6
  authors:
7
7
  - Justin Bowen
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-12 00:00:00.000000000 Z
11
+ date: 2026-12-04 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: actionpack
@@ -136,14 +136,14 @@ dependencies:
136
136
  requirements:
137
137
  - - "~>"
138
138
  - !ruby/object:Gem::Version
139
- version: '0.1'
139
+ version: '0.4'
140
140
  type: :runtime
141
141
  prerelease: false
142
142
  version_requirements: !ruby/object:Gem::Requirement
143
143
  requirements:
144
144
  - - "~>"
145
145
  - !ruby/object:Gem::Version
146
- version: '0.1'
146
+ version: '0.4'
147
147
  - !ruby/object:Gem::Dependency
148
148
  name: jbuilder
149
149
  requirement: !ruby/object:Gem::Requirement
@@ -210,16 +210,22 @@ dependencies:
210
210
  name: openai
211
211
  requirement: !ruby/object:Gem::Requirement
212
212
  requirements:
213
- - - "~>"
213
+ - - ">="
214
214
  - !ruby/object:Gem::Version
215
215
  version: '0.34'
216
+ - - "<"
217
+ - !ruby/object:Gem::Version
218
+ version: '2'
216
219
  type: :development
217
220
  prerelease: false
218
221
  version_requirements: !ruby/object:Gem::Requirement
219
222
  requirements:
220
- - - "~>"
223
+ - - ">="
221
224
  - !ruby/object:Gem::Version
222
225
  version: '0.34'
226
+ - - "<"
227
+ - !ruby/object:Gem::Version
228
+ version: '2'
223
229
  - !ruby/object:Gem::Dependency
224
230
  name: ruby_llm
225
231
  requirement: !ruby/object:Gem::Requirement