rails_ai_admin 0.4.1 → 0.5.0

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.
Files changed (84) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +64 -0
  3. data/README.md +4 -9
  4. data/SECURITY.md +1 -1
  5. data/app/assets/builds/rails_ai_admin.js +5 -5
  6. data/app/controllers/rails_ai_admin/application_controller.rb +19 -6
  7. data/app/controllers/rails_ai_admin/assistant_controller.rb +20 -7
  8. data/app/controllers/rails_ai_admin/audit_controller.rb +5 -1
  9. data/app/controllers/rails_ai_admin/bulk_changes_controller.rb +26 -6
  10. data/app/controllers/rails_ai_admin/dashboard_controller.rb +3 -2
  11. data/app/controllers/rails_ai_admin/deleted_records_controller.rb +12 -4
  12. data/app/controllers/rails_ai_admin/files_controller.rb +16 -4
  13. data/app/controllers/rails_ai_admin/mcp_controller.rb +30 -4
  14. data/app/controllers/rails_ai_admin/mcp_tokens_controller.rb +4 -2
  15. data/app/controllers/rails_ai_admin/operations_controller.rb +5 -2
  16. data/app/controllers/rails_ai_admin/resources_controller.rb +44 -5
  17. data/app/controllers/rails_ai_admin/selections_controller.rb +41 -5
  18. data/app/helpers/rails_ai_admin/assistant_helper.rb +3 -1
  19. data/app/helpers/rails_ai_admin/fields_helper.rb +36 -7
  20. data/app/helpers/rails_ai_admin/history_helper.rb +1 -1
  21. data/app/views/layouts/rails_ai_admin/application.html.erb +1 -0
  22. data/app/views/layouts/rails_ai_admin/frame.html.erb +1 -1
  23. data/app/views/layouts/rails_ai_admin/status.html.erb +2 -2
  24. data/app/views/rails_ai_admin/assistant/_transcript.html.erb +5 -1
  25. data/app/views/rails_ai_admin/audit/index.html.erb +1 -1
  26. data/app/views/rails_ai_admin/deleted_records/index.html.erb +3 -2
  27. data/app/views/rails_ai_admin/fields/_input.html.erb +2 -1
  28. data/app/views/rails_ai_admin/selections/confirm_destroy.html.erb +1 -0
  29. data/config/locales/en.yml +2 -0
  30. data/db/assistant_migrate/20261103000001_create_rails_ai_admin_assistant.rb +1 -0
  31. data/db/migrate/20261122000001_add_missing_indexes_to_rails_ai_admin_tables.rb +12 -0
  32. data/lib/generators/rails_ai_admin/assistant/assistant_generator.rb +4 -1
  33. data/lib/generators/rails_ai_admin/assistant/templates/admin_assistant.rb +6 -0
  34. data/lib/generators/rails_ai_admin/assistant/templates/assistant_eval.yml +25 -0
  35. data/lib/generators/rails_ai_admin/install/templates/admin_context_devise.rb.tt +2 -1
  36. data/lib/generators/rails_ai_admin/install/templates/admin_context_rails.rb.tt +5 -2
  37. data/lib/rails_ai_admin/assistant/budget.rb +4 -2
  38. data/lib/rails_ai_admin/assistant/coordinator.rb +18 -4
  39. data/lib/rails_ai_admin/assistant/evaluation.rb +124 -0
  40. data/lib/rails_ai_admin/assistant/records.rb +2 -1
  41. data/lib/rails_ai_admin/assistant/retention.rb +12 -1
  42. data/lib/rails_ai_admin/assistant/runtime.rb +49 -1
  43. data/lib/rails_ai_admin/assistant/tools.rb +58 -18
  44. data/lib/rails_ai_admin/assistant.rb +1 -0
  45. data/lib/rails_ai_admin/authorization/access.rb +34 -23
  46. data/lib/rails_ai_admin/authorization/pundit_adapter.rb +6 -3
  47. data/lib/rails_ai_admin/collections/dispatcher.rb +3 -3
  48. data/lib/rails_ai_admin/collections/queries.rb +1 -1
  49. data/lib/rails_ai_admin/configuration.rb +39 -8
  50. data/lib/rails_ai_admin/doctor.rb +44 -9
  51. data/lib/rails_ai_admin/field.rb +37 -22
  52. data/lib/rails_ai_admin/fields/association.rb +27 -10
  53. data/lib/rails_ai_admin/fields/type.rb +1 -1
  54. data/lib/rails_ai_admin/forms/plan.rb +4 -2
  55. data/lib/rails_ai_admin/input_schema.rb +4 -4
  56. data/lib/rails_ai_admin/integrations/propose_operation.rb +18 -4
  57. data/lib/rails_ai_admin/integrations/tool_views.rb +29 -3
  58. data/lib/rails_ai_admin/mcp.rb +23 -13
  59. data/lib/rails_ai_admin/navigation/list_state.rb +3 -3
  60. data/lib/rails_ai_admin/navigation/saved_views.rb +6 -5
  61. data/lib/rails_ai_admin/operations/restore.rb +25 -4
  62. data/lib/rails_ai_admin/operations/runner.rb +51 -15
  63. data/lib/rails_ai_admin/outbox/dispatcher.rb +6 -2
  64. data/lib/rails_ai_admin/presentation/association_panel.rb +6 -6
  65. data/lib/rails_ai_admin/presentation/audit_log.rb +8 -3
  66. data/lib/rails_ai_admin/presentation/csv_export.rb +21 -8
  67. data/lib/rails_ai_admin/presentation/csv_import.rb +9 -1
  68. data/lib/rails_ai_admin/presentation/dashboard.rb +5 -2
  69. data/lib/rails_ai_admin/presentation/history.rb +1 -1
  70. data/lib/rails_ai_admin/prune.rb +16 -5
  71. data/lib/rails_ai_admin/queries/list.rb +138 -38
  72. data/lib/rails_ai_admin/record_version.rb +1 -1
  73. data/lib/rails_ai_admin/registry.rb +5 -0
  74. data/lib/rails_ai_admin/request_log_filter.rb +4 -2
  75. data/lib/rails_ai_admin/resource.rb +4 -0
  76. data/lib/rails_ai_admin/schema_suggestions.rb +13 -5
  77. data/lib/rails_ai_admin/templates/catalog.rb +4 -2
  78. data/lib/rails_ai_admin/templates/inspector.rb +6 -2
  79. data/lib/rails_ai_admin/templates/safe_paths.rb +2 -1
  80. data/lib/rails_ai_admin/version.rb +1 -1
  81. data/lib/rails_ai_admin/work.rb +1 -1
  82. data/lib/rails_ai_admin.rb +10 -6
  83. data/lib/tasks/rails_ai_admin.rake +20 -0
  84. metadata +25 -2
