Class: Kward::PromptInterface

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/prompt_interface.rb,
lib/kward/prompt_interface/banner.rb

Defined Under Namespace

Classes: Banner, SubmittedInput

Constant Summary collapse

HELP_TEXT =
"Enter sends • Shift+Enter inserts newline • ↑/↓ history • Ctrl+D exits empty prompt".freeze
BUSY_HELP_TEXT =
"Ctrl+C cancels".freeze
SPINNER_FRAMES =
%w[         ].freeze
SPINNER_INTERVAL =
0.1
1.0
COMPOSER_MAX_INPUT_ROWS =
6
TRANSCRIPT_BUFFER_LIMIT =
200_000
Banner::LOGO_PIXELS
Banner::MESSAGE
KEYBOARD_PROTOCOL_ENABLE =
"\e[>1u".freeze
KEYBOARD_PROTOCOL_RESTORE =
"\e[<u".freeze
BRACKETED_PASTE_ENABLE =
"\e[?2004h".freeze
BRACKETED_PASTE_RESTORE =
"\e[?2004l".freeze
BRACKETED_PASTE_START =
"\e[200~".freeze
BRACKETED_PASTE_END =
"\e[201~".freeze
SYNCHRONIZED_OUTPUT_ENABLE =
"\e[?2026h".freeze
SYNCHRONIZED_OUTPUT_DISABLE =
"\e[?2026l".freeze
CURSOR_SHOW =
"\e[?25h".freeze
CURSOR_HIDE =
"\e[?25l".freeze
SHIFT_ENTER_SEQUENCES =
["\e[13;2u", "\e[13;2~", "\e[27;2;13~", "\e\r", "\e\n"].freeze
EXIT_INPUT =
:exit_input
CANCEL_INPUT =
:cancel_input
SELECT_CANCEL =
:select_cancel

Instance Method Summary collapse

Constructor Details

#initialize(input: $stdin, output: $stdout, slash_commands: [], overlay_settings: nil, footer: nil, composer_status: nil, busy_help: true, attachment_badges: nil, attachment_parser: nil, banner_pixels: nil, banner_message: nil) ⇒ PromptInterface

Returns a new instance of PromptInterface.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/kward/prompt_interface.rb', line 44

def initialize(input: $stdin, output: $stdout, slash_commands: [], overlay_settings: nil, footer: nil, composer_status: nil, busy_help: true, attachment_badges: nil, attachment_parser: nil, banner_pixels: nil, banner_message: nil)
  @input_io = input
  @output_io = output
  @reader = TTY::Reader.new(input: input, output: output, interrupt: :error)
  @mutex = Mutex.new
  @input = ""
  @cursor = 0
  @started = false
  @asking = false
  @busy = false
  @busy_activity = "streaming"
  @queued_count = 0
  @steered_count = 0
  @spinner_frame_index = 0
  @last_spinner_tick = monotonic_now
  @last_footer_refresh = monotonic_now
  @prompt_label = "You>"
  @assistant_label = "Assistant"
  @stream_block = nil
  @rendered_rows = 0
  @last_composer_rows = []
  @cursor_rendered_row = 0
  @stream_col = 0
  @stream_pending_wrap = false
  @transcript_buffer = +""
  @transcript_display_rows_cache_width = nil
  @transcript_display_rows_cache = nil
  @visual_banner_count = 0
  @transcript_viewport_rows = 0
  @restoring_transcript = false
  @pending_keys = []
  @attachments = []
  @kill_buffer = ""
  @original_console_mode = nil
  @raw_mode_active = false
  @history = []
  @history_index = nil
  @history_draft = nil
  @prefill_input = nil
  @slash_commands = normalize_slash_commands(slash_commands)
  @slash_selection_index = 0
  @slash_overlay_dismissed_input = nil
  @select_state = nil
  @question_state = nil
  @last_width = screen_width
  @last_height = screen_height
  @reserved_rows = 0
  @color_enabled = ANSI.enabled?(output)
  @cursor_visible = true
  @synchronized_output_depth = 0
  @overlay_settings = normalize_overlay_settings(overlay_settings)
  @footer = footer
  @composer_status = composer_status
  @busy_help = busy_help
  @attachment_badges = attachment_badges
  @attachment_parser = attachment_parser
  @banner = Banner.new(message: banner_message, pixels: banner_pixels, screen_height: method(:screen_height))
