Module: Legion::CLI::Chat::SessionRecovery

Defined in:
lib/legion/cli/chat/session_recovery.rb

Constant Summary collapse

STATES =
%i[none interrupted_prompt interrupted_turn].freeze

Class Method Summary collapse

Class Method Details

.classify(messages) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/legion/cli/chat/session_recovery.rb', line 12

def classify(messages)
  cleaned = filter_artifacts(messages)
  return :none if cleaned.empty?

  last = cleaned.last
  role = msg_role(last)

  case role
  when 'user' then :interrupted_prompt
  when 'tool_result', 'tool' then :interrupted_turn
  when 'assistant'
    tool_calls = last.is_a?(Hash) ? (last[:tool_calls] || last['tool_calls']) : nil
    tool_calls.is_a?(Array) && tool_calls.any? ? :interrupted_turn : :none
  else :none
  end
end

.recover(messages) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/legion/cli/chat/session_recovery.rb', line 29

def recover(messages)
  cleaned = filter_artifacts(messages)
  state = classify(cleaned)

  case state
  when :none
    { state: :none, messages: cleaned, recovery_message: nil }
  when :interrupted_prompt
    msg = 'Continue from where you left off. The previous session was interrupted.'
    { state: :interrupted_prompt, messages: cleaned, recovery_message: msg }
  when :interrupted_turn
    tool_name = detect_interrupted_tool(cleaned)
    msg = 'Continue from where you left off. The previous session was interrupted'
    msg += " during tool execution (#{tool_name})" if tool_name
    msg += '.'
    repaired = repair_orphaned_tool_use(cleaned)
    { state: :interrupted_turn, messages: repaired, recovery_message: msg }
  end
end