rails_console_ai 0.38.0 → 0.39.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.
@@ -0,0 +1,160 @@
1
+ module RailsConsoleAi
2
+ # Where the safety guards keep their runtime state: which guards are blocking,
3
+ # whether they are bypassed, what has been allowed for this session.
4
+ #
5
+ # This used to be plain `Thread.current[:key]`, which is fiber-local despite
6
+ # the name. Code the model wrote only had to run inside a new Thread, a Fiber,
7
+ # or an external Enumerator (`enum.next`) to find every flag nil and every
8
+ # guard off — not as an attack, just by reaching for ordinary concurrency.
9
+ #
10
+ # State set with .with is scoped to the block. While the block is running it
11
+ # is visible to
12
+ # - every fiber on the calling thread (it is held in a thread variable), and
13
+ # - every thread and fiber spawned inside the block (it is also published to
14
+ # fiber storage, which new threads and fibers inherit). Fiber storage is
15
+ # Ruby 3.2+; on older Rubies a spawned thread still starts with no state.
16
+ #
17
+ # A spawned thread holds a reference to the scope, not a copy of its values:
18
+ # when the block exits, the scope is closed and stops applying everywhere.
19
+ # That is deliberate. A worker a thread pool happened to create during a
20
+ # guarded execution would otherwise carry "writes blocked" for the rest of the
21
+ # process's life, into work that has nothing to do with the session. The cost
22
+ # is that a thread still running after the execution that spawned it has
23
+ # returned is no longer guarded.
24
+ #
25
+ # State set with []= belongs to the calling thread and lasts until changed.
26
+ #
27
+ # Writes are mirrored to the old `Thread.current[:rails_console_ai_<key>]`
28
+ # fiber-locals and reads fall back to them, so host-app code that reads or
29
+ # sets those keys directly keeps working.
30
+ module GuardState
31
+ SCOPE = :rails_console_ai_guard_scope
32
+ BASE = :rails_console_ai_guard_base
33
+
34
+ INHERITABLE = Fiber.respond_to?(:[]=)
35
+
36
+ LEGACY_KEYS = %i[
37
+ allowlist
38
+ block_all_db
39
+ block_http
40
+ block_in_process_requests
41
+ block_writes
42
+ bypass_guards
43
+ bypass_methods
44
+ guards_disabled
45
+ last_safety_error
46
+ session_active
47
+ ].map { |key| [key, :"rails_console_ai_#{key}"] }.to_h.freeze
48
+
49
+ class Scope
50
+ attr_reader :parent, :values
51
+
52
+ def initialize(parent, values)
53
+ @parent = parent
54
+ @values = values.dup.freeze
55
+ @open = true
56
+ end
57
+
58
+ def open?
59
+ @open
60
+ end
61
+
62
+ def close!
63
+ @open = false
64
+ end
65
+ end
66
+
67
+ class << self
68
+ # Nearest enclosing scope that sets the key, then this thread's own state,
69
+ # then the legacy fiber-local.
70
+ def [](key)
71
+ scope = current_scope
72
+ while scope
73
+ return scope.values[key] if scope.open? && scope.values.key?(key)
74
+ scope = scope.parent
75
+ end
76
+
77
+ thread = Thread.current
78
+ own = thread.thread_variable_get(BASE)
79
+ return own[key] if own && own.key?(key)
80
+
81
+ legacy = LEGACY_KEYS[key]
82
+ legacy && thread[legacy]
83
+ end
84
+
85
+ def []=(key, value)
86
+ if value.nil?
87
+ base.delete(key)
88
+ else
89
+ base[key] = value
90
+ end
91
+ legacy = LEGACY_KEYS[key]
92
+ Thread.current[legacy] = value if legacy
93
+ end
94
+
95
+ # The calling thread's own (unscoped) state.
96
+ def base
97
+ thread = Thread.current
98
+ own = thread.thread_variable_get(BASE)
99
+ unless own
100
+ own = {}
101
+ thread.thread_variable_set(BASE, own)
102
+ end
103
+ own
104
+ end
105
+
106
+ def with(values)
107
+ thread = Thread.current
108
+ previous = current_scope
109
+ scope = Scope.new(previous, values)
110
+ legacy_before = values.keys.map { |key| LEGACY_KEYS[key] }.compact.map { |legacy| [legacy, thread[legacy]] }
111
+
112
+ install(scope)
113
+ values.each do |key, value|
114
+ legacy = LEGACY_KEYS[key]
115
+ thread[legacy] = value if legacy
116
+ end
117
+
118
+ begin
119
+ yield
120
+ ensure
121
+ scope.close!
122
+ install(previous)
123
+ legacy_before.each { |legacy, value| thread[legacy] = value }
124
+ end
125
+ end
126
+
127
+ # A SafetyError raised in a spawned thread is also recorded on the thread
128
+ # that opened the guarded execution, because that is where the executor
129
+ # looks for errors the model's code rescued and carried on from.
130
+ def record_error(error)
131
+ self[:last_safety_error] = error
132
+ sink = self[:error_sink]
133
+ sink[:last_safety_error] = error if sink
134
+ end
135
+
136
+ # Clear everything held for the calling thread. For tests.
137
+ def reset!
138
+ thread = Thread.current
139
+ thread.thread_variable_set(BASE, nil)
140
+ install(nil)
141
+ LEGACY_KEYS.each_value { |legacy| thread[legacy] = nil }
142
+ end
143
+
144
+ private
145
+
146
+ # The thread variable wins over fiber storage: a fiber created during an
147
+ # earlier execution (an enumerator kept in a variable, say) still carries
148
+ # that execution's closed scope in its storage, and must see the current
149
+ # one. Fiber storage is only what a newly spawned thread starts from.
150
+ def current_scope
151
+ Thread.current.thread_variable_get(SCOPE) || (INHERITABLE ? Fiber[SCOPE] : nil)
152
+ end
153
+
154
+ def install(scope)
155
+ Thread.current.thread_variable_set(SCOPE, scope)
156
+ Fiber[SCOPE] = scope if INHERITABLE
157
+ end
158
+ end
159
+ end
160
+ end
@@ -13,6 +13,9 @@ module RailsConsoleAi
13
13
  end