end

Instance Method Details

#ask(message = "You>") ⇒ Object



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
# File 'lib/kward/prompt_interface.rb', line 194

def ask(message = "You>")
  was_composing = @started && @asking
  start
  @mutex.synchronize do
    preserve_input = was_composing && !@busy && !@input.empty?
    @prompt_label = message.to_s
    unless preserve_input
      @input = @prefill_input.to_s
      @prefill_input = nil
      @cursor = @input.length
      @attachments.clear
      reset_history_navigation
    end
    @pending_keys.clear
    @asking = true
    @busy = false
    @queued_count = 0
    render_prompt_locked
  end

  loop do
    key = read_key(nonblock: true)
    result = nil
    @mutex.synchronize do
      if key.nil?
        resized = handle_resize_locked
        footer_refreshed = tick_footer_locked
        render_prompt_locked if resized || footer_refreshed
      else
        result = handle_key(key)
        render_prompt_locked unless result.is_a?(String) || result == EXIT_INPUT
      end
    end
    return result if result.is_a?(String)
    return nil if result == EXIT_INPUT

    sleep 0.02 if key.nil?
  end
end

#ask_user_question(questions) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/kward/prompt_interface.rb', line 287

def ask_user_question(questions)
  return [] if questions.empty?

  start
  saved_state = nil
  answers = []
  @mutex.synchronize { saved_state = begin_question_prompt_state }

  questions.each_with_index do |question, index|
    answer = ask_single_user_question(question, index + 1, questions.length)
    if answer == SELECT_CANCEL
      finish_question_prompt(saved_state)
      return nil
    end
    answers << answer
  end

  finish_question_prompt(saved_state)
  answers
rescue StandardError
  finish_question_prompt(saved_state) if saved_state
  raise
end

#begin_busy_input(message = "You>", activity: "streaming") ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/kward/prompt_interface.rb', line 322

def begin_busy_input(message = "You>", activity: "streaming")
  start
  @mutex.synchronize do
    @prompt_label = message.to_s
    @busy_activity = normalize_busy_activity(activity)
    @input = ""
    @cursor = 0
    @attachments.clear
    @pending_keys.clear
    @asking = true
    @busy = true
    @queued_count = 0
    @steered_count = 0
    reset_spinner_locked
    reset_history_navigation
    render_prompt_locked
  end
end

#clear_steered_countObject



357
358
359
360
361
362
363
# File 'lib/kward/prompt_interface.rb', line 357

def clear_steered_count
  @mutex.synchronize do
    @steered_count = 0
    @busy_activity = "streaming"
    render_prompt_locked if @asking
  end
end

#clear_transcriptObject



453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/kward/prompt_interface.rb', line 453

def clear_transcript
  @mutex.synchronize do
    @transcript_buffer = +""
    invalidate_transcript_display_rows_cache
    @visual_banner_count = 0
    @transcript_viewport_rows = 0
    @stream_block = nil
    @stream_col = 0
    @stream_pending_wrap = false
    width, height = screen_size
    with_synchronized_output_locked { redraw_screen_locked(width: width, height: height) }
    @output_io.flush
  end
end

#closeObject



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/kward/prompt_interface.rb', line 116

def close
  @mutex.synchronize do
    return unless @started

    clear_prompt_for_output_locked
    restore_scroll_region_locked
    @output_io.print(BRACKETED_PASTE_RESTORE)
    @output_io.print(KEYBOARD_PROTOCOL_RESTORE)
    set_cursor_visible_locked(true, force: true)
    @output_io.puts
    @output_io.flush
    @started = false
    restore_console_mode_locked
  end
end

#finish_busy_inputObject



365
366
367
368
369
370
371
372
373
374
# File 'lib/kward/prompt_interface.rb', line 365

def finish_busy_input
  @mutex.synchronize do
    @busy = false
    @busy_activity = "streaming"
    @queued_count = 0
    @steered_count = 0
    @asking = true
    render_prompt_locked
  end
