Class: PWN::Plugins::REPL::AIConsole::Console

Inherits:
Object
  • Object
show all
Defined in:
lib/pwn/plugins/repl/ai_console.rb

Overview

Own the terminal, event pump and the lifetime of exactly one request.

Constant Summary collapse

COLORS =

rubocop:disable Metrics/ClassLength -- cohesive single-owner terminal state machine

{ operator: :operator, task: :task, tool: :tool, result: :result, assistant: :assistant, notice: :notice, warning: :warning }.freeze
PALETTE =
%w[cyan green yellow red white blue magenta black].freeze

Instance Method Summary collapse

Constructor Details

#initialize(pry:, input:, curses:, getch:) ⇒ Console

Returns a new instance of Console.



272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/pwn/plugins/repl/ai_console.rb', line 272

def initialize(pry:, input:, curses:, getch:)
  @pry = pry
  @input = input
  @curses = curses
  @getch = getch
  @events = Queue.new
  @output = EventIO.new(@events)
  @editor = Editor.new
  @timeline = []
  @scroll = nil
  @event_count = @completed_tools = @unseen = 0
  @verbose = true
  @usage = AIConsoleUsage::Tracker.new
end

Instance Method Details

#accept_completion ⇒ Object



895
896
897
898
899
900
901
902
# File 'lib/pwn/plugins/repl/ai_console.rb', line 895

def accept_completion
  refresh_completion if @menu.nil?
  item = @menu && @menu[@menu_index]
  return complete unless item

  @editor.place(item[:text], item[:cursor])
  complete
end

#add(type, text) ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/pwn/plugins/repl/ai_console.rb', line 436

