Module: RailsConsoleAi

Defined in:
lib/rails_console_ai.rb,
lib/rails_console_ai/repl.rb,
lib/rails_console_ai/engine.rb,
lib/rails_console_ai/railtie.rb,
lib/rails_console_ai/version.rb,
lib/rails_console_ai/executor.rb,
lib/rails_console_ai/slack_bot.rb,
lib/rails_console_ai/sub_agent.rb,
lib/rails_console_ai/channel/api.rb,
lib/rails_console_ai/prefixed_io.rb,
app/models/rails_console_ai/agent.rb,
app/models/rails_console_ai/skill.rb,
lib/rails_console_ai/agent_loader.rb,
lib/rails_console_ai/agent_runner.rb,
lib/rails_console_ai/channel/base.rb,
lib/rails_console_ai/skill_loader.rb,
lib/rails_console_ai/storage/base.rb,
app/models/rails_console_ai/memory.rb,
lib/rails_console_ai/channel/slack.rb,
lib/rails_console_ai/configuration.rb,
lib/rails_console_ai/safety_guards.rb,
app/models/rails_console_ai/session.rb,
lib/rails_console_ai/providers/base.rb,
lib/rails_console_ai/session_logger.rb,
lib/rails_console_ai/tools/registry.rb,
lib/rails_console_ai/channel/console.rb,
lib/rails_console_ai/console_methods.rb,
lib/rails_console_ai/context_builder.rb,
lib/rails_console_ai/providers/local.rb,
lib/rails_console_ai/providers/openai.rb,
lib/rails_console_ai/tools/code_tools.rb,
lib/rails_console_ai/channel/sub_agent.rb,
lib/rails_console_ai/providers/bedrock.rb,
lib/rails_console_ai/tools/model_tools.rb,
lib/rails_console_ai/tools/memory_tools.rb,
lib/rails_console_ai/tools/schema_tools.rb,
app/helpers/rails_console_ai/diff_helper.rb,
lib/rails_console_ai/conversation_engine.rb,
lib/rails_console_ai/providers/anthropic.rb,
app/models/rails_console_ai/agent_version.rb,
app/models/rails_console_ai/skill_version.rb,
lib/rails_console_ai/storage/file_storage.rb,
app/models/rails_console_ai/memory_version.rb,
app/helpers/rails_console_ai/sessions_helper.rb,
lib/rails_console_ai/storage/database_storage.rb,
lib/generators/rails_console_ai/install_generator.rb,
app/controllers/rails_console_ai/agents_controller.rb,
app/controllers/rails_console_ai/skills_controller.rb,
app/controllers/rails_console_ai/memories_controller.rb,
app/controllers/rails_console_ai/sessions_controller.rb,
app/controllers/rails_console_ai/application_controller.rb,
app/controllers/rails_console_ai/agent_versions_controller.rb,
app/controllers/rails_console_ai/skill_versions_controller.rb,
app/controllers/rails_console_ai/memory_versions_controller.rb

Defined Under Namespace

Modules: BuiltinGuards, Channel, ConsoleMethods, DiffHelper, Generators, Providers, SessionLogger, SessionsHelper, Storage, Tools Classes: Agent, AgentLoader, AgentRunner, AgentVersion, AgentVersionsController, AgentsController, ApplicationController, Configuration, ConfigurationError, ContextBuilder, ConversationEngine, Engine, Executor, MemoriesController, Memory, MemoryVersion, MemoryVersionsController, PrefixedIO, Railtie, Repl, RunnerTimeoutError, SafetyError, SafetyGuards, Session, SessionsController, Skill, SkillLoader, SkillVersion, SkillVersionsController, SkillsController, SlackBot, SubAgent, TeeIO

Constant Summary collapse

GUIDE_KEY =
'rails_console_ai.md'.freeze
VERSION =
'0.32.0'.freeze

Class Method Summary collapse

Class Method Details

.abort_agent(session_id) ⇒ Object