end

#finish_stream_blockObject



433
434
435
436
437
# File 'lib/kward/prompt_interface.rb', line 433

def finish_stream_block
  @mutex.synchronize do
    write_stream_block_locked(nil, "", finish: true)
  end
end

Returns:

  • (Boolean)


311
312
313
# File 'lib/kward/prompt_interface.rb', line 311

def modal_active?
  @mutex.synchronize { !@question_state.nil? || !@select_state.nil? }
end

#poll_inputObject



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/kward/prompt_interface.rb', line 376

def poll_input
  key = read_key(nonblock: true)
  @mutex.synchronize do
    if key.nil?
      resized = handle_resize_locked
      spun = tick_spinner_locked
      footer_refreshed = tick_footer_locked
      render_prompt_locked if resized || spun || footer_refreshed
      return nil
    end

    result = handle_key(key)
    render_prompt_locked unless [EXIT_INPUT, CANCEL_INPUT].include?(result)
    [EXIT_INPUT, CANCEL_INPUT].include?(result) ? result : result
  end
end


399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/kward/prompt_interface.rb', line 399

def print_visual_banner
  @mutex.synchronize do
    width, height = screen_size
    rows = banner_rows(width)
    return if rows.empty?

    with_synchronized_output_locked do
      prepare_transcript_output_locked
      rows.each do |row|
        write_visual_transcript_text_locked(row)
        write_visual_transcript_text_locked("\n")
      end
      @visual_banner_count += 1
      invalidate_transcript_display_rows_cache
      remember_transcript_viewport_locked(height)
      @stream_block = nil
      restore_composer_cursor_locked
    end
    @output_io.flush
  end
end

#redrawObject



445
446
447
448
449
450
451
# File 'lib/kward/prompt_interface.rb', line 445

def redraw
  @mutex.synchronize do
    width, height = screen_size
    with_synchronized_output_locked { redraw_screen_locked(width: width, height: height) }
    @output_io.flush
  end
end

#restore_transcriptObject



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/kward/prompt_interface.rb', line 169

def restore_transcript
  @mutex.synchronize do
    clear_prompt_for_output_locked
    @output_io.print(SYNCHRONIZED_OUTPUT_ENABLE)
    @transcript_buffer = +""
    invalidate_transcript_display_rows_cache
    @visual_banner_count = 0
    @transcript_viewport_rows = 0
    @stream_block = nil
    @stream_col = 0
    @stream_pending_wrap = false
    @restoring_transcript = true
  end

  yield
ensure
  @mutex.synchronize do
    @restoring_transcript = false
    @output_io.print(SYNCHRONIZED_OUTPUT_DISABLE)
    width, height = screen_size
    redraw_screen_locked(width: width, height: height)
    @output_io.flush
  end
end

#say(message) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/kward/prompt_interface.rb', line 132

def say(message)
  @mutex.synchronize do
    text = message.to_s
    if @restoring_transcript
      write_transcript_text_locked(text)
      write_transcript_text_locked("\n") unless text.end_with?("\n")
      @stream_block = nil
      next
    end

    with_synchronized_output_locked do
      clear_prompt_for_output_locked
      write_transcript_text_locked(text)
      write_transcript_text_locked("\n") unless text.end_with?("\n")
      @stream_block = nil
      render_prompt_after_output_locked
    end
    @output_io.flush
  end
end

#say_visual(message) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/kward/prompt_interface.rb', line 153

def say_visual(message)
  @mutex.synchronize do
    return if @restoring_transcript

    with_synchronized_output_locked do
      clear_prompt_for_output_locked
      text = message.to_s
      write_visual_transcript_text_locked(text)
      write_visual_transcript_text_locked("\n") unless text.end_with?("\n")
      @stream_block = nil
      render_prompt_after_output_locked
    end
    @output_io.flush
  end
end

#select(message, choices, title: "Sessions", custom: false, initial_index: 0) ⇒ Object



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
# File 'lib/kward/prompt_interface.rb', line 244