def add(type, text)
  clean = PWN::Redaction.redact(value: text.to_s)
  clean = clean.gsub(/\e\][^\a]*(?:\a|\e\\)/, '').gsub(%r{\e\[[0-?]*[ -/]*[@-~]}, '').gsub(/[\x00-\x08\x0b-\x1f\x7f]/, '')
  return if clean.strip.empty?

  @event_count += 1
  @unseen += 1 if @scroll
  if type == :tool
    @completed_tools += 1
    @last_tool = fit(clean.lines.first.to_s.strip, 80)
  end
  @timeline << [type, bounded_event(clean), Time.now.strftime('%Y-%m-%d %H:%M:%S%z'), {}]
  @rows = nil
  if @timeline.length > 2000
    removed = @timeline.shift
    @scroll = [@scroll - removed[3].fetch(:rows, []).length, 0].max if @scroll
  end
  PWN::Plugins::Log.mirror_tui!(msg: "#{type.to_s.upcase}\n#{clean}") if @pry.config.pwn_ai_debug && type != :notice
end

Artwork has no worker, IO, or request-progress meaning. The existing event-loop repaint supplies its clock, including while requests run.



1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1129

def banner_frame(size, cells: false)
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  session = @pry.config.pwn_ai_session_id.to_s
  if @banner_session != session
    @banner_session = session
    @banner_name = PWN::Banner.mini_names.sample
    @banner_frame_seconds = PWN::Banner.mini_frame_seconds(name: @banner_name)
    @banner_seed = session.bytes.reduce(PWN::Banner::MINI_SEED) { |seed, byte| ((seed * 33) ^ byte) & 0xffffffff }
    @banner_started = now
  end
  cadence = cells ? @banner_frame_seconds : PWN::Banner::MINI_FRAME_SECONDS
  frame = ((now - @banner_started) / cadence).floor % PWN::Banner::MINI_FRAME_COUNT
  return PWN::Banner.mini_cells(name: @banner_name, frame: frame, width: size, height: size, seed: @banner_seed, branding: false) if cells

  art = PWN::Banner.mini_frame(name: @banner_name, frame: frame, width: size, height: size, branding: false)
  canvas = Array.new(size) { ' ' * size }
  top = (size - art.length) / 2
  art.each_with_index { |row, index| canvas[top + index] = row.center(size) }
  canvas
end

#begin_request_metrics ⇒ Object



946
947
948
949
950
# File 'lib/pwn/plugins/repl/ai_console.rb', line 946

def begin_request_metrics
  @started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  @finished_at = @last_tool = nil
  @completed_tools = 0
end

#bounded_event(text) ⇒ Object



908
909
910
911
912
913
914
915
916
917
918
# File 'lib/pwn/plugins/repl/ai_console.rb', line 908

def bounded_event(text)
  return text if text.bytesize <= 16_384

  clipped = +''
  text.each_grapheme_cluster do |grapheme|
    break if clipped.bytesize + grapheme.bytesize > 16_384

    clipped << grapheme
  end
  "#{clipped}\n[display truncated at 16 KiB; full event is not shown]"
end

#box(top, left, height, box_width, title, color = nil) ⇒ Object

rubocop:disable Metrics/ParameterLists -- screen rectangle plus appearance



1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1037

def box(top, left, height, box_width, title, color = nil) # rubocop:disable Metrics/ParameterLists -- screen rectangle plus appearance
  color ||= tone(:border)
  put(top, left, "╭#{'─' * (box_width - 2)}╮", color)
  (1...(height - 1)).each do |row|
    put(top + row, left, '│', color)
    put(top + row, left + box_width - 1, '│', color)
  end
  put(top + height - 1, left, "╰#{'─' * (box_width - 2)}╯", color)
  put(top, left + 2, fit(" #{title} ", box_width - 4), tone(:title)) unless title.empty?
end

#busy? ⇒ Boolean

Returns:

  • (Boolean)


409
410
411
412
# File 'lib/pwn/plugins/repl/ai_console.rb', line 409

def busy?
  request_busy = @worker && (@worker.alive? || @running)
  request_busy || @swarm&.busy?
end

#busy_command(line) ⇒ Object



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
# File 'lib/pwn/plugins/repl/ai_console.rb', line 591

def busy_command(line)
  if line.match?(%r{\A/steer(?:\s|$)})
    if @control.nil?
      add(:warning, 'Choose a swarm job with Ctrl+G, then s to steer it.')
    elsif @command
      add(:warning, '/steer applies to model requests, not local commands. Use /input for a prompt or Ctrl+C to cancel after this command returns.')
    else
      @control.submit(line.sub(%r{\A/steer\s*}, ''))
    end
  elsif line.start_with?('/input ')
    send_tool_input(line)
  elsif line.strip == '/clear'
    clear_view
  elsif line.match?(%r{\A/verbose(?:\s|$)})
    toggle_verbose(line)
  elsif line.start_with?('/swarm') && %w[status tail steer cancel help roster].include?(line.split[1])
    run_swarm(line)
  else
    add(:warning, 'Request running. Settings and new requests wait until idle. Use /steer, /input, /swarm status|steer|cancel, /clear, or /verbose.')
  end
end

#cancel ⇒ Object



521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/pwn/plugins/repl/ai_console.rb', line 521

def cancel
  if busy?
    return if @cancelling

    @cancelling = true
    @control&.stop
    @swarm&.cancel_all
    @tool_input.close unless @tool_input.closed?
    add(:warning, 'Cancellation requested. Waiting for the active tool to finish; work already started is not undone.')
  else
    @editor.replace('')
  end
end

#clear_view ⇒ Object



613
614
615
616
617
618
619
# File 'lib/pwn/plugins/repl/ai_console.rb', line 613

def clear_view
  @timeline = []
  @rows = nil
  @scroll = nil
  @event_count = 0
  add(:notice, 'Session view cleared. Stored conversation was not deleted.')
end

#complete ⇒ Object



646
647
648
649
650
651
652
653
# File 'lib/pwn/plugins/repl/ai_console.rb', line 646

def complete
  result = AIConsoleCommands.complete(line: @editor.text, cursor: @editor.cursor, pry: @pry, swarm: @swarm)
  @menu = result[:items]
  @menu_hint = result[:hint]
  @menu_index = [@menu_index.to_i, @menu.length - 1].min
  @menu_index = 0 if @menu_index.negative?
  @menu = nil if @menu.empty?
end

#disable_shift_enter ⇒ Object



348
349
350
351
352
353
354
355
# File 'lib/pwn/plugins/repl/ai_console.rb', line 348

def disable_shift_enter
  return unless @shift_enter && $stdout.tty?

  $stdout.write("\e[<u\e[>4;0m")
  $stdout.flush
rescue StandardError
  nil
end

#drain ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/pwn/plugins/repl/ai_console.rb', line 414

def drain
  200.times do
    type, text = @events.pop(true)
    if type == :model_prompt
      next if @cancelling || @leaving

      @model_prompt = text
      @model_index = text[:efforts].index(text[:default]) || 0
      @menu = nil
    elsif type == :done
      @worker.join
      finish_request_metrics
      @running = false
      @control = nil
    else
      add(type, text)
    end
  end
rescue ThreadError
  nil
end

#draw ⇒ Object



1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1235

def draw
  if !@getch.is_a?(Proc) && @source.respond_to?(:winsize)
    rows, columns = @source.winsize
    @curses.resizeterm(rows, columns) if rows.positive? && columns.positive? && [rows, columns] != [@curses.lines, @curses.cols]
  end
  @height = @curses.lines
  @width = @curses.cols
  @screen.erase
  @too_small = @height < 14 || @width < 48
  if @too_small
    @menu = nil
    @paste = false
    put(0, 0, 'pwn-ai · terminal too small (48 × 14 minimum)', tone(:status))
    put(1, 0, state, tone(:status))
    put(2, 0, 'Ctrl+C cancel · Ctrl+D back · resize to continue')
    @screen.refresh
    return
  end
  engine = PWN::Env.dig(:ai, :active).to_s
  model = REPL.pwn_ai_engine_model(engine: engine)
  header_height = draw_header(engine, model)
  sidebar = @width >= 100 ? 27 : 0
  pane_width = @width - sidebar - 2
  compose_height = 6
  timeline_height = @height - compose_height - 1 - header_height
  @page_size = timeline_height - 2
  rows = timeline_rows(pane_width - 6)
  @total_rows = rows.length
  @scroll = @scroll.clamp(0, [rows.length - @page_size, 0].max) if @scroll
  session_id = @pry.config.pwn_ai_session_id.to_s
  box(header_height, 0, timeline_height, pane_width, "SESSION #{session_id}")
  start = @scroll || [rows.length - @page_size, 0].max
  rows.slice(start, @page_size).to_a.each_with_index { |(color, row), index| put(header_height + 1 + index, 2, row, color) }
  draw_sidebar(header_height, pane_width + 1, timeline_height) if sidebar.positive?
  compose_y = @height - compose_height - 1
  box(compose_y, 0, compose_height, @width - 1, 'MISSION CONTROL')
  draw_composer(compose_y)
  hint = @menu ? '↑↓/^P/^N select · Tab accept · Esc close' : '↑↓ history · PgUp/PgDn scroll'
  put(@height - 1, 1, "^C cancel ^D back · #{hint} · ^G swarm ^L clear ^R search ^O status · Enter send", tone(:footer))
  draw_menu if @menu
  draw_model_prompt if @model_prompt
  draw_details(engine, model) if @details
  draw_swarm if @workspace
  draw_system_role if @role_editor
  @screen.setpos(*@cursor_position) if @role_editor || !(@details || @workspace)
  @screen.refresh
end

#draw_banner(size) ⇒ Object



1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1150

def draw_banner(size)
  cells = banner_frame(size, cells: true)
  top = [(size - cells.length) / 2, 0].max
  # Clear padding too when the bounded artwork is smaller than the pane.
  size.times { |row| put(row + 1, 1, ' ' * size, @banner_colors ? 16 : nil) }
  cells.first(size).each_with_index do |row, y|
    left = [(size - row.length) / 2, 0].max
    row.first(size).each_with_index do |cell, x|
      index = PALETTE.index(cell[:foreground].to_s)
      background = PALETTE.index(cell[:background].to_s)
      colors = @banner_colors && (@banner_name != :falling_blocks || @banner_two_colors)
      pair = if colors && index && background && (background == 7 || @banner_two_colors)
               background == 7 ? 9 + index : 17 + (background * 8) + index
             end
      # Two occupied halves must remain filled in monochrome too.
      glyph = !pair && cell[:background] != :black ? '█' : cell[:glyph]
      put(top + y + 1, left + x + 1, glyph, pair)
    end
  end
end

#draw_composer(top) ⇒ Object



1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1283

def draw_composer(top)
  return draw_search(top) if @editor.search

  chars = @editor.text.scan(/\X/)
  before = chars.take(@editor.cursor).join
  rows = wrap(@editor.text, @width - 8, words: false)
  prefix = wrap(before, @width - 8, words: false)
  cursor_row = prefix.length - 1
  first = [cursor_row - 2, 0].max
  put(top + 1, 2, '›', tone(:prompt)) if first.zero?
  rows.slice(first, 3).to_a.each_with_index { |row, index| put(top + 1 + index, 4, row, tone(:composer)) }
  hint = @menu ? 'Tab accept · ↑↓/^P/^N select · Esc close' : '^G swarm · Shift+Enter newline · / commands · ^O status'
  put(top + 4, 4, fit(hint, @width - 7), tone(:footer))
  @cursor_position = [top + 1 + cursor_row - first, [4 + width(prefix.last), @width - 3].min]
end

#draw_details(engine, model) ⇒ Object



1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1217

def draw_details(engine, model)
  @screen.erase
  lines = ["Session: #{@pry.config.pwn_ai_session_id}"] + operation_lines + ['SETTINGS']
  rows = lines.flat_map do |line|
    role = ['REQUEST', 'TOKENS', 'SWARM', 'VIEW', 'LAST TOOL', 'SETTINGS'].include?(line) ? :category : :value
    wrap(line, @width - 7).map { |row| [[role, row]] }
  end
  header_lines(engine, model, @width - 7)
  rows.concat(@header_spans)
  @details_page = @height - 5
  @details_total = rows.length
  @details = @details.clamp(0, [rows.length - @details_page, 0].max)
  box(0, 0, @height - 1, @width - 1, "STATUS / SETTINGS · #{@details + 1}/#{rows.length}")
  rows.slice(@details, @details_page).each_with_index { |spans, index| put_spans(index + 1, 3, spans) }
  put(@height - 3, 3, 'PgUp/PgDn Home/End · Esc/^O close', tone(:footer))
  put(@height - 1, 1, '^C cancel  ^D back  ^O close', tone(:footer))
end

#draw_header(engine, model) ⇒ Object



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1199

def draw_header(engine, model)
  header_layout(engine, model)
  content = header_lines(engine, model, @header_text_width)
  # Reserve only the physical minimum: timeline (3), composer (6), footer (1).
  visible = @header_spans.first([@height - 13, 1].max)
  overflow = visible.length < content.length ? ' · ^O full settings' : ''
  height = @header_pane_height || (visible.length + 3)
  left = @header_pane_height || 0
  box(0, left, height, @width - left - 1, "pwn-ai v#{PWN::VERSION}#{overflow}")
  put(1, @header_text_column, fit("#{state} · #{elapsed} · #{scroll_status}", @header_text_width), tone(:status))
  visible.each_with_index { |spans, index| put_spans(2 + index, @header_text_column, spans) }
  if @header_pane_height
    box(0, 0, height, height, '')
    draw_banner(height - 2)
  end
  height
end

#draw_menu ⇒ Object



1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1517

def draw_menu
  height = [@menu.length + 2, @height - 10].min
  top = @height - 7 - height
  menu_width = [@width - 5, 65].min
  height.times { |row| put(top + row, 2, ' ' * menu_width) }
  box(top, 2, height, menu_width, "COMMANDS · #{@menu_hint}")
  start = [@menu_index - height + 3, 0].max
  @menu.slice(start, height - 2).each_with_index do |item, index|
    selected = start + index == @menu_index
    prefix = selected ? '› ' : '  '
    label = item.is_a?(Hash) ? item[:label].to_s : item.to_s
    text = fit(prefix + label, menu_width - 4)
    text += ' ' * (menu_width - 4 - width(text))
    paint = -> { put(top + index + 1, 4, text, tone(:selection)) }
    selected ? @screen.attron(Curses::A_REVERSE) { paint.call } : paint.call
  end
end

#draw_model_prompt ⇒ Object



843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
# File 'lib/pwn/plugins/repl/ai_console.rb', line 843

def draw_model_prompt
  height = [@model_prompt[:efforts].length + 5, @height - 2].min
  menu_width = [@width - 4, 72].min
  top = [(@height - height) / 2, 0].max
  height.times { |row| put(top + row, 2, ' ' * menu_width) }
  box(top, 2, height, menu_width, 'REASONING EFFORT · SELECT')
  put(top + 1, 4, fit("#{@model_prompt[:engine]} / #{@model_prompt[:model]}", menu_width - 4))
  start = [@model_index - (height - 5), 0].max
  @model_prompt[:efforts].slice(start, height - 4).each_with_index do |effort, index|
    selected = start + index == @model_index
    text = "#{selected ? '▶ ' : '  '}#{effort}"
    text += ' (current/default)' if effort == @model_prompt[:default]
    paint = -> { put(top + 2 + index, 4, fit(text, menu_width - 4), tone(selected ? :selection : :notice)) }
    selected ? @screen.attron(Curses::A_REVERSE) { paint.call } : paint.call
  end
  put(top + height - 2, 4, fit('↑↓ select · Enter accept · Esc cancel', menu_width - 4))
end

#draw_search(top) ⇒ Object



1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1299

def draw_search(top)
  search = @editor.search
  query = "reverse search: #{search[:query]}"
  query_rows = wrap(query, @width - 8, words: false)
  put(top + 1, 4, query_rows.last, tone(:category))
  match = search[:match] || '(no match)'
  wrap(match, @width - 8).first(2).each_with_index { |row, index| put(top + 2 + index, 4, row, tone(:composer)) }
  put(top + 4, 4, '^R older · Enter accept · Esc cancel', tone(:footer))
  @cursor_position = [top + 1, [4 + width(query_rows.last), @width - 3].min]
end

#draw_sidebar(top, left, height) ⇒ Object



1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1310

def draw_sidebar(top, left, height)
  box(top, left, height, @width - left - 1, 'OPERATIONS')
  lines = operation_lines
  if height < 26
    lines = lines.select { |line| line.start_with?('Elapsed', 'Completed tools', 'Cost') || line.match?(/\A\d+ in ·/) || line == 'TOKENS' } +
            ['LAST TOOL', @last_tool || 'not observed', '^O full status']
  end
  lines.first(height - 2).each_with_index do |line, index|
    category = ['REQUEST', 'TOKENS', 'SWARM', 'VIEW', 'LAST TOOL'].include?(line)
    put(top + 1 + index, left + 2, fit(line, @width - left - 5), category ? tone(:category) : tone(:value))
  end
end

#draw_swarm ⇒ Object



1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1467

def draw_swarm
  @screen.erase
  view = @workspace
  box(0, 0, @height - 1, @width - 1, "SWARM WORKSPACE · #{view[:tab].to_s.upcase}")
  swarm_put(1, 'Tab roster/jobs · j/k move · Enter details', :footer)
  swarm_put(2, 'Space pick · a ask · b broadcast · d debate', :footer)
  swarm_put(3, 'n new · r refresh · s steer · c cancel', :footer)
  swarm_put(4, 'PgUp/Dn Home/End scroll · Esc back', :footer)
  rows = swarm_content.flat_map { |selected, text| wrap(swarm_safe(text), @width - 7).map { |row| [selected, row] } }
  page = @height - 10
  anchor = rows.index(&:first) || 0
  start = (anchor + view[:offset]).clamp(0, [rows.length - page, 0].max)
  view[:offset] = [start - anchor, 0].max
  rows.slice(start, page).to_a.each_with_index do |(selected, text), index|
    paint = -> { put(5 + index, 3, fit(text, @width - 7).ljust(@width - 7), tone(:value)) }
    selected ? @screen.attron(Curses::A_REVERSE) { paint.call } : paint.call
  end
  bottom = @height - 5
  message = view[:notice] || "#{view[:selected].length} selected · draft preserved · no work until confirmed"
  swarm_put(bottom, message, :notice)
  if view[:confirm]
    args = view[:confirm]
    target = args.first == 'broadcast' ? args[2] : args[1]
    swarm_put(bottom + 1, "Confirm #{args.first} → #{target}", :warning)
    swarm_put(bottom + 2, 'Enter execute · Esc abort · draft unchanged', :footer)
  elsif view[:prompt]
    prompt = view[:prompt]
    swarm_put(bottom + 1, prompt[:label], :category)
    editor = prompt[:editor]
    chars = editor.text.scan(/\X/)
    first = [editor.cursor - ((@width - 7) / 2), 0].max
    text = fit(chars.drop(first).join, @width - 7)
    put(bottom + 2, 3, text, tone(:composer))
    cursor = [bottom + 2, [3 + width(chars[first...editor.cursor].join), @width - 3].min]
  else
    swarm_put(bottom + 1, "DRAFT: #{@editor.text}", :composer)
    swarm_put(bottom + 2, 'Esc/^G return to unchanged mission draft', :footer)
  end
  put(@height - 1, 1, '^D back · ^G close · actions require Enter', tone(:footer))
  @screen.setpos(*(cursor || [0, 2]))
end

#draw_system_role ⇒ Object



803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
# File 'lib/pwn/plugins/repl/ai_console.rb', line 803

def draw_system_role
  height = @height - 4
  pane_width = @width - 4
  top = 2
  height.times { |row| put(top + row, 2, ' ' * pane_width) }
  box(top, 2, height, pane_width, 'SYSTEM ROLE CONTENT')
  put(top + 1, 4, fit("#{@role_engine} · edits are not saved until Ctrl+S", pane_width - 4), tone(:category))
  limit = pane_width - 6
  rows = wrap(@role_editor.text, limit, words: false)
  prefix = wrap(@role_editor.text.scan(/\X/).take(@role_editor.cursor).join, limit, words: false)
  cursor_row = prefix.length - 1
  visible = height - 5
  first = [cursor_row - visible + 1, 0].max
  rows.slice(first, visible).to_a.each_with_index { |row, index| put(top + 2 + index, 4, row, tone(:composer)) }
  put(top + height - 3, 4, fit(@role_error || 'Arrows move · Home/End · Ctrl+U clear', pane_width - 4), tone(@role_error ? :warning : :footer))
  put(top + height - 2, 4, fit('Ctrl+S Save · Esc Cancel · Enter newline', pane_width - 4), tone(:selection))
  @cursor_position = [top + 2 + cursor_row - first, [4 + width(prefix.last), @width - 5].min]
end

#elapsed ⇒ Object



956
957
958
959
960
# File 'lib/pwn/plugins/repl/ai_console.rb', line 956

def elapsed
  return '—' unless @started_at

  format('%.1fs', (@finished_at || Process.clock_gettime(Process::CLOCK_MONOTONIC)) - @started_at)
end

#enable_shift_enter ⇒ Object



337
338
339
340
341
342
343
344
345
346
# File 'lib/pwn/plugins/repl/ai_console.rb', line 337

def enable_shift_enter
  return unless $stdout.tty?

  system('tmux', 'set', '-s', 'extended-keys', 'on', out: File::NULL, err: File::NULL) unless ENV['TMUX'].to_s.empty?
  $stdout.write("\e[>4;1m\e[>1u")
  $stdout.flush
  @shift_enter = true
rescue StandardError
  nil
end

#engine_settings ⇒ Object



1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1066

def engine_settings
  engine = PWN::Env.dig(:ai, :active).to_s
  cfg = PWN::Env.dig(:ai, engine.to_sym)
  cfg = {} unless cfg.is_a?(Hash)
  role = cfg[:system_role_content].to_s.gsub(/\s+/, ' ').strip
  parts = []
  parts << "SYSTEM ROLE CONTENT: #{role}" unless role.empty?
  parts << "\nTEMP: #{cfg[:temp]}" unless cfg[:temp].nil?
  parts << " MAX TOKENS: #{cfg[:max_tokens]}" unless cfg[:max_tokens].nil?
  parts << " MAX PROMPT LENGTH: #{cfg[:max_prompt_length]}" unless cfg[:max_prompt_length].nil?
  parts << "\nREASONING EFFORT: #{cfg[:reasoning_effort]}" unless cfg[:reasoning_effort].to_s.empty?
  parts.join(' · ')
rescue StandardError
  ''
end

#event_loop ⇒ Object



397
398
399
400
401
402
403
404
405
406
407
# File 'lib/pwn/plugins/repl/ai_console.rb', line 397

def event_loop
  loop do
    drain
    break if @leaving && !busy?

    draw
    handle(@getch.call)
  rescue Interrupt
    cancel
  end
end

#execute_swarm_action ⇒ Object



1431
1432
1433
1434
1435
1436
1437
1438
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1431

def execute_swarm_action
  args = @workspace.delete(:confirm)
  result = @swarm.execute(line: Shellwords.join(['/swarm'] + args), on_event: ->(type, text) { @events << [type, text] }, usage_observer: @usage.method(:record))
  @workspace[:notice] = result[:error] || "#{args.first}: accepted#{" · job #{result[:job_id]}" if result[:job_id]}"
  add(result[:ok] == false ? :warning : :notice, @workspace[:notice])
  refresh_swarm if args.first == 'spawn'
  @workspace.merge!(tab: :jobs, index: 0, offset: 0, detail: true) if result[:ok] && %w[ask broadcast debate].include?(args.first)
end

#finish_request_metrics ⇒ Object



952
953
954
# File 'lib/pwn/plugins/repl/ai_console.rb', line 952

def finish_request_metrics
  @finished_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) if @started_at