14
14
 
15
15
  def format_assistant_message(result)
16
+ # A turn with thinking goes back exactly as it arrived (see ChatResult).
17
+ return { role: 'assistant', content: result.content_blocks } if result.content_blocks
18
+
16
19
  # Rebuild the assistant content blocks from the raw response
17
20
  content_blocks = []
18
21
  content_blocks << { 'type' => 'text', 'text' => result.text } if result.text && !result.text.empty?
@@ -85,10 +88,35 @@ module RailsConsoleAi
85
88
  cache_read_input_tokens: usage['cache_read_input_tokens'],
86
89
  cache_write_input_tokens: usage['cache_creation_input_tokens'],
87
90
  tool_calls: tool_calls,
88
- stop_reason: stop
91
+ stop_reason: stop,
92
+ content_blocks: replay_blocks(data)
89
93
  )
90
94
  end
91
95
 
96
+ THINKING_BLOCK_TYPES = %w[thinking redacted_thinking].freeze
97
+
98
+ # The turn's blocks in their original order, or nil when none of them is
99
+ # thinking. Thinking blocks are passed through untouched — the signature
100
+ # covers their content, and with thinking display omitted the `thinking`
101
+ # text is legitimately empty. Empty text blocks are dropped because the
102
+ # API rejects them on the way back in.
103
+ def replay_blocks(data)
104
+ content = data['content']
105
+ return nil unless content.is_a?(Array)
106
+ return nil unless content.any? { |c| THINKING_BLOCK_TYPES.include?(c['type']) }
107
+
108
+ content.map do |c|
109
+ case c['type']
110
+ when *THINKING_BLOCK_TYPES
111
+ c
112
+ when 'text'
113
+ { 'type' => 'text', 'text' => c['text'] } unless c['text'].to_s.empty?
114
+ when 'tool_use'
115
+ { 'type' => 'tool_use', 'id' => c['id'], 'name' => c['name'], 'input' => c['input'] || {} }
116
+ end
117
+ end.compact
118
+ end
119
+
92
120
  # Text content is always rendered as a one-element block array, even though
