Files
Shivam MishraandGitHub 9749a3dc96 feat: capture captain sessions for v2 assistant responses [CW-7485] (#14971)
Records a `Captain::Session` row for every Captain V2 assistant response
delivered in a conversation, so we can show how a response was generated
and report on credit, FAQ, and document usage. Stacked on #14970 (the
`captain_sessions` model).

## What changed

- `FaqLookupTool` now records the retrieved FAQ ids (and their backing
document ids) into the shared run state, accumulated across tool calls.
- `AgentRunnerService` exposes the raw ai-agents run result via
`last_run_result`; the `generate_response` return shape is unchanged, so
the playground path is unaffected.
- New `Captain::Assistant::SessionCaptureService` builds the session:
scenario resolved from the answering agent name, model from
`assistant.agent_model`, token usage plus the trimmed current-turn
conversation history stored in `run_context`.
- `ResponseBuilderJob` captures after delivery: `credits_consumed`
mirrors the actual charge (1.0 for a billed response, 0.0 for handoffs,
where the session points at the customer-facing handoff message).
Capture runs outside the delivery transaction and swallows its own
failures, so a logging bug can never block or roll back a customer
reply.

V1 responses and copilot are out of scope; copilot capture comes next.

## How to test

On an account with `captain_integration_v2` enabled and an inbox
connected to an assistant with approved FAQs, send a customer message on
a pending conversation. After the assistant replies, a
`Captain::Session` row should exist with the conversation as subject,
the reply message as result, the FAQs/documents used, and the run
context for that turn. Asking for a human agent should produce a
zero-credit session pointing at the handoff message.

<img width="2428" height="1058" alt="CleanShot 2026-07-15 at 17 25
40@2x"
src="https://github.com/user-attachments/assets/d8e44923-c17b-494f-8c33-c8fa4219438c"
/>
2026-07-16 18:20:44 +05:30

73 lines
2.0 KiB
Ruby

module Concerns::Agentable
extend ActiveSupport::Concern
DEFAULT_TEMPERATURE = 0.5
def agent
Agents::Agent.new(
name: agent_name,
instructions: ->(context) { agent_instructions(context) },
tools: agent_tools,
model: agent_model,
temperature: temperature.presence&.to_f || DEFAULT_TEMPERATURE,
response_schema: agent_response_schema
)
end
def agent_instructions(context = nil)
enhanced_context = prompt_context
if context
state = context.context[:state] || {}
config = state[:assistant_config] || {}
enhanced_context = enhanced_context.merge(
current_time: format_current_time(state[:timezone]),
conversation: state[:conversation] || {},
contact: config['feature_contact_attributes'].present? ? state[:contact] : nil,
campaign: state[:campaign] || {}
)
end
Captain::PromptRenderer.render(template_name, enhanced_context.with_indifferent_access)
end
def agent_model
route = Llm::FeatureRouter.resolve(feature: 'assistant', account: account)
return route[:model] if route[:source] == :account_override || account&.feature_enabled?('captain_integration_v2')
installation_model.presence || route[:model]
end
private
def agent_name
raise NotImplementedError, "#{self.class} must implement agent_name"
end
def template_name
self.class.name.demodulize.underscore
end
def agent_tools
[] # Default implementation, override if needed
end
def installation_model
InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_MODEL')&.value
end
def agent_response_schema
Captain::ResponseSchema
end
def format_current_time(timezone)
tz = ActiveSupport::TimeZone[timezone] if timezone.present?
time = tz ? Time.current.in_time_zone(tz) : Time.current
time.strftime('%A, %B %d, %Y %I:%M %p %Z')
end
def prompt_context
raise NotImplementedError, "#{self.class} must implement prompt_context"
end
end