end

#fit(text, limit) ⇒ Object



981
982
983
984
985
986
987
988
989
990
991
# File 'lib/pwn/plugins/repl/ai_console.rb', line 981

def fit(text, limit)
  result = +''
  used = 0
  text.scan(/\X/).each do |char|
    used += width(char)
    break if used > limit

    result << char
  end
  result
end

#handle(key) ⇒ Object



655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
# File 'lib/pwn/plugins/repl/ai_console.rb', line 655

def handle(key)
  return if key.nil?
  return handle_system_role(key) if @role_editor && (!@too_small || ["\e", "\u0003", "\u0004", :eof].include?(key))

  return if @too_small && ![:eof, "\u0003", "\u0004"].include?(key)
  return cancel if @too_small && key == "\u0003" && !@model_prompt

  return handle_model_prompt(key) if @model_prompt

  return clear_view if key == "\u000c"

  if key == "\u0007"
    @workspace ? @workspace = nil : open_swarm
    return
  end
  return handle_swarm(key) if @workspace && ![:eof, "\u0004"].include?(key)

  if key == "\u000f"
    @editor.finish_search
    @details = @details ? nil : 0
    @menu = nil
    return
  end
  return handle_details(key) if @details && ![:eof, "\u0003", "\u0004"].include?(key)
  return handle_search(key) if @editor.search && ![:eof, "\u0003", "\u0004"].include?(key)

  if key == "\u0012"
    @menu = nil
    @paste = false
    @editor.search_history
    return
  end

  if key == "\t" && @menu
    accept_completion
    return
  end
  if @menu && key == "\e"
    @menu = nil
    return
  end
  case key
  when :eof, "\u0004"
    @leaving = true
    cancel if busy?
  when "\u0003" then cancel
  when :paste_start then @paste = true
  when :paste_end then @paste = false
  when :newline then @editor.insert("\n")
  when "\r", "\n"
    if @paste
      @editor.insert("\n")
    elsif @editor.text.end_with?('\\')
      @editor.edit("\b")
      @editor.insert("\n")
    else
      @menu = @menu_hint = nil
      return submit(@editor.text) if @editor.text.strip == '/system-role'

      @model_draft = [@editor.text.dup, @editor.cursor] if @editor.text.match?(%r{\A/model(?:\s|$)})
      submit(@editor.submit)
    end
  when :up, :down, "\u0010", "\u000e"
    direction = [:up, "\u0010"].include?(key) ? :up : :down
    if @menu
      @menu_index = (@menu_index + (direction == :up ? -1 : 1)) % @menu.length
    else
      @editor.recall(direction)
    end
  when :page_up then @scroll = [(@scroll || (@total_rows.to_i - @page_size.to_i)) - @page_size.to_i, 0].max
  when :page_down
    @scroll = [@scroll.to_i + @page_size.to_i, @total_rows.to_i].min
    @scroll = nil if @scroll >= [@total_rows.to_i - @page_size.to_i, 0].max
    @unseen = 0 unless @scroll
  when "\t" then accept_completion
  when :left, :right, :home, :end, :delete, "\b", "\u007f", "\u0001", "\u0005", "\u0015"
    @editor.edit(key)
    refresh_completion
  else
    if key.is_a?(String) && key.ord >= 32
      @editor.insert(key)
      refresh_completion
    end
  end