@@ -59,6 +59,8 @@ module RailsAiAdmin
59
59
  AGGREGATE_FUNCTIONS = %i[sum average minimum maximum].freeze
60
60
  # Categories an aggregate can be grouped by, each a bounded set of values.
61
61
  GROUP_TYPES = %i[boolean enum select belongs_to].freeze
62
+ # Fields aggregates can group into calendar periods.
63
+ PERIOD_TYPES = %i[date datetime].freeze
62
64
  # Text that partial matching makes sense for; ids stay exact.
63
65
  CONTAINS_TYPES = %i[text textarea email url].freeze
64
66
  # Fixed choice lists, where "any of" is a set of checkboxes.
@@ -176,10 +178,10 @@ module RailsAiAdmin
176
178
  when :json then format_json(value)
177
179
  when :password then "—"
178
180
  when :rich_text then plain_text(value.to_s)
179
- when :references then Array(value).map { |key| "##{key}" }.join(", ")
181
+ when :references then Array(value).map { |key| "##{key}" }.join(", ").truncate_bytes(16_000)
180
182
  when :file then value.respond_to?(:filename) ? "#{value.filename} (#{ActiveSupport::NumberHelper.number_to_human_size(value.byte_size)})" : value.to_s
181
183
  when :files then I18n.t(:files, scope: %i[rails_ai_admin fields], count: Array(value).size, default: "#{Array(value).size} files")
182
- else value.to_s
184
+ else value.to_s.scrub("").truncate_bytes(16_000)
183
185
  end
184
186
  end
185
187
 
@@ -210,7 +212,7 @@ module RailsAiAdmin
210
212
  text = JSON.pretty_generate(value)
211
213
  text.bytesize > 16_000 ? "#{text.byteslice(0, 16_000).scrub("")}…" : text
212
214
  rescue JSON::ParserError, JSON::GeneratorError
213
- value.to_s.truncate(16_000)
215
+ value.to_s.scrub("").truncate_bytes(16_000)
214
216
  end
215
217
 
216
218
  # Decimal text padded to the declared or column scale ("10.50", not
@@ -232,14 +234,14 @@ module RailsAiAdmin
232
234
  # Coerces form or JSON input values, preserving false, zero and null. Input
233
235
  # is strict: blank text, control characters, out-of-scale decimals and
234
236
  # impossible calendar dates are rejected with a field message.
235
- def coerce(value, time_zone: "UTC") = coerce_value(value, time_zone, strict: true)
237
+ def coerce(value, time_zone: "UTC", replay: false) = coerce_value(value, time_zone, strict: true, replay: replay)
236
238
 
237
239
  # Internal: types a value produced by host code (a computation or a
238
240
  # preflight preview). It checks the scalar type only, so a handler result is
239
241
  # never rejected by the input-only rules above.
240
242
  def coerce_output(value, time_zone: "UTC") = coerce_value(value, time_zone, strict: false)
241
243
 
242
- def coerce_scalar(value, time_zone: "UTC", strict: true)
244
+ def coerce_scalar(value, time_zone: "UTC", strict: true, replay: false)
243
245
  if blank_input?(value, strict)
244
246
  # Clearing a password would remove the sign-in secret; leave it out instead.
245
247
  raise ArgumentError, message(:blank, "cannot be blank") if scalar_type == :password
@@ -266,11 +268,11 @@ module RailsAiAdmin
266
268
  scalar_type == :password ? Secret.new(value) : String.new(value)
267
269
  when :time
268
270
  value = value.strftime("%H:%M:%S") if value.respond_to?(:strftime) && !value.is_a?(String)
269
- parts = value.is_a?(String) && value.match(TIME_OF_DAY)
271
+ parts = value.is_a?(String) && value.valid_encoding? && value.match(TIME_OF_DAY)
270
272
  raise ArgumentError, message(:not_time, "must be a time of day (HH:MM)") unless parts
271
273
  "#{parts[1]}:#{parts[2]}:#{parts[3] || '00'}"
272
- when :file then coerce_file(value)
273
- when :files then coerce_files(value)
274
+ when :file then coerce_file(value, replay: replay)
275
+ when :files then coerce_files(value, replay: replay)
274
276
  when :references
275
277
  raise ArgumentError, message(:not_list, "must be a list of records") unless value.is_a?(Array) && value.size <= MAX_REFERENCES + 1
276
278
  keys = value.map { |item| item.is_a?(Integer) && item.positive? ? item.to_s : item }.reject { |item| item == "" }
@@ -291,15 +293,17 @@ module RailsAiAdmin
291
293
  raise ArgumentError, message(:invalid, "is invalid") unless value.valid_encoding?
292
294
  String.new(value)
293
295
  when :integer
294
- raise ArgumentError, message(:not_integer, "must be an integer") unless value.is_a?(Integer) || (value.is_a?(String) && value.match?(/\A[+-]?\d+\z/))
296
+ raise ArgumentError, message(:not_integer, "must be an integer") unless value.is_a?(Integer) || (value.is_a?(String) && value.valid_encoding? && value.match?(/\A[+-]?\d+\z/))
295
297
  raise ArgumentError, message(:out_of_range, "is out of range") if value.is_a?(String) && value.length > 100
296
298
  number = value.is_a?(String) ? Integer(value, 10) : value
297
299
  raise ArgumentError, message(:out_of_range, "is out of range") unless (-(2**63)..(2**63 - 1)).cover?(number)
298
300
  number
