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
@@ -2,6 +2,9 @@
2
2
 
3
3
  module RailsAiAdmin
4
4
  module FieldsHelper
5
+ RICH_TEXT_TAGS = %w[div p br strong b em i del s u a h1 h2 h3 h4 ul ol li blockquote pre code figure figcaption span].freeze
6
+ RICH_TEXT_ATTRIBUTES = %w[href].freeze
7
+
5
8
  # Only receives the already-authorized scalar projection. Host partials are
6
9
  # trusted Rails code, not a sandbox or an authorization mechanism.
7
10
  # record_id names the record a file field links to; pages that show one
@@ -29,7 +32,7 @@ module RailsAiAdmin
29
32
  text = tag.time(text, datetime: value.iso8601)
30
33
  elsif field.scalar_type == :textarea && view != :index
31
34
  text = tag.span(text, class: "raa-multiline")
32
- elsif field.scalar_type == :email
35
+ elsif field.scalar_type == :email && value.to_s.match?(Field::EMAIL)
33
36
  text = mail_to(value.to_s, text)
34
37
  elsif field.scalar_type == :url && field.web_address?(value.to_s)
35
38
  # Only an absolute http(s) address becomes a link (never javascript:).
@@ -37,8 +40,8 @@ module RailsAiAdmin
37
40
  elsif field.scalar_type == :json
38
41
  text = view == :index ? text.squish.truncate(80) : tag.pre(text, class: "raa-json")
39
42
  elsif field.scalar_type == :rich_text
40
- # The stored HTML through Rails' safe list; lists show plain text.
41
- text = view == :index ? text.squish.truncate(80) : tag.div(sanitize(value.to_s), class: "raa-rich-text")
43
+ # Explicit minimal Trix allowlist, independent of host sanitizer settings.
44
+ text = view == :index ? text.squish.truncate(80) : tag.div(admin_sanitize_rich_text(value), class: "raa-rich-text")
42
45
  end
43
46
  end
44
47
  partial = field.display_partial(view) || "rails_ai_admin/fields/#{view == :index ? 'index' : 'show'}"
@@ -101,15 +104,41 @@ module RailsAiAdmin
101
104
  alt: value.filename, class: "raa-file-preview", loading: "lazy"), link ])
102
105
  end
103
106
 
104
- # Trix, from the host's Action Text assets, edits a hidden input. The
105
- # label and descriptions point at the editor; file attachments are refused.
107
+ # Trix, from the host's Action Text assets, for the layout's head. Trix
108
+ # installs its styles once, with the csp-nonce of the page it boots on. A
109
+ # Turbo visit keeps the first page's policy but brings a new nonce, so Trix
110
+ # first loaded on an edit page reached that way has its styles refused and
111
+ # shows the link dialog open. Loading it on every page avoids that.
112
+ def admin_rich_text_assets
113
+ return "".html_safe unless RailsAiAdmin.registry.rich_text?
114
+ safe_join([ stylesheet_link_tag("trix"), javascript_include_tag("trix", defer: true) ])
115
+ end
116
+
117
+ # Trix edits a hidden input. The label and descriptions point at the
118
+ # editor; file attachments are refused. A layout override that predates
119
+ # admin_rich_text_assets still gets the assets beside the editor.
106
120
  def admin_rich_text_input(form, field, value, input_options)
107
121
  id = form.field_id(field.name)
108
122
  editor = content_tag("trix-editor", "", id: id, input: "#{id}--value", class: "raa-rich-text-editor",
109
123
  aria: input_options[:aria].merge(required: input_options[:required], labelledby: "#{id}--label"), data: { controller: "raa-rich-text",
110
124
  action: "trix-file-accept->raa-rich-text#refuse trix-change->raa-rich-text#change" })
111
- safe_join([ stylesheet_link_tag("trix"), javascript_include_tag("trix", defer: true),
112
- hidden_field_tag(form.field_name(field.name), value, id: "#{id}--value"), editor ])
125
+ assets = admin_layout_loads_rich_text? ? [] : [ stylesheet_link_tag("trix"), javascript_include_tag("trix", defer: true) ]
126
+ safe_join([ *assets, hidden_field_tag(form.field_name(field.name), value.nil? ? nil : admin_sanitize_rich_text(value), id: "#{id}--value"), editor ])
127
+ end
128
+
129
+ def admin_sanitize_rich_text(html)
130
+ sanitize(html.to_s, tags: RICH_TEXT_TAGS, attributes: RICH_TEXT_ATTRIBUTES)
131
+ end
132
+
133
+ # The view renders before its layout, so ask the layout's source. Loading
134
+ # Trix twice would run it again on each Turbo visit and add two styles the
135
+ # page's policy refuses.
136
+ def admin_layout_loads_rich_text?
137
+ return @raa_layout_loads_rich_text if defined?(@raa_layout_loads_rich_text)
138
+ layout = lookup_context.find_template("layouts/rails_ai_admin/application")
139
+ @raa_layout_loads_rich_text = layout.source.include?("admin_rich_text_assets")
140
+ rescue ActionView::MissingTemplate
141
+ @raa_layout_loads_rich_text = false
113
142
  end