93
121
  # the API accepts a bare string. The breakpoint below can only be attached
94
122
  # to a block, so a string tail would have to be promoted to a block — and
@@ -164,8 +164,15 @@ module RailsConsoleAi
164
164
 
165
165
  class ProviderError < StandardError; end
166
166
 
167
+ # content_blocks is the assistant turn exactly as the model returned it, in
168
+ # the provider's own request shape, and is only set when the turn contains
169
+ # thinking. A thinking block is signed against everything that came before
170
+ # it, so a turn that has one must be sent back block for block: rebuilding it
171
+ # from `text` and `tool_calls` drops the thinking, and the model then starts
172
+ # every round of a tool loop without the reasoning that led to the last one.
167
173
  ChatResult = Struct.new(:text, :input_tokens, :output_tokens, :tool_calls, :stop_reason,
168
- :cache_read_input_tokens, :cache_write_input_tokens, :cost, keyword_init: true) do
174
+ :cache_read_input_tokens, :cache_write_input_tokens, :cost,
175
+ :content_blocks, keyword_init: true) do
169
176
  def total_tokens
170
177
  (input_tokens || 0) + (output_tokens || 0)
171
178
  end
@@ -1,3 +1,5 @@
1
+ require 'base64'
2
+
1
3
  module RailsConsoleAi
2
4
  module Providers
3
5
  class Bedrock < Base
@@ -10,6 +12,9 @@ module RailsConsoleAi
10
12
  end
11
13
 
12
14
  def format_assistant_message(result)
15
+ # A turn with thinking goes back exactly as it arrived (see ChatResult).
16
+ return { role: 'assistant', content: result.content_blocks } if result.content_blocks
17
+
13
18
  content = []
14
19
  content << { text: result.text } if result.text && !result.text.empty?
15
20
  (result.tool_calls || []).each do |tc|
@@ -78,7 +83,8 @@ module RailsConsoleAi
78
83
  cache_read_input_tokens: usage.respond_to?(:cache_read_input_tokens) ? usage.cache_read_input_tokens : nil,
79
84
  cache_write_input_tokens: usage.respond_to?(:cache_write_input_tokens) ? usage.cache_write_input_tokens : nil,
80
85
  tool_calls: tool_calls,
81
- stop_reason: stop
86
+ stop_reason: stop,
87
+ content_blocks: replay_blocks(response)
82
88
  )
83
89
  rescue aws_error_class => e
84
90
  raise ProviderError, "AWS Bedrock error (#{e.class}): #{e.message}"
@@ -128,6 +134,7 @@ module RailsConsoleAi
128
134
  else
129
135
  [{ text: msg[:content].to_s }]
130
136
  end
137
+ content.map! { |block| decode_redacted_reasoning(block) }
131
138
  # Bedrock rejects empty or whitespace-only text blocks in content arrays
132
139
  content.reject! { |block| block.is_a?(Hash) && block.key?(:text) && !block.key?(:tool_use) && !block.key?(:tool_result) && block[:text].to_s.strip.empty? }
133
140
  # Bedrock also rejects messages with completely empty content arrays
@@ -188,6 +195,47 @@ module RailsConsoleAi
188
195
  formatted
189
196
  end
190
197
 