299
301
  when :decimal
300
- raise ArgumentError, message(:not_decimal, "must be a decimal") unless value.is_a?(Integer) || value.is_a?(BigDecimal) || (value.is_a?(String) && value.match?(/\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)\z/))
302
+ raise ArgumentError, message(:not_decimal, "must be a decimal") unless value.is_a?(Integer) || value.is_a?(BigDecimal) || (value.is_a?(String) && value.valid_encoding? && value.match?(/\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)\z/))
301
303
  raise ArgumentError, message(:out_of_range, "is out of range") if value.is_a?(String) && value.length > MAX_NUMBER_TEXT
302
- number = BigDecimal(value.to_s)
304
+ raise ArgumentError, message(:out_of_range, "is out of range") if value.is_a?(Integer) && value.abs >= 10**MAX_NUMBER_TEXT
305
+ raise ArgumentError, message(:out_of_range, "is out of range") if value.is_a?(BigDecimal) && value.finite? && value.exponent.abs > MAX_NUMBER_TEXT
306
+ number = value.is_a?(BigDecimal) ? value : BigDecimal(value.to_s)
303
307
  raise ArgumentError, message(:not_finite, "must be finite") unless number.finite?
304
308
  check_decimal_limits!(number) if strict
305
309
  number
@@ -309,11 +313,11 @@ module RailsAiAdmin
309
313
  raise ArgumentError, message(:not_boolean, "must be a boolean")
310
314
  when :date
311
315
  value = value.iso8601 if value.is_a?(Date) && !value.is_a?(DateTime)
312
- raise ArgumentError, message(:not_date, "must be an ISO date") unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}\z/)
316
+ raise ArgumentError, message(:not_date, "must be an ISO date") unless value.is_a?(String) && value.valid_encoding? && value.match?(/\A\d{4}-\d{2}-\d{2}\z/)
313
317
  Date.iso8601(value)
314
318
  when :datetime
315
319
  value = value.to_time.getutc.iso8601(6) if value.is_a?(Time) || value.is_a?(ActiveSupport::TimeWithZone) || value.is_a?(DateTime)
316
- parts = value.is_a?(String) && value.match(DATETIME)
320
+ parts = value.is_a?(String) && value.valid_encoding? && value.match(DATETIME)
317
321
  raise ArgumentError, message(:not_timestamp, "must be an ISO timestamp") unless parts
318
322
  # Ruby and Active Support roll 2026-02-30 into March (DEP-013); an
319
323
  # impossible calendar day or clock time is rejected instead (RAA-010).
@@ -385,8 +389,8 @@ module RailsAiAdmin
385
389
 
386
390
  private
387
391
 
388
- def coerce_value(value, time_zone, strict:)
389
- typed = coerce_scalar(value, time_zone: time_zone, strict: strict)
392
+ def coerce_value(value, time_zone, strict:, replay: false)
393
+ typed = coerce_scalar(value, time_zone: time_zone, strict: strict, replay: replay)
390
394
  return typed unless @plugin && !typed.nil?
391
395
  normalized = invoke(:normalize, immutable_copy(typed), field: @descriptor, time_zone: time_zone)
392
396
  normalized = coerce_scalar(wire(normalized), time_zone: time_zone, strict: strict)
@@ -414,26 +418,28 @@ module RailsAiAdmin
414
418
  # blob. Its identified content type and size must fit the declaration.
415
419
  # A files change: new uploads to add and attachment ids to remove. A list
416
420
  # is never replaced as a whole, so concurrent additions are kept.
417
- def coerce_files(value)
421
+ def coerce_files(value, replay: false)
418
422
  value = value.to_h { |key, item| [ key.to_s, item ] } if value.is_a?(Hash)
419
423
  unless value.is_a?(Hash) && (value.keys - %w[add remove]).empty? && value.values.all? { |item| item.is_a?(Array) }
420
424
  raise ArgumentError, message(:invalid, "is invalid")
421
425
  end
422
- add = Array(value["add"]).map { |item| coerce_file(item) }
423
- remove = Array(value["remove"]).map { |item| item.is_a?(Integer) && item.positive? ? item.to_s : item }
424
- raise ArgumentError, message(:unavailable_choice, "is not an available choice") unless remove.all? { |item| item.is_a?(String) && item.match?(REFERENCE) }
425
- raise ArgumentError, message(:too_many_files, "can hold at most %{count} files", count: options[:max_files]) if add.size > options[:max_files] || remove.size > MAX_REFERENCES
426
+ raw_add = Array(value["add"])
427
+ raw_remove = Array(value["remove"])
428
+ raise ArgumentError, message(:too_many_files, "can hold at most %{count} files", count: options[:max_files]) if raw_add.size > options[:max_files] || raw_remove.size > MAX_REFERENCES
429
+ add = raw_add.map { |item| coerce_file(item, replay: replay) }
430
+ remove = raw_remove.map { |item| item.is_a?(Integer) && item.positive? ? item.to_s : item }
431
+ raise ArgumentError, message(:unavailable_choice, "is not an available choice") unless remove.all? { |item| item.is_a?(String) && item.valid_encoding? && item.match?(REFERENCE) }
426
432
  { "add" => add.uniq.freeze, "remove" => remove.uniq.sort.freeze }.freeze
427
433
  end
428
434
 
429
- def coerce_file(value)
435
+ def coerce_file(value, replay: false)
430
436
  if value.is_a?(Fields::RejectedUpload)
431
437
  raise ArgumentError, message(:file_too_large, "is larger than %{size}", size: ActiveSupport::NumberHelper.number_to_human_size(options[:max_size]))
432
438
  end
433
439
  raise ConfigurationError, "file fields need Active Storage" unless defined?(::ActiveStorage::Blob)
434
440
  raise ArgumentError, message(:invalid, "is invalid") unless value.is_a?(String) && value.valid_encoding? && value.length.between?(1, 1000)
435
441
  blob = ::ActiveStorage::Blob.find_signed(value)