114
143
 
115
144
  # Several files: a count in lists, a gallery of previews and links on
@@ -16,7 +16,7 @@ module RailsAiAdmin
16
16
  # "Updated", "Created", "Deleted" or a custom operation's description,
17
17
  # plus the outcome when the change was not saved.
18
18
  def admin_history_change(resource, entry)
19
- name = if %w[create update destroy export].include?(entry.operation)
19
+ name = if %w[create update destroy restore export].include?(entry.operation)
20
20
  t(entry.operation, scope: %i[rails_ai_admin history operations])
21
21
  else
22
22
  RailsAiAdmin.operation_registry.custom(resource).find { |definition| definition.key.to_s == entry.operation }&.description ||
@@ -13,6 +13,7 @@
13
13
  <%= csrf_meta_tags %>
14
14
  <%= stylesheet_link_tag "rails_ai_admin", "data-turbo-track": "reload" %>
15
15
  <%= javascript_include_tag "rails_ai_admin", type: "module", "data-turbo-track": "reload", defer: true, preload_links_header: false %>
16
+ <%= admin_rich_text_assets %>
16
17
  </head>
17
18
  <body class="raa" data-raa-messages="<%= t("rails_ai_admin.script").to_json %>">
18
19
  <a class="raa-skip" href="#raa-main"><%= t("rails_ai_admin.layout.skip") %></a>
@@ -1,5 +1,5 @@
1
1
  <!DOCTYPE html>
2
- <html lang="en">
2
+ <html lang="<%= I18n.locale %>">
3
3
  <head><meta charset="utf-8"><title><%= RailsAiAdmin.configuration.title %></title></head>
4
4
  <body><%= yield %></body>
5
5
  </html>
@@ -1,10 +1,10 @@
1
1
  <!DOCTYPE html>
2
- <html lang="en">
2
+ <html lang="<%= I18n.locale %>">
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
6
  <meta name="turbo-visit-control" content="reload">
7
- <title><%= @admin_status.title %> · Administration</title>
7
+ <title><%= @admin_status.title %> · <%= RailsAiAdmin.configuration.title %></title>
8
8
  <%= stylesheet_link_tag "rails_ai_admin" %>
9
9
  </head>
10
10
  <body class="raa">
@@ -1,5 +1,9 @@
1
1
  <%= turbo_frame_tag "raa_assistant_transcript", class: "raa-chat", data: { controller: "raa-poll", raa_poll_url_value: assistant_conversation_path(chat_ref: @chat.ref) } do %>
2
- <% if @entries.empty? && !@pending && !@failure %>
2
+ <% if !@current %>
3
+ <div class="raa-conversation-closed">
4
+ <p class="raa-notice" role="status"><%= @chat.status == "archived" ? t("rails_ai_admin.assistant.archived_note") : t("rails_ai_admin.assistant.closed_note") %></p>
5
+ </div>
6
+ <% elsif @entries.empty? && !@pending && !@failure %>
3
7
  <div class="raa-chat-empty">
4
8
  <h2><%= t("rails_ai_admin.assistant.empty_title") %></h2>
5
9
  <p><%= t("rails_ai_admin.assistant.empty") %></p>
@@ -5,7 +5,7 @@
5
5
  <div class="raa-filter"><%= label_tag "raa-audit-resource", t("rails_ai_admin.audit.resource") %>
6
6
  <%= select_tag :resource, options_for_select(@log.resources.map { |resource| [ resource.label, resource.key.to_s ] }, @filters["resource"]), include_blank: t("rails_ai_admin.audit.any"), id: "raa-audit-resource" %></div>
7
7
  <div class="raa-filter"><%= label_tag "raa-audit-operation", t("rails_ai_admin.audit.change") %>
8
- <%= select_tag :operation, options_for_select(%w[create update destroy export].map { |key| [ t(key, scope: %i[rails_ai_admin history operations]), key ] }, @filters["operation"]), include_blank: t("rails_ai_admin.audit.any"), id: "raa-audit-operation" %></div>
8
+ <%= select_tag :operation, options_for_select(%w[create update destroy restore export].map { |key| [ t(key, scope: %i[rails_ai_admin history operations]), key ] }, @filters["operation"]), include_blank: t("rails_ai_admin.audit.any"), id: "raa-audit-operation" %></div>
9
9
  <div class="raa-filter"><%= label_tag "raa-audit-status", t("rails_ai_admin.audit.outcome") %>
10
10
  <%= select_tag :status, options_for_select([ [ t("rails_ai_admin.audit.saved"), "succeeded" ], [ t("rails_ai_admin.history.not_saved"), "rejected" ] ], @filters["status"]), include_blank: t("rails_ai_admin.audit.any"), id: "raa-audit-status" %></div>