198
+ # The turn's blocks in their original order as Converse request hashes, or
199
+ # nil when none of them is reasoning (Converse's name for thinking).
200
+ def replay_blocks(response)
201
+ content = response.output&.message&.content
202
+ return nil unless content.is_a?(Array)
203
+
204
+ blocks = content.map { |c| replay_block(c) }.compact
205
+ blocks.any? { |b| b.key?(:reasoning_content) } ? blocks : nil
206
+ end
207
+
208
+ def replay_block(block)
209
+ if block.respond_to?(:tool_use) && (tool_use = block.tool_use)
210
+ { tool_use: { tool_use_id: tool_use.tool_use_id, name: tool_use.name, input: tool_use.input || {} } }
211
+ elsif block.respond_to?(:text) && block.text
212
+ { text: block.text } unless block.text.empty?
213
+ elsif block.respond_to?(:reasoning_content) && (reasoning = block.reasoning_content)
214
+ replay_reasoning(reasoning)
215
+ end
216
+ end
217
+
218
+ # Redacted reasoning is opaque bytes. The conversation is stored as JSON,
219
+ # which cannot hold them, so it is kept base64-encoded and decoded again
220
+ # on the way out (#decode_redacted_reasoning).
221
+ def replay_reasoning(reasoning)
222
+ if reasoning.respond_to?(:reasoning_text) && (text = reasoning.reasoning_text)
223
+ body = { text: text.text.to_s }
224
+ body[:signature] = text.signature if text.signature
225
+ { reasoning_content: { reasoning_text: body } }
226
+ elsif reasoning.respond_to?(:redacted_content) && reasoning.redacted_content
227
+ { reasoning_content: { redacted_content_base64: Base64.strict_encode64(reasoning.redacted_content) } }
228
+ end
229
+ end
230
+
231
+ def decode_redacted_reasoning(block)
232
+ encoded = block.is_a?(Hash) && block[:reasoning_content].is_a?(Hash) &&
233
+ block[:reasoning_content][:redacted_content_base64]
234
+ return block unless encoded
235
+
236
+ { reasoning_content: { redacted_content: Base64.strict_decode64(encoded) } }
237
+ end
238
+
191
239
  def extract_text(response)
192
240
  content = response.output&.message&.content
193
241
  return '' unless content.is_a?(Array)
@@ -1,3 +1,6 @@
1
+ require 'rails_console_ai/guard_state'
2
+ require 'rails_console_ai/sql_writes'
3
+
1
4
  module RailsConsoleAi
2
5
  # Raised by safety guards to block dangerous operations.
3
6
  # Host apps should raise this error in their custom guards.
@@ -5,21 +8,21 @@ module RailsConsoleAi
5
8
  class SafetyError < StandardError
6
9
  attr_reader :guard, :blocked_key
7
10
 
8
- # Thread-local tracking so the executor can detect safety errors
9
- # even when swallowed by a rescue inside eval'd code.
11
+ # Tracked so the executor can detect safety errors even when swallowed by a
12
+ # rescue inside eval'd code — including code running in a thread it spawned.
10
13
  def self.last_raised
11
- Thread.current[:rails_console_ai_last_safety_error]
14
+ GuardState[:last_safety_error]
12
15
  end
13
16
 
14
17
  def self.clear!
15
- Thread.current[:rails_console_ai_last_safety_error] = nil
18
+ GuardState[:last_safety_error] = nil
16
19
  end
17
20
 
18
21
  def initialize(message, guard: nil, blocked_key: nil)
19
22
  super(message)
20
23
  @guard = guard
21
24
  @blocked_key = blocked_key
22
- Thread.current[:rails_console_ai_last_safety_error] = self
25
+ GuardState.record_error(self)
23
26
  end
24
27
  end
25
28
 
@@ -41,31 +44,26 @@ module RailsConsoleAi
41
44
  end
42
45
 
43
46
  def enabled?
44
- @enabled && !Thread.current[:rails_console_ai_guards_disabled]
47
+ @enabled && !GuardState[:guards_disabled]
45
48
  end
46
49
 
47
50
  def enable!
48
- Thread.current[:rails_console_ai_guards_disabled] = nil
51
+ GuardState[:guards_disabled] = nil
49
52
  end
50
53
 
51
54
  def disable!
52
- Thread.current[:rails_console_ai_guards_disabled] = true
55
+ GuardState[:guards_disabled] = true
53
56
  end
54
57
 
55
58
  # Hard sandbox: block ALL database access (reads and writes) for the duration of the