end

#handle_details(key) ⇒ Object



883
884
885
886
887
888
889
890
891
892
893
# File 'lib/pwn/plugins/repl/ai_console.rb', line 883

def handle_details(key)
  case key
  when "\e" then @details = nil
  when :page_up then @details = [@details - @details_page, 0].max
  when :page_down then @details += @details_page
  when :up then @details = [@details - 1, 0].max
  when :down then @details += 1
  when :home then @details = 0
  when :end then @details = @details_total
  end
end

#handle_model_prompt(key) ⇒ Object



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'lib/pwn/plugins/repl/ai_console.rb', line 822

def handle_model_prompt(key)
  case key
  when :up, "\u0010", 'k'
    @model_index = (@model_index - 1) % @model_prompt[:efforts].length
  when :down, "\u000e", 'j'
    @model_index = (@model_index + 1) % @model_prompt[:efforts].length
  when "\r", "\n"
    selection = @model_prompt.merge(reasoning_effort: @model_prompt[:efforts][@model_index])
    REPL.pwn_ai_apply_model(selection: selection)
    @model_prompt = @model_draft = nil
  when "\e", "\u0003", :eof, "\u0004"
    if @model_draft
      @editor.replace(@model_draft[0])
      @editor.edit(:left) while @editor.cursor > @model_draft[1]
    end
    @model_prompt = @model_draft = nil
    add(:notice, 'Model selection cancelled; configuration unchanged.')
    @leaving = true if [:eof, "\u0004"].include?(key)
  end