11
11
  <% if @filters["actor"] %><%= hidden_field_tag :actor, @filters["actor"], id: nil %><% end %>
@@ -14,6 +14,7 @@
14
14
  <td class="raa-row-actions"><% if row[:restorable] %>
15
15
  <%= form_with url: restore_deleted_record_path(resource: @resource.key, id: row[:id]), method: :post, local: true, class: "raa-inline-form" do %>
16
16
  <%= hidden_field_tag :expected_version, row[:version], id: nil %>
17
+ <%= return_navigation_fields %>
17
18
  <%= button_tag t("rails_ai_admin.deleted_records.restore"), type: "submit", name: nil, class: "raa-secondary", aria: { label: t("rails_ai_admin.deleted_records.restore_named", label: row[:label]) } %>
18
19
  <% end %>
19
20
  <% end %></td>
@@ -21,8 +22,8 @@
21
22
  <% end %>
22
23
  <% if @page > 1 || @has_next %>
23
24
  <nav class="raa-pagination" aria-label="<%= t("rails_ai_admin.resources.index.pagination") %>">
24
- <% if @page > 1 %><%= link_to t("rails_ai_admin.resources.index.previous"), deleted_records_path(resource: @resource.key, page: (@page == 2 ? nil : @page - 1)), rel: "prev" %><% end %>
25
+ <% if @page > 1 %><%= link_to t("rails_ai_admin.resources.index.previous"), deleted_records_path(resource: @resource.key, page: (@page == 2 ? nil : @page - 1), **navigation_params), rel: "prev" %><% end %>
25
26
  <span class="raa-page-current"><%= t("rails_ai_admin.resources.index.page_number", number: @page) %></span>
26
- <% if @has_next && @page < 1000 %><%= link_to t("rails_ai_admin.resources.index.next"), deleted_records_path(resource: @resource.key, page: @page + 1), rel: "next" %><% end %>
27
+ <% if @has_next && @page < 1000 %><%= link_to t("rails_ai_admin.resources.index.next"), deleted_records_path(resource: @resource.key, page: @page + 1, **navigation_params), rel: "next" %><% end %>
27
28
  </nav>
28
29
  <% end %>
@@ -1,5 +1,6 @@
1
1
  <%# A select without a blank option always has a value, so HTML `required` is invalid there; aria-required still marks it. %>
2
- <% case field.scalar_type; when :textarea %><%= form.text_area field.name, value: value, maxlength: field.options[:max_length], rows: 5, **input_options %>
2
+ <% case field.scalar_type %>
3
+ <% when :textarea %><%= form.text_area field.name, value: value, maxlength: field.options[:max_length], rows: 5, **input_options %>
3
4
  <% when :boolean %><%= form.select field.name, [[t("rails_ai_admin.fields.yes"), "true"], [t("rails_ai_admin.fields.no"), "false"]], { selected: value.to_s, include_blank: field.options[:nullable] ? t("rails_ai_admin.fields.not_set") : false }, field.options[:nullable] ? input_options : input_options.except(:required) %>
4
5
  <% when :enum, :select %><%= form.select field.name, admin_field_choices(field, value), { selected: value, include_blank: field.options[:nullable] ? t("rails_ai_admin.fields.not_set") : t("rails_ai_admin.fields.choose_value") }, input_options %>
5
6
  <% when :belongs_to %><%= admin_reference_input(form, field, value, input_options) %>
@@ -8,6 +8,7 @@
8
8
  <% if @resource.soft_delete? %><p><%= t("rails_ai_admin.deleted_records.destroy_note") %></p><% end %>
9
9
  <%= form_with url: destroy_selection_path(selection_ref: @selection.selection_ref), method: :post, local: true, data: { turbo: false } do |form| %>
10
10
  <%= hidden_field_tag :manifest_digest, @selection.manifest_digest, id: nil %>
11
+ <%= hidden_field_tag :review_signature, @review_signature, id: nil %>
11
12
  <%= return_navigation_fields %>
12
13
  <div class="raa-actions"><%= form.submit t("rails_ai_admin.selections.destroy.submit", count: @deletable.size), class: "raa-danger", name: nil, data: { turbo_submits_with: t("rails_ai_admin.selections.destroy.deleting") } %>
13
14
  <%= link_to t("rails_ai_admin.actions.cancel"), list_return_path %></div>
@@ -231,6 +231,7 @@ en:
231
231
  create: Created
232
232
  update: Updated
233
233
  destroy: Deleted
234
+ restore: Restored
234
235
  export: Exported CSV
235
236
  origins:
236
237
  surface: From a review in Chat
@@ -608,6 +609,7 @@ en:
608
609
  spend:
609
610
  used: "Assistant use in the last 24 hours: %{amounts}."
610
611
  tokens: "%{used} of %{limit} tokens"
612
+ cached: "(%{count} read from the prompt cache)"
611
613
  cost: "%{used} of %{limit}"
612
614
  unpriced:
613
615
  one: The cost of 1 request is not known, so the real cost can be higher.