56
59
  # block. Used to fence in sub-agents that must never touch the DB (e.g. the
57
- # output-explorer, which only examines an in-memory string). Scoped via thread-local,
58
- # so it covers synchronous work in the calling thread and is restored afterward —
59
- # nestable, and independent of enable!/disable! and the registered guard set.
60
- def with_database_blocked
60
+ # output-explorer, which only examines an in-memory string). Scoped to the block
61
+ # (see GuardState), so it covers the calling thread and anything it spawns, and is
62
+ # restored afterward — nestable, and independent of enable!/disable! and the
63
+ # registered guard set.
64
+ def with_database_blocked(&block)
61
65
  BuiltinGuards.ensure_write_blocker_installed!
62
- prev = Thread.current[:rails_console_ai_block_all_db]
63
- Thread.current[:rails_console_ai_block_all_db] = true
64
- begin
65
- yield
66
- ensure
67
- Thread.current[:rails_console_ai_block_all_db] = prev
68
- end
66
+ GuardState.with(block_all_db: true, &block)
69
67
  end
70
68
 
71
69
  def empty?
@@ -83,9 +81,10 @@ module RailsConsoleAi
83
81
  @allowlist[guard_name] << key unless @allowlist[guard_name].include?(key)
84
82
  end
85
83
 
86
- # Add a thread-local allowlist entry (runtime "allow for this session").
84
+ # Add a runtime allowlist entry ("allow for this session"), held by the
85
+ # session's thread.
87
86
  def allow(guard_name, key)
88
- thread_list = Thread.current[:rails_console_ai_allowlist] ||= {}
87
+ thread_list = session_allowlist
89
88
  guard_name = guard_name.to_sym
90
89
  thread_list[guard_name] ||= []
91
90
  thread_list[guard_name] << key unless thread_list[guard_name].include?(key)
@@ -103,14 +102,14 @@ module RailsConsoleAi
103
102
  }
104
103
  # Check global (config-time) allowlist
105
104
  return true if match.call(@allowlist[guard_name])
106
- # Check thread-local (runtime session) allowlist
107
- thread_list = Thread.current[:rails_console_ai_allowlist]
105
+ # Check the runtime (session) allowlist
106
+ thread_list = GuardState[:allowlist]
108
107
  return true if thread_list && match.call(thread_list[guard_name])
109
108
  false
110
109
  end
111
110
 
112
111
  def allowlist
113
- thread_list = Thread.current[:rails_console_ai_allowlist]
112
+ thread_list = GuardState[:allowlist]
114
113
  return @allowlist unless thread_list
115
114
  merged = @allowlist.dup
116
115
  thread_list.each { |k, v| merged[k] = (merged[k] || []) + v }
@@ -127,17 +126,18 @@ module RailsConsoleAi
127
126
  bypass_set = resolve_bypass_methods(channel_mode)
128
127
  Array(additional_bypass_methods).each { |m| bypass_set << m }
129
128
 
130
- prev_active = Thread.current[:rails_console_ai_session_active]
131
- prev_bypass = Thread.current[:rails_console_ai_bypass_methods]
132
- Thread.current[:rails_console_ai_session_active] = true
133
- Thread.current[:rails_console_ai_bypass_methods] = bypass_set
134
- begin
129
+ # The allowlist and the error sink are carried in the scope so threads the
130
+ # guarded code spawns consult the session's allowlist and report blocked
131
+ # operations back to the session's thread.
132
+ GuardState.with(
133
+ session_active: true,
134
+ bypass_methods: bypass_set,
135
+ allowlist: session_allowlist,
136
+ error_sink: GuardState.base
137
+ ) do
135
138
  @guards.values.reduce(block) { |inner, guard|
136
139
  -> { guard.call(&inner) }
137
140
  }.call
138
- ensure
139
- Thread.current[:rails_console_ai_session_active] = prev_active
140
- Thread.current[:rails_console_ai_bypass_methods] = prev_bypass
141
141
  end
142
142
  end
143
143
 