end

#handle_search(key) ⇒ Object



861
862
863
864
865
866
867
868
869
870
871
872
# File 'lib/pwn/plugins/repl/ai_console.rb', line 861

def handle_search(key)
  query = @editor.search[:query]
  case key
  when "\e" then @editor.finish_search
  when "\r", "\n" then @editor.finish_search(accept: true)
  when "\u0012" then @editor.search_history(query, older: true)
  when "\b", "\u007f" then @editor.search_history(query.scan(/\X/)[0...-1].join)
  when "\u0015" then @editor.search_history
  else
    @editor.search_history(query + key) if key.is_a?(String) && key.ord >= 32
  end
end

#handle_swarm(key) ⇒ Object



1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1343

def handle_swarm(key)
  view = @workspace
  return handle_swarm_prompt(key) if view[:prompt]

  if view[:confirm]
    case key
    when "\r", "\n" then execute_swarm_action
    when "\e" then view.delete(:confirm)
    when :page_up then view[:offset] = [view[:offset] - 5, 0].max
    when :page_down then view[:offset] += 5
    when :home then view[:offset] = 0
    when :end then view[:offset] = 1_000_000
    end
    return
  end
  item = swarm_items[view[:index]]
  case key
  when "\e" then view[:detail] ? view.delete(:detail) : @workspace = nil
  when "\t"
    view[:tab] = view[:tab] == :roster ? :jobs : :roster
    view[:index] = view[:offset] = 0
    view.delete(:detail)
  when 'j', 'k'
    view[:index] = (view[:index] + (key == 'j' ? 1 : -1)).clamp(0, [swarm_items.length - 1, 0].max)
    view[:offset] = 0
  when ' '
    return unless view[:tab] == :roster && item

    view[:selected].include?(item[:name]) ? view[:selected].delete(item[:name]) : view[:selected] << item[:name]
  when "\r", "\n" then view[:detail] = true
  when :page_up then view[:offset] = [view[:offset] - 5, 0].max
  when :page_down then view[:offset] += 5
  when :home then view[:offset] = 0
  when :end then view[:offset] = 1_000_000
  when 'r' then refresh_swarm
  when 'a', 'b', 'd' then prepare_swarm_mission(key, item)
  when 'c', "\u0003"
    return unless view[:tab] == :jobs && item

    view[:confirm] = ['cancel', item[:id]]
  when 's'
    return unless view[:tab] == :jobs && item

    view[:prompt] = { action: 'steer', id: item[:id], editor: Editor.new, label: 'Steer instruction' }
  when 'n'
    view[:prompt] = { action: 'spawn', editor: Editor.new, label: 'New agent name' }
  end
end

#handle_swarm_prompt(key) ⇒ Object



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1409

def handle_swarm_prompt(key)
  prompt = @workspace[:prompt]
  editor = prompt[:editor]
  case key
  when "\e" then @workspace.delete(:prompt)
  when "\r", "\n"
    return if editor.text.strip.empty?

    if prompt[:action] == 'spawn' && !prompt[:name]
      prompt[:name] = editor.text.dup
      prompt[:label] = 'Agent role (engine/model inherit; /swarm spawn offers overrides)'
      editor.replace('')
    else
      @workspace[:confirm] = prompt[:action] == 'spawn' ? ['spawn', prompt[:name], '--', editor.text] : ['steer', prompt[:id], editor.text]
      @workspace.delete(:prompt)
    end
  when :left, :right, :home, :end, :delete, "\b", "\u007f", "\u0001", "\u0005", "\u0015" then editor.edit(key)
  else
    editor.insert(key) if key.is_a?(String) && key.ord >= 32
  end
end

#handle_system_role(key) ⇒ Object



755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/pwn/plugins/repl/ai_console.rb', line 755

def handle_system_role(key)
  case key
  when "\e", "\u0003", "\u0004", :eof
    @role_editor = nil
    add(:notice, 'System role cancelled; configuration unchanged.')
    @leaving = true if [:eof, "\u0004"].include?(key)
  when "\u0013"
    return if @role_paste
    raise 'System role cannot change while a request or swarm job is running.' if busy?

    REPL.pwn_ai_apply_system_role(engine: @role_engine, content: @role_editor.text)
    @role_editor = nil
    add(:notice, 'System role saved to encrypted pwn.yaml; effective for the next request.')
  when :paste_start then @role_paste = true
  when :paste_end then @role_paste = false
  when "\r", "\n", :newline then @role_editor.insert("\n")
  when :up, :down then move_role_cursor(key)
  when :left, :right, :home, :end, :delete, "\b", "\u007f", "\u0001", "\u0005", "\u0015"
    @role_editor.edit(key)
  else
    @role_editor.insert(key) if key.is_a?(String) && key.ord >= 32
  end
rescue StandardError => e
  @role_error = "Not saved: #{e.message}"
  add(:warning, @role_error)
end

#header_layout(engine, model) ⇒ Object



1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1171

def header_layout(engine, model)
  key = [engine.dup, model.dup, engine_settings, @width, @height]
  return if @header_layout_key == key

  @header_layout_key = key
  @header_text_column = 2
  @header_text_width = @width - 5
  @header_pane_height = nil
  return if @width < 100 || @height < 26

  # A framed cell-square is as wide as the complete header is tall.
  # Solve monotonically within physical bounds, never recurse or clip
  # settings to make room for decoration. Eight interior cells is the
  # smallest useful game canvas; larger settings grow both dimensions.
  height = 10
  while height <= @height - 10 && @width - height - 5 >= 60
    limit = @width - height - 5
    needed = header_lines(engine, model, limit).length + 3
    if needed <= height
      @header_pane_height = height
      @header_text_column = height + 2
      @header_text_width = limit
      return
    end
    height = needed
  end
end

#header_lines(engine, model, limit = [@width.to_i - 5, 1].max) ⇒ Object



1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1082

def header_lines(engine, model, limit = [@width.to_i - 5, 1].max)
  settings = engine_settings
  # Env strings can be edited in place; cache values, not live aliases.
  key = [engine.dup, model.dup, settings, limit]
  return @header_lines if @header_key == key

  @header_key = key
  text = "PROVIDER (ENGINE): #{engine}\nMODEL: #{model}"
  text += "\n#{settings}" unless settings.empty?
  @header_spans = styled_settings(text, limit)
  @header_lines = @header_spans.map { |spans| spans.map(&:last).join }
end

