iachat/enterprise/app/services/captain
Rodribm10 f3f8a8d5c1 feat(captain): rate limiting with runaway loop detection + bot_handoff
Três camadas de proteção contra runaway token burn no AgentRunnerService:

1. MAX_TURNS_PER_MESSAGE = 15
   Cap dentro de uma única chamada run(). Já estava aplicado;
   agora extraído como constante nomeada.

2. MAX_TURNS_PER_CONVERSATION = 30
   Cap ao longo da vida da conversa. Contador em
   conversation.custom_attributes['captain_turn_count']. Ao atingir,
   dispara bot_handoff automático e responde com mensagem de
   transferência pra humano.

3. TOOL_LOOP_THRESHOLD = 3
   Detecta a mesma (tool_name, args) invocada 3+ vezes no resultado
   de um único run (sintoma do loop faq_lookup que queimou tokens
   em 2026-04-19). Ao detectar: dispara bot_handoff e aborta o turno.

trigger_bot_handoff! aciona conversation.bot_handoff! quando
disponível, removendo a conversa do pipeline automático.

Motivação: dois incidentes reais de queima de crédito OpenAI em
2026-04-19. Ver memory/feedback_never_touch_captain_without_safety_caps.md
pras invariantes completas.

Tests atualizados: mock_result agora stuba :messages (usado pelo
novo tool_loop_detected?) e max_turns esperado é 15.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 11:16:54 -03:00
..
assistant feat(captain): rate limiting with runaway loop detection + bot_handoff 2026-04-19 11:16:54 -03:00
contact_memories fix(captain-memory): temporal memory model + aggressive dedup 2026-04-19 08:30:42 -03:00
copilot feat: Migrate ruby llm captain (#12981) 2025-12-04 18:26:10 +05:30
inter chore(style): fix rubocop offenses and update typing indicators 2026-02-25 15:06:58 -03:00
lifecycle feat(lifecycle): add Dispatcher service with guards→render→send pipeline 2026-04-15 01:53:01 -03:00
llm feat(captain): add AI reports page with insights generation 2026-02-27 07:05:58 -03:00
notifications feat: sistema de notificações de reserva com templates configuráveis 2026-03-01 21:53:11 -03:00
onboarding feat: legacy features to ruby llm (#12994) 2025-12-11 14:17:28 +05:30
payments chore(style): fix rubocop offenses and update typing indicators 2026-02-25 15:06:58 -03:00
reservations chore(style): fix rubocop offenses and update typing indicators 2026-02-25 15:06:58 -03:00
tools fix(captain): aceita DD/MM sem ano e amplia tratamento de requires_input no generate_pix 2026-04-18 18:37:17 -03:00
open_ai_message_builder_service.rb feat(ai): implement dynamic debounce with sidekiq and concurrency locking with redis 2026-03-01 02:04:55 -03:00
tool_registry_service.rb feat: Update UI for Copilot (#11561) 2025-06-02 22:02:03 -05:00