436
- raise ArgumentError, message(:file_unavailable, "is not an available upload") unless blob && !blob.attachments.exists?
442
+ raise ArgumentError, message(:file_unavailable, "is not an available upload") unless blob && (replay || !blob.attachments.exists?)
437
443
  raise ArgumentError, message(:file_too_large, "is larger than %{size}", size: ActiveSupport::NumberHelper.number_to_human_size(options[:max_size])) if blob.byte_size > options[:max_size]
438
444
  raise ArgumentError, message(:file_type, "is not an accepted file type") unless accepts?(blob.content_type.to_s)
439
445
  String.new(value)
@@ -554,6 +560,9 @@ module RailsAiAdmin
554
560
  end
555
561
  end
556
562
 
563
+ SEARCHABLE_TYPES = %i[text textarea email url enum select belongs_to].freeze
564
+ SEARCHABLE_MODES = [ nil, false, true, :prefix, :contains, :exact ].freeze
565
+
557
566
  def validate_query_options!
558
567
  if UNQUERYABLE_TYPES.include?(scalar_type) && (options[:searchable] || options[:sortable] || options[:filterable])
559
568
  raise ConfigurationError, "#{scalar_type} fields cannot search, sort or filter"
@@ -561,6 +570,12 @@ module RailsAiAdmin
561
570
  if scalar_type == :time && (options[:searchable] || options[:filterable])
562
571
  raise ConfigurationError, "time fields can sort but cannot search or filter"
563
572
  end
573
+ unless SEARCHABLE_MODES.include?(options[:searchable])
574
+ raise ConfigurationError, "Field searchable must be false, true, :prefix, :contains or :exact"
575
+ end
576
+ if options[:searchable] && !SEARCHABLE_TYPES.include?(scalar_type)
577
+ raise ConfigurationError, "#{scalar_type} fields cannot be searchable"
578
+ end
564
579
  unless options[:aggregatable].nil? || [ true, false ].include?(options[:aggregatable])
565
580
  raise ConfigurationError, "Field aggregatable must be true or false"
566
581
  end
@@ -66,9 +66,10 @@ module RailsAiAdmin
66
66
 
67
67
  # resource: the declaring resource. Its own fields are checked against the
68
68
  # model reflection; operation input fields only need a registered target.
69
- def initialize(context, resource = nil)
69
+ # assistant: when true, target resources must also hold the assistant? grant.
70
+ def initialize(context, resource = nil, assistant: false)
70
71
  raise AccessDenied, "UNAUTHENTICATED" unless context.is_a?(Context)
71
- @context, @resource = context, resource
72
+ @context, @resource, @assistant = context, resource, assistant == true
72
73
  @accesses = {}
73
74
  @references = Hash.new { |hash, key| hash[key] = {} }
74
75
  end
@@ -81,6 +82,10 @@ module RailsAiAdmin
81
82
  return self if pending.empty?
82
83
  raise ConfigurationError, "Too many references to resolve at once" if pending.size > MAX_BATCH
83
84
  access = target_access(field)
85
+ if @assistant && !assistant_allowed?(access)
86
+ pending.each { |id| cache[id] = unavailable(field, id) }
87
+ return self
88
+ end
84
89
  model = access.resource.model_class
85
90
  keys = pending.select { |id| key_shape?(model, id) }
86
91
  found = keys.empty? ? {} : access.relation.where(model.primary_key => keys).to_a.index_by { |record| record.id.to_s }
@@ -108,7 +113,7 @@ module RailsAiAdmin
108
113
  model = access.resource.model_class
109
114
  table = model.arel_table
110
115
  title = access.fields(:sort).find { |candidate| candidate.name == access.resource.title }
111
- relation = access.relation.reorder(nil)
116
+ relation = Queries::List.unique_records(access.relation).reorder(nil)
112
117
  relation = relation.order(table[title.column].asc) if title
113
118
  records = relation.order(table[model.primary_key].asc).limit(MAX_CHOICES + 1).to_a
114
119
  cache = @references[cache_key(field)]
@@ -130,7 +135,9 @@ module RailsAiAdmin
130
135
  raise ConfigurationError, "Invalid picker limit" unless limit.is_a?(Integer) && limit.between?(1, SEARCH_LIMIT)
131
136
  access = Authorization::Access.new(context, target)
132
137
  access.authorize!(:index)
133
- term = term.strip if term.is_a?(String) && term.valid_encoding?
138
+ return [] if term.nil?
139
+ raise AccessDenied, "INVALID_QUERY" unless term.is_a?(String) && term.valid_encoding?
140
+ term = term.strip
134
141
  return [] if term.blank?
135
142
  model = target.model_class
136
143
  exact = access.canonical_id?(term) ? access.relation.where(model.primary_key => term).limit(1).to_a : []
@@ -144,7 +151,7 @@ module RailsAiAdmin
144
151
  end
145
152
  (exact + matches).uniq(&:id).first(limit).filter_map do |record|
146
153
  access.authorize!(:show, record)
147
- [ access.record_label(record).freeze, record.id.to_s.freeze ]
154
+ [ access.record_label(record, view: :index).freeze, record.id.to_s.freeze ]
148
155
  rescue AccessDenied
149
156
  nil
150
157
  end
@@ -162,16 +169,26 @@ module RailsAiAdmin
162
169
  end
163
170
  end
164
171
 
165
- # Integer keys are checked before the query so malformed text never reaches
166
- # an integer comparison; other key types rely on the column's own cast.
172
+ # Integer and UUID keys are checked before the query so malformed text never
173
+ # reaches a typed comparison on PostgreSQL.
167
174
  def key_shape?(model, id)
168
- return false unless id.match?(Field::REFERENCE)
169
- column = model.columns_hash[model.primary_key]
170
- column&.type == :integer ? id.match?(INTEGER_KEY) && Integer(id, 10) <= 2**63 - 1 : true
175
+ return false unless id.is_a?(String) && id.valid_encoding? && id.match?(Field::REFERENCE)
176
+ case model.type_for_attribute(model.primary_key).type
177
+ when :integer then id.match?(INTEGER_KEY) && Integer(id, 10) <= 2**63 - 1
178
+ when :uuid then id.match?(/\A[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}\z/)
179
+ else true
180
+ end
181
+ end
182
+
183
+ def assistant_allowed?(access)
184
+ access.authorize_assistant!
185
+ rescue AccessDenied
186
+ false
171
187
  end