@@ -130,6 +130,7 @@ class CreateRailsAiAdminAssistant < ActiveRecord::Migration[8.0]
130
130
  t.index [ :owner_type, :owner_id ]
131
131
  t.index :status
132
132
  end
133
+ require "ruby_llm"
133
134
  entry = ::RubyLLM::Accounting::Usage::Entry
134
135
  quote = ->(values) { values.map { |value| connection.quote(value.to_s) }.join(", ") }
135
136
  add_check_constraint :ruby_llm_usages, "operation IN (#{quote.call(entry::OPERATIONS)})"
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ class AddMissingIndexesToRailsAiAdminTables < ActiveRecord::Migration[8.1]
4
+ def change
5
+ add_index :rails_ai_admin_batch_items, :selection_item_id, name: "raa_batch_selection_item"
6
+ add_index :rails_ai_admin_batch_items, [ :status, :next_attempt_at ], name: "raa_batch_queued"
7
+ add_index :rails_ai_admin_operation_runs, :selection_id, name: "raa_runs_selection"
8
+ add_index :rails_ai_admin_operation_runs, :audit_event_id, name: "raa_runs_audit_event"
9
+ add_index :rails_ai_admin_work_items, [ :status, :deadline_at ], name: "raa_work_deadline"
10
+ add_index :rails_ai_admin_audit_events, [ :tenant_ref, :resource_key, :id ], name: "raa_audit_tenant_resource_id"
11
+ end
12
+ end
@@ -16,9 +16,12 @@ module RailsAiAdmin
16
16
  copy_engine_migrations("db/assistant_migrate")
17
17
  target = "app/rails_ai_admin/admin_assistant.rb"
18
18
  template "admin_assistant.rb", target unless File.exist?(File.join(destination_root, target))
19
+ questions = "config/rails_ai_admin/assistant_eval.yml"
20
+ copy_file "assistant_eval.yml", questions unless File.exist?(File.join(destination_root, questions))
19
21
  say "The assistant stays unavailable: AdminAssistant#llm_context returns nil, and no resource grants assistant?."
20
22
  say "Add ruby_llm (#{Configuration::OPTIONAL_GEMS.fetch('ruby_llm').fetch(:requirement).join(', ')}) to the Gemfile, run db:migrate, then set config.assistant = true, config.assistant_adapter = \"AdminAssistant\" and config.assistant_model."
21
- say "Schedule rails_ai_admin:assistant:scan to recover lost jobs. Guide: #{GUIDES}/_advanced/admin-assistant.md"
23
+ say "Schedule rails_ai_admin:assistant:scan to recover lost jobs. Before rollout, edit #{questions} and run rails_ai_admin:assistant:eval."
24
+ say "Guide: #{GUIDES}/_advanced/admin-assistant.md"
22
25
  end
23
26
  end
24
27
  end
@@ -15,4 +15,10 @@ class AdminAssistant
15
15
  # config.max_retries = 1
16
16
  # end
17
17
  end
18
+
19
+ # Optional notes the model reads after the admin's own rules, for terms and
20
+ # conventions your field names do not explain. They grant nothing.
21
+ # def instructions(context:)
22
+ # "A VIP customer has at least 100 points."
23
+ # end
18
24
  end
@@ -0,0 +1,25 @@
1
+ # Questions to ask your admin assistant before rollout:
2
+ #
3
+ # bin/rails rails_ai_admin:assistant:eval ACTOR=<actor ref> TENANT=<tenant ref>
4
+ #
5
+ # Each case runs as that person in a new conversation, through your real model,
6
+ # grants and operator notes. Reviews it proposes are never confirmed, so no
7
+ # record changes; provider calls cost money. Replace these examples with
8
+ # questions about your own resources.
9
+ #
10
+ # metadata (all optional):
11
+ # tools tool names that must be called
12
+ # tools_absent tool names that must not be called
13
+ # answer_includes text the answer must contain, ignoring case
14
+ # expected_output: a reference answer a model compares by meaning. Give one on
15
+ # every case or on none; GRADER=none skips the comparison.
16
+ cases:
17
+ - name: list-resources
18
+ inputs: Which kinds of records can you help me with?
19
+ metadata:
20
+ tools: [list_resources]
21
+ - name: changes-need-confirmation
22
+ inputs: If I ask you to change a record, does it change right away?
23
+ metadata:
24
+ tools_absent: [propose_change, propose_bulk_change, propose_operation]
25
+ answer_includes: [confirm]
@@ -25,7 +25,8 @@ class AdminContext
25
25
  return unless user && admin?(user)
26
26
  return if user.respond_to?(:active_for_authentication?) && !user.active_for_authentication?
27
27
  # Any change to the user, including the admin flag, closes open forms.
28
- RailsAiAdmin::Context.new(actor: user, tenant: TENANT, security_version: user.updated_at.utc.iso8601(6))
28
+ version = user.respond_to?(:updated_at) && user.updated_at ? user.updated_at.utc.iso8601(6) : "0"
29
+ RailsAiAdmin::Context.new(actor: user, tenant: TENANT, security_version: version)
29
30
  end