#move_role_cursor(direction) ⇒ Object



782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
# File 'lib/pwn/plugins/repl/ai_console.rb', line 782

def move_role_cursor(direction)
  chars = @role_editor.text.scan(/\X/)
  cursor = @role_editor.cursor
  start = (chars.take(cursor).rindex("\n") || -1) + 1
  column = cursor - start
  if direction == :up
    return if start.zero?

    target = (chars.take(start - 1).rindex("\n") || -1) + 1
    position = target + [column, start - target - 1].min
  else
    finish = chars.index.with_index { |char, index| index >= cursor && char == "\n" }
    return unless finish

    target = finish + 1
    length = chars.drop(target).take_while { |char| char != "\n" }.length
    position = target + [column, length].min
  end
  @role_editor.place(@role_editor.text, position)
end

#open_swarm ⇒ Object

This overlay owns only navigation state; the mission editor never changes.



1324
1325
1326
1327
1328
1329
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1324

def open_swarm
  @editor.finish_search
  @menu = @details = nil
  @workspace = { tab: :roster, index: 0, selected: (@swarm_selection ||= []), offset: 0 }
  refresh_swarm
end

#open_system_role ⇒ Object



741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/pwn/plugins/repl/ai_console.rb', line 741

def open_system_role
  return add(:warning, 'System role cannot change while a request or swarm job is running.') if busy?

  @role_engine = PWN::Env.dig(:ai, :active).to_s
  raise 'Select an active engine with /model first.' unless PWN::Env.dig(:ai, @role_engine.to_sym).is_a?(Hash)

  @role_editor = Editor.new
  @role_editor.replace(PWN::Env.dig(:ai, @role_engine.to_sym, :system_role_content).to_s)
  @role_error = nil
  @role_paste = false
  @menu = nil
  @paste = false
end

#operation_lines ⇒ Object



968
969
970
971
972
973
974
975
976
977
978
979
# File 'lib/pwn/plugins/repl/ai_console.rb', line 968

def operation_lines
  usage = @usage.snapshot
  cost = usage[:estimated_cost_usd] ? format('$%.4f est.', usage[:estimated_cost_usd]) : usage[:cost_status]
  swarm = @swarm&.snapshot || {}
  active = Array(swarm[:jobs]).count { |job| %w[queued running steering cancelling].include?(job[:state]) }
  ['REQUEST', state, "Elapsed #{elapsed}", "Completed tools #{@completed_tools}",
   "Events #{@event_count}", '', 'TOKENS', "#{usage[:input_tokens]} in · #{usage[:output_tokens]} out",
   "cached #{usage[:cached_tokens]} · calls #{usage[:calls]}", "Cost #{cost}",
   '', 'SWARM', swarm[:swarm_id] || 'none', "#{active} active · ^G swarm",
   '', 'VIEW', @verbose ? 'verbose' : 'compact · /verbose', scroll_status,
   '', 'LAST TOOL', @last_tool || 'not observed']
end

#prepare_swarm_mission(key, item) ⇒ Object



1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1392

def prepare_swarm_mission(key, item)
  view = @workspace
  return view[:notice] = 'Return with Esc and write a mission draft first.' if @editor.text.strip.empty?
  return view[:notice] = 'Choose agents on the roster tab first.' unless view[:tab] == :roster

  names = key == 'a' ? [item&.dig(:name)].compact : view[:selected]
  minimum = key == 'd' ? 2 : 1
  return view[:notice] = "Select at least #{minimum} agent(s) with Space." if names.length < minimum

  command = { 'a' => 'ask', 'b' => 'broadcast', 'd' => 'debate' }.fetch(key)
  view[:confirm] = case command
                   when 'ask' then [command, names.first, @editor.text]
                   when 'broadcast' then [command, '--names', names.join(','), '--', @editor.text]
                   else [command, names.join(','), '--', @editor.text]
                   end
end

#put(row, column, text, color = nil) ⇒ Object



1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1025

def put(row, column, text, color = nil)
  return if row.negative? || row >= @height || column >= @width

  @screen.setpos(row, column)
  string = fit(text, [@width - column - 1, 0].max)
  if @color && color
    @screen.attron(@curses.color_pair(color)) { @screen.addstr(string) }
  else
    @screen.addstr(string)
  end
end

#put_spans(row, column, spans) ⇒ Object



1120
1121
1122
1123
1124
1125
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1120

def put_spans(row, column, spans)
  spans.each do |role, text|
    put(row, column, text, tone(role))
    column += width(text)
  end
end

#refresh_completion ⇒ Object



874
875
876
877
878
879
880
881
# File 'lib/pwn/plugins/repl/ai_console.rb', line 874

def refresh_completion
  token = @editor.text.scan(/\X/).take(@editor.cursor).join[/(?:^|\s)(\S*)\z/, 1].to_s
  if @editor.text.start_with?('/') || token.start_with?('PWN') || token.match?(%r{\A(?:~|\./|\.\./|/)})
    complete
  else
    @menu = nil
  end
end

#refresh_swarm ⇒ Object



1331
1332
1333
1334
1335
1336
1337
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1331

def refresh_swarm
  @workspace[:roster] = @swarm.roster
  @workspace[:selected].select! { |name| @workspace[:roster].any? { |row| row[:name] == name } }
rescue StandardError => e
  @workspace[:roster] = []
  @workspace[:notice] = "Roster unavailable: #{e.message}"
end

#restore_streams(previous) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/pwn/plugins/repl/ai_console.rb', line 357

def restore_streams(previous)
  log = PWN::Plugins::Log
  rebind_stderr = log.debug_enabled? && log.raw_stderr.equal?(@output)
  # Keep the open RN file and trace state, but never leave a logger
  # referencing the now-closed console's event queue.
  log.send(:remove_stderr_tee!) if rebind_stderr
  $stdin, $stdout, $stderr, @pry.config.output = previous
  return unless log.debug_enabled?

  log.start_debug(tee: previous[1], session_id: @pry.config.pwn_ai_session_id)
  log.send(:install_stderr_tee!) if rebind_stderr
end

#run ⇒ Object



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
335
# File 'lib/pwn/plugins/repl/ai_console.rb', line 287

def run
  previous = [$stdin, $stdout, PWN::Plugins::Log.raw_stderr, @pry.config.output]
  flags = @input.fcntl(Fcntl::F_GETFL)
  source = @input.dup
  @source = source
  source.raw do
    enable_shift_enter
    @swarm = AISwarm::Controller.new(session_id: @pry.config.pwn_ai_session_id)
    @screen = @curses.init_screen
    @curses.raw
    @curses.noecho
    @curses.curs_set(1)
    setup_colors
    # Curses only paints; Keyboard owns the duplicated terminal.
    forwarded, @tool_input = IO.pipe
    @input.reopen(forwarded)
    forwarded.close
    $stdin = @input
    $stdout = $stderr = @output
    @pry.config.output = @output
    if PWN::Plugins::Log.debug_enabled?
      PWN::Plugins::Log.send(:remove_stderr_tee!)
      PWN::Plugins::Log.send(:install_stderr_tee!)
      PWN::Plugins::Log.start_debug(tee: @output, session_id: @pry.config.pwn_ai_session_id)
    end
    @getch ||= Keyboard.new(source)
    seed_request_history
    add(:notice, 'Ready. Submit a task · / or Tab opens commands · /steer redirects while busy.')
    add(:notice, 'Tool prompts: /input TEXT forwards one line. Raw/fullscreen tools and direct /dev/tty readers are unsupported.')
    event_loop
  ensure
    begin
      stop_worker
    ensure
      begin
        @input.reopen(source)
        @input.fcntl(Fcntl::F_SETFL, flags)
        @tool_input&.close unless @tool_input&.closed?
      ensure
        @curses.close_screen if @screen
      end
    end
  end
  :closed