172
188
 
173
189
  def build(field, access, record, id)
174
190
  if record
191
+ access.authorize_assistant! if @assistant
175
192
  access.authorize!(:show, record)
176
193
  return Reference.new(id.dup.freeze, access.record_label(record).freeze, access.resource.key, true)
177
194
  end
@@ -25,7 +25,7 @@ module RailsAiAdmin
25
25
  end
26
26
 
27
27
  def metadata
28
- unless scalar && Field::TYPES.include?(scalar) && scalar != :belongs_to && version.is_a?(String) && version.match?(/\A[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}\z/)
28
+ unless scalar && Field::TYPES.include?(scalar) && !Field::PLUGIN_EXCLUDED.include?(scalar) && version.is_a?(String) && version.match?(/\A[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}\z/)
29
29
  raise ConfigurationError, "Field type needs a built-in scalar and bounded version"
30
30
  end
31
31
  partials = %i[form_partial index_partial show_partial].to_h { |key| [ key, public_send(key) ] }
@@ -11,8 +11,9 @@ module RailsAiAdmin
11
11
  MAX_FIELDS = 128
12
12
  MAX_TABS = 8
13
13
  MAX_PANELS = 16
14
- MAX_VALUE_BYTES = 262_144
15
- MAX_BYTES = 1_048_576
14
+ # Accommodates Field::MAX_RICH_TEXT (1 MB) after JSON escaping.
15
+ MAX_VALUE_BYTES = 1_572_864
16
+ MAX_BYTES = 4_194_304
16
17
  attr_reader :tabs, :entries
17
18
 
18
19
  def initialize(fields:, values:, readonly_fields: [], readonly_values: {}, order: nil)
@@ -47,6 +48,7 @@ module RailsAiAdmin
47
48
  private
48
49
 
49
50
  def scalar(value, type: nil)
51
+ return nil if type == :password
50
52
  copy = case value
51
53
  when nil, true, false, Integer then value
52
54
  when String then String.new(value).encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
@@ -18,7 +18,7 @@ module RailsAiAdmin
18
18
  @partial = partial
19
19
  end
20
20
 
21
- def coerce(input, time_zone: "UTC")
21
+ def coerce(input, time_zone: "UTC", replay: false)
22
22
  return Coercion.new({}, { "base" => [ Field.error_message(:not_object, "must be an object") ] }) unless input.is_a?(Hash)
23
23
  values, errors = {}, {}
24
24
  input = input.stringify_keys
@@ -26,12 +26,12 @@ module RailsAiAdmin
26
26
  @fields.each do |name, field|
27
27
  # An empty password box means "keep the current password".
28
28
  input_value = input[name]
29
- if !input.key?(name) || field.scalar_type == :password && input_value.is_a?(String) && input_value.match?(Field::BLANK)
29
+ if !input.key?(name) || field.scalar_type == :password && input_value.is_a?(String) && input_value.valid_encoding? && input_value.match?(Field::BLANK)
30
30
  errors[name] = [ Field.error_message(:required, "is required") ] if !@partial && field.options[:required]
31
31
  next
32
32
  end
33
33
  begin
34
- values[name] = field.coerce(input[name], time_zone: time_zone)
34
+ values[name] = field.coerce(input[name], time_zone: time_zone, replay: replay)
35
35
  rescue ArgumentError => error
36
36
  errors[name] = [ error.message ]
37
37
  end
@@ -65,7 +65,7 @@ module RailsAiAdmin
65
65
  when Hash then value.stringify_keys.sort.to_h.transform_values { |entry| canonical(entry) }
66
66
  when Array then value.map { |entry| canonical(entry) }
67
67
  when BigDecimal then { "$decimal" => value.to_s("F") }
68
- when Time, ActiveSupport::TimeWithZone then { "$time" => value.utc.iso8601(6) }
68
+ when Time, ActiveSupport::TimeWithZone then { "$time" => value.to_time.getutc.iso8601(6) }
69
69
  when Date then { "$date" => value.iso8601 }
70
70
  when Fields::FileValue, Fields::RejectedUpload then value.to_h.transform_keys(&:to_s)
71
71
  when Field::Secret then { "$secret" => OpenSSL::HMAC.hexdigest("SHA256", secret_key, value) }
@@ -69,14 +69,21 @@ module RailsAiAdmin
69
69
  entry = @catalog.find { |item| item[:resource].key.to_s == resource.to_s && item[:definition].key.to_s == operation.to_s }
70
70
  raise AccessDenied unless entry && record.is_a?(String) && record.match?(RECORD_REF) && input.is_a?(Hash)
71
71
  resource, definition = entry[:resource], entry[:definition]
72
+ access = Authorization::Access.new(@context, resource)
73
+ access.authorize_assistant!
74
+ raise AccessDenied unless resource.action_enabled?(definition.key)
72
75
  intent_id = Digest::UUID.uuid_v5(NAMESPACE, [ @context.actor_ref, @context.tenant_ref, @conversation, tool_call.id ].join("\n"))
73
76
  # A replay of an already confirmed call reports it before re-checking the
74
77
  # command grant, which a completed change may legitimately withdraw.
75
78
  done = OperationRun.find_by(id: intent_id, actor_ref: @context.actor_ref, tenant_ref: @context.tenant_ref, status: "succeeded")
76
- if done && done.origin == "assistant" && done.resource_key == resource.key.to_s && done.operation == definition.key.to_s
79
+ if done
80
+ unless done.origin == "assistant" && done.resource_key == resource.key.to_s && done.operation == definition.key.to_s &&
81
+ done.target_id == record && done.security_version == @context.security_version &&
82
+ replay_input_matches?(done, definition, input)
83
+ raise AccessDenied, "IDEMPOTENCY_CONFLICT"
84
+ end
77
85
  return { status: "reviewed", message: "The user already confirmed this proposal. Do not propose it again." }
78
86
  end
79
- access = Authorization::Access.new(@context, resource)
80
87
  target = access.find!(record, action: definition.key)