@@ -163,7 +163,7 @@ module RailsConsoleAi
163
163
 
164
164
  bypass_mod = Module.new do
165
165
  define_method(method_sym) do |*args, &blk|
166
- if Thread.current[:rails_console_ai_bypass_methods]&.include?(spec)
166
+ if GuardState[:bypass_methods]&.include?(spec)
167
167
  RailsConsoleAi.configuration.safety_guards.without_guards { super(*args, &blk) }
168
168
  else
169
169
  super(*args, &blk)
@@ -181,6 +181,13 @@ module RailsConsoleAi
181
181
 
182
182
  private
183
183
 
184
+ # The runtime allowlist in effect: the enclosing guarded execution's when
185
+ # there is one (so a spawned thread adds to the session's list, not its own),
186
+ # otherwise the calling thread's.
187
+ def session_allowlist
188
+ GuardState[:allowlist] || (GuardState[:allowlist] = {})
189
+ end
190
+
184
191
  def resolve_bypass_methods(channel_mode)
185
192
  config = RailsConsoleAi.configuration
186
193
  methods = Set.new(config.bypass_guards_for_methods)
@@ -207,14 +214,10 @@ module RailsConsoleAi
207
214
  public
208
215
 
209
216
  # Bypass all safety guards for the duration of the block.
210
- # Thread-safe: uses a thread-local flag that is restored after the block,
211
- # even if the block raises an exception.
212
- def without_guards
213
- prev = Thread.current[:rails_console_ai_bypass_guards]
214
- Thread.current[:rails_console_ai_bypass_guards] = true
215
- yield
216
- ensure
217
- Thread.current[:rails_console_ai_bypass_guards] = prev
217
+ # Thread-safe: scoped to the calling thread and anything it spawns inside
218
+ # the block (see GuardState), and restored after the block even if it raises.
219
+ def without_guards(&block)
220
+ GuardState.with(bypass_guards: true, &block)
218
221
  end
219
222
  end
220
223
 
@@ -222,11 +225,8 @@ module RailsConsoleAi
222
225
  # Works on all Rails versions (5+) and all database adapters.
223
226
  # Prepends a write-intercepting module once, controlled by a thread-local flag.
224
227
  module BuiltinGuards
225
- # Blocks INSERT, UPDATE, DELETE, DROP, CREATE, ALTER, TRUNCATE
228
+ # Blocks statements that write — see SqlWrites for what counts as one.
226
229
  module WriteBlocker