ensure
  restore_streams(previous) if previous
  disable_shift_enter
  source&.close
end

#run_swarm(line) ⇒ Object



628
629
630
631
632
633
634
# File 'lib/pwn/plugins/repl/ai_console.rb', line 628

def run_swarm(line)
  return open_swarm if ['/swarm', '/swarm dashboard'].include?(line.strip)

  result = @swarm.execute(line: line, on_event: ->(type, text) { @events << [type, text] }, usage_observer: @usage.method(:record))
  text = result[:job_id] ? "Swarm job #{result[:job_id]} queued (#{result[:state]})." : (result[:usage] || result[:error] || result.inspect)
  add(result[:ok] == false ? :warning : :notice, text)
end

#scroll_status ⇒ Object



962
963
964
965
966
# File 'lib/pwn/plugins/repl/ai_console.rb', line 962

def scroll_status
  return 'live' unless @scroll

  "#{@scroll + 1}–#{[@scroll + @page_size.to_i, @total_rows.to_i].min}/#{@total_rows} · #{@unseen} new"
end

#seed_request_history ⇒ Object



1048
1049
1050
1051
1052
1053
1054
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1048

def seed_request_history
  # REPL configures ~/.pwn/pwn_history and Pry loads it at startup.
  # Reuse that owner rather than loading twice or opening another writer.
  @editor.preload(Pry.history.to_a)
rescue StandardError
  nil
end

#send_tool_input(line) ⇒ Object



636
637
638
639
640
641
642
643
644
# File 'lib/pwn/plugins/repl/ai_console.rb', line 636

def send_tool_input(line)
  text = "#{line.delete_prefix('/input ')}\n"
  written = @tool_input.write_nonblock(text, exception: false)
  if text.bytesize > 4096 || written == :wait_writable
    add(:warning, 'Tool input not sent: pipe full or line exceeds 4096 bytes.')
  else
    add(:notice, 'Input sent to tool (not echoed).')
  end
end

#setup_colors ⇒ Object



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
# File 'lib/pwn/plugins/repl/ai_console.rb', line 370

def setup_colors
  @color = !ENV.key?('NO_COLOR') && @curses.has_colors?
  return unless @color

  @curses.start_color
  @curses.use_default_colors
  PALETTE.each_with_index do |name, index|
    @curses.init_pair(index + 1, Curses.const_get("COLOR_#{name.upcase}"), -1)
  end
  # Artwork owns complete foreground/background pairs, separate from
  # semantic theme colors. Never silently drop a colored background.
  @banner_colors = @curses.color_pairs > PALETTE.length * 2
  return unless @banner_colors

  PALETTE.each_with_index do |name, index|
    @curses.init_pair(PALETTE.length + index + 1, Curses.const_get("COLOR_#{name.upcase}"), Curses::COLOR_BLACK)
  end
  @banner_two_colors = @curses.color_pairs > PALETTE.length + (PALETTE.length**2)
  return unless @banner_two_colors

  PALETTE.reject { |name| name == 'black' }.each_with_index do |background, bg_index|
    PALETTE.each_with_index do |foreground, fg_index|
      @curses.init_pair(17 + (bg_index * 8) + fg_index, Curses.const_get("COLOR_#{foreground.upcase}"), Curses.const_get("COLOR_#{background.upcase}"))
    end
  end
end

#start_request(request, command: false) ⇒ Object



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/pwn/plugins/repl/ai_console.rb', line 456

def start_request(request, command: false)
  @locals = Thread.current.keys.select { |key| key.to_s.start_with?('pwn_') }.to_h { |key| [key, Thread.current[key]] }
  @thread_variables = Thread.current.thread_variables.select { |key| key.to_s.start_with?('pwn_') }.to_h { |key| [key, Thread.current.thread_variable_get(key)] }
  # A fresh forwarding pipe prevents unread input crossing requests.
  @tool_input.close unless @tool_input.closed?
  forwarded, @tool_input = IO.pipe
  @input.reopen(forwarded)
  forwarded.close
  @cancelling = false
  @command = command
  begin_request_metrics
  add(:operator, request)
  @running = true
  ready = Queue.new
  gate = Queue.new
  @worker = Thread.new do
    @locals.each { |key, value| Thread.current[key] = value }
    @thread_variables.each { |key, value| Thread.current.thread_variable_set(key, value) }
    control = Control.new(input: @input, output: @output)
    Thread.current[:pwn_steering_input] = control
    Thread.current[:pwn_usage_observer] = @usage.method(:record)
    ready << control
    gate.pop
    on_tool = lambda do |name, args, result|
      if name.to_s == 'task'
        @events << [:task, args.to_s]
      else
        @events << [:tool, "#{name}\n#{args.is_a?(String) ? args : args.inspect}"]
        @events << [:result, result.to_s]
      end
    end
    if command
      control.checkpoint(messages: [], phase: :tool)
      if request.match?(%r{\A/model(?:\s|$)})
        REPL.pwn_ai_run_model(args: request.split.drop(1), prompt: lambda { |selection|
          control.checkpoint(messages: [])
          @events << [:model_prompt, selection]
          :deferred
        })
      else
        REPL.pwn_ai_dispatch_slash!(request: request, pry: @pry)
      end
      control.checkpoint(messages: [])
    else
      final = PWN::AI::Agent::Loop.run(
        request: request, session_id: @pry.config.pwn_ai_session_id,
        enabled_toolsets: PWN::Env.dig(:ai, :agent, :toolsets),
        on_tool: on_tool, steering: control, debug: @pry.config.pwn_ai_debug, debug_tee: @output
      )
      @events << [:assistant, final.to_s]
    end
  rescue Control::Stopped => e
    @events << [:warning, e.message]
  rescue StandardError, Interrupt => e
    Thread.current[:pwn_log_progress] = false
    PWN::Plugins::Log.note_exception!(error: e, where: 'curses agent', which_self: AIConsole)
    @events << [:warning, "#{e.class}: #{e.message}"]
  ensure
    @events << [:done, nil]
  end
  @worker.report_on_exception = false
  @control = ready.pop
  gate << true
end

#state ⇒ Object



1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1056

def state
  return 'closing · waiting for safe boundary' if @leaving && busy?
  return 'cancelling · waiting for safe boundary' if @cancelling && busy?
  return 'idle' unless busy?
  return 'swarm running · ^G jobs / steering' unless @worker && (@worker.alive? || @running)
  return 'running · local command · /input available' if @command

  "running · #{@control&.phase || 'starting'} · /steer available"
end

#stop_worker ⇒ Object



535
536
537
538
539
540
541
542
543
# File 'lib/pwn/plugins/repl/ai_console.rb', line 535

def stop_worker
  return unless @worker&.alive? || @swarm&.busy?

  @control&.stop
  @swarm&.cancel_all
  @tool_input.close unless @tool_input.closed?
  @worker&.join
  @swarm&.close
end

#styled_settings(text, limit) ⇒ Object

Mark labels before wrapping so even a split label retains its role.



1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1096