81
88
  values = proposal_values(resource, definition, target, input, intent_id)
82
89
  return values if values.key?(:status)
@@ -93,22 +100,29 @@ module RailsAiAdmin
93
100
 
94
101
  private
95
102
 
96
- # Opted-in operations on resources the actor may currently list.
103
+ # Opted-in operations on resources the actor may currently expose to an assistant.
97
104
  def build_catalog
98
105
  RailsAiAdmin.registry.resources.flat_map do |resource|
99
106
  access = Authorization::Access.new(@context, resource)
100
107
  begin
101
- access.authorize!(:index)
108
+ access.authorize_assistant!
102
109
  rescue AccessDenied
103
110
  next []
104
111
  end
105
112
  resource.assistant_operations.filter_map do |key|
113
+ next unless resource.action_enabled?(key)
106
114
  definition = RailsAiAdmin.operation_registry.fetch(resource, key)
107
115
  { resource: resource, definition: definition } if definition.custom? && definition.scope == :member
108
116
  end
109
117
  end
110
118
  end
111
119
 
120
+ def replay_input_matches?(run, definition, input)
121
+ return false unless run.input_digest
122
+ result = InputSchema.new(definition.handler_class.input).coerce(input, time_zone: @context.time_zone)
123
+ result.valid? && InputSchema.digest(result.values) == run.input_digest
124
+ end
125
+
112
126
  # Typed values of a new or replayed intent for this exact tool call.
113
127
  def proposal_values(resource, definition, target, input, intent_id)
114
128
  existing = OperationRun.find_by(id: intent_id, actor_ref: @context.actor_ref, tenant_ref: @context.tenant_ref)
@@ -44,6 +44,19 @@ module RailsAiAdmin
44
44
  defined?(::RailsToolViews::Registry) ? true : false
45
45
  end
46
46
 
47
+ # Read-only check used by diagnostics so doctor never mutates the
48
+ # host-owned rails_tool_views registry.
49
+ def check_registration!
50
+ raise ConfigurationError, "rails_tool_views is not loaded" unless available?
51
+ component = begin
52
+ ::RailsToolViews.registry.fetch(KEY)
53
+ rescue ::RailsToolViews::Error => error
54
+ raise unless error.code == "UNKNOWN_COMPONENT"
55
+ return nil
56
+ end
57
+ verify_component!(component)
58
+ end
59
+
47
60
  # Re-registers after a host `reset_registry!`. The contract is constant,
48
61
  # so an existing registration must be exactly this one.
49
62
  def ensure_registered!
@@ -54,6 +67,10 @@ module RailsAiAdmin
54
67
  raise unless error.code == "UNKNOWN_COMPONENT"
55
68
  register
56
69
  end
70
+ verify_component!(component)
71
+ end
72
+
73
+ def verify_component!(component)
57
74
  unless component.policy.equal?(POLICY) && component.actions.fetch("confirm").handler.equal?(CONFIRM) &&
58
75
  component.actions["dismiss"]&.handler.equal?(DISMISS)
59
76
  raise ConfigurationError, "#{KEY} is registered by other code"
@@ -135,7 +152,7 @@ module RailsAiAdmin
135
152
  values.to_h do |name, value|
136
153
  wire = case value
137
154
  when BigDecimal then value.to_s("F")
138
- when Time, ActiveSupport::TimeWithZone then value.utc.iso8601(6)
155
+ when Time, ActiveSupport::TimeWithZone then value.to_time.getutc.iso8601(6)
139
156
  when Date then value.iso8601
140
157
  else value
141
158
  end
@@ -207,6 +224,9 @@ module RailsAiAdmin
207
224
  context = current_context
208
225
  review = review(context, request.props) if context && request.actor == context.actor_ref && request.tenant == context.tenant_ref
209
226
  raise ::RailsToolViews::Error.new("NOT_ALLOWED", status: 403) unless review
227
+ if request.respond_to?(:surface) && request.surface&.state.is_a?(Hash) && request.surface.state["outcome"].present?
228
+ raise ::RailsToolViews::Error.new("CONFLICT", status: 409, message: "This review was already decided.")
229
+ end
210
230
  run = review.run
211
231
  result = Operations::Runner.new.execute(context: context, intent_ref: run.id, input: JSON.parse(request.props.fetch("input")),
212
232
  human_confirmed: true, origin: :surface, binding: { resource_key: run.resource_key, operation: run.operation, target_id: run.target_id })
@@ -232,8 +252,14 @@ module RailsAiAdmin
232
252
  context = current_context
233
253
  review = review(context, request.props) if context && request.actor == context.actor_ref && request.tenant == context.tenant_ref
234
254
  raise ::RailsToolViews::Error.new("NOT_ALLOWED", status: 403) unless review
235
- expired = OperationRun.where(id: review.run.id, status: "proposed", approved_by_ref: nil)
236
- .update_all(expires_at: Time.current, updated_at: Time.current)
255
+ if request.respond_to?(:surface) && request.surface&.state.is_a?(Hash) && request.surface.state["outcome"].present?
256
+ raise ::RailsToolViews::Error.new("CONFLICT", status: 409, message: "This review was already decided.")
257
+ end
258
+ now = Time.current
259
+ expired = OperationRun.where(id: review.run.id, status: "proposed", approved_by_ref: nil,
260
+ security_version: context.security_version)
261
+ .where(OperationRun.arel_table[:expires_at].gt(now))
262
+ .update_all(expires_at: now - 1.second, updated_at: now)
237
263
  raise ::RailsToolViews::Error.new("CONFLICT", status: 409, message: "This review was already decided.") unless expired == 1
238
264
  continue_chat(context, request, review, "Nothing was changed.", decision: "dismissed")
239
265
  ::RailsToolViews::Transition.new(state: { "outcome" => "dismissed", "message" => "Dismissed. Nothing was changed." }, agent: false)
@@ -37,13 +37,16 @@ module RailsAiAdmin
37
37
 
38
38
  # Returns [record, token]; the token is never readable again.
39
39
  def self.issue!(context, name:, lifetime:)
