Class: Legion::TTY::Screens::Chat

Inherits:
Base
  • Object
show all
Includes:
CustomCommands, ExportCommands, MessageCommands, ModelCommands, SessionCommands, UiCommands
Defined in:
lib/legion/tty/screens/chat.rb,
lib/legion/tty/screens/chat/ui_commands.rb,
lib/legion/tty/screens/chat/model_commands.rb,
lib/legion/tty/screens/chat/custom_commands.rb,
lib/legion/tty/screens/chat/export_commands.rb,
lib/legion/tty/screens/chat/message_commands.rb,
lib/legion/tty/screens/chat/session_commands.rb

Overview

rubocop:disable Metrics/ClassLength

Defined Under Namespace

Modules: CustomCommands, ExportCommands, MessageCommands, ModelCommands, SessionCommands, UiCommands

Constant Summary collapse

SLASH_COMMANDS =
%w[/help /quit /clear /compact /copy /diff /model /session /cost /export /tools /dashboard
/hotkeys /save /load /sessions /system /delete /plan /palette /extensions /config
/theme /search /grep /stats /personality /undo /history /pin /pins /rename
/context /alias /snippet /debug /uptime /time /bookmark /welcome /tips
/wc /import /mute /autosave /react /macro /tag /tags /repeat /count
/template /fav /favs /log /version
/focus /retry /merge /sort
/chain /info /scroll /summary
/prompt /reset /replace /highlight /multiline
/annotate /annotations /filter /truncate
/tee /pipe
/archive /archives
/calc /rand
/echo /env
/ls /pwd
/wrap /number
/speak /silent
/color /timestamps
/top /bottom /head /tail
/draft /revise
/mark /freq
/about /commands
/ask /define
/status /prefs
/stopwatch /ago
/goto /inject
/transform /concat
/prefix /suffix
/split /swap
/timer /notify].freeze
PERSONALITIES =
{
  'default' => 'You are Legion, an async cognition engine and AI assistant. Be helpful and concise.',
  'concise' => 'You are Legion. Respond in as few words as possible. No filler.',
  'detailed' => 'You are Legion. Provide thorough, detailed explanations with examples when helpful.',
  'friendly' => 'You are Legion, a friendly AI companion. Use a warm, conversational tone.',
  'technical' => 'You are Legion, a senior engineer. Use precise technical language. Include code examples.'
}.freeze

Constants included from CustomCommands

CustomCommands::TEMPLATES

Constants included from UiCommands

UiCommands::CALC_MATH_PATTERN, UiCommands::CALC_SAFE_PATTERN, UiCommands::FREQ_ROW_FMT, UiCommands::FREQ_STOP_WORDS, UiCommands::HELP_TEXT, UiCommands::TIPS

Constants included from MessageCommands

MessageCommands::INJECT_VALID_ROLES, MessageCommands::TRANSFORM_OPS

Instance Attribute Summary collapse

Attributes inherited from Base

#app

Instance Method Summary collapse

Methods inherited from Base

#deactivate, #teardown

Constructor Details

#initialize(app, output: $stdout, input_bar: nil) ⇒ Chat

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



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
102
103
104
105
106
107
108
# File 'lib/legion/tty/screens/chat.rb', line 71

def initialize(app, output: $stdout, input_bar: nil)
  super(app)
  @output = output
  @message_stream = Components::MessageStream.new
  @status_bar = Components::StatusBar.new
  @running = false
  @input_bar = input_bar || build_default_input_bar
  @llm_chat = app.respond_to?(:llm_chat) ? app.llm_chat : nil
  @token_tracker = Components::TokenTracker.new(provider: detect_provider)
  @session_store = SessionStore.new
  @session_name = 'default'
  @plan_mode = false
  @pinned_messages = []
  @aliases = {}
  @snippets = {}
  @macros = {}
  @debug_mode = false
  @session_start = Time.now
  @muted_system = false
  @autosave_enabled = false
  @autosave_interval = 60
  @last_autosave = Time.now
  @recording_macro = nil
  @macro_buffer = []
  @last_command = nil
  @focus_mode = false
  @last_user_input = nil
  @highlights = []
  @multiline_mode = false
  @speak_mode = false
  @silent_mode = false
  @draft = nil
  @stopwatch_start = nil
  @stopwatch_elapsed = 0
  @timer_thread = nil
  @message_prefix = nil
  @message_suffix = nil