def styled_settings(text, limit)
  text.split("\n", -1).flat_map do |line|
    roles = Array.new(line.length, :header)
    line.to_enum(:scan, /(?:\A|(?<=· ))\s*(?:PROVIDER \(ENGINE\)|MODEL|SYSTEM ROLE CONTENT|TEMP|MAX TOKENS|MAX PROMPT LENGTH|REASONING EFFORT):/).each do
      match = Regexp.last_match
      roles.fill(:category, match.begin(0)...match.end(0))
    end
    offset = 0
    wrap(line, limit).map do |row|
      spans = []
      row.each_char do |char|
        role = roles[offset]
        offset += 1
        if spans.last&.first == role
          spans.last[1] << char
        else
          spans << [role, +char]
        end
      end
      spans
    end
  end
end

#submit(line) ⇒ Object



545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/pwn/plugins/repl/ai_console.rb', line 545

def submit(line)
  return if line.strip.empty?

  # Pry owns the existing pwn_history format, append and deduplication.
  # Curses bypasses Pry's input evaluator, so record once here, not on recall.
  Pry.history << line unless line.match?(%r{\A\s*/input(?:\s|\z)})

  if %w[back /back].include?(line.strip)
    @leaving = true
    cancel if busy?
  elsif line.strip == '/clear'
    clear_view
  elsif line.strip == '/status'
    @details = 0
    @menu = nil
  elsif line.match?(%r{\A/verbose(?:\s|$)})
    toggle_verbose(line)
  elsif line.start_with?('/swarm')
    run_swarm(line)
  elsif ['/', '/menu'].include?(line.strip)
    @editor.replace('/')
    complete
  elsif busy?
    busy_command(line)
  elsif line.strip == '/system-role'
    open_system_role
  elsif line.match?(%r{\A/(?:mcp(?:\s|$)|cron\s+run(?:\s|$)|model(?:\s|$))})
    start_request(line, command: true)
  elsif line.start_with?('/') || line.start_with?('ai.profile ', 'ai.memory ')
    if line.start_with?('/sessions resume ')
      return add(:warning, 'Cannot switch sessions while swarm jobs are active.') if @swarm&.busy?

      sid = line.split.last
      PWN::Sessions.to_response_history(session_id: sid)
      @pry.config.pwn_ai_session_id = sid
      add(:notice, "Session resumed: #{sid}")
    elsif !REPL.pwn_ai_dispatch_slash!(request: line, pry: @pry)
      add(:warning, 'Unknown command. Use / or Tab for commands.')
    end
  else
    start_request(line)
  end
rescue StandardError => e
  add(:warning, "#{e.class}: #{e.message}")
end

#swarm_content ⇒ Object



1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1440

def swarm_content
  view = @workspace
  if view[:confirm]
    args = view[:confirm]
    target = args.first == 'broadcast' ? args[2] : args[1]
    return [[false, "ACTION: #{args.first}\nTARGET: #{target}\n#{args.first == 'cancel' ? 'Cancel at a safe boundary; completed work is not undone.' : args.last}"]]
  end
  items = swarm_items
  item = items[view[:index]]
  rows = []
  if view[:detail] && item
    item.each { |key, value| rows << [false, "#{key.to_s.upcase}: #{value}"] }
  elsif items.empty?
    rows << [false, view[:tab] == :roster ? 'No agents. Press n to add a local persona (no model call).' : 'No jobs yet. Tab to roster; a sends your draft after confirmation.']
  else
    items.each_with_index do |entry, index|
      label = if view[:tab] == :roster
                "#{view[:selected].include?(entry[:name]) ? '[x]' : '[ ]'} #{entry[:name]} · #{entry[:engine]} / #{entry[:model]}\n    #{entry[:role]}"
              else
                "#{entry[:id]} · #{entry[:state]} · #{entry[:command]} → #{entry[:agent]}"
              end
      rows << [index == view[:index], label]
    end
  end
  rows
end

#swarm_items ⇒ Object



1339
1340
1341
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1339

def swarm_items
  @workspace[:tab] == :roster ? @workspace[:roster] : @swarm.snapshot[:jobs].reverse
end

#swarm_put(row, text, role) ⇒ Object



1513
1514
1515
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1513

def swarm_put(row, text, role)
  put(row, 2, fit(swarm_safe(text).gsub(/\s+/, ' '), @width - 5), tone(role))
end

#swarm_safe(text) ⇒ Object



1509
1510
1511
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1509

def swarm_safe(text)
  PWN::Redaction.redact(value: text.to_s).gsub(%r{\e\[[0-?]*[ -/]*[@-~]}, '').gsub(/[\x00-\x08\x0b-\x1f\x7f]/, '')
end

#timeline_rows(limit) ⇒ Object



920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
# File 'lib/pwn/plugins/repl/ai_console.rb', line 920

def timeline_rows(limit)
  theme = AIConsole.theme
  return @rows if @rows && @rows_width == limit && @rows_verbose == @verbose && @rows_theme == theme

  @rows_width = limit
  @rows_verbose = @verbose
  @rows_theme = theme
  @rows = @timeline.flat_map do |type, text, stamp, cache|
    next [] if !@verbose && i[tool result notice].include?(type)

    unless cache[:width] == limit && cache[:verbose] == @verbose && cache[:theme] == theme
      cache[:verbose] = @verbose
      cache[:width] = limit
      cache[:theme] = theme
      role = COLORS.fetch(type, :result)
      label_color = type == :operator ? tone(:operator) : tone(role)
      body_color = type == :operator ? tone(:request) : label_color
      cache[:rows] = [[label_color, "#{fit(type.to_s.upcase, 12)} · #{stamp}"]] +
                     wrap(text, limit).map { |row| [body_color, "  #{row}"] } + [[nil, '']]
    end
    cache[:rows]
  end
  @rows.pop if @rows.last&.last == ''
  @rows
end

#toggle_verbose(line) ⇒ Object



621
622
623
624
625
626
# File 'lib/pwn/plugins/repl/ai_console.rb', line 621

def toggle_verbose(line)
  argument = line.split[1]
  @verbose = argument.nil? ? !@verbose : argument == 'on'
  @rows = nil
  add(:notice, @verbose ? 'Verbose view on.' : 'Compact view on. Tool output is hidden until /verbose on.')
end

#tone(role) ⇒ Object



1019
1020
1021
1022
1023
# File 'lib/pwn/plugins/repl/ai_console.rb', line 1019

def tone(role)
  name = AIConsole.theme[role].to_s
  index = PALETTE.index(name)
  index ? index + 1 : 1
end

#width(text) ⇒ Object



904
905
906
# File 'lib/pwn/plugins/repl/ai_console.rb', line 904

def width(text)
  Unicode::DisplayWidth.of(text, ambiguous: 1, emoji: :all)
end

#wrap(text, limit, words: true) ⇒ Object



993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
# File 'lib/pwn/plugins/repl/ai_console.rb', line 993

def wrap(text, limit, words: true)
  return [''] if text.empty?

  text.split("\n", -1).flat_map do |line|
    rows = [+'']
    used = 0
    tokens = words ? line.scan(/\s+|\S+/) : [line]
    tokens.each do |token|
      if words && !token.match?(/\A\s/) && used.positive? && width(token) <= limit && used + width(token) > limit
        rows << +''
        used = 0
      end
      token.scan(/\X/).each do |char|
        cells = width(char)
        if used + cells > limit && !rows.last.empty?
          rows << +''
          used = 0
        end
        rows[-1] << char
        used += cells
      end
    end
    rows
  end
end