40
- raise AccessDenied, "INVALID_QUERY" unless name.is_a?(String) && name.strip.length.between?(1, 80) && LIFETIMES.key?(lifetime.to_s)
41
- raise AccessDenied, "INVALID_QUERY" if for_owner(context).active.count >= MAX_ACTIVE
42
- token = "#{TOKEN_PREFIX}#{SecureRandom.urlsafe_base64(32)}"
43
- record = create!(id: SecureRandom.uuid, actor_ref: context.actor_ref, tenant_ref: context.tenant_ref,
44
- security_version: context.security_version, name: name.strip.squish, token_digest: digest(token),
45
- expires_at: Time.current + LIFETIMES.fetch(lifetime.to_s))
46
- [ record, token ]
40
+ raise AccessDenied, "INVALID_QUERY" unless name.is_a?(String) && name.valid_encoding? && name.strip.length.between?(1, 80) && LIFETIMES.key?(lifetime.to_s)
41
+ transaction(requires_new: true) do
42
+ # PostgreSQL refuses FOR UPDATE with COUNT, so lock and count the rows.
43
+ raise AccessDenied, "INVALID_QUERY" if for_owner(context).active.order(:id).lock.pluck(:id).size >= MAX_ACTIVE
44
+ token = "#{TOKEN_PREFIX}#{SecureRandom.urlsafe_base64(32)}"
45
+ record = create!(id: SecureRandom.uuid, actor_ref: context.actor_ref, tenant_ref: context.tenant_ref,
46
+ security_version: context.security_version, name: name.strip.squish, token_digest: digest(token),
47
+ expires_at: Time.current + LIFETIMES.fetch(lifetime.to_s))
48
+ [ record, token ]
49
+ end
47
50
  end
48
51
 
49
52
  def self.authenticate(token)
@@ -74,13 +77,19 @@ module RailsAiAdmin
74
77
  # Returns [status, body or nil].
75
78
  def handle(message)
76
79
  raise Error.new(-32600, "Invalid request") unless message.is_a?(Hash) && message["jsonrpc"] == "2.0" && message["method"].is_a?(String)
77
- id = message["id"]
78
80
  notification = !message.key?("id")
79
- result = dispatch(message["method"], message["params"].is_a?(Hash) ? message["params"] : {})
81
+ id = message["id"]
82
+ unless notification || id.nil? || id.is_a?(String) || id.is_a?(Integer) || (id.is_a?(Float) && id.finite?)
83
+ raise Error.new(-32600, "Invalid request id")
84
+ end
85
+ raw_params = message["params"]
86
+ raise Error.new(-32602, "Params must be an object") unless raw_params.nil? || raw_params.is_a?(Hash)
87
+ result = dispatch(message["method"], raw_params || {})
80
88
  return [ 202, nil ] if notification
81
89
  [ 200, { "jsonrpc" => "2.0", "id" => id, "result" => result } ]
82
90
  rescue Error => error
83
- [ 200, { "jsonrpc" => "2.0", "id" => message.is_a?(Hash) ? message["id"] : nil, "error" => { "code" => error.code, "message" => error.message } } ]
91
+ response_id = message.is_a?(Hash) && (message["id"].is_a?(String) || message["id"].is_a?(Integer)) ? message["id"] : nil
92
+ [ 200, { "jsonrpc" => "2.0", "id" => response_id, "error" => { "code" => error.code, "message" => error.message } } ]
84
93
  end
85
94
 
86
95
  private
@@ -116,9 +125,10 @@ module RailsAiAdmin
116
125
  def call(params)
117
126
  tool = tools.find { |candidate| candidate.name == params["name"] }
118
127
  raise Error.new(-32602, "Unknown tool") unless tool
119
- arguments = params["arguments"] || {}
120
- raise Error.new(-32602, "Arguments must be an object") unless arguments.is_a?(Hash)
121
- result = tool.execute(tool_call: ToolCall.new("mcp-#{SecureRandom.uuid}"), **arguments.transform_keys(&:to_sym))
128
+ arguments = params.key?("arguments") ? params["arguments"] : {}
129
+ arguments = {} if arguments.nil?
130
+ raise Error.new(-32602, "Arguments must be an object") unless arguments.is_a?(Hash) && !arguments.key?("tool_call")
131
+ result = tool.execute(**arguments.transform_keys(&:to_sym), tool_call: ToolCall.new("mcp-#{SecureRandom.uuid}"))
122
132
  result = result.merge("review_url" => @review_url.call(result["surface"])) if result.is_a?(Hash) && result["surface"].is_a?(String)
123
133
  if result.is_a?(Hash) && result["bulk_change"].is_a?(String)
124
134
  result = result.except("bulk_change").merge("review_url" => @bulk_review_url.call(result["selection"], result["bulk_change"]))
@@ -20,8 +20,8 @@ module RailsAiAdmin
20
20
  elsif value.is_a?(String) && value.bytesize <= MAX_HEADER_BYTES
21
21
  begin
22
22
  decoded = Base64.urlsafe_decode64(value).force_encoding(Encoding::UTF_8)
23
- decoded.bytesize <= MAX_JSON_BYTES && decoded.valid_encoding? ? JSON.parse(decoded) : INVALID
24
- rescue ArgumentError, JSON::ParserError
23
+ decoded.bytesize <= MAX_JSON_BYTES && decoded.valid_encoding? ? JSON.parse(decoded, max_nesting: 8) : INVALID
24
+ rescue ArgumentError, JSON::JSONError
25
25
  INVALID
26
26
  end
27
27
  else
@@ -157,7 +157,7 @@ module RailsAiAdmin
157
157
  return INVALID unless value.is_a?(Hash) && value.size <= Queries::List::MAX_FILTER_CONDITIONS
158
158
  parsed = {}
159
159
  value.each do |name, conditions|
160
- return INVALID unless (name.is_a?(String) || name.is_a?(Symbol)) && name.to_s.match?(/\A[a-z][a-z0-9_]{0,79}\z/) && conditions.is_a?(Hash)
160
+ return INVALID unless (name.is_a?(String) || name.is_a?(Symbol)) && name.to_s.valid_encoding? && name.to_s.match?(/\A[a-z][a-z0-9_]{0,79}\z/) && conditions.is_a?(Hash)
161
161
  conditions.each do |operator, condition|