end

Instance Attribute Details

#message_streamObject (readonly)

Returns the value of attribute message_stream.



68
69
70
# File 'lib/legion/tty/screens/chat.rb', line 68

def message_stream
  @message_stream
end

#status_barObject (readonly)

Returns the value of attribute status_bar.



68
69
70
# File 'lib/legion/tty/screens/chat.rb', line 68

def status_bar
  @status_bar
end

Instance Method Details

#activateObject

rubocop:enable Metrics/AbcSize, Metrics/MethodLength



112
113
114
115
116
117
118
119
120
121
122
# File 'lib/legion/tty/screens/chat.rb', line 112

def activate
  @running = true
  cfg = safe_config
  @status_bar.update(model: cfg[:provider], session: 'default')
  setup_system_prompt
  @message_stream.add_message(
    role: :system,
    content: "Welcome#{", #{cfg[:name]}" if cfg[:name]}. Type /help for commands."
  )
  @status_bar.update(message_count: @message_stream.messages.size)
end

#handle_input(key) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/legion/tty/screens/chat.rb', line 208

def handle_input(key)
  case key
  when :up
    @message_stream.scroll_up
    :handled
  when :down
    @message_stream.scroll_down
    :handled
  else
    :pass
  end
end

#handle_slash_command(input) ⇒ Object

rubocop:enable Metrics/AbcSize



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/legion/tty/screens/chat.rb', line 153

def handle_slash_command(input)
  return nil unless input.start_with?('/')

  cmd = input.split.first
  unless SLASH_COMMANDS.include?(cmd)
    expanded = @aliases[cmd]
    return nil unless expanded

    return handle_slash_command("#{expanded} #{input.split(nil, 2)[1]}".strip)
  end

  result = dispatch_slash(cmd, input)
  @last_command = input if cmd != '/repeat'
  record_macro_step(input, cmd, result)
  result
end

#handle_user_message(input) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/legion/tty/screens/chat.rb', line 170

def handle_user_message(input)
  @last_user_input = input
  @message_stream.add_message(role: :user, content: input)
  tee_message("[user] #{input}") if @tee_path
  if @plan_mode
    @message_stream.add_message(role: :system, content: '(bookmarked)')
  else
    @message_stream.add_message(role: :assistant, content: '')
    send_to_llm(apply_message_decorators(input))
  end
  @status_bar.update(message_count: @message_stream.messages.size)
  check_autosave
  render_screen
end

#render(width, height) ⇒ Object



202
203
204
205
206
# File 'lib/legion/tty/screens/chat.rb', line 202

def render(width, height)
  return render_focus(width, height) if @focus_mode

  render_normal(width, height)
end

#runObject

rubocop:disable Metrics/AbcSize



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/legion/tty/screens/chat.rb', line 129

def run
  activate
  while @running
    render_screen
    input = read_input
    break if input.nil?

    if @app.respond_to?(:screen_manager) && @app.screen_manager.overlay
      @app.screen_manager.dismiss_overlay
      next
    end

    result = handle_slash_command(input)
    if result == :quit
      auto_save_session
      @running = false
      break
    elsif result.nil?
      handle_user_message(input) unless input.strip.empty?
    end
  end
end

#running?Boolean

Returns:

  • (Boolean)


124
125
126
# File 'lib/legion/tty/screens/chat.rb', line 124

def running?
  @running
end

#send_to_llm(message) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/legion/tty/screens/chat.rb', line 185

def send_to_llm(message)
  unless @llm_chat || daemon_available?
    @message_stream.append_streaming('LLM not configured. Use /help for commands.')
    return
  end

  if daemon_available?
    send_via_daemon(message)
  else
    send_via_direct(message)
  end
rescue StandardError => e
  Legion::Logging.error("send_to_llm failed: #{e.message}") if defined?(Legion::Logging)
  @status_bar.update(thinking: false)
  @message_stream.append_streaming("\n[Error: #{e.message}]")
end