Abort a queued or running agent run. Returns true if the run was aborted, false if it had already finished (or doesn't exist). Queued runs are never picked up; a run already executing keeps going but its result is discarded when it completes.



107
108
109
110
111
# File 'lib/rails_console_ai.rb', line 107

def abort_agent(session_id)
  n = Session.where(id: session_id, status: %w[queued running])
             .update_all(status: 'aborted', error_message: 'Aborted')
  n == 1
end

.check_agent(session_id) ⇒ Object

Returns the current status string for an enqueued agent run, or nil if the session id is not found. Status is one of: 'queued' | 'running' | 'ready' | 'failed' | 'aborted'.



90
91
92
# File 'lib/rails_console_ai.rb', line 90

def check_agent(session_id)
  Session.where(id: session_id).pluck(:status).first
end

.configurationObject



10
11
12
# File 'lib/rails_console_ai.rb', line 10

def configuration
  @configuration ||= Configuration.new
end

.configure {|configuration| ... } ⇒ Object

Yields:



14
15
16
# File 'lib/rails_console_ai.rb', line 14

def configure
  yield(configuration) if block_given?
end

.current_userObject



52
53
54
# File 'lib/rails_console_ai.rb', line 52

def current_user
  @current_user
end

.current_user=(name) ⇒ Object



56
57
58
# File 'lib/rails_console_ai.rb', line 56

def current_user=(name)
  @current_user = name
end

.get_agent_response(session_id) ⇒ Object

Returns a hash describing an agent run:

{ status:, result:, error: }

All three keys are nil when the session id is not found.



97
98
99
100
101
# File 'lib/rails_console_ai.rb', line 97

def get_agent_response(session_id)
  row = Session.where(id: session_id).select(:status, :result, :error_message).first
  return { status: nil, result: nil, error: nil } unless row
  { status: row.status, result: row.result, error: row.error_message }
end

.loggerObject



39
40
41
42
43
44
45
46
# File 'lib/rails_console_ai.rb', line 39

def logger
  @logger ||= if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
                Rails.logger
              else
                require 'logger'
                Logger.new($stderr, progname: 'RailsConsoleAi')
              end
end

.logger=(log) ⇒ Object



48
49
50
# File 'lib/rails_console_ai.rb', line 48

def logger=(log)
  @logger = log
end

.migrate!Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/rails_console_ai.rb', line 352

def migrate!
  conn = session_connection
  table = 'rails_console_ai_sessions'

  unless conn.table_exists?(table)
    $stderr.puts "\e[33mRailsConsoleAi: #{table} does not exist. Run RailsConsoleAi.setup! first.\e[0m"
    return
  end

  migrations = []

  unless conn.column_exists?(table, :name)
    conn.add_column(table, :name, :string, limit: 255)
    conn.add_index(table, :name) unless conn.index_exists?(table, :name)
    migrations << 'name'
  end

  unless conn.column_exists?(table, :slack_thread_ts)
    conn.add_column(table, :slack_thread_ts, :string, limit: 255)
    conn.add_index(table, :slack_thread_ts) unless conn.index_exists?(table, :slack_thread_ts)
    migrations << 'slack_thread_ts'
  end

  unless conn.column_exists?(table, :slack_channel_name)
    conn.add_column(table, :slack_channel_name, :string, limit: 255)
    migrations << 'slack_channel_name'
  end

  unless conn.column_exists?(table, :status)
    conn.add_column(table, :status, :string, limit: 20)
    migrations << 'status'
  end

  unless conn.column_exists?(table, :result)
    conn.add_column(table, :result, :text)
    migrations << 'result'
  end

  unless conn.column_exists?(table, :error_message)
    conn.add_column(table, :error_message, :text)
    migrations << 'error_message'
  end

  unless conn.column_exists?(table, :options)
    conn.add_column(table, :options, :text)
    migrations << 'options'
  end

  unless conn.index_exists?(table, [:mode, :status], name: 'idx_rca_sessions_mode_status')
    conn.add_index(table, [:mode, :status], name: 'idx_rca_sessions_mode_status')
    migrations << 'idx_rca_sessions_mode_status'
  end

  # Bring skills/memories/agents tables fully up to date. Each setup_* method is
  # internally idempotent (guards both `create_table` and every `add_column` /
  # `add_index`), so running it on an existing install adds any missing columns
  # (e.g. `status`, `approved_by`, `approved_at`) and indexes without disturbing
  # data. Note: we always call these — the previous version skipped them when
  # the base table already existed, which meant column probes never ran on
  # upgrade and methods like Skill#status hit NameError. See:
  # https://github.com/cortfr/rails_console_ai/issues (whichever issue you file)
  pre_columns = {
    skills:   table_columns(conn, 'rails_console_ai_skills'),
    memories: table_columns(conn, 'rails_console_ai_memories'),
    agents:   table_columns(conn, 'rails_console_ai_agents')
  }

  setup_skills_tables!(conn)
  setup_memories_tables!(conn)
  setup_agents_tables!(conn)

  [[:skills, 'rails_console_ai_skills'], [:memories, 'rails_console_ai_memories'], [:agents, 'rails_console_ai_agents']].each do |key, name|
    post = table_columns(conn, name)
    added = post - pre_columns[key]
    migrations.concat(added.map { |c| "#{name}.#{c}" }) unless added.empty?
  end

  if migrations.empty?
    $stdout.puts "\e[32mRailsConsoleAi: #{table} is up to date.\e[0m"
  else
    RailsConsoleAi::Session.reset_column_information if defined?(RailsConsoleAi::Session)
    $stdout.puts "\e[32mRailsConsoleAi: added columns: #{migrations.join(', ')}.\e[0m"
  end
rescue => e
  $stderr.puts "\e[31mRailsConsoleAi migrate failed: #{e.class}: #{e.message}\e[0m"
end

.reset_configuration!Object



18
19
20
21
# File 'lib/rails_console_ai.rb', line 18

def reset_configuration!
  @configuration = Configuration.new
  reset_storage!
end

.reset_storage!Object



35
36
37
# File 'lib/rails_console_ai.rb', line 35

def reset_storage!
  @storage = nil
end

.run_agent(query, name: nil, user_name: nil, use_thinking_model: false, max_wall_clock_seconds: 600) ⇒ Object

Enqueue an agent run. Returns the Integer session id immediately; the actual work is picked up by rake rails_console_ai:agents.

use_thinking_model: run on the configured thinking-tier model max_wall_clock_seconds: hard kill the run after N seconds (nil = no cap)



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/rails_console_ai.rb', line 65

def run_agent(query, name: nil, user_name: nil,
              use_thinking_model: false,
              max_wall_clock_seconds: 600)
  require 'rails_console_ai/session_logger'
  options = {
    'use_thinking_model'     => !!use_thinking_model,
    'max_wall_clock_seconds' => max_wall_clock_seconds
  }
  id = SessionLogger.log(
    query: query,
    conversation: [],
    mode: 'agent_api',
    name: name,
    user_name: user_name,
    status: 'queued',
    executed: false,
    options: options
  )
  raise 'Failed to enqueue agent run (session logging disabled or table missing)' unless id
  id
end

.setup!Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/rails_console_ai.rb', line 147

def setup!
  conn = session_connection
  table = 'rails_console_ai_sessions'

  unless conn.table_exists?(table)
    conn.create_table(table) do |t|
      t.text    :query,         null: false
      t.text    :conversation,  null: false
      t.integer :input_tokens,  default: 0
      t.integer :output_tokens, default: 0
      t.string  :user_name,     limit: 255
      t.string  :mode,          limit: 20, null: false
      t.text    :code_executed
      t.text    :code_output
      t.text    :code_result
      t.text    :console_output
      t.boolean :executed,      default: false
      t.string  :provider,      limit: 50
      t.string  :model,         limit: 100
      t.string  :name,          limit: 255
      t.string  :slack_thread_ts, limit: 255
      t.string  :slack_channel_name, limit: 255
      t.integer :duration_ms
      t.text    :options
      t.datetime :created_at,   null: false
    end

    conn.add_index(table, :created_at)
    conn.add_index(table, :user_name)
    conn.add_index(table, :name)
    conn.add_index(table, :slack_thread_ts)

    $stdout.puts "\e[32mRailsConsoleAi: created #{table} table.\e[0m"
  end

  setup_skills_tables!(conn)
  setup_memories_tables!(conn)
  setup_agents_tables!(conn)

  migrate!
rescue => e
  $stderr.puts "\e[31mRailsConsoleAi setup failed: #{e.class}: #{e.message}\e[0m"
end

.setup_agents_tables!(conn) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/rails_console_ai.rb', line 306

def setup_agents_tables!(conn)
  agents_table   = 'rails_console_ai_agents'
  versions_table = 'rails_console_ai_agent_versions'

  if conn.table_exists?(agents_table) && !conn.column_exists?(agents_table, :content)
    conn.drop_table(agents_table)
    $stdout.puts "\e[33mRailsConsoleAi: dropped legacy #{agents_table}.\e[0m"
  end
  if conn.table_exists?(versions_table) && !conn.column_exists?(versions_table, :content)
    conn.drop_table(versions_table)
    $stdout.puts "\e[33mRailsConsoleAi: dropped legacy #{versions_table}.\e[0m"
  end

  unless conn.table_exists?(agents_table)
    conn.create_table(agents_table) do |t|
      t.string   :name,        limit: 255, null: false
      t.text     :content,     null: false
      t.string   :status,      limit: 20,  default: 'proposed', null: false
      t.string   :approved_by, limit: 255
      t.datetime :approved_at
      t.integer  :use_count,   default: 0, null: false
      t.datetime :last_used_at
      t.datetime :created_at,  null: false
      t.datetime :updated_at,  null: false
    end
    conn.add_index(agents_table, :name, unique: true)
    conn.add_index(agents_table, :status)
    $stdout.puts "\e[32mRailsConsoleAi: created #{agents_table} table.\e[0m"
  end

  unless conn.table_exists?(versions_table)
    conn.create_table(versions_table) do |t|
      t.integer  :agent_id
      t.string   :name,        limit: 255
      t.text     :content
      t.string   :status,      limit: 20
      t.string   :edited_by,   limit: 255
      t.text     :change_note
      t.datetime :created_at,  null: false
    end
    conn.add_index(versions_table, :agent_id)
    conn.add_index(versions_table, :created_at)
    $stdout.puts "\e[32mRailsConsoleAi: created #{versions_table} table.\e[0m"
  end
end

.setup_memories_tables!(conn) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/rails_console_ai.rb', line 240

def setup_memories_tables!(conn)
  memories_table = 'rails_console_ai_memories'
  versions_table = 'rails_console_ai_memory_versions'

  if conn.table_exists?(memories_table) && !conn.column_exists?(memories_table, :content)
    conn.drop_table(memories_table)
    $stdout.puts "\e[33mRailsConsoleAi: dropped legacy #{memories_table}.\e[0m"
  end
  if conn.table_exists?(versions_table) && !conn.column_exists?(versions_table, :content)
    conn.drop_table(versions_table)
    $stdout.puts "\e[33mRailsConsoleAi: dropped legacy #{versions_table}.\e[0m"
  end

  unless conn.table_exists?(memories_table)
    conn.create_table(memories_table) do |t|
      t.string   :name,        limit: 255, null: false
      t.text     :content,     null: false
      t.string   :status,      limit: 20,  default: 'proposed', null: false
      t.string   :approved_by, limit: 255
      t.datetime :approved_at
      t.integer  :use_count,   default: 0, null: false
      t.datetime :last_used_at
      t.datetime :created_at,  null: false
      t.datetime :updated_at,  null: false
    end
    conn.add_index(memories_table, :name, unique: true)
    conn.add_index(memories_table, :status)
    $stdout.puts "\e[32mRailsConsoleAi: created #{memories_table} table.\e[0m"
  end

  # Existing installs have the content-based memories table but predate the
  # approval columns — the drop-on-missing-content guard above won't fire for
  # them, so add the columns in place. Memories created before approval existed
  # were trusted under the old no-approval regime, so grandfather them to
  # "approved" rather than yanking them out from under the AI; only memories
  # created from now on start in "proposed".
  if conn.table_exists?(memories_table) && !conn.column_exists?(memories_table, :status)
    conn.add_column(memories_table, :status, :string, limit: 20, default: 'proposed', null: false)
    conn.execute("UPDATE #{conn.quote_table_name(memories_table)} SET status = 'approved'")
  end
  if conn.table_exists?(memories_table)
    conn.add_column(memories_table, :approved_by, :string, limit: 255) unless conn.column_exists?(memories_table, :approved_by)
    conn.add_column(memories_table, :approved_at, :datetime) unless conn.column_exists?(memories_table, :approved_at)
    conn.add_index(memories_table, :status) unless conn.index_exists?(memories_table, :status)
  end

  unless conn.table_exists?(versions_table)
    conn.create_table(versions_table) do |t|
      t.integer  :memory_id
      t.string   :name,        limit: 255
      t.text     :content
      t.string   :status,      limit: 20
      t.string   :edited_by,   limit: 255
      t.text     :change_note
      t.datetime :created_at,  null: false
    end
    conn.add_index(versions_table, :memory_id)
    conn.add_index(versions_table, :created_at)
    $stdout.puts "\e[32mRailsConsoleAi: created #{versions_table} table.\e[0m"
  end

  if conn.table_exists?(versions_table) && !conn.column_exists?(versions_table, :status)
    conn.add_column(versions_table, :status, :string, limit: 20)
  end
end

.setup_skills_tables!(conn) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/rails_console_ai.rb', line 191

def setup_skills_tables!(conn)
  skills_table   = 'rails_console_ai_skills'
  versions_table = 'rails_console_ai_skill_versions'

  # Old shape had per-field columns (body, tags, bypass_guards_for_methods,
  # description). New shape stores the raw .md in `content`. Pre-production,
  # so we drop and recreate when the old shape is detected.
  if conn.table_exists?(skills_table) && !conn.column_exists?(skills_table, :content)
    conn.drop_table(skills_table)
    $stdout.puts "\e[33mRailsConsoleAi: dropped legacy #{skills_table} (replaced with single-content schema).\e[0m"
  end
  if conn.table_exists?(versions_table) && !conn.column_exists?(versions_table, :content)
    conn.drop_table(versions_table)
    $stdout.puts "\e[33mRailsConsoleAi: dropped legacy #{versions_table}.\e[0m"
  end

  unless conn.table_exists?(skills_table)
    conn.create_table(skills_table) do |t|
      t.string   :name,        limit: 255, null: false
      t.text     :content,     null: false
      t.string   :status,      limit: 20,  default: 'proposed', null: false
      t.string   :approved_by, limit: 255
      t.datetime :approved_at
      t.integer  :use_count,   default: 0, null: false
      t.datetime :last_used_at
      t.datetime :created_at,  null: false
      t.datetime :updated_at,  null: false
    end
    conn.add_index(skills_table, :name, unique: true)
    conn.add_index(skills_table, :status)
    $stdout.puts "\e[32mRailsConsoleAi: created #{skills_table} table.\e[0m"
  end

  unless conn.table_exists?(versions_table)
    conn.create_table(versions_table) do |t|
      t.integer  :skill_id
      t.string   :name,        limit: 255
      t.text     :content
      t.string   :status,      limit: 20
      t.string   :edited_by,   limit: 255
      t.text     :change_note
      t.datetime :created_at,  null: false
    end
    conn.add_index(versions_table, :skill_id)
    conn.add_index(versions_table, :created_at)
    $stdout.puts "\e[32mRailsConsoleAi: created #{versions_table} table.\e[0m"
  end
end

.statusObject



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/rails_console_ai.rb', line 113

def status
  c = configuration
  key = c.resolved_api_key
  masked_key = if key.nil? || key.empty? || key == 'no-key'
                 c.provider == :local ? "\e[32m(not required)\e[0m" : "\e[31m(not set)\e[0m"
               else
                 key[0..6] + '...' + key[-4..-1]
               end

  lines = []
  lines << "\e[36m[RailsConsoleAi v#{VERSION}]\e[0m"
  lines << "  Provider:       #{c.provider}"
  lines << "  Model:          #{c.resolved_model}"
  lines << "  API key:        #{masked_key}"
  lines << "  Local URL:      #{c.local_url}" if c.provider == :local
  lines << "  Max tokens:     #{c.max_tokens || '(auto)'}"
  lines << "  Temperature:    #{c.temperature}"
  lines << "  Timeout:        #{c.timeout}s"
  lines << "  Max tool rounds:#{c.max_tool_rounds}"
  lines << "  Auto-execute:   #{c.auto_execute}"
  guards = c.safety_guards
  if guards.empty?
    lines << "  Safe mode:      \e[33m(no guards configured)\e[0m"
  else
    status = guards.enabled? ? "\e[32mON\e[0m" : "\e[31mOFF\e[0m"
    lines << "  Safe mode:      #{status} (#{guards.names.join(', ')})"
  end
  lines << "  Memories:       #{c.memories_enabled}"
  lines << "  Session logging:#{session_table_status}"
  lines << "  Debug:          #{c.debug}"
  $stdout.puts lines.join("\n")
  nil
end

.storageObject



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rails_console_ai.rb', line 23

def storage
  @storage ||= begin
    adapter = configuration.storage_adapter
    if adapter
      adapter
    else
      require 'rails_console_ai/storage/file_storage'
      Storage::FileStorage.new
    end
  end
end

.teardown!Object



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/rails_console_ai.rb', line 439

def teardown!
  conn = session_connection
  table = 'rails_console_ai_sessions'

  unless conn.table_exists?(table)
    $stdout.puts "\e[33mRailsConsoleAi: #{table} does not exist, nothing to remove.\e[0m"
    return
  end

  count = conn.select_value("SELECT COUNT(*) FROM #{conn.quote_table_name(table)}")
  $stdout.print "\e[33mDrop #{table} (#{count} sessions)? [y/N] \e[0m"
  answer = $stdin.gets.to_s.strip.downcase

  unless answer == 'y' || answer == 'yes'
    $stdout.puts "\e[33mCancelled.\e[0m"
    return
  end

  conn.drop_table(table)
  $stdout.puts "\e[32mRailsConsoleAi: dropped #{table}.\e[0m"
rescue => e
  $stderr.puts "\e[31mRailsConsoleAi teardown failed: #{e.class}: #{e.message}\e[0m"
end