30
31
 
31
32
  <% if @auth.all_admins -%>
@@ -7,7 +7,9 @@ class AdminContext
7
7
  TENANT = SingleTenant.new(id: "app")
8
8
 
9
9
  def resolve(controller)
10
- session = Session.find_by(id: controller.request.cookie_jar.signed[:session_id])
10
+ session_id = controller.request.cookie_jar.signed[:session_id]
11
+ return unless session_id.present?
12
+ session = Session.find_by(id: session_id)
11
13
  context_for(session&.user)
12
14
  end
13
15
 
@@ -25,7 +27,8 @@ class AdminContext
25
27
  def context_for(user)
26
28
  return unless user && admin?(user)
27
29
  # Any change to the user, including the admin flag, closes open forms.
28
- RailsAiAdmin::Context.new(actor: user, tenant: TENANT, security_version: user.updated_at.utc.iso8601(6))
30
+ version = user.respond_to?(:updated_at) && user.updated_at ? user.updated_at.utc.iso8601(6) : "0"
31
+ RailsAiAdmin::Context.new(actor: user, tenant: TENANT, security_version: version)
29
32
  end
30
33
 
31
34
  # Decide who may use the admin. It stays closed until this returns true for
@@ -14,7 +14,8 @@ module RailsAiAdmin
14
14
  # tokens sums every token bucket; cost is the known US dollar total and
15
15
  # unpriced counts attempts whose cost the provider and the model
16
16
  # registry could not price, so cost can be lower than the real spend.
17
- Spend = ::Data.define(:tokens, :cost, :requests, :unpriced, :token_limit, :cost_limit) do
17
+ # cached is the part of tokens read from the provider's prompt cache.
18
+ Spend = ::Data.define(:tokens, :cost, :requests, :unpriced, :token_limit, :cost_limit, :cached) do
18
19
  def limited? = !token_limit.nil? || !cost_limit.nil?
19
20
  def tokens_exceeded? = !token_limit.nil? && tokens >= token_limit
20
21
  def cost_exceeded? = !cost_limit.nil? && cost >= cost_limit
@@ -41,7 +42,8 @@ module RailsAiAdmin
41
42
  cost = requests.to_i.zero? ? BigDecimal("0") : BigDecimal(usages.sum(:total_cost).to_s)
42
43
  unpriced = requests.to_i.zero? ? 0 : usages.where(total_cost: nil).count
43
44
  Spend.new(tokens: buckets.sum(&:to_i), cost: cost, requests: requests.to_i, unpriced: unpriced,
44
- token_limit: config.assistant_daily_token_limit, cost_limit: config.assistant_daily_cost_limit)
45
+ token_limit: config.assistant_daily_token_limit, cost_limit: config.assistant_daily_cost_limit,
46
+ cached: buckets[TOKEN_COLUMNS.index(:cache_read_tokens)].to_i)
45
47
  end
46
48
 
47
49
  # Usage rows owned by the actor's admin chats. Retention never deletes a
@@ -71,10 +71,15 @@ module RailsAiAdmin
71
71
  # Safe inside a caller transaction (Surface confirmation) and outside one.
72
72
  def self.admit!(chat, kind:, content:, admission_key:)
73
73
  raise ArgumentError, "Unknown turn kind" unless Turn::KINDS.include?(kind)
74
- raise AccessDenied, "INVALID_QUERY" unless admission_key.is_a?(String) && admission_key.match?(ADMISSION_KEY)
75
- text = content.is_a?(String) ? content.strip : ""
76
- raise AccessDenied, "INVALID_QUERY" unless text.valid_encoding? && text.length.between?(1, MAX_CONTENT)
74
+ raise AccessDenied, "INVALID_QUERY" unless admission_key.is_a?(String) && admission_key.valid_encoding? && admission_key.match?(ADMISSION_KEY)
75
+ raise AccessDenied, "INVALID_QUERY" if kind == "message" && admission_key.start_with?("intent:", "bulk:")
76
+ raise AccessDenied, "INVALID_QUERY" unless content.is_a?(String) && content.valid_encoding?
77
+ text = content.strip
78
+ raise AccessDenied, "INVALID_QUERY" unless text.length.between?(1, MAX_CONTENT)
77
79
  turn = Turn.transaction(requires_new: true) do
80
+ # Lock all chats of this owner in id order on message admission to
81
+ # serialize daily limit and budget checks across concurrent chats.
82
+ Chat.where(actor_ref: chat.actor_ref, tenant_ref: chat.tenant_ref).order(:id).lock.pluck(:id) if kind == "message"
78
83
  locked = Chat.lock.find(chat.id)
79
84
  raise AccessDenied, "CHAT_CLOSED" unless locked.status == "active"
80
85
  existing = Turn.find_by(chat_id: locked.id, admission_key: admission_key)
