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, SafetyError, SafetyGuards, Session, SessionsController, Skill, SkillLoader, SkillVersion, SkillVersionsController, SkillsController, SlackBot, SubAgent, TeeIO

Constant Summary collapse

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

Class Method Summary collapse

Class Method Details

.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’.



78
79
80
# File 'lib/rails_console_ai.rb', line 78

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

.configurationObject



8
9
10
# File 'lib/rails_console_ai.rb', line 8

def configuration
  @configuration ||= Configuration.new
end

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

Yields:



12
13
14
# File 'lib/rails_console_ai.rb', line 12

def configure
  yield(configuration) if block_given?
end

.current_userObject



50
51
52
# File 'lib/rails_console_ai.rb', line 50

def current_user
  @current_user
end

.current_user=(name) ⇒ Object



54
55
56
# File 'lib/rails_console_ai.rb', line 54

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.



85
86
87
88
89
# File 'lib/rails_console_ai.rb', line 85

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



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

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



46
47
48
# File 'lib/rails_console_ai.rb', line 46

def logger=(log)
  @logger = log
end

.migrate!Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
# File 'lib/rails_console_ai.rb', line 336

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.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



16
17
18
19
# File 'lib/rails_console_ai.rb', line 16

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

.reset_storage!Object



33
34
35
# File 'lib/rails_console_ai.rb', line 33

def reset_storage!
  @storage = nil
end

.run_agent(query, name: nil, user_name: nil) ⇒ Object

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



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rails_console_ai.rb', line 60

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

.setup!Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/rails_console_ai.rb', line 125

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.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



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
305
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
# File 'lib/rails_console_ai.rb', line 274

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

  unless conn.table_exists?(agents_table)
    conn.create_table(agents_table) do |t|
      t.string   :name,        limit: 255, null: false
      t.text     :description
      t.text     :body
      t.integer  :max_rounds
      t.string   :model,       limit: 100
      t.text     :tools
      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"
  else
    unless conn.column_exists?(agents_table, :status)
      conn.add_column(agents_table, :status, :string, limit: 20, default: 'proposed', null: false)
      conn.add_index(agents_table, :status) unless conn.index_exists?(agents_table, :status)
    end
    unless conn.column_exists?(agents_table, :approved_by)
      conn.add_column(agents_table, :approved_by, :string, limit: 255)
    end
    unless conn.column_exists?(agents_table, :approved_at)
      conn.add_column(agents_table, :approved_at, :datetime)
    end
    unless conn.column_exists?(agents_table, :use_count)
      conn.add_column(agents_table, :use_count, :integer, default: 0, null: false)
    end
    unless conn.column_exists?(agents_table, :last_used_at)
      conn.add_column(agents_table, :last_used_at, :datetime)
    end
  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     :description
      t.text     :body
      t.integer  :max_rounds
      t.string   :model,       limit: 100
      t.text     :tools
      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



233
234
235
236
237
238
239
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
# File 'lib/rails_console_ai.rb', line 233

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

  unless conn.table_exists?(memories_table)
    conn.create_table(memories_table) do |t|
      t.string   :name,        limit: 255, null: false
      t.text     :description
      t.text     :tags
      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)
    $stdout.puts "\e[32mRailsConsoleAi: created #{memories_table} table.\e[0m"
  else
    unless conn.column_exists?(memories_table, :use_count)
      conn.add_column(memories_table, :use_count, :integer, default: 0, null: false)
    end
    unless conn.column_exists?(memories_table, :last_used_at)
      conn.add_column(memories_table, :last_used_at, :datetime)
    end
  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     :description
      t.text     :tags
      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
end

.setup_skills_tables!(conn) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
# File 'lib/rails_console_ai.rb', line 168

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

  unless conn.table_exists?(skills_table)
    conn.create_table(skills_table) do |t|
      t.string   :name,        limit: 255, null: false
      t.text     :description
      t.text     :body
      t.text     :tags
      t.text     :bypass_guards_for_methods
      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"
  else
    # Idempotent column-add probes for existing installs.
    unless conn.column_exists?(skills_table, :status)
      conn.add_column(skills_table, :status, :string, limit: 20, default: 'proposed', null: false)
      conn.add_index(skills_table, :status) unless conn.index_exists?(skills_table, :status)
    end
    unless conn.column_exists?(skills_table, :approved_by)
      conn.add_column(skills_table, :approved_by, :string, limit: 255)
    end
    unless conn.column_exists?(skills_table, :approved_at)
      conn.add_column(skills_table, :approved_at, :datetime)
    end
    unless conn.column_exists?(skills_table, :use_count)
      conn.add_column(skills_table, :use_count, :integer, default: 0, null: false)
    end
    unless conn.column_exists?(skills_table, :last_used_at)
      conn.add_column(skills_table, :last_used_at, :datetime)
    end
  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     :description
      t.text     :body
      t.text     :tags
      t.text     :bypass_guards_for_methods
      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"
  else
    unless conn.column_exists?(versions_table, :status)
      conn.add_column(versions_table, :status, :string, limit: 20)
    end
  end
end

.statusObject



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/rails_console_ai.rb', line 91

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



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

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



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/rails_console_ai.rb', line 418

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