162
162
  return INVALID unless (operator.is_a?(String) || operator.is_a?(Symbol)) && FILTER_OPERATORS.include?(operator.to_s)
163
163
  if operator.to_s == "in"
@@ -47,11 +47,12 @@ module RailsAiAdmin
47
47
  name = normalize_name(name)
48
48
  state = ListState.new(@access, state).state.except("page")
49
49
  SavedView.transaction(requires_new: true) do
50
- row = owned.lock.find_by(name: name)
50
+ existing = owned.order(:id).lock.to_a
51
+ row = existing.find { |candidate| candidate.name == name }
51
52
  if row
52
53
  row.update!(state: JSON.generate(state))
53
54
  else
54
- raise Rejected, :limit if owned.count >= MAX_PER_RESOURCE
55
+ raise Rejected, :limit if existing.size >= MAX_PER_RESOURCE
55
56
  row = SavedView.create!(actor_ref: @context.actor_ref, tenant_ref: @context.tenant_ref,
56
57
  resource_key: @resource.key.to_s, name: name, state: JSON.generate(state))
57
58
  end
@@ -66,7 +67,7 @@ module RailsAiAdmin
66
67
 
67
68
  def delete(id)
68
69
  @access.authorize!(:index)
69
- raise AccessDenied unless id.is_a?(String) && id.match?(/\A[1-9]\d{0,18}\z/)
70
+ raise AccessDenied unless id.is_a?(String) && id.valid_encoding? && id.match?(/\A[1-9]\d{0,18}\z/) && Integer(id, 10) <= 2**63 - 1
70
71
  owned.where(id: id).delete_all.positive? || raise(AccessDenied)
71
72
  end
72
73
 
@@ -86,9 +87,9 @@ module RailsAiAdmin
86
87
  end
87
88
 
88
89
  def parse(text)
89
- value = JSON.parse(text)
90
+ value = JSON.parse(text, max_nesting: 8)
90
91
  value.is_a?(Hash) ? value : {}
91
- rescue JSON::ParserError
92
+ rescue JSON::JSONError
92
93
  {}
93
94
  end
94
95
  end
@@ -12,25 +12,46 @@ module RailsAiAdmin
12
12
 
13
13
  def call(context:, resource:, id:, expected_version:, origin: :ui)
14
14
  raise AccessDenied, "UNAUTHENTICATED" unless context.is_a?(Context)
15
+ raise ConfigurationError, "Unsupported origin" unless Runner::ORIGINS.include?(origin.to_s)
15
16
  raise AccessDenied unless resource.soft_delete? && resource.action_enabled?(:restore)
16
- raise AccessDenied, "INVALID_QUERY" unless expected_version.is_a?(String) && expected_version.match?(/\A(?:0|[1-9]\d{0,18})\z/)
17
+ raise AccessDenied, "INVALID_QUERY" unless expected_version.is_a?(String) && expected_version.valid_encoding? && expected_version.match?(/\A(?:0|[1-9]\d{0,18})\z/) && Integer(expected_version, 10) <= 2**63 - 1
17
18
  access = Authorization::Access.new(context, resource)
18
19
  raise AccessDenied unless access.canonical_id?(id)
19
20
  model = resource.model_class
21
+ ensure_connection!(model)
20
22
  OperationRun.transaction(requires_new: true) do
21
- record = access.discarded_relation.lock.find_by(model.primary_key => id) || raise(AccessDenied)
23
+ record = model.unscoped.lock.find_by(model.primary_key => id)
24
+ raise AccessDenied unless record && access.discarded_relation.where(model.primary_key => record.id).exists?
22
25
  access.authorize!(:restore, record)
23
26
  raise AccessDenied, "CONFLICT" unless RecordVersion.of(record) == expected_version.to_i
24
27
  record.public_send("#{resource.soft_delete}=", nil)
25
- record.save!(validate: false)
28
+ record.save!
26
29
  raise AccessDenied unless access.relation.where(model.primary_key => record.id).exists?
27
30
  audit = AuditEvent.create!(actor_ref: context.actor_ref, tenant_ref: context.tenant_ref, resource_key: resource.key.to_s,
28
31
  operation: "restore", status: "succeeded", code: "OK", record_id: record.id.to_s, correlation_ref: SecureRandom.uuid,
29
32
  origin: origin.to_s, changed_fields: [], created_at: Time.current)
30
33
  Result.new(code: "OK", record_id: record.id.to_s, audit_ref: audit.id)
31
34
  end
32
- rescue ActiveRecord::StaleObjectError, ActiveRecord::RecordNotUnique, ActiveRecord::Deadlocked, ActiveRecord::LockWaitTimeout
35
+ rescue ActiveRecord::StaleObjectError, ActiveRecord::RecordNotUnique, ActiveRecord::Deadlocked, ActiveRecord::LockWaitTimeout,
36
+ ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, ActiveRecord::InvalidForeignKey
33
37
  raise AccessDenied, "CONFLICT", cause: nil
38
+ rescue ActiveRecord::StatementInvalid => error
39
+ raise unless defined?(SQLite3::BusyException) && error.cause.is_a?(SQLite3::BusyException)
40
+ raise AccessDenied, "CONFLICT", cause: nil
41
+ end
42
+
43
+ private
44
+
45
+ def ensure_connection!(model)
46
+ unless model.connection_pool.equal?(OperationRun.connection_pool) && model.connection_pool.equal?(AuditEvent.connection_pool)
47
+ raise ConfigurationError, "Domain, intent and audit must use the same connection pool"
48
+ end
49
+ unless RecordVersion.supported?(model)
50
+ raise ConfigurationError, "Writes require lock_version or an updated_at timestamp, and a single primary key"
51
+ end
52
+ unless %w[SQLite PostgreSQL].include?(model.connection.adapter_name)
53
+ raise ConfigurationError, "Only SQLite and PostgreSQL are supported for writes"
54
+ end
34
55
  end
35
56
  end
36
57
  end