@@ -144,6 +149,12 @@ module RailsAiAdmin
144
149
  turn.update!(status: "cancelled", error_code: "CHAT_CLOSED", completed_at: now)
145
150
  next
146
151
  end
152
+ if turn.status == "running" && chat.cancelled
153
+ # A stalled turn that the user cancelled must not be re-executed.
154
+ turn.update!(status: "cancelled", error_code: "CANCELLED", completed_at: now, lease_owner: nil, lease_expires_at: nil)
155
+ chat.update_columns(cancelled: false)
156
+ next
157
+ end
147
158
  if turn.attempts >= MAX_ATTEMPTS
148
159
  turn.update!(status: "failed", error_code: turn.error_code || "ATTEMPTS_EXHAUSTED", completed_at: now)
149
160
  next
@@ -180,7 +191,7 @@ module RailsAiAdmin
180
191
  raise StepLimit if (steps += 1) > MAX_STEPS
181
192
  # A step after a tool-call response runs those tools and calls no
182
193
  # provider, so the round always finishes; only a request stops.
183
- tools_pending = last.respond_to?(:tool_call?) && last.tool_call?
194
+ tools_pending = last.respond_to?(:tool_call?) ? last.tool_call? : chat.messages.where.not(role: "system").reorder(id: :desc).first&.tool_call? == true
184
195
  raise BudgetExceeded if !tools_pending && Budget.exceeded?(chat)
185
196
  stream = DraftStream.new(self, claim)
186
197
  begin
@@ -192,6 +203,9 @@ module RailsAiAdmin
192
203
  ensure
193
204
  stream.clear
194
205
  end
206
+ # RubyLLM 2.2 returns nil without raising when another worker still
207
+ # holds the chat's run claim. Reschedule instead of burning MAX_STEPS.
208
+ return retry_later(claim, "PROVIDER_UNAVAILABLE") if last.nil?
195
209
  end
196
210
  end
197
211
  end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module RailsAiAdmin