def select(message, choices, title: "Sessions", custom: false, initial_index: 0)
  return nil if choices.empty? && !custom

  start
  @mutex.synchronize do
    @prompt_label = message.to_s
    @input = ""
    @cursor = 0
    @attachments.clear
    @pending_keys.clear
    @asking = true
    @busy = false
    @queued_count = 0
    choice_labels = choices.map(&:to_s)
    selection_index = choice_labels.empty? ? 0 : [[initial_index.to_i, 0].max, choice_labels.length - 1].min
    @select_state = { choices: choice_labels, selection_index: selection_index, title: title.to_s, custom: custom }
    reset_history_navigation
    render_prompt_locked
  end

  loop do
    key = read_key(nonblock: true)
    result = nil
    @mutex.synchronize do
      if key.nil?
        resized = handle_resize_locked
        footer_refreshed = tick_footer_locked
        render_prompt_locked if resized || footer_refreshed
      else
        result = handle_select_key(key)
        render_prompt_locked unless result.is_a?(String) || result == SELECT_CANCEL
      end
    end

    if result.is_a?(String) || result == SELECT_CANCEL
      finish_select_prompt
      return result == SELECT_CANCEL ? nil : result
    end

    sleep 0.02 if key.nil?
  end
end

#set_queued_count(count) ⇒ Object



341
342
343
344
345
346
347
# File 'lib/kward/prompt_interface.rb', line 341

def set_queued_count(count)
  @mutex.synchronize do
    @queued_count = count.to_i
    @steered_count = 0 if @queued_count.positive?
    render_prompt_locked if @asking
  end
end

#set_steered_count(count) ⇒ Object



349
350
351
352
353
354
355
# File 'lib/kward/prompt_interface.rb', line 349

def set_steered_count(count)
  @mutex.synchronize do
    @steered_count = count.to_i
    @queued_count = 0 if @steered_count.positive?
    render_prompt_locked if @asking
  end
end

#startObject



103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/kward/prompt_interface.rb', line 103

def start
  @mutex.synchronize do
    return if @started

    enter_raw_mode_locked
    @started = true
    @asking = true
    @output_io.print(KEYBOARD_PROTOCOL_ENABLE)
    @output_io.print(BRACKETED_PASTE_ENABLE)
    render_prompt_locked
  end
end

#start_stream_block(label) ⇒ Object



421
422
423
424
425
# File 'lib/kward/prompt_interface.rb', line 421

def start_stream_block(label)
  @mutex.synchronize do
    write_stream_block_locked(label, "", finish: false)
  end
end

#update_assistant_label(label) ⇒ Object



393
394
395
396
397
# File 'lib/kward/prompt_interface.rb', line 393

def update_assistant_label(label)
  @mutex.synchronize do
    @assistant_label = label.to_s.empty? ? "Assistant" : label.to_s
  end
end

#update_overlay_settings(settings) ⇒ Object



315
316
317
318
319
320
# File 'lib/kward/prompt_interface.rb', line 315

def update_overlay_settings(settings)
  @mutex.synchronize do
    @overlay_settings = normalize_overlay_settings(settings)
    render_prompt_locked if @started && @asking
  end
end

#write_delta(delta) ⇒ Object



427
428
429
430
431
# File 'lib/kward/prompt_interface.rb', line 427

def write_delta(delta)
  @mutex.synchronize do
    write_stream_block_locked(nil, delta.to_s, finish: false)
  end
end

#write_stream_block(label, delta, finish: false) ⇒ Object



439
440
441
442
443
# File 'lib/kward/prompt_interface.rb', line 439

def write_stream_block(label, delta, finish: false)
  @mutex.synchronize do
    write_stream_block_locked(label, delta.to_s, finish: finish)
  end
end

#yes?(message, default: false) ⇒ Boolean

Returns:

  • (Boolean)


234
235
236
237
238
239
240
241
242
# File 'lib/kward/prompt_interface.rb', line 234

def yes?(message, default: false)
  answer = ask("#{message} #{default ? "[Y/n]" : "[y/N]"}")
  return default if answer.nil?

  answer = answer.strip.downcase
  return default if answer.empty?

  answer.start_with?("y")
end