feat: scenario tools [CW-4597] (#11908)

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Sojan Jose <sojan@pepalo.com>
This commit is contained in:
Shivam Mishra
2025-07-21 16:42:12 +05:30
committed by GitHub
parent bb9e3a5495
commit b71a0da10d
21 changed files with 1139 additions and 6 deletions

View File

@@ -32,6 +32,10 @@ class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::Base
render json: response
end
def tools
@tools = Captain::Assistant.available_agent_tools
end
private
def set_assistant

View File

@@ -18,6 +18,7 @@
#
class Captain::Assistant < ApplicationRecord
include Avatarable
include Concerns::CaptainToolsHelpers
self.table_name = 'captain_assistants'

View File

@@ -21,6 +21,8 @@
# index_captain_scenarios_on_enabled (enabled)
#
class Captain::Scenario < ApplicationRecord
include Concerns::CaptainToolsHelpers
self.table_name = 'captain_scenarios'
belongs_to :assistant, class_name: 'Captain::Assistant'
@@ -31,14 +33,60 @@ class Captain::Scenario < ApplicationRecord
validates :instruction, presence: true
validates :assistant_id, presence: true
validates :account_id, presence: true
validate :validate_instruction_tools
scope :enabled, -> { where(enabled: true) }
before_save :populate_tools
before_save :resolve_tool_references
private
def populate_tools
# TODO: Implement tools population logic
# Validates that all tool references in the instruction are valid.
# Parses the instruction for tool references and checks if they exist
# in the available tools configuration.
#
# @return [void]
# @api private
# @example Valid instruction
# scenario.instruction = "Use [Add Contact Note](tool://add_contact_note) to document"
# scenario.valid? # => true
#
# @example Invalid instruction
# scenario.instruction = "Use [Invalid Tool](tool://invalid_tool) to process"
# scenario.valid? # => false
# scenario.errors[:instruction] # => ["contains invalid tools: invalid_tool"]
def validate_instruction_tools
return if instruction.blank?
tool_ids = extract_tool_ids_from_text(instruction)
return if tool_ids.empty?
available_tool_ids = self.class.available_tool_ids
invalid_tools = tool_ids - available_tool_ids
return unless invalid_tools.any?
errors.add(:instruction, "contains invalid tools: #{invalid_tools.join(', ')}")
end
# Resolves tool references from the instruction text into the tools field.
# Parses the instruction for tool references and materializes them as
# tool IDs stored in the tools JSONB field.
#
# @return [void]
# @api private
# @example
# scenario.instruction = "First [@Add Private Note](tool://add_private_note) then [@Update Priority](tool://update_priority)"
# scenario.save!
# scenario.tools # => ["add_private_note", "update_priority"]
#
# scenario.instruction = "No tools mentioned here"
# scenario.save!
# scenario.tools # => nil
def resolve_tool_references
return if instruction.blank?
tool_ids = extract_tool_ids_from_text(instruction)
self.tools = tool_ids.presence
end
end

View File

@@ -0,0 +1,76 @@
# Provides helper methods for working with Captain agent tools including
# tool resolution, text parsing, and metadata retrieval.
module Concerns::CaptainToolsHelpers
extend ActiveSupport::Concern
# Regular expression pattern for matching tool references in text.
# Matches patterns like [Tool name](tool://tool_id) following markdown link syntax.
TOOL_REFERENCE_REGEX = %r{\[[^\]]+\]\(tool://([^/)]+)\)}
class_methods do
# Returns all available agent tools with their metadata.
# Only includes tools that have corresponding class files and can be resolved.
#
# @return [Array<Hash>] Array of tool hashes with :id, :title, :description, :icon
def available_agent_tools
@available_agent_tools ||= load_agent_tools
end
# Resolves a tool class from a tool ID.
# Converts snake_case tool IDs to PascalCase class names and constantizes them.
#
# @param tool_id [String] The snake_case tool identifier
# @return [Class, nil] The tool class if found, nil if not resolvable
def resolve_tool_class(tool_id)
class_name = "Captain::Tools::#{tool_id.classify}Tool"
class_name.safe_constantize
end
# Returns an array of all available tool IDs.
# Convenience method that extracts just the IDs from available_agent_tools.
#
# @return [Array<String>] Array of available tool IDs
def available_tool_ids
@available_tool_ids ||= available_agent_tools.map { |tool| tool[:id] }
end
private
# Loads agent tools from the YAML configuration file.
# Filters out tools that cannot be resolved to actual classes.
#
# @return [Array<Hash>] Array of resolvable tools with metadata
# @api private
def load_agent_tools
tools_config = YAML.load_file(Rails.root.join('config/agents/tools.yml'))
tools_config.filter_map do |tool_config|
tool_class = resolve_tool_class(tool_config['id'])
if tool_class
{
id: tool_config['id'],
title: tool_config['title'],
description: tool_config['description'],
icon: tool_config['icon']
}
else
Rails.logger.warn "Tool class not found for ID: #{tool_config['id']}"
nil
end
end
end
end
# Extracts tool IDs from text containing tool references.
# Parses text for (tool://tool_id) patterns and returns unique tool IDs.
#
# @param text [String] Text to parse for tool references
# @return [Array<String>] Array of unique tool IDs found in the text
def extract_tool_ids_from_text(text)
return [] if text.blank?
tool_matches = text.scan(TOOL_REFERENCE_REGEX)
tool_matches.flatten.uniq
end
end

View File

@@ -7,6 +7,10 @@ class Captain::AssistantPolicy < ApplicationPolicy
true
end
def tools?
@account_user.administrator?
end
def create?
@account_user.administrator?
end

View File

@@ -0,0 +1,6 @@
json.array! @tools do |tool|
json.id tool[:id]
json.title tool[:title]
json.description tool[:description]
json.icon tool[:icon]
end

View File

@@ -0,0 +1,26 @@
class Captain::Tools::AddContactNoteTool < Captain::Tools::BasePublicTool
description 'Add a note to a contact profile'
param :note, type: 'string', desc: 'The note content to add to the contact'
def perform(tool_context, note:)
contact = find_contact(tool_context.state)
return 'Contact not found' unless contact
return 'Note content is required' if note.blank?
log_tool_usage('add_contact_note', { contact_id: contact.id, note_length: note.length })
create_contact_note(contact, note)
"Note added successfully to contact #{contact.name} (ID: #{contact.id})"
end
private
def create_contact_note(contact, note)
contact.notes.create!(content: note)
end
def permissions
%w[contact_manage]
end
end

View File

@@ -0,0 +1,34 @@
class Captain::Tools::AddLabelToConversationTool < Captain::Tools::BasePublicTool
description 'Add a label to a conversation'
param :label_name, type: 'string', desc: 'The name of the label to add'
def perform(tool_context, label_name:)
conversation = find_conversation(tool_context.state)
return 'Conversation not found' unless conversation
label_name = label_name&.strip&.downcase
return 'Label name is required' if label_name.blank?
label = find_label(label_name)
return 'Label not found' unless label
add_label_to_conversation(conversation, label_name)
log_tool_usage('added_label', conversation_id: conversation.id, label: label_name)
"Label '#{label_name}' added to conversation ##{conversation.display_id}"
end
private
def find_label(label_name)
account_scoped(Label).find_by(title: label_name)
end
def add_label_to_conversation(conversation, label_name)
conversation.add_labels(label_name)
rescue StandardError => e
Rails.logger.error "Failed to add label to conversation: #{e.message}"
raise
end
end

View File

@@ -0,0 +1,33 @@
class Captain::Tools::AddPrivateNoteTool < Captain::Tools::BasePublicTool
description 'Add a private note to a conversation'
param :note, type: 'string', desc: 'The private note content'
def perform(tool_context, note:)
conversation = find_conversation(tool_context.state)
return 'Conversation not found' unless conversation
return 'Note content is required' if note.blank?
log_tool_usage('add_private_note', { conversation_id: conversation.id, note_length: note.length })
create_private_note(conversation, note)
'Private note added successfully'
end
private
def create_private_note(conversation, note)
conversation.messages.create!(
account: @assistant.account,
inbox: conversation.inbox,
sender: @assistant,
message_type: :outgoing,
content: note,
private: true
)
end
def permissions
%w[conversation_manage conversation_unassigned_manage conversation_participating_manage]
end
end

View File

@@ -0,0 +1,45 @@
require 'agents'
class Captain::Tools::BasePublicTool < Agents::Tool
def initialize(assistant)
@assistant = assistant
super()
end
def active?
# Public tools are always active
true
end
def permissions
# Override in subclasses to specify required permissions
# Returns empty array for public tools (no permissions required)
[]
end
private
def account_scoped(model_class)
model_class.where(account_id: @assistant.account_id)
end
def find_conversation(state)
conversation_id = state&.dig(:conversation, :id)
return nil unless conversation_id
account_scoped(::Conversation).find_by(id: conversation_id)
end
def find_contact(state)
contact_id = state&.dig(:contact, :id)
return nil unless contact_id
account_scoped(::Contact).find_by(id: contact_id)
end
def log_tool_usage(action, details = {})
Rails.logger.info do
"#{self.class.name}: #{action} for assistant #{@assistant&.id} - #{details.inspect}"
end
end
end

View File

@@ -0,0 +1,48 @@
class Captain::Tools::UpdatePriorityTool < Captain::Tools::BasePublicTool
description 'Update the priority of a conversation'
param :priority, type: 'string', desc: 'The priority level: low, medium, high, urgent, or nil to remove priority'
def perform(tool_context, priority:)
@conversation = find_conversation(tool_context.state)
return 'Conversation not found' unless @conversation
@normalized_priority = normalize_priority(priority)
return "Invalid priority. Valid options: #{valid_priority_options}" unless valid_priority?(@normalized_priority)
log_tool_usage('update_priority', { conversation_id: @conversation.id, priority: priority })
execute_priority_update
end
private
def execute_priority_update
update_conversation_priority(@conversation, @normalized_priority)
priority_text = @normalized_priority || 'none'
"Priority updated to '#{priority_text}' for conversation ##{@conversation.display_id}"
end
def normalize_priority(priority)
priority == 'nil' || priority.blank? ? nil : priority
end
def valid_priority?(priority)
valid_priorities.include?(priority)
end
def valid_priorities
@valid_priorities ||= [nil] + Conversation.priorities.keys
end
def valid_priority_options
(valid_priorities.compact + ['nil']).join(', ')
end
def update_conversation_priority(conversation, priority)
conversation.update!(priority: priority)
end
def permissions
%w[conversation_manage conversation_unassigned_manage conversation_participating_manage]
end
end