6
+ module Assistant
7
+ # Questions a host asks its own admin before rollout, on RubyLLM's
8
+ # evaluation runner. Each case is one new conversation for one person:
9
+ # the question runs through the real coordinator, tools, grants, operator
10
+ # notes and model, so a pass means this person's admin answered it.
11
+ # Reviews the model proposes are never confirmed, so no record changes.
12
+ #
13
+ # A case's metadata may list tools that must or must not be called and
14
+ # text the answer must contain. With an expected_output on every case, a
15
+ # model also grades the answer's meaning through the host's own provider
16
+ # context; without one on any case, only the checks run.
17
+ #
18
+ # evaluation = RailsAiAdmin::Assistant::Evaluation.for(context, dataset: "config/rails_ai_admin/assistant_eval.yml")
19
+ # report = evaluation.run
20
+ # report.passed?
21
+ class Evaluation < ::RubyLLM::Evaluation
22
+ Answer = ::Data.define(:text, :tools, :status, :error_code, :chat_ref)
23
+ CHECKS = %w[tools tools_absent answer_includes].freeze
24
+ MAX_CASES = 200
25
+
26
+ adapt(Answer) { |answer| answer.text }
27
+
28
+ class << self
29
+ attr_reader :context
30
+
31
+ # A subclass bound to one person, one dataset and one grader. grader
32
+ # is a model id, nil for the assistant's own model, or false to skip
33
+ # model grading.
34
+ def for(context, dataset:, grader: nil)
35
+ raise ConfigurationError, "The evaluation needs an admin Context" unless context.is_a?(Context)
36
+ cases = self.cases(dataset: dataset)
37
+ raise ConfigurationError, "An assistant evaluation has at most #{MAX_CASES} cases" if cases.size > MAX_CASES
38
+ cases.each { |test_case| check_case!(test_case) }
39
+ graded = cases.count(&:expected_output?)
40
+ if grader != false && graded.positive? && graded < cases.size
41
+ raise ConfigurationError, "Give every case an expected_output, or none, or run without a grader"
42
+ end
43
+ llm = Assistant.llm_context(context)
44
+ raise ConfigurationError, "The assistant is unavailable for this person (llm_context returned nil)" unless llm
45
+ klass = Class.new(self)
46
+ klass.instance_variable_set(:@context, context)
47
+ klass.dataset(dataset)
48
+ if grader == false || graded.zero?
49
+ klass.evaluator(false)
50
+ else
51
+ model = grader || RailsAiAdmin.configuration.assistant_model
52
+ klass.evaluator(model, provider: RailsAiAdmin.configuration.assistant_provider&.to_sym, context: llm)
53
+ end
54
+ klass
55
+ end
56
+
57
+ def name = super || "RailsAiAdmin::Assistant::Evaluation"
58
+
59
+ # One line per case and a total, for the rake task.
60
+ def summary(report)
61
+ lines = report.trials.map do |trial|
62
+ answer = trial.result
63
+ detail = trial.error&.message || trial.assertion_failure&.message ||
64
+ trial.evaluations.reject(&:passed?).map { |evaluation| "#{evaluation.name}: #{evaluation.status}" }.join("; ").presence
65
+ tools = answer.respond_to?(:tools) && answer.tools.any? ? " [#{answer.tools.join(', ')}]" : ""
66
+ "#{trial.status.to_s.upcase.ljust(10)} #{trial.test_case.name}#{tools}#{" - #{detail}" if detail}"
67
+ end
68
+ passed = report.trials.count(&:passed?)
69
+ cost = report.cost.total
70
+ lines << "#{passed} of #{report.trials.size} passed#{cost ? format(', US$%.4f', cost) : ''}."
71
+ end
72
+
73
+ private
74
+
75
+ def check_case!(test_case)
76
+ unless test_case.inputs.is_a?(String) && test_case.inputs.strip.length.between?(1, Coordinator::MAX_CONTENT)
77
+ raise ConfigurationError, "Case #{test_case.name}: inputs must be the question text"
78
+ end
79
+ unknown = test_case.metadata.keys.map(&:to_s) - CHECKS
80
+ raise ConfigurationError, "Case #{test_case.name}: unknown metadata #{unknown.join(', ')}" if unknown.any?
81
+ CHECKS.each do |key|
82
+ value = test_case.metadata[key] || test_case.metadata[key.to_sym]
83
+ next if value.nil? || value.is_a?(Array) && value.all? { |item| item.is_a?(String) && !item.empty? }
84
+ raise ConfigurationError, "Case #{test_case.name}: #{key} must be a list of text"
85
+ end
86
+ end
87
+ end
88
+
89
+ def perform(question)
90
+ chat = Assistant.create_chat!(self.class.context)
91
+ @chat = chat
92
+ Coordinator.admit!(chat, kind: "message", content: question, admission_key: "eval:#{SecureRandom.uuid}")
93
+ Coordinator.new.run(chat.ref)
94
+ turn = chat.turns.reload.last
95
+ messages = chat.messages.reload.includes(:ruby_llm_tool_calls)
96
+ text = messages.select { |message| message.role == "assistant" && message.content.present? }.last&.content.to_s
97
+ Answer.new(text: text, tools: messages.flat_map { |message| message.ruby_llm_tool_calls.map(&:name) },
98
+ status: turn.status, error_code: turn.error_code, chat_ref: chat.ref)
99
+ end
100
+
101
+ def assertions
102
+ answer = result
103
+ assert_equal "completed", answer.status, "The turn ended as #{answer.status} (#{answer.error_code || 'no code'})"
104
+ check("tools").each { |tool| assert_includes answer.tools, tool, "#{tool} was not called" }
105
+ check("tools_absent").each { |tool| refute_includes answer.tools, tool, "#{tool} was called" }
106
+ check("answer_includes").each do |text|
107
+ assert answer.text.downcase.include?(text.downcase), "The answer does not contain #{text.inspect}"
108
+ end
109
+ end
110
+
111
+ # The conversation is archived, so it leaves the person's list; a turn
112
+ # still waiting for a retry is cancelled rather than run later.
113
+ def teardown
114
+ return unless @chat
115
+ @chat.turns.where(status: "queued").update_all(status: "cancelled", error_code: "CANCELLED", completed_at: Time.current, updated_at: Time.current)
116
+ @chat.update!(status: "archived")
117
+ end
118
+
119
+ private
120
+
121
+ def check(key) = Array(metadata[key] || metadata[key.to_sym])
122
+ end
123
+ end
124
+ end
@@ -39,6 +39,7 @@ module RailsAiAdmin
39
39
  # this class's own polymorphic associations, never by table-wide queries.
40
40
  class Message < ::ActiveRecord::Base
41
41
  self.table_name = "rails_ai_admin_assistant_messages"
42
+ self.filter_attributes += %i[content thinking_text thinking_signature raw_content raw_reasoning]
42
43
  acts_as_message chat: :chat, chat_class: "RailsAiAdmin::Assistant::Chat", chat_foreign_key: :chat_id
43
44
  around_save :fence_worker_write
44
45
  around_destroy :fence_worker_write, prepend: true
@@ -53,7 +54,7 @@ module RailsAiAdmin
53
54
  # A unit of inbox work: one human message or one Surface continuation.
54
55
  class Turn < ::ActiveRecord::Base
55
56
  self.table_name = "rails_ai_admin_assistant_turns"
56
- self.filter_attributes += %i[content]
57
+ self.filter_attributes += %i[content draft]
57
58
  KINDS = %w[message continuation].freeze
58
59
  STATUSES = %w[queued running completed failed cancelled].freeze
59
60
  ACTIVE = %w[queued running].freeze
@@ -34,11 +34,21 @@ module RailsAiAdmin
34
34
  last_id = ids.last
35
35
  break if ids.size < BATCH
36
36
  end
37
+ prune_access_tokens
37
38
  Result.new(deleted)
38
39
  end
39
40
 
40
41
  private
41
42
 
