fix(captain): preserve customer turn during response rewrite

This commit is contained in:
aakashb95
2026-07-17 18:06:42 +05:30
parent b898cd3738
commit 097c7215ab
2 changed files with 10 additions and 0 deletions
@@ -20,6 +20,7 @@ class Captain::Assistant::AgentRunnerService
def generate_response(message_history: [])
message_to_process, context = run_payload(message_history)
@last_run_result = runner.run(message_to_process, context: context, max_turns: 10)
record_turn_start(@last_run_result)
@last_run_result = rewrite_oversized_response(@last_run_result) if response_too_long?(@last_run_result)
raise "Captain response exceeds the channel limit of #{message_length_limit} characters" if response_too_long?(@last_run_result)
@@ -106,6 +107,12 @@ class Captain::Assistant::AgentRunnerService
)
end
def record_turn_start(result)
history = Array(result.context&.dig(:conversation_history))
turn_start_index = history.rindex { |message| message[:role].to_s == 'user' }
result.context[:captain_v2_turn_start_index] = turn_start_index if turn_start_index
end
def response_too_long?(result)
message_length_limit && response_text(result).length > message_length_limit
end
@@ -58,6 +58,9 @@ class Captain::Assistant::SessionCaptureService
# (assistant replies, tool calls/results, handoff hops).
def current_turn_history
history = Array(context[:conversation_history])
turn_start_index = context[:captain_v2_turn_start_index]
return history[turn_start_index..] if turn_start_index
last_user_index = history.rindex { |message| message[:role].to_s == 'user' }
last_user_index ? history[last_user_index..] : history
end