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

Inherits:
Base
  • Object
show all
Includes:
Logging::Helper, 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 /tool
/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
/gaia /skills /apollo].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



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
109
110
111
112
113
114
115
# File 'lib/legion/tty/screens/chat.rb', line 75

def initialize(app, output: $stdout, input_bar: nil) # rubocop:disable Lint/UnusedMethodArgument
  super(app)
  @output = output
  @message_stream = Components::MessageStream.new
  @status_bar = Components::StatusBar.new
  @llm_chat = nil
  @token_tracker = Components::TokenTracker.new(
    provider: detect_provider,
    model: nil
  )
  @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
  @streaming = false
  @apollo_autoingest = false
end

Instance Attribute Details

#message_streamObject (readonly)

Returns the value of attribute message_stream.



72
73
74
# File 'lib/legion/tty/screens/chat.rb', line 72

def message_stream
  @message_stream
end

#status_barObject (readonly)

Returns the value of attribute status_bar.



72
73
74
# File 'lib/legion/tty/screens/chat.rb', line 72

def status_bar
  @status_bar
end

Instance Method Details

#activateObject

rubocop:enable Metrics/AbcSize, Metrics/MethodLength



119
120
121
122
123
124
125
126
127
128
# File 'lib/legion/tty/screens/chat.rb', line 119

def activate
  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



202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/legion/tty/screens/chat.rb', line 202

def handle_input(key)
  case key
  when :page_up
    @message_stream.scroll_up(10)
    :handled
  when :page_down
    @message_stream.scroll_down(10)
    :handled
  else
    :pass
  end
end

#handle_line(line) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
# File 'lib/legion/tty/screens/chat.rb', line 138

def handle_line(line)
  return :handled if line.strip.empty?

  result = handle_slash_command(line)
  if result == :quit
    auto_save_session
    return :quit
  end
  handle_user_message(line) if result.nil?
  :handled
end

#handle_slash_command(input) ⇒ Object



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

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



167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/legion/tty/screens/chat.rb', line 167

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
end

#needs_input_bar?Boolean

Returns:

  • (Boolean)


130
131
132
# File 'lib/legion/tty/screens/chat.rb', line 130

def needs_input_bar?
  true
end

#render(width, height) ⇒ Object



196
197
198
199
200
# File 'lib/legion/tty/screens/chat.rb', line 196

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

  render_normal(width, height)
end

#send_to_llm(message) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/legion/tty/screens/chat.rb', line 181

def send_to_llm(message)
  unless daemon_available?
    @message_stream.append_streaming(
      'LegionIO daemon is not running. Start it with: legionio start'
    )
    return
  end

  send_via_daemon(message)
rescue StandardError => e
  log.error { "send_to_llm failed: #{e.message}" }
  @status_bar.update(thinking: false)
  @message_stream.append_streaming("\n[Error: #{e.message}]")
end

#streaming?Boolean

Returns:

  • (Boolean)


134
135
136
# File 'lib/legion/tty/screens/chat.rb', line 134

def streaming?
  @streaming
end