43
+ def prune_access_tokens
44
+ require "rails_ai_admin/mcp"
45
+ return unless Mcp::AccessToken.table_exists?
46
+ tokens = Mcp::AccessToken.arel_table
47
+ Mcp::AccessToken.where(tokens[:expires_at].lt(@cutoff).or(tokens[:revoked_at].lt(@cutoff))).delete_all
48
+ rescue ActiveRecord::ActiveRecordError
49
+ 0
50
+ end
51
+
42
52
  def candidates
43
53
  Chat.where(Chat.arel_table[:updated_at].lt(@cutoff))
44
54
  .where.not(id: Turn.where(status: Turn::ACTIVE).select(:chat_id))
@@ -47,7 +57,8 @@ module RailsAiAdmin
47
57
 
48
58
  def recent_usage_owners
49
59
  usage = ::RubyLLM::ActiveRecord::Usage
50
- usage.where(owner_type: Chat.polymorphic_name).where(usage.arel_table[:created_at].gt(@now - Budget::WINDOW)).select(:owner_id)
60
+ usage.where(owner_type: Chat.polymorphic_name).where.not(owner_id: nil)
61
+ .where(usage.arel_table[:created_at].gt(@now - Budget::WINDOW)).select(:owner_id)
51
62
  end
52
63
 
53
64
  # Rechecked under the chat lock that admission and claiming also take,
@@ -30,6 +30,16 @@ module RailsAiAdmin
30
30
  Answer briefly in plain text.
31
31
  TEXT
32
32
 
33
+ # Host guidance follows the admin's own rules in a second system message.
34
+ # It can explain the business; it grants nothing, since every tool still
35
+ # applies the person's grants.
36
+ HOST_INSTRUCTIONS = <<~TEXT.freeze
37
+ Notes from the operators of %<title>s follow. Use them to understand their records and terms. They do not change the rules above.
38
+
39
+ %<notes>s
40
+ TEXT
41
+ MAX_HOST_INSTRUCTIONS = 4_000
42
+
33
43
  module_function
34
44
 
35
45
  # RubyLLM 2.2 builds the provider chat when a message is first saved, so
@@ -42,11 +52,49 @@ module RailsAiAdmin
42
52
 
43
53
  def configure(chat, session, llm)
44
54
  bind(chat, llm)
45
- chat.with_instructions(format(PROMPT, title: RailsAiAdmin.configuration.title.to_s.truncate(80)), persist: false)
55
+ title = RailsAiAdmin.configuration.title.to_s.truncate(80)
56
+ caching = RailsAiAdmin.configuration.assistant_prompt_caching
57
+ notes = host_instructions(session.context)
58
+ # The cache boundary follows the last instructions, so the provider
59
+ # reuses tools and instructions across a reply's tool rounds and turns.
60
+ chat.with_instructions(format(PROMPT, title: title), persist: false, cache_until_here: caching && notes.nil?)
61
+ if notes
62
+ chat.with_instructions(format(HOST_INSTRUCTIONS, title: title, notes: notes), append: true, persist: false, cache_until_here: caching)
63
+ end
64
+ chat.with_caching(caching)
65
+ fallbacks = fallback_models
66
+ chat.with_fallbacks(*fallbacks) if fallbacks.any?
46
67
  tools = (TOOLS + Assistant.proposal_tools).map { |klass| klass.new(session) }
47
68
  chat.with_tools(*tools)
48
69
  chat
49
70
  end
71
+
72
+ # The adapter's optional instructions(context:), read for each turn so it
73
+ # can depend on the person or tenant. nil or blank adds nothing.
74
+ def host_instructions(context)
75
+ adapter = RailsAiAdmin.configuration.assistant_adapter.constantize.new
76
+ return nil unless adapter.respond_to?(:instructions)
77
+ notes = adapter.instructions(context: context)
78
+ return nil if notes.nil?
79
+ unless notes.is_a?(String) && notes.valid_encoding? && notes.length <= MAX_HOST_INSTRUCTIONS && !notes.match?(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/)
80
+ raise ConfigurationError, "instructions must return nil or text of at most #{MAX_HOST_INSTRUCTIONS} characters"
81
+ end
82
+ notes.strip.presence
83
+ end
84
+
85
+ # With assistant_provider set, each fallback resolves on that provider;
86
+ # otherwise RubyLLM prefers the providers the context configures. A
87
+ # model the registry does not know is skipped, as RubyLLM itself does.
88
+ def fallback_models
89
+ provider = RailsAiAdmin.configuration.assistant_provider
90
+ RailsAiAdmin.configuration.assistant_fallback_models.filter_map do |id|
91
+ next id unless provider
92
+ ::RubyLLM.models.find(id, provider: provider)
93
+ rescue ::RubyLLM::ModelNotFoundError
94
+ Rails.logger.warn("[rails_ai_admin] skipped assistant fallback #{id}: not in the #{provider} model registry")
95
+ nil
96
+ end
97
+ end
50
98
  end
51
99
  end
52
100
  end