227
- WRITE_PATTERN = /\A\s*(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b/i
228
- TABLE_PATTERN = /\b(?:INTO|FROM|UPDATE|TABLE|TRUNCATE)\s+[`"]?(\w+)[`"]?/i
229
-
230
230
  private
231
231
 
232
232
  # Hard sandbox: when active, block ALL database access (reads and writes), not just
@@ -234,7 +234,7 @@ module RailsConsoleAi
234
234
  # output-explorer, which only examines an in-memory string). Deliberately does NOT
235
235
  # honor the bypass flag — it is a true wall, not a safe-mode toggle.
236
236
  def rails_console_ai_check_db_blocked!(_sql)
237
- return unless Thread.current[:rails_console_ai_block_all_db]
237
+ return unless GuardState[:block_all_db]
238
238
 
239
239
  raise RailsConsoleAi::SafetyError.new(
240
240
  "Database access is disabled here. The captured data is in the `output` " \
@@ -245,20 +245,34 @@ module RailsConsoleAi
245
245
  end
246
246
 
247
247
  def rails_console_ai_check_write!(sql)
248
- return if Thread.current[:rails_console_ai_bypass_guards]
249
- return unless Thread.current[:rails_console_ai_block_writes] && sql.match?(WRITE_PATTERN)
248
+ return unless GuardState[:block_writes]
250
249
 
251
- table = sql.match(TABLE_PATTERN)&.captures&.first
250
+ writes = SqlWrites.find(sql, mysql: rails_console_ai_mysql?)
251
+ return if writes.empty?
252
+ return if GuardState[:bypass_guards]
253
+
254
+ # Every write in the statement has to be allowed, not just the first:
255
+ # `WITH d AS (DELETE FROM a ...) INSERT INTO b ...` touches both.
252
256
  guards = RailsConsoleAi.configuration.safety_guards
253
- return if table && guards.allowed?(:database_writes, table)
257
+ blocked = writes.find do |write|
258
+ !(write.table && [write.table, write.qualified_table].uniq.any? { |key| guards.allowed?(:database_writes, key) })
259
+ end
260
+ return unless blocked
254
261
 
255
262
  raise RailsConsoleAi::SafetyError.new(
256
- "Database write blocked: #{sql.strip.split(/\s+/).first(3).join(' ')}...",
263
+ "Database write blocked: #{blocked.summary}...",
257
264
  guard: :database_writes,
258
- blocked_key: table
265
+ blocked_key: blocked.table
259
266
  )
260
267
  end
261
268
 
269
+ # MySQL reads comments, string escapes and double quotes differently from
270
+ # every other database, which changes where a statement's code starts and
271
+ # stops.
272
+ def rails_console_ai_mysql?
273
+ respond_to?(:adapter_name) && adapter_name.to_s.match?(/mysql|trilogy|maria/i)
274
+ end
275
+
262
276
  public
263
277
 
264
278
  def execute(sql, *args, **kwargs)
@@ -295,21 +309,48 @@ module RailsConsoleAi
295
309
  def self.database_writes
296
310
  ->(& block) {
297
311
  ensure_write_blocker_installed!
298
- Thread.current[:rails_console_ai_block_writes] = true
299
- begin
300
- block.call
301
- ensure
302
- Thread.current[:rails_console_ai_block_writes] = false
303
- end
312
+ GuardState.with(block_writes: true, &block)
304
313
  }
305
314
  end
306
315
 
316
+ # Rails 7.1 moved the work beneath the public methods WriteBlocker wraps.
317
+ # select_all, find_by_sql and insert_all/upsert_all now go straight to
318
+ # internal_exec_query, and from Rails 8 everything funnels into raw_execute,
319
+ # so a bulk insert, or a write passed to a select method, never reached the
320
+ # check — and neither did the reads the hard sandbox is meant to stop.
321
+ LOW_LEVEL_ENTRY_POINTS = %i[internal_exec_query raw_execute].freeze
322
+
323
+ # Built per adapter class, wrapping only the entry points that class has and
324
+ # keeping their visibility: defining one where Rails doesn't would make
325
+ # respond_to? lie to anything that feature-tests the adapter.
326
+ def self.low_level_write_blocker(adapter_class)
327
+ Module.new do
328
+ LOW_LEVEL_ENTRY_POINTS.each do |name|
329
+ visibility =
330
+ if adapter_class.private_method_defined?(name) then :private
331
+ elsif adapter_class.protected_method_defined?(name) then :protected
332
+ elsif adapter_class.public_method_defined?(name) then :public
333
+ end
334
+ next unless visibility
335
+
336
+ define_method(name) do |sql, *args, **kwargs, &block|
337
+ rails_console_ai_check_db_blocked!(sql)
338
+ rails_console_ai_check_write!(sql)
339
+ super(sql, *args, **kwargs, &block)
340
+ end
341
+ send(visibility, name)
342
+ end
343
+ end
344
+ end
345
+
307
346
  def self.ensure_write_blocker_installed!
308
347
  return if @write_blocker_installed
309
348
 
310
- connection = ActiveRecord::Base.connection
311
- unless connection.class.ancestors.include?(WriteBlocker)
312
- connection.class.prepend(WriteBlocker)
349
+ adapter_class = ActiveRecord::Base.connection.class
350
+ unless adapter_class.ancestors.include?(WriteBlocker)
351
+ # Prepended first so WriteBlocker's own (private) checks sit above it.
352
+ adapter_class.prepend(low_level_write_blocker(adapter_class))
353
+ adapter_class.prepend(WriteBlocker)
313
354
  end
314
355
  @write_blocker_installed = true
315
356
  end
@@ -321,8 +362,8 @@ module RailsConsoleAi
321
362
  SAFE_METHODS = %w[GET HEAD OPTIONS TRACE].freeze
322
363
 
323
364
  def request(req, *args, &block)
324
- if Thread.current[:rails_console_ai_block_http] && !SAFE_METHODS.include?(req.method)
325
- return super if Thread.current[:rails_console_ai_bypass_guards]
365
+ if GuardState[:block_http] && !SAFE_METHODS.include?(req.method)
366
+ return super if GuardState[:bypass_guards]
326
367
 
327
368
  host = @address.to_s
328
369
  guards = RailsConsoleAi.configuration.safety_guards
@@ -341,18 +382,13 @@ module RailsConsoleAi
341
382
  def self.http_mutations
342
383
  ->(&block) {
343
384
  ensure_http_blocker_installed!
344
- Thread.current[:rails_console_ai_block_http] = true
345
- begin
346
- block.call
347
- ensure
348
- Thread.current[:rails_console_ai_block_http] = false
349
- end
385
+ GuardState.with(block_http: true, &block)
350
386
  }
351
387
  end
352
388
 
353
389
  def self.mailers
354
390
  ->(&block) {
355
- return block.call if Thread.current[:rails_console_ai_bypass_guards]
391
+ return block.call if GuardState[:bypass_guards]
356
392
 
357
393
  old_value = ActionMailer::Base.perform_deliveries
358
394
  ActionMailer::Base.perform_deliveries = false
@@ -388,8 +424,8 @@ module RailsConsoleAi
388
424
  end
389
425
 
390
426
  def self.check_in_process_request!(http_method, path)
391
- return unless Thread.current[:rails_console_ai_block_in_process_requests]
392
- return if Thread.current[:rails_console_ai_bypass_guards]
427
+ return unless GuardState[:block_in_process_requests]
428
+ return if GuardState[:bypass_guards]
393
429
 
394
430
  key = path.to_s
395
431
  guards = RailsConsoleAi.configuration.safety_guards
@@ -409,13 +445,7 @@ module RailsConsoleAi
409
445
  def self.in_process_requests
410
446
  ->(&block) {
411
447
  ensure_in_process_blocker_installed!
412
- prev = Thread.current[:rails_console_ai_block_in_process_requests]
413
- Thread.current[:rails_console_ai_block_in_process_requests] = true
414
- begin
415
- block.call
416
- ensure
417
- Thread.current[:rails_console_ai_block_in_process_requests] = prev
418
- end
448
+ GuardState.with(block_in_process_requests: true, &block)
419
449
  }
420
450
  end
421
451
 
@@ -430,7 +430,7 @@ module RailsConsoleAi
430
430
  user_name: user_name
431
431
  )
432
432
 
433
- sandbox_binding = Object.new.instance_eval { binding }
433
+ sandbox_binding = RailsConsoleAi.sandbox_binding
434
434
  engine = ConversationEngine.new(
435
435
  binding_context: sandbox_binding,
436
436
  channel: channel,
@@ -589,7 +589,7 @@ module RailsConsoleAi
589
589
  user_name: user_name
590
590
  )
591
591
 
592
- sandbox_binding = Object.new.instance_eval { binding }
592
+ sandbox_binding = RailsConsoleAi.sandbox_binding
593
593
  engine = ConversationEngine.new(
594
594
  binding_context: sandbox_binding,
595
595
  channel: channel,
@@ -1025,7 +1025,7 @@ module RailsConsoleAi
1025
1025
 
1026
1026
  channel = Channel::Slack.new(slack_bot: self, channel_id: "boot", thread_ts: "boot")
1027
1027
  engine = ConversationEngine.new(
1028
- binding_context: Object.new.instance_eval { binding },
1028
+ binding_context: RailsConsoleAi.sandbox_binding,
1029
1029
  channel: channel
1030
1030
  )
1031
1031
  puts "\nFull system prompt for Slack sessions:"