Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: add crypto utilities to AI tool runner (#39343)

Samab51aa7d81bd
diff --git a/Gemfile.lock b/Gemfile.lock
index e6abe8ffc78..efefc8a5bc3 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -304,7 +304,7 @@ GEM
mime-types-data (~> 3.2025, >= 3.2025.0507)
mime-types-data (3.2026.0407)
mini_mime (1.1.5)
- mini_racer (0.20.0)
+ mini_racer (0.21.0)
libv8-node (~> 24.12.0.1)
mini_scheduler (0.18.0)
sidekiq (>= 6.5, < 8.0)
@@ -1081,7 +1081,7 @@ CHECKSUMS
mime-types (3.7.0) sha256=dcebf61c246f08e15a4de34e386ebe8233791e868564a470c3fe77c00eed5e56
mime-types-data (3.2026.0407) sha256=909395cf029731355136527aa11bf58ea0655ee782359ccbf32c66238a8cadb3
mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef
- mini_racer (0.20.0) sha256=860e944c20894413c0e4921f8531166b22180d988e75a5dc152be9505da91ff2
+ mini_racer (0.21.0) sha256=caacdfe0713dc611452f83e2d5a5250a4607da409050bbaf5dca0f5104ee4c59
mini_scheduler (0.18.0) sha256=d2f084f38da8d76c5844a92f0d6bd01fc9982a8b5e6c7679b6cf44c82da33503
mini_sql (1.6.0) sha256=5296637f6a4af5bb43e06788037e9a2968ff9c8eb65928befcba8cb41f42d6ee
mini_suffix (0.3.3) sha256=8d1d33f92f69a2247c9b7d27173235da90479d955cdb863b63a7f53843b722e7
diff --git a/plugins/discourse-ai/lib/agents/tool_runner.rb b/plugins/discourse-ai/lib/agents/tool_runner.rb
index 3ff500bb3e6..9a3fb1c2be8 100644
--- a/plugins/discourse-ai/lib/agents/tool_runner.rb
+++ b/plugins/discourse-ai/lib/agents/tool_runner.rb
@@ -1,5 +1,12 @@
# frozen_string_literal: true
+require_relative "tool_runner/http"
+require_relative "tool_runner/llm"
+require_relative "tool_runner/index"
+require_relative "tool_runner/upload"
+require_relative "tool_runner/discourse"
+require_relative "tool_runner/crypto"
+
module DiscourseAi
module Agents
class ToolRunner
@@ -21,6 +28,13 @@ module DiscourseAi
CUSTOM_FIELD_MODELS = { "post" => Post, "topic" => Topic, "user" => User }.freeze
+ include HTTP
+ include Llm
+ include Index
+ include Upload
+ include Discourse
+ include Crypto
+
def initialize(
parameters:,
llm:,
@@ -50,34 +64,7 @@ module DiscourseAi
end
def system_guardian
- @system_guardian ||= Guardian.new(Discourse.system_user)
- end
-
- def resolve_user(username)
- if username.present?
- User.find_by(username: username)
- else
- @bot_user || Discourse.system_user
- end
- end
-
- def resolve_guardian(username)
- user = resolve_user(username)
- return nil, nil if user.nil?
- guardian = user.staged? ? system_guardian : Guardian.new(user)
- [user, guardian]
- end
-
- def resolve_category(category_id_or_name)
- if category_id_or_name.is_a?(Integer) ||
- category_id_or_name.to_i.to_s == category_id_or_name.to_s
- Category.find_by(id: category_id_or_name.to_i)
- else
- Category
- .where(name: category_id_or_name)
- .or(Category.where(slug: category_id_or_name))
- .first
- end
+ @system_guardian ||= Guardian.new(::Discourse.system_user)
end
def mini_racer_context
@@ -94,6 +81,7 @@ module DiscourseAi
attach_upload(ctx)
attach_chain(ctx)
attach_secrets(ctx)
+ attach_crypto(ctx)
attach_sleep(ctx)
attach_discourse(ctx)
ctx.eval(framework_script)
@@ -151,8 +139,74 @@ module DiscourseAi
},
};
+ const crypto = {
+ hmacSha256: function(key, data) {
+ return _crypto_hmac_sha256_hex(key, data);
+ },
+ hmacSha1: function(key, data) {
+ return _crypto_hmac_sha1_hex(key, data);
+ },
+ hmacSha256Base64: function(key, data) {
+ return _crypto_hmac_sha256_base64(key, data);
+ },
+ hmacSha1Base64: function(key, data) {
+ return _crypto_hmac_sha1_base64(key, data);
+ },
+ hmacSha256Bytes: function(key, data) {
+ return _crypto_hmac_sha256_bytes(key, data);
+ },
+ hmacSha1Bytes: function(key, data) {
+ return _crypto_hmac_sha1_bytes(key, data);
+ },
+ sha256: function(data) {
+ return _crypto_sha256_hex(data);
+ },
+ sha1: function(data) {
+ return _crypto_sha1_hex(data);
+ },
+ md5: function(data) {
+ return _crypto_md5_hex(data);
+ },
+ sha256Base64: function(data) {
+ return _crypto_sha256_base64(data);
+ },
+ sha1Base64: function(data) {
+ return _crypto_sha1_base64(data);
+ },
+ md5Base64: function(data) {
+ return _crypto_md5_base64(data);
+ },
+ sha256Bytes: function(data) {
+ return _crypto_sha256_bytes(data);
+ },
+ sha1Bytes: function(data) {
+ return _crypto_sha1_bytes(data);
+ },
+ base64Encode: function(text) {
+ return _crypto_base64_encode(text);
+ },
+ base64Decode: function(base64) {
+ return _crypto_base64_decode(base64);
+ },
+ base64UrlEncode: function(text) {
+ return _crypto_base64_url_encode(text);
+ },
+ base64UrlDecode: function(base64) {
+ return _crypto_base64_url_decode(base64);
+ },
+ signRsaSha256: function(pemPrivateKey, data) {
+ return _crypto_sign_rsa_sha256(pemPrivateKey, data);
+ },
+ signRsaSha1: function(pemPrivateKey, data) {
+ return _crypto_sign_rsa_sha1(pemPrivateKey, data);
+ },
+ randomBytes: function(length) {
+ return _crypto_random_bytes(length);
+ },
+ };
+
const discourse = {
- baseUrl: #{Discourse.base_url.to_json},
+ baseUrl: #{::Discourse.base_url.to_json},
search: function(params) {
return _discourse_search(params);
},
@@ -305,7 +359,7 @@ module DiscourseAi
source_bindings = @secret_bindings || tool.secret_bindings
missing_aliases = tool.missing_secret_aliases(bindings: source_bindings)
if missing_aliases.present?
- raise Discourse::InvalidParameters.new(
+ raise ::Discourse::InvalidParameters.new(
I18n.t(
"discourse_ai.tools.secret_runtime.missing_required_aliases",
aliases: missing_aliases.join(", "),
@@ -374,106 +428,6 @@ module DiscourseAi
@secrets_cache = secret_ids.present? ? AiSecret.where(id: secret_ids).index_by(&:id) : {}
end
- def rag_search(query, filenames: nil, limit: 10)
- RagDocumentFragment
- .search(
- target_id: tool.id,
- target_type: "AiTool",
- query: query,
- filenames: filenames,
- limit: limit,
- )
- .map { |fragment| { fragment: fragment[:fragment], metadata: fragment[:metadata] } }
- end
-
- def rag_get_file(filename)
- RagDocumentFragment.read_file(target_id: tool.id, target_type: "AiTool", filename: filename)
- end
-
- def attach_truncate(mini_racer_context)
- mini_racer_context.attach(
- "_llm_truncate",
- ->(text, length) do
- @llm.tokenizer.truncate(text, length, strict: SiteSetting.ai_strict_token_counting)
- end,
- )
-
- mini_racer_context.attach(
- "_llm_generate",
- ->(prompt, options) do
- in_attached_function do
- options ||= {}
- response_format = options["response_format"]
-
- response_format = { "type" => "json_object" } if options["json"]
-
- if response_format && !response_format.is_a?(Hash)
- raise Discourse::InvalidParameters.new("response_format must be a hash")
- end
- @llm.generate(
- convert_js_prompt_to_ruby(prompt),
- user: llm_user,
- feature_name: "custom_tool_#{tool.name}",
- response_format: response_format,
- temperature: options["temperature"],
- top_p: options["top_p"],
- max_tokens: options["max_tokens"],
- stop_sequences: options["stop_sequences"],
- )
- end
- end,
- )
- end
-
- def convert_js_prompt_to_ruby(prompt)
- if prompt.is_a?(String)
- prompt
- elsif prompt.is_a?(Hash)
- messages = prompt["messages"]
- if messages.blank? || !messages.is_a?(Array)
- raise Discourse::InvalidParameters.new("Prompt must have messages")
- end
- messages.each(&:symbolize_keys!)
- messages.each { |message| message[:type] = message[:type].to_sym }
- DiscourseAi::Completions::Prompt.new(messages: prompt["messages"])
- else
- raise Discourse::InvalidParameters.new("Prompt must be a string or a hash")
- end
- end
-
- def llm_user
- @llm_user ||=
- begin
- post&.user || @bot_user
- end
- end
-
- def post
- return @post if defined?(@post)
- post_id = @context.post_id
- @post = post_id && Post.find_by(id: post_id)
- end
-
- def attach_index(mini_racer_context)
- mini_racer_context.attach(
- "_index_search",
- ->(*params) do
- in_attached_function do
- query, options = params
- self.running_attached_function = true
- options ||= {}
- options = options.symbolize_keys
- self.rag_search(query, **options)
- end
- end,
- )
-
- mini_racer_context.attach(
- "_index_get_file",
- ->(filename) { in_attached_function { rag_get_file(filename) } },
- )
- end
-
def attach_chain(mini_racer_context)
mini_racer_context.attach("_chain_set_custom_raw", ->(raw) { self.custom_raw = raw })
mini_racer_context.attach(
@@ -519,721 +473,6 @@ module DiscourseAi
)
end
- def attach_discourse(mini_racer_context)
- mini_racer_context.attach(
- "_discourse_get_post",
- ->(post_id) do
- in_attached_function do
- post = Post.find_by(id: post_id)
- return nil if post.nil?
- obj =
- recursive_as_json(
- PostSerializer.new(post, scope: system_guardian, root: false, add_raw: true),
- )
- topic_obj =
- recursive_as_json(
- ListableTopicSerializer.new(post.topic, scope: system_guardian, root: false),
- )
- obj["topic"] = topic_obj
- obj
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_get_topic",
- ->(topic_id) do
- in_attached_function do
- topic = Topic.find_by(id: topic_id)
- return nil if topic.nil?
- data =
- recursive_as_json(
- ListableTopicSerializer.new(topic, scope: system_guardian, root: false),
- )
- data["tags"] = topic.tags.pluck(:name)
- data["first_post_id"] = topic.first_post&.id
- data["category_id"] = topic.category_id
- data["category_name"] = topic.category&.name
- data["category_slug"] = topic.category&.slug
- data
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_get_user",
- ->(user_id_or_username) do
- in_attached_function do
- user = nil
-
- if user_id_or_username.is_a?(Integer) ||
- user_id_or_username.to_i.to_s == user_id_or_username
- user = User.find_by(id: user_id_or_username.to_i)
- else
- user = User.find_by(username: user_id_or_username)
- end
-
- return nil if user.nil?
-
- recursive_as_json(UserSerializer.new(user, scope: system_guardian, root: false))
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_respond_to_agent",
- ->(agent_name, params) do
- in_attached_function do
- # if we have 1000s of agents this can be slow ... we may need to optimize
- agent_class = AiAgent.all_agents.find { |agent| agent.name == agent_name }
- return { error: "Agent not found" } if agent_class.nil?
-
- agent = agent_class.new
- bot = DiscourseAi::Agents::Bot.as(@bot_user || agent.user, agent: agent)
- playground = DiscourseAi::AiBot::Playground.new(bot)
-
- if @context.post_id
- post = Post.find_by(id: @context.post_id)
- return { error: "Post not found" } if post.nil?
-
- reply_post =
- playground.reply_to(
- post,
- custom_instructions: params["instructions"],
- whisper: params["whisper"],
- )
-
- if reply_post
- return(
- { success: true, post_id: reply_post.id, post_number: reply_post.post_number }
- )
- else
- return { error: "Failed to create reply" }
- end
- elsif @context.message_id && @context.channel_id
- message = Chat::Message.find_by(id: @context.message_id)
- channel = Chat::Channel.find_by(id: @context.channel_id)
- return { error: "Message or channel not found" } if message.nil? || channel.nil?
-
- reply =
- playground.reply_to_chat_message(message, channel, @context.context_post_ids)
-
- if reply
- return { success: true, message_id: reply.id }
- else
- return { error: "Failed to create chat reply" }
- end
- else
- return { error: "No valid context for response" }
- end
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_create_chat_message",
- ->(params) do
- in_attached_function do
- params = params.symbolize_keys
- channel_name = params[:channel_name]
- username = params[:username]
- message = params[:message]
-
- return { error: "Missing required parameter: channel_name" } if channel_name.blank?
- return { error: "Missing required parameter: message" } if message.blank?
-
- user, guardian = resolve_guardian(username)
- return { error: "User not found: #{username}" } if user.nil?
-
- channel = Chat::Channel.find_by(name: channel_name)
- channel ||= Chat::Channel.find_by(slug: channel_name.parameterize)
- return { error: "Channel not found: #{channel_name}" } if channel.nil?
-
- begin
- message =
- ChatSDK::Message.create(
- raw: message,
- channel_id: channel.id,
- guardian: guardian,
- enforce_membership: !channel.direct_message_channel?,
- )
-
- {
- success: true,
- message_id: message.id,
- message: message.message,
- created_at: message.created_at.iso8601,
- }
- rescue => e
- { error: "Failed to create chat message: #{e.message}" }
- end
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_create_staged_user",
- ->(params) do
- in_attached_function do
- params = params.symbolize_keys
- email = params[:email]
- username = params[:username]
- name = params[:name]
-
- # Validate parameters
- return { error: "Missing required parameter: email" } if email.blank?
- return { error: "Missing required parameter: username" } if username.blank?
-
- # Check if user already exists
- existing_user = User.find_by_email(email) || User.find_by_username(username)
- return { error: "User already exists", user_id: existing_user.id } if existing_user
-
- begin
- user =
- User.create!(
- email: email,
- username: username,
- name: name || username,
- staged: true,
- approved: true,
- trust_level: TrustLevel[0],
- )
-
- { success: true, user_id: user.id, username: user.username, email: user.email }
- rescue => e
- { error: "Failed to create staged user: #{e.message}" }
- end
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_create_topic",
- ->(params) do
- in_attached_function do
- params = params.symbolize_keys
- category_name = params[:category_name]
- category_id = params[:category_id]
- title = params[:title]
- raw = params[:raw]
- username = params[:username]
- tags = params[:tags]
-
- if category_id.blank? && category_name.blank?
- return { error: "Missing required parameter: category_id or category_name" }
- end
- return { error: "Missing required parameter: title" } if title.blank?
- return { error: "Missing required parameter: raw" } if raw.blank?
-
- user, guardian = resolve_guardian(username)
- return { error: "User not found: #{username}" } if user.nil?
-
- category = resolve_category(category_id.presence || category_name)
- return { error: "Category not found" } if category.nil?
- return { error: "Permission denied" } unless guardian.can_create?(Topic, category)
-
- begin
- post_creator =
- PostCreator.new(
- user,
- title: title,
- raw: raw,
- category: category.id,
- tags: tags,
- skip_validations: true,
- guardian: guardian,
- )
-
- post = post_creator.create
-
- if post_creator.errors.present?
- return { error: post_creator.errors.full_messages.join(", ") }
- end
-
- {
- success: true,
- topic_id: post.topic_id,
- post_id: post.id,
- topic_slug: post.topic.slug,
- topic_url: post.topic.url,
- }
- rescue => e
- { error: "Failed to create topic: #{e.message}" }
- end
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_create_post",
- ->(params) do
- in_attached_function do
- params = params.symbolize_keys
- topic_id = params[:topic_id]
- raw = params[:raw]
- username = params[:username]
- reply_to_post_number = params[:reply_to_post_number]
-
- # Validate parameters
- return { error: "Missing required parameter: topic_id" } if topic_id.blank?
- return { error: "Missing required parameter: raw" } if raw.blank?
-
- user, guardian = resolve_guardian(username)
- return { error: "User not found: #{username}" } if user.nil?
-
- topic = Topic.find_by(id: topic_id)
- return { error: "Topic not found" } if topic.nil?
- return { error: "Permission denied" } unless guardian.can_create?(Post, topic)
-
- begin
- post_creator =
- PostCreator.new(
- user,
- raw: raw,
- topic_id: topic_id,
- reply_to_post_number: reply_to_post_number,
- skip_validations: true,
- guardian: guardian,
- )
-
- post = post_creator.create
-
- if post_creator.errors.present?
- return { error: post_creator.errors.full_messages.join(", ") }
- end
-
- {
- success: true,
- post_id: post.id,
- post_number: post.post_number,
- cooked: post.cooked,
- }
- rescue => e
- { error: "Failed to create post: #{e.message}" }
- end
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_search",
- ->(params) do
- in_attached_function do
- search_params = params.symbolize_keys
- if search_params.delete(:with_private)
- search_params[:current_user] = Discourse.system_user
- end
- search_params[:result_style] = :detailed
- results = DiscourseAi::Utils::Search.perform_search(**search_params)
- recursive_as_json(results)
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_get_agent",
- ->(agent_name) do
- in_attached_function do
- agent = AiAgent.find_by(name: agent_name)
-
- return { error: "Agent not found" } if agent.nil?
-
- # Return a subset of relevant agent attributes
- {
- agent:
- agent.attributes.slice(
- "id",
- "name",
- "description",
- "enabled",
- "system_prompt",
- "temperature",
- "top_p",
- "vision_enabled",
- "tools",
- "max_context_posts",
- "allow_chat_channel_mentions",
- "allow_chat_direct_messages",
- "allow_topic_mentions",
- "allow_personal_messages",
- ),
- }
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_update_agent",
- ->(agent_id_or_name, updates) do
- in_attached_function do
- # Find agent by ID or name
- agent = nil
- if agent_id_or_name.is_a?(Integer) || agent_id_or_name.to_i.to_s == agent_id_or_name
- agent = AiAgent.find_by(id: agent_id_or_name.to_i)
- else
- agent = AiAgent.find_by(name: agent_id_or_name)
- end
-
- return { error: "Agent not found" } if agent.nil?
-
- allowed_updates = {}
-
- if updates["system_prompt"].present?
- allowed_updates[:system_prompt] = updates["system_prompt"]
- end
-
- if updates["temperature"].is_a?(Numeric)
- allowed_updates[:temperature] = updates["temperature"]
- end
-
- allowed_updates[:top_p] = updates["top_p"] if updates["top_p"].is_a?(Numeric)
-
- if updates["description"].present?
- allowed_updates[:description] = updates["description"]
- end
-
- allowed_updates[:enabled] = updates["enabled"] if updates["enabled"].is_a?(
- TrueClass,
- ) || updates["enabled"].is_a?(FalseClass)
-
- if agent.update(allowed_updates)
- return(
- {
- success: true,
- agent:
- agent.attributes.slice(
- "id",
- "name",
- "description",
- "enabled",
- "system_prompt",
- "temperature",
- "top_p",
- ),
- }
- )
- else
- return { error: agent.errors.full_messages.join(", ") }
- end
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_edit_post",
- ->(post_id, raw, options) do
- in_attached_function do
- post = Post.find_by(id: post_id)
- return { error: "Post not found" } if post.nil?
-
- options ||= {}
- edit_reason = options["edit_reason"]
-
- user, guardian = resolve_guardian(options["username"])
- return { error: "User not found: #{options["username"]}" } if user.nil?
- return { error: "Permission denied" } unless guardian.can_edit?(post)
-
- revisor = PostRevisor.new(post)
- if revisor.revise!(user, { raw: raw, edit_reason: edit_reason })
- { success: true, post_id: post.id }
- else
- { error: post.errors.full_messages.join(", ") }
- end
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_edit_topic",
- ->(topic_id, updates, options) do
- in_attached_function do
- topic = Topic.find_by(id: topic_id)
- return { error: "Topic not found" } if topic.nil?
-
- updates ||= {}
- options ||= {}
-
- user, guardian = resolve_guardian(options["username"])
- return { error: "User not found: #{options["username"]}" } if user.nil?
- return { error: "Permission denied" } unless guardian.can_see?(topic)
-
- # Handle category change
- if updates.key?("category")
- if topic.private_message?
- return { error: "Cannot change category of private messages" }
- end
-
- category = resolve_category(updates["category"])
- return { error: "Category not found" } if category.nil?
-
- unless guardian.can_move_topic_to_category?(category.id)
- return { error: "Permission denied" }
- end
-
- unless topic.change_category_to_id(category.id, silent: !!options["silent"])
- return { error: "Failed to change category", details: topic.errors.full_messages }
- end
- end
-
- # Handle visibility change
- if updates.key?("visible")
- unless guardian.can_toggle_topic_visibility?(topic)
- return { error: "Permission denied" }
- end
-
- visibility_reason =
- Topic.visibility_reasons[
- updates["visible"] ? :manually_relisted : :manually_unlisted
- ]
-
- topic.update_status(
- "visible",
- updates["visible"],
- user,
- { visibility_reason_id: visibility_reason },
- )
- end
-
- # Handle tags change
- if updates.key?("tags")
- unless DiscourseTagging.tag_topic_by_names(
- topic,
- guardian,
- updates["tags"],
- append: !!options["append"],
- )
- return { error: "Failed to apply tags", details: topic.errors.full_messages }
- end
- topic.first_post&.publish_change_to_clients!(:revised)
- end
-
- {
- success: true,
- topic: {
- id: topic.id,
- category_id: topic.category_id,
- category_name: topic.category&.name,
- category_slug: topic.category&.slug,
- tags: topic.tags.pluck(:name),
- visible: topic.visible,
- visibility_reason_id: topic.visibility_reason_id,
- },
- }
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_get_custom_field",
- ->(type, id, key) do
- in_attached_function do
- return { error: "Invalid type: #{type}" } unless CUSTOM_FIELD_MODELS.key?(type)
- model = find_model_by_type(type, id)
- return nil if model.nil?
- model.custom_fields[key]
- end
- end,
- )
-
- mini_racer_context.attach(
- "_discourse_set_custom_field",
- ->(type, id, key, value) do
- in_attached_function do
- return { error: "Invalid type: #{type}" } unless CUSTOM_FIELD_MODELS.key?(type)
- return { error: "Key is required" } if key.blank?
- if key.to_s.length > MAX_CUSTOM_FIELD_KEY_LENGTH
- return { error: "Key too long (max #{MAX_CUSTOM_FIELD_KEY_LENGTH} characters)" }
- end
- if value.to_s.length > MAX_CUSTOM_FIELD_VALUE_LENGTH
- return { error: "Value too long (max #{MAX_CUSTOM_FIELD_VALUE_LENGTH} characters)" }
- end
-
- model = find_model_by_type(type, id)
- return { error: "#{type.capitalize} not found: #{id}" } if model.nil?
-
- model.custom_fields[key] = value
- model.save_custom_fields
-
- { success: true, key: key, value: model.custom_fields[key] }
- end
- end,
- )
- end
-
- def attach_upload(mini_racer_context)
- mini_racer_context.attach(
- "_upload_get_base64",
- ->(upload_id_or_url, max_pixels) do
- in_attached_function do
- return nil if upload_id_or_url.blank?
-
- upload = nil
-
- # Handle both upload ID and short URL
- if upload_id_or_url.to_s.start_with?("upload://")
- # Handle short URL format
- sha1 = Upload.sha1_from_short_url(upload_id_or_url)
- return nil if sha1.blank?
- upload = Upload.find_by(sha1: sha1)
- else
- # Handle numeric ID
- upload_id = upload_id_or_url.to_i
- return nil if upload_id <= 0
- upload = Upload.find_by(id: upload_id)
- end
-
- return nil if upload.nil?
-
- max_pixels = max_pixels&.to_i
- max_pixels = nil if max_pixels && max_pixels <= 0
-
- encoded_uploads =
- DiscourseAi::Completions::UploadEncoder.encode(
- upload_ids: [upload.id],
- max_pixels: max_pixels || 10_000_000, # Default to 10M pixels if not specified
- )
-
- encoded_uploads.first&.dig(:base64)
- end
- end,
- )
- mini_racer_context.attach(
- "_upload_get_url",
- ->(short_url) do
- in_attached_function do
- return nil if short_url.blank?
-
- sha1 = Upload.sha1_from_short_url(short_url)
- return nil if sha1.blank?
-
- upload = Upload.find_by(sha1: sha1)
- return nil if upload.nil?
- # TODO we may need to introduce an API to unsecure, secure uploads
- return nil if upload.secure?
-
- GlobalPath.full_cdn_url(upload.url)
- end
- end,
- )
- mini_racer_context.attach(
- "_upload_create",
- ->(filename, base_64_content) do
- begin
- in_attached_function do
- # protect against misuse
- filename = File.basename(filename)
-
- Tempfile.create(filename) do |file|
- file.binmode
- file.write(Base64.decode64(base_64_content))
- file.rewind
-
- upload =
- UploadCreator.new(
- file,
- filename,
- for_private_message: @context.private_message,
- ).create_for(@bot_user.id)
-
- if upload&.persisted?
- { "id" => upload.id, "short_url" => upload.short_url, "url" => upload.url }
- else
- error_msg =
- upload&.errors&.full_messages&.join(", ") || "Upload creation failed"
- { "error" => error_msg }
- end
- end
- end
- rescue => e
- { "error" => e.message }
- end
- end,
- )
- end
-
- def attach_http(mini_racer_context)
- mini_racer_context.attach(
- "_http_get",
- ->(url, options) do
- begin
- @http_requests_made += 1
- if @http_requests_made > MAX_HTTP_REQUESTS
- raise TooManyRequestsError.new("Tool made too many HTTP requests")
- end
-
- in_attached_function do
- headers = (options && options["headers"]) || {}
- base64_encode = options && options["base64Encode"]
-
- result = {}
- DiscourseAi::Agents::Tools::Tool.send_http_request(
- url,
- headers: headers,
- ) do |response|
- if base64_encode
- result[:body] = Base64.strict_encode64(response.body)
- else
- result[:body] = response.body
- end
- result[:status] = response.code.to_i
- end
-
- result
- end
- end
- end,
- )
-
- %i[post put patch delete].each do |method|
- mini_racer_context.attach(
- "_http_#{method}",
- ->(url, options) do
- begin
- @http_requests_made += 1
- if @http_requests_made > MAX_HTTP_REQUESTS
- raise TooManyRequestsError.new("Tool made too many HTTP requests")
- end
-
- in_attached_function do
- headers = (options && options["headers"]) || {}
- body = options && options["body"]
- base64_encode = options && options["base64Encode"]
-
- result = {}
- DiscourseAi::Agents::Tools::Tool.send_http_request(
- url,
- method: method,
- headers: headers,
- body: body,
- ) do |response|
- if base64_encode
- result[:body] = Base64.strict_encode64(response.body)
- else
- result[:body] = response.body
- end
- result[:status] = response.code.to_i
- end
-
- result
- rescue => e
- if Rails.env.development?
- p url
- p options
- p e
- puts e.backtrace
- end
- raise e
- end
- end
- end,
- )
- end
- end
-
- def find_model_by_type(type, id)
- CUSTOM_FIELD_MODELS[type]&.find_by(id: id)
- end
-
def resolve_tool_secret!(alias_name)
value, error =
tool.resolve_secret(
@@ -1246,19 +485,19 @@ module DiscourseAi
when nil
value
when :alias_not_declared
- raise Discourse::InvalidParameters.new(
+ raise ::Discourse::InvalidParameters.new(
I18n.t("discourse_ai.tools.secret_runtime.alias_not_declared", alias: alias_name),
)
when :missing_binding
- raise Discourse::InvalidParameters.new(
+ raise ::Discourse::InvalidParameters.new(
I18n.t("discourse_ai.tools.secret_runtime.missing_binding", alias: alias_name),
)
when :secret_not_found
- raise Discourse::InvalidParameters.new(
+ raise ::Discourse::InvalidParameters.new(
I18n.t("discourse_ai.tools.secret_runtime.secret_not_found", alias: alias_name),
)
else
- raise Discourse::InvalidParameters.new(
+ raise ::Discourse::InvalidParameters.new(
I18n.t("discourse_ai.tools.secret_runtime.unknown_error"),
)
end
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/crypto.rb b/plugins/discourse-ai/lib/agents/tool_runner/crypto.rb
new file mode 100644
index 00000000000..a9bd3ddfaa2
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tool_runner/crypto.rb
@@ -0,0 +1,253 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ class ToolRunner
+ # Crypto callbacks are intentionally NOT wrapped in `in_attached_function`.
+ # That flag pauses the execution-time budget during *external* waits
+ # (HTTP, LLM, sleep). Crypto is pure CPU work — it is the script's own
+ # processing time and must count against the runner's timeout.
+ module Crypto
+ MAX_CRYPTO_INPUT_BYTES = 10_000_000
+
+ def attach_crypto(mini_racer_context)
+ # HMAC functions — hex output
+ mini_racer_context.attach(
+ "_crypto_hmac_sha256_hex",
+ ->(key, data) do
+ key = key.to_s
+ data = data.to_s
+ validate_crypto_input!(key, data)
+ OpenSSL::HMAC.hexdigest("SHA256", key, data)
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_hmac_sha1_hex",
+ ->(key, data) do
+ key = key.to_s
+ data = data.to_s
+ validate_crypto_input!(key, data)
+ OpenSSL::HMAC.hexdigest("SHA1", key, data)
+ end,
+ )
+
+ # HMAC functions — base64 output
+ mini_racer_context.attach(
+ "_crypto_hmac_sha256_base64",
+ ->(key, data) do
+ key = key.to_s
+ data = data.to_s
+ validate_crypto_input!(key, data)
+ Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", key, data))
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_hmac_sha1_base64",
+ ->(key, data) do
+ key = key.to_s
+ data = data.to_s
+ validate_crypto_input!(key, data)
+ Base64.strict_encode64(OpenSSL::HMAC.digest("SHA1", key, data))
+ end,
+ )
+
+ # Hash functions — hex output
+ mini_racer_context.attach(
+ "_crypto_sha256_hex",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ Digest::SHA256.hexdigest(data)
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_sha1_hex",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ Digest::SHA1.hexdigest(data)
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_md5_hex",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ Digest::MD5.hexdigest(data)
+ end,
+ )
+
+ # Hash functions — base64 output
+ mini_racer_context.attach(
+ "_crypto_sha256_base64",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ Base64.strict_encode64(Digest::SHA256.digest(data))
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_sha1_base64",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ Base64.strict_encode64(Digest::SHA1.digest(data))
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_md5_base64",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ Base64.strict_encode64(Digest::MD5.digest(data))
+ end,
+ )
+
+ # Encoding utilities
+ mini_racer_context.attach(
+ "_crypto_base64_encode",
+ ->(text) do
+ text = text.to_s
+ validate_crypto_input!(text)
+ Base64.strict_encode64(text)
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_base64_decode",
+ ->(base64) do
+ base64 = base64.to_s
+ validate_crypto_input!(base64)
+ Base64.decode64(base64)
+ end,
+ )
+
+ # URL-safe base64 (no padding) — common in JWTs
+ mini_racer_context.attach(
+ "_crypto_base64_url_encode",
+ ->(text) do
+ text = text.to_s
+ validate_crypto_input!(text)
+ Base64.urlsafe_encode64(text, padding: false)
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_base64_url_decode",
+ ->(base64) do
+ base64 = base64.to_s
+ validate_crypto_input!(base64)
+ # Tolerate input with or without padding
+ padded = base64 + ("=" * ((4 - (base64.length % 4)) % 4))
+ MiniRacer::Binary.new(Base64.urlsafe_decode64(padded))
+ end,
+ )
+
+ # Uint8Array-returning hash variants — useful when the raw bytes are needed
+ # (e.g. feeding into a signer, or concatenating with other binary data).
+ mini_racer_context.attach(
+ "_crypto_sha256_bytes",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ MiniRacer::Binary.new(Digest::SHA256.digest(data))
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_sha1_bytes",
+ ->(data) do
+ data = data.to_s
+ validate_crypto_input!(data)
+ MiniRacer::Binary.new(Digest::SHA1.digest(data))
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_hmac_sha256_bytes",
+ ->(key, data) do
+ key = key.to_s
+ data = data.to_s
+ validate_crypto_input!(key, data)
+ MiniRacer::Binary.new(OpenSSL::HMAC.digest("SHA256", key, data))
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_hmac_sha1_bytes",
+ ->(key, data) do
+ key = key.to_s
+ data = data.to_s
+ validate_crypto_input!(key, data)
+ MiniRacer::Binary.new(OpenSSL::HMAC.digest("SHA1", key, data))
+ end,
+ )
+
+ # RSA PKCS1v15 signing — accepts PKCS8 or PKCS1 PEM private key
+ mini_racer_context.attach(
+ "_crypto_sign_rsa_sha256",
+ ->(pem_key, data) do
+ pem_key = pem_key.to_s
+ data = data.to_s
+ validate_crypto_input!(pem_key, data)
+ key =
+ begin
+ OpenSSL::PKey::RSA.new(pem_key)
+ rescue OpenSSL::PKey::RSAError => e
+ raise ArgumentError, "Invalid RSA private key: #{e.message}"
+ end
+ raise ArgumentError, "Expected an RSA private key for signing" unless key.private?
+ MiniRacer::Binary.new(key.sign(OpenSSL::Digest.new("SHA256"), data))
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_crypto_sign_rsa_sha1",
+ ->(pem_key, data) do
+ pem_key = pem_key.to_s
+ data = data.to_s
+ validate_crypto_input!(pem_key, data)
+ key =
+ begin
+ OpenSSL::PKey::RSA.new(pem_key)
+ rescue OpenSSL::PKey::RSAError => e
+ raise ArgumentError, "Invalid RSA private key: #{e.message}"
+ end
+ raise ArgumentError, "Expected an RSA private key for signing" unless key.private?
+ MiniRacer::Binary.new(key.sign(OpenSSL::Digest.new("SHA1"), data))
+ end,
+ )
+
+ # Cryptographically secure random bytes — useful for nonces / IVs
+ mini_racer_context.attach(
+ "_crypto_random_bytes",
+ ->(length) do
+ length = length.to_i
+ if length <= 0 || length > 1024
+ raise ArgumentError, "randomBytes length must be between 1 and 1024"
+ end
+ MiniRacer::Binary.new(SecureRandom.random_bytes(length))
+ end,
+ )
+ end
+
+ private
+
+ def validate_crypto_input!(*inputs)
+ inputs.each do |input|
+ if input.bytesize > MAX_CRYPTO_INPUT_BYTES
+ raise ArgumentError,
+ "Crypto input exceeds maximum size of #{MAX_CRYPTO_INPUT_BYTES} bytes"
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb b/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
new file mode 100644
index 00000000000..c758c914b67
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
@@ -0,0 +1,622 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ class ToolRunner
+ # Discourse-side bindings exposed to tool scripts.
+ #
+ # Auth model — important when extending:
+ #
+ # Tool scripts are admin-authored but can be invoked by any user who
+ # triggers the agent. Bindings here intentionally grant admin-level power
+ # to the script. Three non-obvious behaviors to preserve or explicitly
+ # revisit if you change them:
+ #
+ # 1. Read bindings (`getPost`, `getTopic`, `getUser`, `getAgent`, `search`)
+ # serialize with `system_guardian`. They return staff-visible data
+ # including PMs and staff-only fields (emails, IPs). Existing tools
+ # rely on this — don't tighten without a corresponding preamble doc
+ # change and a migration plan.
+ #
+ # 2. `resolve_guardian` elevates staged users to `system_guardian`. This
+ # supports a seeding pattern exercised by the "can seed a category
+ # with topics and posts" spec: create a staged user, then author
+ # content as them in a category where they'd normally have no write
+ # access. Trade-off: a tool that accepts an externally-influenced
+ # username and hits a staged record runs as system. The preamble
+ # documents this contract; tool authors are expected to treat untrusted
+ # usernames as privilege-relevant.
+ #
+ # 3. `_discourse_edit_topic` uses `can_see?` as the outer gate. This is
+ # intentional — it's the coarse minimum. Each sub-operation has its
+ # own stricter inner check that matches Discourse core behavior
+ # (e.g. `DiscourseTagging.tag_topic_by_names` allows non-authors to
+ # tag in open-tag categories, which `can_edit?(topic)` would block).
+ # If you add a new sub-operation, add its own inner permission check.
+ # Do not assume the outer `can_see?` is sufficient.
+ module Discourse
+ def attach_discourse(mini_racer_context)
+ mini_racer_context.attach(
+ "_discourse_get_post",
+ ->(post_id) do
+ in_attached_function do
+ post = Post.find_by(id: post_id)
+ return nil if post.nil?
+ obj =
+ recursive_as_json(
+ PostSerializer.new(post, scope: system_guardian, root: false, add_raw: true),
+ )
+ topic_obj =
+ recursive_as_json(
+ ListableTopicSerializer.new(post.topic, scope: system_guardian, root: false),
+ )
+ obj["topic"] = topic_obj
+ obj
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_get_topic",
+ ->(topic_id) do
+ in_attached_function do
+ topic = Topic.find_by(id: topic_id)
+ return nil if topic.nil?
+ data =
+ recursive_as_json(
+ ListableTopicSerializer.new(topic, scope: system_guardian, root: false),
+ )
+ data["tags"] = topic.tags.pluck(:name)
+ data["first_post_id"] = topic.first_post&.id
+ data["category_id"] = topic.category_id
+ data["category_name"] = topic.category&.name
+ data["category_slug"] = topic.category&.slug
+ data
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_get_user",
+ ->(user_id_or_username) do
+ in_attached_function do
+ user = nil
+
+ if user_id_or_username.is_a?(Integer) ||
+ user_id_or_username.to_i.to_s == user_id_or_username
+ user = User.find_by(id: user_id_or_username.to_i)
+ else
+ user = User.find_by(username: user_id_or_username)
+ end
+
+ return nil if user.nil?
+
+ recursive_as_json(UserSerializer.new(user, scope: system_guardian, root: false))
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_respond_to_agent",
+ ->(agent_name, params) do
+ in_attached_function do
+ # if we have 1000s of agents this can be slow ... we may need to optimize
+ agent_class = AiAgent.all_agents.find { |agent| agent.name == agent_name }
+ return { error: "Agent not found" } if agent_class.nil?
+
+ agent = agent_class.new
+ bot = DiscourseAi::Agents::Bot.as(@bot_user || agent.user, agent: agent)
+ playground = DiscourseAi::AiBot::Playground.new(bot)
+
+ if @context.post_id
+ post = Post.find_by(id: @context.post_id)
+ return { error: "Post not found" } if post.nil?
+
+ reply_post =
+ playground.reply_to(
+ post,
+ custom_instructions: params["instructions"],
+ whisper: params["whisper"],
+ )
+
+ if reply_post
+ return(
+ { success: true, post_id: reply_post.id, post_number: reply_post.post_number }
+ )
+ else
+ return { error: "Failed to create reply" }
+ end
+ elsif @context.message_id && @context.channel_id
+ message = Chat::Message.find_by(id: @context.message_id)
+ channel = Chat::Channel.find_by(id: @context.channel_id)
+ return { error: "Message or channel not found" } if message.nil? || channel.nil?
+
+ reply =
+ playground.reply_to_chat_message(message, channel, @context.context_post_ids)
+
+ if reply
+ return { success: true, message_id: reply.id }
+ else
+ return { error: "Failed to create chat reply" }
+ end
+ else
+ return { error: "No valid context for response" }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_create_chat_message",
+ ->(params) do
+ in_attached_function do
+ params = params.symbolize_keys
+ channel_name = params[:channel_name]
+ username = params[:username]
+ message = params[:message]
+
+ return { error: "Missing required parameter: channel_name" } if channel_name.blank?
+ return { error: "Missing required parameter: message" } if message.blank?
+
+ user, guardian = resolve_guardian(username)
+ return { error: "User not found: #{username}" } if user.nil?
+
+ channel = Chat::Channel.find_by(name: channel_name)
+ channel ||= Chat::Channel.find_by(slug: channel_name.parameterize)
+ return { error: "Channel not found: #{channel_name}" } if channel.nil?
+
+ begin
+ message =
+ ChatSDK::Message.create(
+ raw: message,
+ channel_id: channel.id,
+ guardian: guardian,
+ enforce_membership: !channel.direct_message_channel?,
+ )
+
+ {
+ success: true,
+ message_id: message.id,
+ message: message.message,
+ created_at: message.created_at.iso8601,
+ }
+ rescue => e
+ { error: "Failed to create chat message: #{e.message}" }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_create_staged_user",
+ ->(params) do
+ in_attached_function do
+ params = params.symbolize_keys
+ email = params[:email]
+ username = params[:username]
+ name = params[:name]
+
+ # Validate parameters
+ return { error: "Missing required parameter: email" } if email.blank?
+ return { error: "Missing required parameter: username" } if username.blank?
+
+ # Check if user already exists
+ existing_user = User.find_by_email(email) || User.find_by_username(username)
+ return { error: "User already exists", user_id: existing_user.id } if existing_user
+
+ begin
+ user =
+ User.create!(
+ email: email,
+ username: username,
+ name: name || username,
+ staged: true,
+ approved: true,
+ trust_level: TrustLevel[0],
+ )
+
+ { success: true, user_id: user.id, username: user.username, email: user.email }
+ rescue => e
+ { error: "Failed to create staged user: #{e.message}" }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_create_topic",
+ ->(params) do
+ in_attached_function do
+ params = params.symbolize_keys
+ category_name = params[:category_name]
+ category_id = params[:category_id]
+ title = params[:title]
+ raw = params[:raw]
+ username = params[:username]
+ tags = params[:tags]
+
+ if category_id.blank? && category_name.blank?
+ return { error: "Missing required parameter: category_id or category_name" }
+ end
+ return { error: "Missing required parameter: title" } if title.blank?
+ return { error: "Missing required parameter: raw" } if raw.blank?
+
+ user, guardian = resolve_guardian(username)
+ return { error: "User not found: #{username}" } if user.nil?
+
+ category = resolve_category(category_id.presence || category_name)
+ return { error: "Category not found" } if category.nil?
+ return { error: "Permission denied" } unless guardian.can_create?(Topic, category)
+
+ begin
+ post_creator =
+ PostCreator.new(
+ user,
+ title: title,
+ raw: raw,
+ category: category.id,
+ tags: tags,
+ skip_validations: true,
+ guardian: guardian,
+ )
+
+ post = post_creator.create
+
+ if post_creator.errors.present?
+ return { error: post_creator.errors.full_messages.join(", ") }
+ end
+
+ {
+ success: true,
+ topic_id: post.topic_id,
+ post_id: post.id,
+ topic_slug: post.topic.slug,
+ topic_url: post.topic.url,
+ }
+ rescue => e
+ { error: "Failed to create topic: #{e.message}" }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_create_post",
+ ->(params) do
+ in_attached_function do
+ params = params.symbolize_keys
+ topic_id = params[:topic_id]
+ raw = params[:raw]
+ username = params[:username]
+ reply_to_post_number = params[:reply_to_post_number]
+
+ # Validate parameters
+ return { error: "Missing required parameter: topic_id" } if topic_id.blank?
+ return { error: "Missing required parameter: raw" } if raw.blank?
+
+ user, guardian = resolve_guardian(username)
+ return { error: "User not found: #{username}" } if user.nil?
+
+ topic = Topic.find_by(id: topic_id)
+ return { error: "Topic not found" } if topic.nil?
+ return { error: "Permission denied" } unless guardian.can_create?(Post, topic)
+
+ begin
+ post_creator =
+ PostCreator.new(
+ user,
+ raw: raw,
+ topic_id: topic_id,
+ reply_to_post_number: reply_to_post_number,
+ skip_validations: true,
+ guardian: guardian,
+ )
+
+ post = post_creator.create
+
+ if post_creator.errors.present?
+ return { error: post_creator.errors.full_messages.join(", ") }
+ end
+
+ {
+ success: true,
+ post_id: post.id,
+ post_number: post.post_number,
+ cooked: post.cooked,
+ }
+ rescue => e
+ { error: "Failed to create post: #{e.message}" }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_search",
+ ->(params) do
+ in_attached_function do
+ search_params = params.symbolize_keys
+ if search_params.delete(:with_private)
+ search_params[:current_user] = ::Discourse.system_user
+ end
+ search_params[:result_style] = :detailed
+ results = DiscourseAi::Utils::Search.perform_search(**search_params)
+ recursive_as_json(results)
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_get_agent",
+ ->(agent_name) do
+ in_attached_function do
+ agent = AiAgent.find_by(name: agent_name)
+
+ return { error: "Agent not found" } if agent.nil?
+
+ # Return a subset of relevant agent attributes
+ {
+ agent:
+ agent.attributes.slice(
+ "id",
+ "name",
+ "description",
+ "enabled",
+ "system_prompt",
+ "temperature",
+ "top_p",
+ "vision_enabled",
+ "tools",
+ "max_context_posts",
+ "allow_chat_channel_mentions",
+ "allow_chat_direct_messages",
+ "allow_topic_mentions",
+ "allow_personal_messages",
+ ),
+ }
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_update_agent",
+ ->(agent_id_or_name, updates) do
+ in_attached_function do
+ # Find agent by ID or name
+ agent = nil
+ if agent_id_or_name.is_a?(Integer) || agent_id_or_name.to_i.to_s == agent_id_or_name
+ agent = AiAgent.find_by(id: agent_id_or_name.to_i)
+ else
+ agent = AiAgent.find_by(name: agent_id_or_name)
+ end
+
+ return { error: "Agent not found" } if agent.nil?
+
+ allowed_updates = {}
+
+ if updates["system_prompt"].present?
+ allowed_updates[:system_prompt] = updates["system_prompt"]
+ end
+
+ if updates["temperature"].is_a?(Numeric)
+ allowed_updates[:temperature] = updates["temperature"]
+ end
+
+ allowed_updates[:top_p] = updates["top_p"] if updates["top_p"].is_a?(Numeric)
+
+ if updates["description"].present?
+ allowed_updates[:description] = updates["description"]
+ end
+
+ allowed_updates[:enabled] = updates["enabled"] if updates["enabled"].is_a?(
+ TrueClass,
+ ) || updates["enabled"].is_a?(FalseClass)
+
+ if agent.update(allowed_updates)
+ return(
+ {
+ success: true,
+ agent:
+ agent.attributes.slice(
+ "id",
+ "name",
+ "description",
+ "enabled",
+ "system_prompt",
+ "temperature",
+ "top_p",
+ ),
+ }
+ )
+ else
+ return { error: agent.errors.full_messages.join(", ") }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_edit_post",
+ ->(post_id, raw, options) do
+ in_attached_function do
+ post = Post.find_by(id: post_id)
+ return { error: "Post not found" } if post.nil?
+
+ options ||= {}
+ edit_reason = options["edit_reason"]
+
+ user, guardian = resolve_guardian(options["username"])
+ return { error: "User not found: #{options["username"]}" } if user.nil?
+ return { error: "Permission denied" } unless guardian.can_edit?(post)
+
+ revisor = PostRevisor.new(post)
+ if revisor.revise!(user, { raw: raw, edit_reason: edit_reason })
+ { success: true, post_id: post.id }
+ else
+ { error: post.errors.full_messages.join(", ") }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_edit_topic",
+ ->(topic_id, updates, options) do
+ in_attached_function do
+ topic = Topic.find_by(id: topic_id)
+ return { error: "Topic not found" } if topic.nil?
+
+ updates ||= {}
+ options ||= {}
+
+ user, guardian = resolve_guardian(options["username"])
+ return { error: "User not found: #{options["username"]}" } if user.nil?
+ return { error: "Permission denied" } unless guardian.can_see?(topic)
+
+ # Handle category change
+ if updates.key?("category")
+ if topic.private_message?
+ return { error: "Cannot change category of private messages" }
+ end
+
+ category = resolve_category(updates["category"])
+ return { error: "Category not found" } if category.nil?
+
+ unless guardian.can_move_topic_to_category?(category.id)
+ return { error: "Permission denied" }
+ end
+
+ unless topic.change_category_to_id(category.id, silent: !!options["silent"])
+ return(
+ { error: "Failed to change category", details: topic.errors.full_messages }
+ )
+ end
+ end
+
+ # Handle visibility change
+ if updates.key?("visible")
+ unless guardian.can_toggle_topic_visibility?(topic)
+ return { error: "Permission denied" }
+ end
+
+ visibility_reason =
+ Topic.visibility_reasons[
+ updates["visible"] ? :manually_relisted : :manually_unlisted
+ ]
+
+ topic.update_status(
+ "visible",
+ updates["visible"],
+ user,
+ { visibility_reason_id: visibility_reason },
+ )
+ end
+
+ # Handle tags change
+ if updates.key?("tags")
+ unless DiscourseTagging.tag_topic_by_names(
+ topic,
+ guardian,
+ updates["tags"],
+ append: !!options["append"],
+ )
+ return { error: "Failed to apply tags", details: topic.errors.full_messages }
+ end
+ topic.first_post&.publish_change_to_clients!(:revised)
+ end
+
+ {
+ success: true,
+ topic: {
+ id: topic.id,
+ category_id: topic.category_id,
+ category_name: topic.category&.name,
+ category_slug: topic.category&.slug,
+ tags: topic.tags.pluck(:name),
+ visible: topic.visible,
+ visibility_reason_id: topic.visibility_reason_id,
+ },
+ }
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_get_custom_field",
+ ->(type, id, key) do
+ in_attached_function do
+ return { error: "Invalid type: #{type}" } unless CUSTOM_FIELD_MODELS.key?(type)
+ model = find_model_by_type(type, id)
+ return nil if model.nil?
+ model.custom_fields[key]
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_set_custom_field",
+ ->(type, id, key, value) do
+ in_attached_function do
+ return { error: "Invalid type: #{type}" } unless CUSTOM_FIELD_MODELS.key?(type)
+ return { error: "Key is required" } if key.blank?
+ if key.to_s.length > MAX_CUSTOM_FIELD_KEY_LENGTH
+ return { error: "Key too long (max #{MAX_CUSTOM_FIELD_KEY_LENGTH} characters)" }
+ end
+ if value.to_s.length > MAX_CUSTOM_FIELD_VALUE_LENGTH
+ return(
+ { error: "Value too long (max #{MAX_CUSTOM_FIELD_VALUE_LENGTH} characters)" }
+ )
+ end
+
+ model = find_model_by_type(type, id)
+ return { error: "#{type.capitalize} not found: #{id}" } if model.nil?
+
+ model.custom_fields[key] = value
+ model.save_custom_fields
+
+ { success: true, key: key, value: model.custom_fields[key] }
+ end
+ end,
+ )
+ end
+
+ private
+
+ def resolve_user(username)
+ if username.present?
+ User.find_by(username: username)
+ else
+ @bot_user || ::Discourse.system_user
+ end
+ end
+
+ def resolve_guardian(username)
+ user = resolve_user(username)
+ return nil, nil if user.nil?
+ # Staged users have no standing write permissions, but the seeding
+ # pattern (createStagedUser + createTopic/createPost as that user)
+ # needs to succeed. Elevate to system_guardian for them. See module
+ # header for the contract and trade-off.
+ guardian = user.staged? ? system_guardian : Guardian.new(user)
+ [user, guardian]
+ end
+
+ def resolve_category(category_id_or_name)
+ if category_id_or_name.is_a?(Integer) ||
+ category_id_or_name.to_i.to_s == category_id_or_name.to_s
+ Category.find_by(id: category_id_or_name.to_i)
+ else
+ Category
+ .where(name: category_id_or_name)
+ .or(Category.where(slug: category_id_or_name))
+ .first
+ end
+ end
+
+ def find_model_by_type(type, id)
+ CUSTOM_FIELD_MODELS[type]&.find_by(id: id)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/http.rb b/plugins/discourse-ai/lib/agents/tool_runner/http.rb
new file mode 100644
index 00000000000..b38b72fb064
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tool_runner/http.rb
@@ -0,0 +1,88 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ class ToolRunner
+ module HTTP
+ def attach_http(mini_racer_context)
+ mini_racer_context.attach(
+ "_http_get",
+ ->(url, options) do
+ begin
+ @http_requests_made += 1
+ if @http_requests_made > MAX_HTTP_REQUESTS
+ raise TooManyRequestsError.new("Tool made too many HTTP requests")
+ end
+
+ in_attached_function do
+ headers = (options && options["headers"]) || {}
+ base64_encode = options && options["base64Encode"]
+
+ result = {}
+ DiscourseAi::Agents::Tools::Tool.send_http_request(
+ url,
+ headers: headers,
+ ) do |response|
+ if base64_encode
+ result[:body] = Base64.strict_encode64(response.body)
+ else
+ result[:body] = response.body
+ end
+ result[:status] = response.code.to_i
+ end
+
+ result
+ end
+ end
+ end,
+ )
+
+ %i[post put patch delete].each do |method|
+ mini_racer_context.attach(
+ "_http_#{method}",
+ ->(url, options) do
+ begin
+ @http_requests_made += 1
+ if @http_requests_made > MAX_HTTP_REQUESTS
+ raise TooManyRequestsError.new("Tool made too many HTTP requests")
+ end
+
+ in_attached_function do
+ headers = (options && options["headers"]) || {}
+ body = options && options["body"]
+ base64_encode = options && options["base64Encode"]
+
+ result = {}
+ DiscourseAi::Agents::Tools::Tool.send_http_request(
+ url,
+ method: method,
+ headers: headers,
+ body: body,
+ ) do |response|
+ if base64_encode
+ result[:body] = Base64.strict_encode64(response.body)
+ else
+ result[:body] = response.body
+ end
+ result[:status] = response.code.to_i
+ end
+
+ result
+ rescue => e
+ if Rails.env.development?
+ p url
+ p options
+ p e
+ puts e.backtrace
+ end
+ raise e
+ end
+ end
+ end,
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/index.rb b/plugins/discourse-ai/lib/agents/tool_runner/index.rb
new file mode 100644
index 00000000000..d7d436084dc
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tool_runner/index.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ class ToolRunner
+ module Index
+ def attach_index(mini_racer_context)
+ mini_racer_context.attach(
+ "_index_search",
+ ->(*params) do
+ in_attached_function do
+ query, options = params
+ self.running_attached_function = true
+ options ||= {}
+ options = options.symbolize_keys
+ self.rag_search(query, **options)
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_index_get_file",
+ ->(filename) { in_attached_function { rag_get_file(filename) } },
+ )
+ end
+
+ private
+
+ def rag_search(query, filenames: nil, limit: 10)
+ RagDocumentFragment
+ .search(
+ target_id: tool.id,
+ target_type: "AiTool",
+ query: query,
+ filenames: filenames,
+ limit: limit,
+ )
+ .map { |fragment| { fragment: fragment[:fragment], metadata: fragment[:metadata] } }
+ end
+
+ def rag_get_file(filename)
+ RagDocumentFragment.read_file(
+ target_id: tool.id,
+ target_type: "AiTool",
+ filename: filename,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/llm.rb b/plugins/discourse-ai/lib/agents/tool_runner/llm.rb
new file mode 100644
index 00000000000..749cd44cf48
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tool_runner/llm.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ class ToolRunner
+ module Llm
+ def attach_truncate(mini_racer_context)
+ mini_racer_context.attach(
+ "_llm_truncate",
+ ->(text, length) do
+ @llm.tokenizer.truncate(text, length, strict: SiteSetting.ai_strict_token_counting)
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_llm_generate",
+ ->(prompt, options) do
+ in_attached_function do
+ options ||= {}
+ response_format = options["response_format"]
+
+ response_format = { "type" => "json_object" } if options["json"]
+
+ if response_format && !response_format.is_a?(Hash)
+ raise ::Discourse::InvalidParameters.new("response_format must be a hash")
+ end
+ @llm.generate(
+ convert_js_prompt_to_ruby(prompt),
+ user: llm_user,
+ feature_name: "custom_tool_#{tool.name}",
+ response_format: response_format,
+ temperature: options["temperature"],
+ top_p: options["top_p"],
+ max_tokens: options["max_tokens"],
+ stop_sequences: options["stop_sequences"],
+ )
+ end
+ end,
+ )
+ end
+
+ private
+
+ def convert_js_prompt_to_ruby(prompt)
+ if prompt.is_a?(String)
+ prompt
+ elsif prompt.is_a?(Hash)
+ messages = prompt["messages"]
+ if messages.blank? || !messages.is_a?(Array)
+ raise ::Discourse::InvalidParameters.new("Prompt must have messages")
+ end
+ messages.each(&:symbolize_keys!)
+ messages.each { |message| message[:type] = message[:type].to_sym }
+ DiscourseAi::Completions::Prompt.new(messages: prompt["messages"])
+ else
+ raise ::Discourse::InvalidParameters.new("Prompt must be a string or a hash")
+ end
+ end
+
+ def llm_user
+ @llm_user ||=
+ begin
+ post&.user || @bot_user
+ end
+ end
+
+ def post
+ return @post if defined?(@post)
+ post_id = @context.post_id
+ @post = post_id && Post.find_by(id: post_id)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/upload.rb b/plugins/discourse-ai/lib/agents/tool_runner/upload.rb
new file mode 100644
index 00000000000..876daff9e29
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tool_runner/upload.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ class ToolRunner
+ module Upload
+ def attach_upload(mini_racer_context)
+ mini_racer_context.attach(
+ "_upload_get_base64",
+ ->(upload_id_or_url, max_pixels) do
+ in_attached_function do
+ return nil if upload_id_or_url.blank?
+
+ upload = nil
+
+ # Handle both upload ID and short URL
+ if upload_id_or_url.to_s.start_with?("upload://")
+ # Handle short URL format
+ sha1 = ::Upload.sha1_from_short_url(upload_id_or_url)
+ return nil if sha1.blank?
+ upload = ::Upload.find_by(sha1: sha1)
+ else
+ # Handle numeric ID
+ upload_id = upload_id_or_url.to_i
+ return nil if upload_id <= 0
+ upload = ::Upload.find_by(id: upload_id)
+ end
+
+ return nil if upload.nil?
+
+ max_pixels = max_pixels&.to_i
+ max_pixels = nil if max_pixels && max_pixels <= 0
+
+ encoded_uploads =
+ DiscourseAi::Completions::UploadEncoder.encode(
+ upload_ids: [upload.id],
+ max_pixels: max_pixels || 10_000_000, # Default to 10M pixels if not specified
+ )
+
+ encoded_uploads.first&.dig(:base64)
+ end
+ end,
+ )
+ mini_racer_context.attach(
+ "_upload_get_url",
+ ->(short_url) do
+ in_attached_function do
+ return nil if short_url.blank?
+
+ sha1 = ::Upload.sha1_from_short_url(short_url)
+ return nil if sha1.blank?
+
+ upload = ::Upload.find_by(sha1: sha1)
+ return nil if upload.nil?
+ # TODO we may need to introduce an API to unsecure, secure uploads
+ return nil if upload.secure?
+
+ GlobalPath.full_cdn_url(upload.url)
+ end
+ end,
+ )
+ mini_racer_context.attach(
+ "_upload_create",
+ ->(filename, base_64_content) do
+ begin
+ in_attached_function do
+ # protect against misuse
+ filename = File.basename(filename)
+
+ Tempfile.create(filename) do |file|
+ file.binmode
+ file.write(Base64.decode64(base_64_content))
+ file.rewind
+
+ upload =
+ UploadCreator.new(
+ file,
+ filename,
+ for_private_message: @context.private_message,
+ ).create_for(@bot_user.id)
+
+ if upload&.persisted?
+ { "id" => upload.id, "short_url" => upload.short_url, "url" => upload.url }
+ else
+ error_msg =
+ upload&.errors&.full_messages&.join(", ") || "Upload creation failed"
+ { "error" => error_msg }
+ end
+ end
+ end
+ rescue => e
+ { "error" => e.message }
+ end
+ end,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
index 135f30482ad..b2ea02a3e1c 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
@@ -142,7 +142,41 @@
* const apiKey = secrets.get("openai_api_key");
*
* 7. discourse
- * Interacts with Discourse specific features. Access is generally performed as the SystemUser.
+ * Interacts with Discourse specific features.
+ *
+ * Security model — read before writing tools that are invoked by non-admins:
+ *
+ * Tools are authored by admins but can be triggered by any user who mentions
+ * the agent. The runner intentionally grants admin-level power to the script.
+ * Know these non-obvious defaults:
+ *
+ * - Read ops (`getPost`, `getTopic`, `getUser`, `getAgent`, `search`) use the
+ * SystemUser scope. Results may include PMs, user emails, IP addresses,
+ * staff-category content, and other staff-only serializer fields. Do not
+ * return this data verbatim to the invoking user unless you've verified
+ * they're authorized to see it.
+ *
+ * - Write ops (`createTopic`, `createPost`, `editPost`, `editTopic`,
+ * `createChatMessage`) enforce permissions via the Guardian of the user
+ * named by the `username` parameter — *except* when that user is staged,
+ * in which case the action runs with SystemUser privileges. This is
+ * intentional: it supports content-seeding patterns (create a staged
+ * user, then author content as them in categories they couldn't normally
+ * write to). The consequence: any staged username is effectively a
+ * privileged identity. Treat untrusted usernames as privilege-relevant.
+ *
+ * - `createStagedUser` itself has no permission check (admin power). A
+ * tool can spawn a staged user and then write as SystemUser via the rule
+ * above.
+ *
+ * - `updateAgent` can modify any agent on the site, including its
+ * `system_prompt`. A tool attached to agent A can permanently rewrite
+ * agent B's instructions.
+ *
+ * - `getCustomField` / `setCustomField` have no key allowlist and operate
+ * on posts, topics, and users. Some custom fields are security-sensitive
+ * (plugin metadata, tokens, flags). Be deliberate about which keys your
+ * tool reads or writes.
*
* discourse.baseUrl: The base URL of the Discourse site (e.g., "https://meta.discourse.org").
*
@@ -292,6 +326,70 @@
* return { success: true };
* }
*
+ * 9. crypto
+ * Provides cryptographic hashing, HMAC, signing, and encoding utilities.
+ * These bridge to Ruby's OpenSSL — not the Web Crypto API.
+ * All functions are synchronous. Inputs accept strings or Uint8Array (binary
+ * values are sent across the bridge as raw bytes). Functions suffixed with
+ * `Bytes` return Uint8Array, which is preferable when chaining crypto ops.
+ * Input size is limited to 10MB per call.
+ *
+ * HMAC Functions:
+ *
+ * crypto.hmacSha256(key, data): HMAC-SHA256, hex output.
+ * crypto.hmacSha1(key, data): HMAC-SHA1, hex output.
+ * crypto.hmacSha256Base64(key, data): HMAC-SHA256, base64 output.
+ * crypto.hmacSha1Base64(key, data): HMAC-SHA1, base64 output.
+ * crypto.hmacSha256Bytes(key, data): HMAC-SHA256, Uint8Array output.
+ * crypto.hmacSha1Bytes(key, data): HMAC-SHA1, Uint8Array output.
+ *
+ * Hash Functions:
+ *
+ * crypto.sha256(data), crypto.sha1(data), crypto.md5(data): hex output.
+ * crypto.sha256Base64(data), crypto.sha1Base64(data), crypto.md5Base64(data): base64 output.
+ * crypto.sha256Bytes(data), crypto.sha1Bytes(data): Uint8Array output.
+ *
+ * RSA Signing (PKCS1v15):
+ *
+ * crypto.signRsaSha256(pemPrivateKey, data): RSA-SHA256 signature.
+ * crypto.signRsaSha1(pemPrivateKey, data): RSA-SHA1 signature.
+ * Parameters:
+ * pemPrivateKey (string): PEM-encoded RSA private key (PKCS8 or PKCS1).
+ * data (string | Uint8Array): The data to sign.
+ * Returns: Uint8Array (raw signature bytes — for RS256 on 2048-bit keys, 256 bytes)
+ * Throws: Error if the key is not a valid RSA private key.
+ *
+ * Encoding Utilities:
+ *
+ * crypto.base64Encode(text): Base64-encode (equivalent to btoa, absent in V8).
+ * crypto.base64Decode(base64): Decode standard base64. Returns string.
+ * crypto.base64UrlEncode(text): URL-safe base64 encode, no padding (JWT-style).
+ * crypto.base64UrlDecode(base64): URL-safe base64 decode. Returns Uint8Array
+ * (accepts input with or without padding).
+ *
+ * Random:
+ *
+ * crypto.randomBytes(length): Cryptographically secure random bytes.
+ * Parameters:
+ * length (number): Number of bytes, 1–1024.
+ * Returns: Uint8Array
+ *
+ * Example - Webhook signature verification:
+ * function invoke(params) {
+ * const secret = secrets.get("webhook_secret");
+ * const signature = crypto.hmacSha256(secret, params.payload);
+ * return { valid: signature === params.expected_signature };
+ * }
+ *
+ * Example - Signing a JWT (RS256) for a Google service account:
+ * function signJwt(privateKeyPem, claims) {
+ * const header = crypto.base64UrlEncode(JSON.stringify({ alg: "RS256", typ: "JWT" }));
+ * const payload = crypto.base64UrlEncode(JSON.stringify(claims));
+ * const signingInput = header + "." + payload;
+ * const sig = crypto.signRsaSha256(privateKeyPem, signingInput);
+ * return signingInput + "." + crypto.base64UrlEncode(sig);
+ * }
+ *
* Constraints
*
* Execution Time: ≤ 2000ms (default timeout in milliseconds) - This timer *pauses* during external HTTP requests or LLM calls initiated via `http.*` or `llm.generate`, but applies to the script's own processing time.
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner/crypto_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner/crypto_spec.rb
new file mode 100644
index 00000000000..c6a1820fbf7
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/crypto_spec.rb
@@ -0,0 +1,408 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe DiscourseAi::Agents::ToolRunner do
+ def create_tool(script:)
+ AiTool.create!(
+ name: "test #{SecureRandom.uuid}",
+ tool_name: "test_#{SecureRandom.uuid.underscore}",
+ description: "test",
+ parameters: [{ name: "query", type: "string", description: "perform a search" }],
+ script: script,
+ created_by_id: 1,
+ summary: "Test tool summary",
+ )
+ end
+
+ before { enable_current_plugin }
+
+ describe "crypto operations" do
+ describe "HMAC" do
+ it "can compute HMAC-SHA256 hex digest" do
+ tool =
+ create_tool(
+ script:
+ 'function invoke(params) { return crypto.hmacSha256("secret-key", "hello world"); }',
+ )
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(OpenSSL::HMAC.hexdigest("SHA256", "secret-key", "hello world"))
+ end
+
+ it "can compute HMAC-SHA1 hex digest" do
+ tool =
+ create_tool(
+ script:
+ 'function invoke(params) { return crypto.hmacSha1("secret-key", "hello world"); }',
+ )
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(OpenSSL::HMAC.hexdigest("SHA1", "secret-key", "hello world"))
+ end
+
+ it "can compute HMAC-SHA256 base64 digest" do
+ tool =
+ create_tool(
+ script:
+ 'function invoke(params) { return crypto.hmacSha256Base64("secret-key", "hello world"); }',
+ )
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(
+ Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", "secret-key", "hello world")),
+ )
+ end
+
+ it "can compute HMAC-SHA1 base64 digest" do
+ tool =
+ create_tool(
+ script:
+ 'function invoke(params) { return crypto.hmacSha1Base64("secret-key", "hello world"); }',
+ )
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(
+ Base64.strict_encode64(OpenSSL::HMAC.digest("SHA1", "secret-key", "hello world")),
+ )
+ end
+ end
+
+ describe "hashing" do
+ it "can compute SHA256 hex digest" do
+ tool =
+ create_tool(script: 'function invoke(params) { return crypto.sha256("hello world"); }')
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(Digest::SHA256.hexdigest("hello world"))
+ end
+
+ it "can compute SHA1 hex digest" do
+ tool = create_tool(script: 'function invoke(params) { return crypto.sha1("hello world"); }')
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(Digest::SHA1.hexdigest("hello world"))
+ end
+
+ it "can compute MD5 hex digest" do
+ tool = create_tool(script: 'function invoke(params) { return crypto.md5("hello world"); }')
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(Digest::MD5.hexdigest("hello world"))
+ end
+
+ it "can compute SHA256 base64 digest" do
+ tool =
+ create_tool(
+ script: 'function invoke(params) { return crypto.sha256Base64("hello world"); }',
+ )
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(Base64.strict_encode64(Digest::SHA256.digest("hello world")))
+ end
+
+ it "can compute SHA1 base64 digest" do
+ tool =
+ create_tool(
+ script: 'function invoke(params) { return crypto.sha1Base64("hello world"); }',
+ )
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(Base64.strict_encode64(Digest::SHA1.digest("hello world")))
+ end
+
+ it "can compute MD5 base64 digest" do
+ tool =
+ create_tool(script: 'function invoke(params) { return crypto.md5Base64("hello world"); }')
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(Base64.strict_encode64(Digest::MD5.digest("hello world")))
+ end
+ end
+
+ describe "base64 encoding" do
+ it "can encode and decode base64" do
+ script = <<~JS
+ function invoke(params) {
+ const encoded = crypto.base64Encode("Hello World!");
+ const decoded = crypto.base64Decode(encoded);
+ return { encoded: encoded, decoded: decoded };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+
+ expect(result["encoded"]).to eq(Base64.strict_encode64("Hello World!"))
+ expect(result["decoded"]).to eq("Hello World!")
+ end
+
+ it "produces url-safe base64 without padding" do
+ # Build a Uint8Array with bytes whose standard base64 contains '+' and '/'
+ # and needs padding. 0xfb 0xff 0xfe -> standard "+//+", urlsafe "-__-".
+ script = <<~JS
+ function invoke(params) {
+ const bytes = new Uint8Array([0xfb, 0xff, 0xfe, 0xff]);
+ return crypto.base64UrlEncode(bytes);
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result).to eq(Base64.urlsafe_encode64("\xfb\xff\xfe\xff".b, padding: false))
+ expect(result).not_to include("=")
+ expect(result).not_to include("+")
+ expect(result).not_to include("/")
+ end
+
+ it "round trips url-safe base64 through Uint8Array" do
+ script = <<~JS
+ function invoke(params) {
+ const encoded = crypto.base64UrlEncode("héllo wörld");
+ const decoded = crypto.base64UrlDecode(encoded);
+ return {
+ encoded: encoded,
+ isUint8Array: decoded instanceof Uint8Array,
+ length: decoded.length,
+ reencoded: crypto.base64UrlEncode(decoded),
+ };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+
+ expect(result["isUint8Array"]).to eq(true)
+ expect(result["encoded"]).to eq(Base64.urlsafe_encode64("héllo wörld", padding: false))
+ expect(result["reencoded"]).to eq(result["encoded"])
+ end
+
+ it "accepts padded url-safe base64 input" do
+ padded = Base64.urlsafe_encode64("abc") # "YWJj" (no padding needed) -> use different input
+ padded = Base64.urlsafe_encode64("a") # "YQ=="
+ script = <<~JS
+ function invoke(params) {
+ const decoded = crypto.base64UrlDecode(params.input);
+ return String.fromCharCode.apply(null, Array.from(decoded));
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result = tool.runner({ "input" => padded }, llm: nil, bot_user: nil).invoke
+ expect(result).to eq("a")
+ end
+ end
+
+ describe "byte-array variants" do
+ it "returns Uint8Array for sha256Bytes and hmacSha256Bytes" do
+ script = <<~JS
+ function invoke(params) {
+ const h = crypto.sha256Bytes("hello");
+ const m = crypto.hmacSha256Bytes("k", "v");
+ return {
+ hashIsBytes: h instanceof Uint8Array,
+ hashLen: h.length,
+ hashMatches: crypto.base64Encode(h) === params.expectedHash,
+ macMatches: crypto.base64Encode(m) === params.expectedMac,
+ };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result =
+ tool.runner(
+ {
+ "expectedHash" => Base64.strict_encode64(Digest::SHA256.digest("hello")),
+ "expectedMac" => Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", "k", "v")),
+ },
+ llm: nil,
+ bot_user: nil,
+ ).invoke
+
+ expect(result["hashIsBytes"]).to eq(true)
+ expect(result["hashLen"]).to eq(32)
+ expect(result["hashMatches"]).to eq(true)
+ expect(result["macMatches"]).to eq(true)
+ end
+ end
+
+ describe "RSA signing" do
+ let(:rsa_key) { OpenSSL::PKey::RSA.new(2048) }
+
+ it "signs data with RSA-SHA256 and the signature verifies" do
+ script = <<~JS
+ function invoke(params) {
+ const sig = crypto.signRsaSha256(params.pem, params.data);
+ return {
+ isUint8Array: sig instanceof Uint8Array,
+ length: sig.length,
+ base64: crypto.base64Encode(sig),
+ };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result =
+ tool.runner(
+ { "pem" => rsa_key.to_pem, "data" => "payload to sign" },
+ llm: nil,
+ bot_user: nil,
+ ).invoke
+
+ expect(result["isUint8Array"]).to eq(true)
+ expect(result["length"]).to eq(256) # 2048-bit key
+
+ signature = Base64.strict_decode64(result["base64"])
+ expect(rsa_key.verify(OpenSSL::Digest.new("SHA256"), signature, "payload to sign")).to eq(
+ true,
+ )
+ end
+
+ it "produces a JWT that verifies with the public key" do
+ script = <<~JS
+ function invoke(params) {
+ const header = crypto.base64UrlEncode(JSON.stringify({ alg: "RS256", typ: "JWT" }));
+ const payload = crypto.base64UrlEncode(JSON.stringify({ sub: "42", iat: 1700000000 }));
+ const signingInput = header + "." + payload;
+ const sig = crypto.signRsaSha256(params.pem, signingInput);
+ return signingInput + "." + crypto.base64UrlEncode(sig);
+ }
+ JS
+
+ tool = create_tool(script: script)
+ jwt = tool.runner({ "pem" => rsa_key.to_pem }, llm: nil, bot_user: nil).invoke
+
+ header_b64, payload_b64, sig_b64 = jwt.split(".")
+ signing_input = "#{header_b64}.#{payload_b64}"
+ signature = Base64.urlsafe_decode64(sig_b64 + ("=" * ((4 - sig_b64.length % 4) % 4)))
+
+ expect(rsa_key.verify(OpenSSL::Digest.new("SHA256"), signature, signing_input)).to eq(true)
+
+ payload =
+ JSON.parse(
+ Base64.urlsafe_decode64(payload_b64 + ("=" * ((4 - payload_b64.length % 4) % 4))),
+ )
+ expect(payload).to eq({ "sub" => "42", "iat" => 1_700_000_000 })
+ end
+
+ it "raises a clear error when the key is not a valid RSA key" do
+ script = <<~JS
+ function invoke(params) {
+ try {
+ crypto.signRsaSha256("not a pem", "data");
+ return { ok: true };
+ } catch (e) {
+ return { error: e.message };
+ }
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result["error"]).to include("Invalid RSA private key")
+ end
+ end
+
+ describe "randomBytes" do
+ it "returns a Uint8Array of the requested length" do
+ script = <<~JS
+ function invoke(params) {
+ const a = crypto.randomBytes(16);
+ const b = crypto.randomBytes(16);
+ return {
+ isUint8Array: a instanceof Uint8Array,
+ length: a.length,
+ differ: crypto.base64Encode(a) !== crypto.base64Encode(b),
+ };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result["isUint8Array"]).to eq(true)
+ expect(result["length"]).to eq(16)
+ expect(result["differ"]).to eq(true)
+ end
+
+ it "rejects out-of-range lengths" do
+ script = <<~JS
+ function invoke(params) {
+ try { crypto.randomBytes(0); return { ok: true }; }
+ catch (e) { return { error: e.message }; }
+ }
+ JS
+ tool = create_tool(script: script)
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+ expect(result["error"]).to include("between 1 and 1024")
+ end
+ end
+
+ describe "execution budget" do
+ # Regression: crypto callbacks must NOT pause the timer the way HTTP/LLM do.
+ # Crypto is CPU work and should count against the script's timeout, otherwise
+ # a tool can busy-loop in Ruby/OpenSSL indefinitely.
+ #
+ # Test shape: a `while (Date.now() < safety)` loop is the worst-case cap on test
+ # duration — if the timer is broken and never fires, the loop falls through and
+ # returns `ran_to_completion`, which fails the assertion below. A working timer
+ # terminates well before that. We deliberately do not assert on wall-clock elapsed:
+ # slow CI can add hundreds of ms of scheduling jitter between "budget exceeded" and
+ # "Ruby test resumes", and the timeout error is what we actually care about.
+ it "counts crypto work against the timeout budget" do
+ script = <<~JS
+ function invoke(params) {
+ const safety = Date.now() + 1500;
+ while (Date.now() < safety) {
+ crypto.sha256("x");
+ }
+ return { ran_to_completion: true };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: nil)
+ runner.timeout = 50
+
+ result = runner.invoke
+
+ expect(result[:error]).to eq("Script terminated due to timeout")
+ end
+ end
+
+ describe "edge cases" do
+ it "handles empty string inputs" do
+ script = <<~JS
+ function invoke(params) {
+ return {
+ hmac: crypto.hmacSha256("key", ""),
+ hash: crypto.sha256(""),
+ encode: crypto.base64Encode(""),
+ };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+
+ expect(result["hmac"]).to eq(OpenSSL::HMAC.hexdigest("SHA256", "key", ""))
+ expect(result["hash"]).to eq(Digest::SHA256.hexdigest(""))
+ expect(result["encode"]).to eq(Base64.strict_encode64(""))
+ end
+
+ it "works for webhook signature verification" do
+ secret = "whsec_test123"
+ payload = '{"event":"test","data":{"id":1}}'
+ expected_sig = OpenSSL::HMAC.hexdigest("SHA256", secret, payload)
+
+ script = <<~JS
+ function invoke(params) {
+ const signature = crypto.hmacSha256(params.secret, params.payload);
+ return { valid: signature === params.expected, signature: signature };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { "secret" => secret, "payload" => payload, "expected" => expected_sig },
+ llm: nil,
+ bot_user: nil,
+ )
+ result = runner.invoke
+
+ expect(result["valid"]).to eq(true)
+ expect(result["signature"]).to eq(expected_sig)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb
new file mode 100644
index 00000000000..775fe06331d
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb
@@ -0,0 +1,1397 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe DiscourseAi::Agents::ToolRunner do
+ fab!(:llm_model) { Fabricate(:llm_model, name: "claude-2") }
+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:bot_user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }
+ fab!(:topic)
+ fab!(:post) { Fabricate(:post, topic: topic, raw: "bananas are a tasty fruit") }
+ fab!(:tag1) { Fabricate(:tag, name: "tag1") }
+ fab!(:tag2) { Fabricate(:tag, name: "tag2") }
+ fab!(:category) { Fabricate(:category, name: "Test Category", slug: "test-category") }
+ fab!(:pm_topic, :private_message_topic)
+
+ fab!(:tool) do
+ AiTool.create!(
+ name: "test_tool",
+ tool_name: "test_tool",
+ description: "a test tool",
+ script: "function invoke(params) { return { result: 'ok' }; }",
+ summary: "test",
+ created_by: user,
+ )
+ end
+
+ def create_tool(script:)
+ AiTool.create!(
+ name: "test #{SecureRandom.uuid}",
+ tool_name: "test_#{SecureRandom.uuid.underscore}",
+ description: "test",
+ parameters: [{ name: "query", type: "string", description: "perform a search" }],
+ script: script,
+ created_by_id: 1,
+ summary: "Test tool summary",
+ )
+ end
+
+ before do
+ enable_current_plugin
+ SiteSetting.tagging_enabled = true
+ end
+
+ describe "Discourse operations" do
+ context "when using the topic API" do
+ it "can fetch topic details" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.getTopic(params.topic_id);
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "topic_id" => topic.id }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+
+ expect(result["id"]).to eq(topic.id)
+ expect(result["title"]).to eq(topic.title)
+ expect(result["archetype"]).to eq("regular")
+ expect(result["posts_count"]).to eq(1)
+ end
+
+ it "can get a topic with tags and first_post_id" do
+ tag = Fabricate(:tag, name: "test_tag")
+ topic_with_category = Fabricate(:topic, category: category)
+ Fabricate(:post, topic: topic_with_category)
+ topic_with_category.tags << tag
+
+ tool.update!(
+ script:
+ "function invoke(params) { const t = discourse.getTopic(params.topic_id); return { tags: t.tags, first_post_id: t.first_post_id }; }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["tags"]).to contain_exactly("test_tag")
+ expect(result["first_post_id"]).to eq(topic_with_category.first_post.id)
+ end
+
+ it "can get a topic with category info" do
+ topic_with_category = Fabricate(:topic, category: category)
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ const t = discourse.getTopic(params.topic_id);
+ return {
+ category_id: t.category_id,
+ category_name: t.category_name,
+ category_slug: t.category_slug
+ };
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["category_id"]).to eq(category.id)
+ expect(result["category_name"]).to eq("Test Category")
+ expect(result["category_slug"]).to eq("test-category")
+ end
+ end
+
+ context "when using the post API" do
+ it "can fetch post details" do
+ script = <<~JS
+ function invoke(params) {
+ const post = discourse.getPost(params.post_id);
+ return {
+ post: post,
+ topic: post.topic
+ }
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "post_id" => post.id }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+ post_hash = result["post"]
+ topic_hash = result["topic"]
+
+ expect(post_hash["id"]).to eq(post.id)
+ expect(post_hash["topic_id"]).to eq(topic.id)
+ expect(post_hash["raw"]).to eq(post.raw)
+
+ expect(topic_hash["id"]).to eq(topic.id)
+ end
+ end
+
+ context "when using the search API" do
+ before { SearchIndexer.enable }
+ after { SearchIndexer.disable }
+
+ it "can perform a discourse search" do
+ SearchIndexer.index(topic, force: true)
+ SearchIndexer.index(post, force: true)
+
+ script = <<~JS
+ function invoke(params) {
+ return discourse.search({ search_query: params.query });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "query" => "banana" }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+
+ expect(result["rows"].length).to be > 0
+ expect(result["rows"].first["title"]).to eq(topic.title)
+ end
+ end
+
+ context "when using the chat API" do
+ before(:each) do
+ skip "Chat plugin tests skipped because Chat module is not defined." unless defined?(Chat)
+ SiteSetting.chat_enabled = true
+ end
+
+ fab!(:chat_user, :user)
+ fab!(:chat_channel) do
+ Fabricate(:chat_channel).tap do |channel|
+ Fabricate(
+ :user_chat_channel_membership,
+ user: chat_user,
+ chat_channel: channel,
+ following: true,
+ )
+ end
+ end
+
+ it "can create a chat message" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createChatMessage({
+ channel_name: params.channel_name,
+ username: params.username,
+ message: params.message
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ {
+ "channel_name" => chat_channel.name,
+ "username" => chat_user.username,
+ "message" => "Hello from the tool!",
+ },
+ llm: nil,
+ bot_user: bot_user,
+ )
+
+ initial_message_count = Chat::Message.count
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true), "Tool invocation failed: #{result["error"]}"
+ expect(result["message"]).to eq("Hello from the tool!")
+ expect(result["created_at"]).to be_present
+ expect(result).not_to have_key("error")
+
+ expect(Chat::Message.count).to eq(initial_message_count + 1)
+ created_message = Chat::Message.find_by(id: result["message_id"])
+
+ expect(created_message).not_to be_nil
+ expect(created_message.message).to eq("Hello from the tool!")
+ expect(created_message.user_id).to eq(chat_user.id)
+ expect(created_message.chat_channel_id).to eq(chat_channel.id)
+ end
+
+ it "can create a chat message using channel slug" do
+ chat_channel.update!(name: "My Test Channel", slug: "my-test-channel")
+ expect(chat_channel.slug).to eq("my-test-channel")
+
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createChatMessage({
+ channel_name: params.channel_slug,
+ username: params.username,
+ message: params.message
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ {
+ "channel_slug" => chat_channel.slug,
+ "username" => chat_user.username,
+ "message" => "Hello via slug!",
+ },
+ llm: nil,
+ bot_user: bot_user,
+ )
+
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true), "Tool invocation failed: #{result["error"]}"
+
+ created_message = Chat::Message.find_by(id: result["message_id"])
+ expect(created_message).not_to be_nil
+ expect(created_message.message).to eq("Hello via slug!")
+ expect(created_message.chat_channel_id).to eq(chat_channel.id)
+ end
+
+ it "returns an error if the channel is not found" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createChatMessage({
+ channel_name: "non_existent_channel",
+ username: params.username,
+ message: params.message
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { "username" => chat_user.username, "message" => "Test" },
+ llm: nil,
+ bot_user: bot_user,
+ )
+
+ initial_message_count = Chat::Message.count
+ expect { runner.invoke }.to raise_error(
+ MiniRacer::RuntimeError,
+ /Channel not found: non_existent_channel/,
+ )
+
+ expect(Chat::Message.count).to eq(initial_message_count)
+ end
+
+ it "returns an error if the user is not found" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createChatMessage({
+ channel_name: params.channel_name,
+ username: "non_existent_user",
+ message: params.message
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { "channel_name" => chat_channel.name, "message" => "Test" },
+ llm: nil,
+ bot_user: bot_user,
+ )
+
+ initial_message_count = Chat::Message.count
+ expect { runner.invoke }.to raise_error(
+ MiniRacer::RuntimeError,
+ /User not found: non_existent_user/,
+ )
+
+ expect(Chat::Message.count).to eq(initial_message_count)
+ end
+ end
+
+ context "when updating agents" do
+ fab!(:ai_agent) { Fabricate(:ai_agent, name: "TestAgent", system_prompt: "Original prompt") }
+
+ it "can update a agent with proper permissions" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.updateAgent(params.agent_name, {
+ system_prompt: params.new_prompt,
+ temperature: 0.7,
+ top_p: 0.9
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { agent_name: "TestAgent", new_prompt: "Updated system prompt" },
+ llm: nil,
+ bot_user: bot_user,
+ )
+
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["agent"]["system_prompt"]).to eq("Updated system prompt")
+ expect(result["agent"]["temperature"]).to eq(0.7)
+
+ ai_agent.reload
+ expect(ai_agent.system_prompt).to eq("Updated system prompt")
+ expect(ai_agent.temperature).to eq(0.7)
+ expect(ai_agent.top_p).to eq(0.9)
+ end
+ end
+
+ context "when fetching agent information" do
+ fab!(:ai_agent) do
+ Fabricate(
+ :ai_agent,
+ name: "TestAgent",
+ description: "Test description",
+ system_prompt: "Test system prompt",
+ temperature: 0.8,
+ top_p: 0.9,
+ vision_enabled: true,
+ tools: ["Search", ["WebSearch", { param: "value" }, true]],
+ )
+ end
+
+ it "can fetch a agent by name" do
+ script = <<~JS
+ function invoke(params) {
+ const agent = discourse.getAgent(params.agent_name);
+ return agent;
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ agent_name: "TestAgent" }, llm: nil, bot_user: bot_user)
+
+ result = runner.invoke
+
+ expect(result["id"]).to eq(ai_agent.id)
+ expect(result["name"]).to eq("TestAgent")
+ expect(result["description"]).to eq("Test description")
+ expect(result["system_prompt"]).to eq("Test system prompt")
+ expect(result["temperature"]).to eq(0.8)
+ expect(result["top_p"]).to eq(0.9)
+ expect(result["vision_enabled"]).to eq(true)
+ expect(result["tools"]).to include("Search")
+ expect(result["tools"][1]).to be_a(Array)
+ end
+
+ it "raises an error when the agent doesn't exist" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.getAgent("NonExistentAgent");
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: bot_user)
+
+ expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Agent not found/)
+ end
+
+ it "can update a agent after fetching it" do
+ script = <<~JS
+ function invoke(params) {
+ const agent = discourse.getAgent("TestAgent");
+ return agent.update({
+ system_prompt: "Updated through getAgent().update()",
+ temperature: 0.5
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: bot_user)
+
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+
+ ai_agent.reload
+ expect(ai_agent.system_prompt).to eq("Updated through getAgent().update()")
+ expect(ai_agent.temperature).to eq(0.5)
+ end
+ end
+
+ context "when creating staged users" do
+ it "can create a staged user" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createStagedUser({
+ email: params.email,
+ username: params.username,
+ name: params.name
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { email: "[email protected]", username: "testuser123", name: "Test User" },
+ llm: nil,
+ bot_user: nil,
+ )
+
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true)
+ expect(result["username"]).to eq("testuser123")
+ expect(result["email"]).to eq("[email protected]")
+
+ user = User.find_by(id: result["user_id"])
+ expect(user).not_to be_nil
+ expect(user.staged).to eq(true)
+ expect(user.username).to eq("testuser123")
+ expect(user.email).to eq("[email protected]")
+ expect(user.name).to eq("Test User")
+ end
+
+ it "returns an error if user already exists" do
+ existing_user = Fabricate(:user, email: "[email protected]", username: "existinguser")
+
+ script = <<~JS
+ function invoke(params) {
+ try {
+ return discourse.createStagedUser({
+ email: params.email,
+ username: params.username
+ });
+ } catch (e) {
+ return { error: e.message };
+ }
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { email: existing_user.email, username: "newusername" },
+ llm: nil,
+ bot_user: nil,
+ )
+
+ result = runner.invoke
+
+ expect(result["error"]).to eq("User already exists")
+ end
+ end
+
+ context "when creating topics" do
+ it "can create a topic" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createTopic({
+ category_id: params.category_id,
+ title: params.title,
+ raw: params.raw,
+ username: params.username,
+ tags: params.tags
+ });
+ }
+ JS
+
+ admin = Fabricate(:admin)
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ {
+ category_id: category.id,
+ title: "Test Topic Title",
+ raw: "This is the content of the test topic",
+ username: admin.username,
+ tags: %w[test example],
+ },
+ llm: nil,
+ bot_user: nil,
+ )
+
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true)
+ expect(result["topic_id"]).to be_present
+ expect(result["post_id"]).to be_present
+
+ new_topic = Topic.find_by(id: result["topic_id"])
+ expect(new_topic).not_to be_nil
+ expect(new_topic.title).to eq("Test Topic Title")
+ expect(new_topic.category_id).to eq(category.id)
+ expect(new_topic.user_id).to eq(admin.id)
+ expect(new_topic.archetype).to eq("regular")
+ expect(new_topic.tags.pluck(:name)).to contain_exactly("test", "example")
+
+ new_post = Post.find_by(id: result["post_id"])
+ expect(new_post).not_to be_nil
+ expect(new_post.raw).to eq("This is the content of the test topic")
+ end
+
+ it "can create a topic without username (uses system user)" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createTopic({
+ category_id: params.category_id,
+ title: params.title,
+ raw: params.raw
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { category_id: category.id, title: "System User Topic", raw: "Created by system" },
+ llm: nil,
+ bot_user: nil,
+ )
+
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true)
+
+ new_topic = Topic.find_by(id: result["topic_id"])
+ expect(new_topic.user_id).to eq(Discourse.system_user.id)
+ end
+
+ it "returns an error for invalid category" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createTopic({
+ category_id: 99999,
+ title: "Test",
+ raw: "Test"
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: nil)
+
+ expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Category not found/)
+ end
+ end
+
+ context "when creating posts" do
+ fab!(:topic_for_posts) { Fabricate(:post).topic }
+
+ it "can create a post in a topic" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createPost({
+ topic_id: params.topic_id,
+ raw: params.raw,
+ username: params.username
+ });
+ }
+ JS
+
+ regular_user = Fabricate(:user)
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ {
+ topic_id: topic_for_posts.id,
+ raw: "This is a reply to the topic",
+ username: regular_user.username,
+ },
+ llm: nil,
+ bot_user: nil,
+ )
+
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true)
+ expect(result["post_id"]).to be_present
+ expect(result["post_number"]).to be > 1
+
+ new_post = Post.find_by(id: result["post_id"])
+ expect(new_post).not_to be_nil
+ expect(new_post.raw).to eq("This is a reply to the topic")
+ expect(new_post.topic_id).to eq(topic_for_posts.id)
+ expect(new_post.user_id).to eq(regular_user.id)
+ end
+
+ it "can create a reply to a specific post" do
+ _original_post = Fabricate(:post, topic: topic_for_posts, post_number: 2)
+
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createPost({
+ topic_id: params.topic_id,
+ raw: params.raw,
+ reply_to_post_number: params.reply_to_post_number
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ {
+ topic_id: topic_for_posts.id,
+ raw: "This is a reply to post #2",
+ reply_to_post_number: 2,
+ },
+ llm: nil,
+ bot_user: nil,
+ )
+
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true)
+
+ new_post = Post.find_by(id: result["post_id"])
+ expect(new_post.reply_to_post_number).to eq(2)
+ end
+
+ it "returns an error for invalid topic" do
+ script = <<~JS
+ function invoke(params) {
+ return discourse.createPost({
+ topic_id: 99999,
+ raw: "Test"
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: nil)
+
+ expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Topic not found/)
+ end
+ end
+
+ context "when seeding a category with topics" do
+ it "can seed a category with a topic and post" do
+ script = <<~JS
+ function invoke(params) {
+ const user = discourse.createStagedUser({
+ email: '[email protected]',
+ username: 'testuser',
+ name: 'Test User'
+ });
+
+ const topic = discourse.createTopic({
+ category_name: params.category_name,
+ title: 'Test Topic 123 123 123',
+ raw: 'This is the initial post content.',
+ username: user.username
+ });
+
+ const post = discourse.createPost({
+ topic_id: topic.topic_id,
+ raw: 'This is a reply to the topic.',
+ username: user.username
+ });
+
+ return {
+ success: true,
+ user: user,
+ topic: topic,
+ post: post
+ };
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ category_name: category.name }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true)
+
+ seeded_user = User.find_by(username: "testuser")
+ expect(seeded_user).not_to be_nil
+ expect(seeded_user.staged).to eq(true)
+
+ seeded_topic = Topic.find_by(id: result["topic"]["topic_id"])
+ expect(seeded_topic).not_to be_nil
+ expect(seeded_topic.category_id).to eq(category.id)
+
+ expect(seeded_topic.posts.count).to eq(2)
+ end
+ end
+
+ describe "editTopic" do
+ fab!(:topic_with_category) { Fabricate(:topic, category: category) }
+
+ it "can set tags on a topic" do
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['tag1', 'tag2'] }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["tags"]).to contain_exactly("tag1", "tag2")
+ expect(topic_with_category.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
+ end
+
+ it "can append tags on a topic" do
+ old_tag = Fabricate(:tag, name: "old_tag")
+ topic_with_category.tags << old_tag
+ Fabricate(:tag, name: "new_tag")
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['new_tag'] }, { append: true }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(topic_with_category.reload.tags.pluck(:name)).to contain_exactly(
+ "old_tag",
+ "new_tag",
+ )
+ end
+
+ it "can set tags as a specific user" do
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['tag1'] }, { username: 'system' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["tags"]).to eq(["tag1"])
+ expect(topic_with_category.reload.tags.pluck(:name)).to contain_exactly("tag1")
+ end
+
+ it "publishes to MessageBus when setting tags" do
+ mb_topic = Fabricate(:topic)
+ Fabricate(:post, topic: mb_topic)
+ Fabricate(:tag, name: "msgbus_tag")
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setTags(params.topic_id, ['msgbus_tag']); }",
+ )
+
+ messages =
+ MessageBus.track_publish("/topic/#{mb_topic.id}") do
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: mb_topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ end
+
+ expect(messages).not_to be_empty
+ expect(messages.first.data[:type]).to eq(:revised)
+ end
+
+ it "can set category on a topic by slug" do
+ new_category = Fabricate(:category, slug: "new-category")
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { category: "new-category" });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(topic_with_category.reload.category_id).to eq(new_category.id)
+ end
+
+ it "can set category on a topic by ID" do
+ new_category = Fabricate(:category)
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { category: params.category_id });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ category_id: new_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(topic_with_category.reload.category_id).to eq(new_category.id)
+ end
+
+ it "can set category on a topic by name" do
+ new_category = Fabricate(:category, name: "New Category Name", slug: "different-slug")
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { category: "New Category Name" });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(topic_with_category.reload.category_id).to eq(new_category.id)
+ end
+
+ it "returns error when setting category on private message" do
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(params.topic_id, { category: params.category_id });
+ } catch(e) {
+ return { error: e.message };
+ }
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: pm_topic.id,
+ category_id: category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["error"]).to include("private")
+ end
+
+ it "can unlist a topic" do
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { visible: false });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["visible"]).to eq(false)
+ expect(topic_with_category.reload.visible).to eq(false)
+ expect(topic_with_category.visibility_reason_id).to eq(
+ Topic.visibility_reasons[:manually_unlisted],
+ )
+ end
+
+ it "can relist a topic" do
+ topic_with_category.update!(visible: false)
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { visible: true });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["visible"]).to eq(true)
+ expect(topic_with_category.reload.visible).to eq(true)
+ expect(topic_with_category.visibility_reason_id).to eq(
+ Topic.visibility_reasons[:manually_relisted],
+ )
+ end
+
+ it "throws error for non-existent topic" do
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(999999, { tags: ['tag1'] });
+ } catch(e) {
+ return { thrown: true, message: e.message };
+ }
+ }
+ JS
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ result = runner.invoke
+ expect(result["thrown"]).to eq(true)
+ expect(result["message"]).to include("not found")
+ end
+
+ it "can edit multiple topic properties at once" do
+ new_category = Fabricate(:category, slug: "multi-edit")
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, {
+ category: "multi-edit",
+ tags: ['tag1', 'tag2'],
+ visible: false
+ });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(result["topic"]["tags"]).to contain_exactly("tag1", "tag2")
+ expect(result["topic"]["visible"]).to eq(false)
+ topic_with_category.reload
+ expect(topic_with_category.category_id).to eq(new_category.id)
+ expect(topic_with_category.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
+ expect(topic_with_category.visible).to eq(false)
+ end
+
+ it "setTags alias works for backwards compatibility" do
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setTags(params.topic_id, ['tag1', 'tag2']); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_with_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(topic_with_category.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
+ end
+ end
+
+ describe "editPost" do
+ it "can edit a post" do
+ edit_post = Fabricate(:post)
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editPost(params.post_id, 'new raw content', { edit_reason: 'AI edit' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: edit_post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(edit_post.reload.raw).to eq("new raw content")
+ expect(edit_post.edit_reason).to eq("AI edit")
+ expect(edit_post.last_editor_id).to eq(bot_user.id)
+ end
+
+ it "can edit a post as a specific user" do
+ other_user = Fabricate(:user, admin: true)
+ edit_post = Fabricate(:post)
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editPost(params.post_id, 'new raw content', { username: '#{other_user.username}' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: edit_post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(edit_post.reload.last_editor_id).to eq(other_user.id)
+ end
+
+ it "denies editing a post when the user lacks permission" do
+ post_author = Fabricate(:user)
+ unprivileged_user = Fabricate(:user)
+ edit_post = Fabricate(:post, user: post_author)
+ original_raw = edit_post.raw
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editPost(params.post_id, 'hacked content', { username: '#{unprivileged_user.username}' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: edit_post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ expect { runner.invoke }.to raise_error(/Permission denied/)
+ expect(edit_post.reload.raw).to eq(original_raw)
+ end
+ end
+
+ describe "guardian permission checks" do
+ fab!(:private_category) do
+ Fabricate(:category).tap do |c|
+ c.set_permissions(staff: :full)
+ c.save!
+ end
+ end
+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }
+
+ def run_tool(script, parameters)
+ tool.update!(script: script)
+ described_class.new(parameters: parameters, llm: llm, bot_user: bot_user, tool: tool).invoke
+ end
+
+ it "denies regular user access to restricted topics and categories" do
+ params = { username: user.username }
+
+ expect {
+ run_tool(
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { visible: false }, { username: params.username }); }",
+ params.merge(topic_id: private_topic.id),
+ )
+ }.to raise_error(MiniRacer::RuntimeError, /Permission denied/)
+
+ expect {
+ run_tool(
+ 'function invoke(params) { return discourse.createTopic({ title: "Test title", raw: "Test body", category_id: params.category_id, username: params.username }); }',
+ params.merge(category_id: private_category.id),
+ )
+ }.to raise_error(MiniRacer::RuntimeError, /Permission denied/)
+
+ expect {
+ run_tool(
+ 'function invoke(params) { return discourse.createPost({ topic_id: params.topic_id, raw: "Test reply", username: params.username }); }',
+ params.merge(topic_id: private_topic.id),
+ )
+ }.to raise_error(MiniRacer::RuntimeError, /Permission denied/)
+ end
+
+ it "defaults to bot_user when no username is provided" do
+ new_category = Fabricate(:category)
+ result =
+ run_tool(
+ 'function invoke(params) { return discourse.createTopic({ title: "Bot topic title here", raw: "Bot topic body content", category_id: params.category_id }); }',
+ { category_id: new_category.id },
+ )
+ expect(result["success"]).to eq(true)
+ expect(Topic.find(result["topic_id"]).user_id).to eq(bot_user.id)
+
+ result =
+ run_tool(
+ 'function invoke(params) { return discourse.createPost({ topic_id: params.topic_id, raw: "Bot reply content" }); }',
+ { topic_id: topic.id },
+ )
+ expect(result["success"]).to eq(true)
+ expect(Post.find(result["post_id"]).user_id).to eq(bot_user.id)
+
+ topic_for_visibility = Fabricate(:topic, category: category)
+ result =
+ run_tool(
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { visible: false }); }",
+ { topic_id: topic_for_visibility.id },
+ )
+ expect(result["success"]).to eq(true)
+ expect(topic_for_visibility.reload.visible).to eq(false)
+ end
+
+ it "allows moderator to toggle visibility on a topic" do
+ mod = Fabricate(:moderator)
+ topic_for_mod = Fabricate(:topic, category: category)
+ result =
+ run_tool(
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { visible: false }, { username: params.username }); }",
+ { topic_id: topic_for_mod.id, username: mod.username },
+ )
+ expect(result["success"]).to eq(true)
+ expect(topic_for_mod.reload.visible).to eq(false)
+ end
+
+ it "allows user to createTopic in a permitted category" do
+ result =
+ run_tool(
+ 'function invoke(params) { return discourse.createTopic({ title: "A valid topic title here", raw: "Some body content for the topic", category_id: params.category_id, username: params.username }); }',
+ { category_id: category.id, username: user.username },
+ )
+ expect(result["success"]).to eq(true)
+ expect(result["topic_id"]).to be_present
+ end
+
+ it "allows user to createPost in a permitted topic" do
+ result =
+ run_tool(
+ 'function invoke(params) { return discourse.createPost({ topic_id: params.topic_id, raw: "A reply to the topic", username: params.username }); }',
+ { topic_id: topic.id, username: user.username },
+ )
+ expect(result["success"]).to eq(true)
+ expect(result["post_id"]).to be_present
+ end
+
+ it "returns error when user cannot move topic to category" do
+ regular_user = Fabricate(:user)
+ new_category = Fabricate(:category)
+ new_category.set_permissions(staff: :full)
+ new_category.save!
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(params.topic_id, { category: params.category_id }, { username: params.username });
+ } catch(e) {
+ return { error: e.message };
+ }
+ }
+ JS
+ topic_for_perms = Fabricate(:topic, category: category)
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_for_perms.id,
+ category_id: new_category.id,
+ username: regular_user.username,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["error"]).to include("Permission denied")
+ end
+
+ it "returns error when user cannot toggle topic visibility" do
+ regular_user = Fabricate(:user)
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(params.topic_id, { visible: false }, { username: params.username });
+ } catch(e) {
+ return { error: e.message };
+ }
+ }
+ JS
+ topic_for_visibility = Fabricate(:topic, category: category)
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic_for_visibility.id,
+ username: regular_user.username,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["error"]).to include("Permission denied")
+ end
+ end
+
+ describe "custom fields" do
+ it "can get a custom field from a post" do
+ cf_post = Fabricate(:post)
+ cf_post.custom_fields["test_key"] = "test_value"
+ cf_post.save_custom_fields
+
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.getCustomField('post', params.post_id, 'test_key'); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: cf_post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result).to eq("test_value")
+ end
+
+ it "can set a custom field on a post" do
+ cf_post = Fabricate(:post)
+
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setCustomField('post', params.post_id, 'ai_processed', 'yes'); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: cf_post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+
+ expect(result["success"]).to eq(true)
+ expect(cf_post.reload.custom_fields["ai_processed"]).to eq("yes")
+ end
+
+ it "returns null for non-existent custom field" do
+ cf_post = Fabricate(:post)
+
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.getCustomField('post', params.post_id, 'nonexistent'); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: cf_post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result).to be_nil
+ end
+
+ it "works with topic custom fields" do
+ cf_topic = Fabricate(:topic)
+
+ tool.update!(
+ script:
+ "function invoke(params) { discourse.setCustomField('topic', params.topic_id, 'processed', 'true'); return discourse.getCustomField('topic', params.topic_id, 'processed'); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: cf_topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result).to eq("true")
+ end
+
+ it "throws error for invalid type in setCustomField" do
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setCustomField('invalid', 1, 'key', 'val'); }",
+ )
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Invalid type/)
+ end
+
+ it "throws error for invalid type in getCustomField" do
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.getCustomField('invalid', 1, 'key'); }",
+ )
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Invalid type/)
+ end
+
+ it "throws error for key too long" do
+ cf_post = Fabricate(:post)
+ long_key = "k" * (described_class::MAX_CUSTOM_FIELD_KEY_LENGTH + 1)
+
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setCustomField('post', params.post_id, params.key, 'val'); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: cf_post.id,
+ key: long_key,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Key too long/)
+ end
+
+ it "throws error for value too long" do
+ cf_post = Fabricate(:post)
+ long_value = "v" * (described_class::MAX_CUSTOM_FIELD_VALUE_LENGTH + 1)
+
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setCustomField('post', params.post_id, 'key', params.value); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: cf_post.id,
+ value: long_value,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Value too long/)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner/http_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner/http_spec.rb
new file mode 100644
index 00000000000..c178bef24ec
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/http_spec.rb
@@ -0,0 +1,221 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe DiscourseAi::Agents::ToolRunner do
+ fab!(:llm_model) { Fabricate(:llm_model, name: "claude-2") }
+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
+ fab!(:bot_user) { Discourse.system_user }
+
+ def create_tool(script:)
+ AiTool.create!(
+ name: "test #{SecureRandom.uuid}",
+ tool_name: "test_#{SecureRandom.uuid.underscore}",
+ description: "test",
+ parameters: [{ name: "query", type: "string", description: "perform a search" }],
+ script: script,
+ created_by_id: 1,
+ summary: "Test tool summary",
+ )
+ end
+
+ before { enable_current_plugin }
+
+ describe "HTTP operations" do
+ it "can base64 encode binary HTTP responses" do
+ binary_data = (0..255).map(&:chr).join
+ expected_base64 = Base64.strict_encode64(binary_data)
+
+ script = <<~JS
+ function invoke(params) {
+ const result = http.post("https://example.com/binary", {
+ body: "test",
+ base64Encode: true
+ });
+ return result.body;
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: nil)
+
+ stub_request(:post, "https://example.com/binary").to_return(
+ status: 200,
+ body: binary_data,
+ headers: {
+ },
+ )
+
+ result = runner.invoke
+
+ expect(result).to eq(expected_base64)
+ expect(Base64.strict_decode64(result).bytes).to eq((0..255).to_a)
+ end
+
+ it "can base64 encode binary GET responses" do
+ binary_data = (0..255).map(&:chr).join
+ expected_base64 = Base64.strict_encode64(binary_data)
+
+ script = <<~JS
+ function invoke(params) {
+ const result = http.get("https://example.com/binary", {
+ base64Encode: true
+ });
+ return result.body;
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: nil)
+
+ stub_request(:get, "https://example.com/binary").to_return(
+ status: 200,
+ body: binary_data,
+ headers: {
+ },
+ )
+
+ result = runner.invoke
+
+ expect(result).to eq(expected_base64)
+ expect(Base64.strict_decode64(result).bytes).to eq((0..255).to_a)
+ end
+
+ it "can perform HTTP requests with various verbs" do
+ %i[post put delete patch].each do |verb|
+ script = <<~JS
+ function invoke(params) {
+ result = http.#{verb}("https://example.com/api",
+ {
+ headers: { TestHeader: "TestValue" },
+ body: JSON.stringify({ data: params.data })
+ }
+ );
+
+ return result.body;
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "data" => "test data" }, llm: nil, bot_user: nil)
+
+ stub_request(verb, "https://example.com/api").with(
+ body: "{\"data\":\"test data\"}",
+ headers: {
+ "Accept" => "*/*",
+ "Testheader" => "TestValue",
+ "User-Agent" => "Discourse AI Bot 1.0 (https://www.discourse.org)",
+ },
+ ).to_return(status: 200, body: "Success", headers: {})
+
+ result = runner.invoke
+
+ expect(result).to eq("Success")
+ end
+ end
+
+ it "can perform GET HTTP requests, with 1 param" do
+ script = <<~JS
+ function invoke(params) {
+ result = http.get("https://example.com/" + params.query);
+ return result.body;
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
+
+ stub_request(:get, "https://example.com/test").with(
+ headers: {
+ "Accept" => "*/*",
+ "User-Agent" => "Discourse AI Bot 1.0 (https://www.discourse.org)",
+ },
+ ).to_return(status: 200, body: "Hello World", headers: {})
+
+ result = runner.invoke
+
+ expect(result).to eq("Hello World")
+ end
+
+ it "is limited to MAX http requests" do
+ script = <<~JS
+ function invoke(params) {
+ let i = 0;
+ while (i < 21) {
+ http.get("https://example.com/");
+ i += 1;
+ }
+ return "will not happen";
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({}, llm: nil, bot_user: nil)
+
+ stub_request(:get, "https://example.com/").to_return(
+ status: 200,
+ body: "Hello World",
+ headers: {
+ },
+ )
+
+ expect { runner.invoke }.to raise_error(DiscourseAi::Agents::ToolRunner::TooManyRequestsError)
+ end
+
+ it "can perform GET HTTP requests" do
+ script = <<~JS
+ function invoke(params) {
+ result = http.get("https://example.com/" + params.query,
+ { headers: { TestHeader: "TestValue" } }
+ );
+
+ return result.body;
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
+
+ stub_request(:get, "https://example.com/test").with(
+ headers: {
+ "Accept" => "*/*",
+ "Testheader" => "TestValue",
+ "User-Agent" => "Discourse AI Bot 1.0 (https://www.discourse.org)",
+ },
+ ).to_return(status: 200, body: "Hello World", headers: {})
+
+ result = runner.invoke
+
+ expect(result).to eq("Hello World")
+ end
+
+ it "will not timeout on slow HTTP reqs" do
+ script = <<~JS
+ function invoke(params) {
+ result = http.get("https://example.com/" + params.query,
+ { headers: { TestHeader: "TestValue" } }
+ );
+
+ return result.body;
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
+
+ stub_request(:get, "https://example.com/test").to_return do
+ sleep 0.01
+ { status: 200, body: "Hello World", headers: {} }
+ end
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
+
+ runner.timeout = 10
+
+ result = runner.invoke
+
+ expect(result).to eq("Hello World")
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner/index_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner/index_spec.rb
new file mode 100644
index 00000000000..6dc587b09eb
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/index_spec.rb
@@ -0,0 +1,218 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe DiscourseAi::Agents::ToolRunner do
+ fab!(:llm_model) { Fabricate(:llm_model, name: "claude-2") }
+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
+ fab!(:bot_user) { Discourse.system_user }
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:tool) do
+ AiTool.create!(
+ name: "test_tool",
+ tool_name: "test_tool",
+ description: "a test tool",
+ script: "function invoke(params) { return { result: 'ok' }; }",
+ summary: "test",
+ created_by: user,
+ )
+ end
+
+ def create_tool(script: nil, rag_chunk_tokens: nil, rag_chunk_overlap_tokens: nil)
+ AiTool.create!(
+ name: "test #{SecureRandom.uuid}",
+ tool_name: "test_#{SecureRandom.uuid.underscore}",
+ description: "test",
+ parameters: [{ name: "query", type: "string", description: "perform a search" }],
+ script: script || "function invoke(params) { return params; }",
+ created_by_id: 1,
+ summary: "Test tool summary",
+ rag_chunk_tokens: rag_chunk_tokens || 374,
+ rag_chunk_overlap_tokens: rag_chunk_overlap_tokens || 10,
+ )
+ end
+
+ before { enable_current_plugin }
+
+ describe "RAG index operations" do
+ context "when defining RAG fragments" do
+ fab!(:cloudflare_embedding_def)
+
+ before do
+ SiteSetting.authorized_extensions = "txt"
+ SiteSetting.ai_embeddings_selected_model = cloudflare_embedding_def.id
+ SiteSetting.ai_embeddings_enabled = true
+ Jobs.run_immediately!
+ end
+
+ def create_upload(content, filename)
+ upload = nil
+ Tempfile.create(filename) do |file|
+ file.write(content)
+ file.rewind
+
+ upload = UploadCreator.new(file, filename).create_for(Discourse.system_user.id)
+ end
+ upload
+ end
+
+ def stub_embeddings
+ @counter = 0
+ stub_request(:post, cloudflare_embedding_def.url).to_return(
+ status: 200,
+ body: lambda { |req| { result: { data: [([@counter += 2] * 1024)] } }.to_json },
+ headers: {
+ },
+ )
+ end
+
+ it "allows search within uploads" do
+ stub_embeddings
+
+ upload1 = create_upload(<<~TXT, "test.txt")
+ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
+ TXT
+
+ upload2 = create_upload(<<~TXT, "test.txt")
+ 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
+ TXT
+
+ tool = create_tool(rag_chunk_tokens: 10, rag_chunk_overlap_tokens: 4, script: <<~JS)
+ function invoke(params) {
+ let result1 = index.search("testing a search", { limit: 1 });
+ let result2 = index.search("testing another search", { limit: 3, filenames: ["test.txt"] });
+
+ return [result1, result2];
+ }
+ JS
+
+ RagDocumentFragment.link_target_and_uploads(tool, [upload1.id, upload2.id])
+
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+
+ expected = [
+ [{ "fragment" => "44 45 46 47 48 49 50", "metadata" => nil }],
+ [
+ { "fragment" => "44 45 46 47 48 49 50", "metadata" => nil },
+ { "fragment" => "36 37 38 39 40 41 42 43 44 45", "metadata" => nil },
+ { "fragment" => "30 31 32 33 34 35 36 37", "metadata" => nil },
+ ],
+ ]
+
+ expect(result).to eq(expected)
+
+ tool.rag_chunk_tokens = 5
+ tool.rag_chunk_overlap_tokens = 2
+ tool.save!
+
+ RagDocumentFragment.update_target_uploads(tool, [upload1.id, upload2.id])
+ result = tool.runner({}, llm: nil, bot_user: nil).invoke
+
+ expect(result.length).to eq(2)
+ expect(result[0][0]["fragment"].length).to eq(8)
+ expect(result[1].length).to eq(3)
+ end
+ end
+
+ describe "#rag_get_file" do
+ before { SiteSetting.authorized_extensions = "md|txt" }
+
+ it "returns full file content in fragment order" do
+ upload = Fabricate(:upload, original_filename: "skill.md")
+ UploadReference.create!(upload: upload, target: tool)
+
+ RagDocumentFragment.create!(
+ target: tool,
+ upload: upload,
+ fragment: "Part 2",
+ fragment_number: 2,
+ )
+ RagDocumentFragment.create!(
+ target: tool,
+ upload: upload,
+ fragment: "Part 1",
+ fragment_number: 1,
+ )
+ RagDocumentFragment.create!(
+ target: tool,
+ upload: upload,
+ fragment: "Part 3",
+ fragment_number: 3,
+ )
+
+ tool.update!(
+ script: "function invoke(params) { return { content: index.getFile(params.filename) }; }",
+ )
+
+ runner =
+ described_class.new(
+ parameters: {
+ "filename" => "skill.md",
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+
+ expect(result["content"]).to eq("Part 1\nPart 2\nPart 3")
+ end
+
+ it "returns null for non-existent file" do
+ tool.update!(
+ script: "function invoke(params) { return { content: index.getFile(params.filename) }; }",
+ )
+
+ runner =
+ described_class.new(
+ parameters: {
+ "filename" => "nonexistent.md",
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+
+ expect(result["content"]).to be_nil
+ end
+
+ it "picks the latest upload when duplicate filenames exist" do
+ old_upload = Fabricate(:upload, original_filename: "skill.md")
+ new_upload = Fabricate(:upload, original_filename: "skill.md")
+ UploadReference.create!(upload: old_upload, target: tool)
+ UploadReference.create!(upload: new_upload, target: tool)
+
+ RagDocumentFragment.create!(
+ target: tool,
+ upload: old_upload,
+ fragment: "old content",
+ fragment_number: 1,
+ )
+ RagDocumentFragment.create!(
+ target: tool,
+ upload: new_upload,
+ fragment: "new content",
+ fragment_number: 1,
+ )
+
+ tool.update!(
+ script: "function invoke(params) { return { content: index.getFile(params.filename) }; }",
+ )
+
+ runner =
+ described_class.new(
+ parameters: {
+ "filename" => "skill.md",
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+
+ expect(result["content"]).to eq("new content")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner/llm_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner/llm_spec.rb
new file mode 100644
index 00000000000..5389b852cc6
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/llm_spec.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe DiscourseAi::Agents::ToolRunner do
+ fab!(:llm_model) { Fabricate(:llm_model, name: "claude-2") }
+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
+ fab!(:bot_user) { Discourse.system_user }
+
+ def create_tool(script:)
+ AiTool.create!(
+ name: "test #{SecureRandom.uuid}",
+ tool_name: "test_#{SecureRandom.uuid.underscore}",
+ description: "test",
+ parameters: [{ name: "query", type: "string", description: "perform a search" }],
+ script: script,
+ created_by_id: 1,
+ summary: "Test tool summary",
+ )
+ end
+
+ before { enable_current_plugin }
+
+ describe "LLM operations" do
+ it "has access to llm truncation tools" do
+ script = <<~JS
+ function invoke(params) {
+ return llm.truncate("Hello World", 1);
+ }
+ JS
+
+ tool = create_tool(script: script)
+
+ runner = tool.runner({}, llm: llm, bot_user: nil)
+ result = runner.invoke
+
+ expect(result).to eq("Hello")
+ end
+
+ it "is able to run llm completions" do
+ script = <<~JS
+ function invoke(params) {
+ return llm.generate("question two") + llm.generate(
+ { messages: [
+ { type: "system", content: "system message" },
+ { type: "user", content: "user message" }
+ ]}
+ );
+ }
+ JS
+
+ tool = create_tool(script: script)
+
+ result = nil
+ prompts = nil
+ responses = ["Hello ", "World"]
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(responses) do |_, _, _prompts|
+ runner = tool.runner({}, llm: llm, bot_user: nil)
+ result = runner.invoke
+ prompts = _prompts
+ end
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "system message",
+ messages: [{ type: :user, content: "user message" }],
+ )
+ expect(result).to eq("Hello World")
+ expect(prompts[0]).to eq("question two")
+ expect(prompts[1]).to eq(prompt)
+ end
+
+ it "can generate JSON from LLM" do
+ tool_record =
+ AiTool.create!(
+ name: "test_tool",
+ tool_name: "test_tool",
+ description: "a test tool",
+ script: "function invoke() { return llm.generate('test', { json: true }); }",
+ summary: "test",
+ created_by_id: 1,
+ )
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ ['{"key": "value"}'],
+ ) do |_, _, _, prompt_options|
+ runner =
+ described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool_record)
+ result = runner.invoke
+ expect(result).to eq({ "key" => "value" })
+
+ expect(prompt_options.last[:response_format]).to eq({ "type" => "json_object" })
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner/upload_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner/upload_spec.rb
new file mode 100644
index 00000000000..e383d00f9e1
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/upload_spec.rb
@@ -0,0 +1,141 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe DiscourseAi::Agents::ToolRunner do
+ fab!(:bot_user) { Discourse.system_user }
+
+ def create_tool(script:)
+ AiTool.create!(
+ name: "test #{SecureRandom.uuid}",
+ tool_name: "test_#{SecureRandom.uuid.underscore}",
+ description: "test",
+ parameters: [{ name: "query", type: "string", description: "perform a search" }],
+ script: script,
+ created_by_id: 1,
+ summary: "Test tool summary",
+ )
+ end
+
+ before { enable_current_plugin }
+
+ let(:jpg) { plugin_file_from_fixtures("1x1.jpg") }
+
+ describe "upload operations" do
+ describe "upload base64 encoding" do
+ it "can get base64 data from upload ID and short URL" do
+ upload = UploadCreator.new(jpg, "1x1.jpg").create_for(Discourse.system_user.id)
+
+ script_id = <<~JS
+ function invoke(params) {
+ return upload.getBase64(params.upload_id, params.max_pixels);
+ }
+ JS
+
+ tool = create_tool(script: script_id)
+ runner =
+ tool.runner(
+ { "upload_id" => upload.id, "max_pixels" => 1_000_000 },
+ llm: nil,
+ bot_user: nil,
+ )
+ result_id = runner.invoke
+
+ expect(result_id).to be_present
+ expect(result_id).to be_a(String)
+ expect(result_id.length).to be > 0
+
+ script_url = <<~JS
+ function invoke(params) {
+ return upload.getBase64(params.short_url, params.max_pixels);
+ }
+ JS
+
+ tool = create_tool(script: script_url)
+ runner =
+ tool.runner(
+ { "short_url" => upload.short_url, "max_pixels" => 1_000_000 },
+ llm: nil,
+ bot_user: nil,
+ )
+ result_url = runner.invoke
+
+ expect(result_url).to be_present
+ expect(result_url).to be_a(String)
+ expect(result_url).to eq(result_id)
+
+ script_invalid = <<~JS
+ function invoke(params) {
+ return upload.getBase64(99999);
+ }
+ JS
+
+ tool = create_tool(script: script_invalid)
+ runner = tool.runner({}, llm: nil, bot_user: nil)
+ result_invalid = runner.invoke
+
+ expect(result_invalid).to be_nil
+ end
+ end
+
+ describe "upload URL resolution" do
+ it "can resolve upload short URLs to public URLs" do
+ upload =
+ Fabricate(
+ :upload,
+ sha1: "abcdef1234567890abcdef1234567890abcdef12",
+ url: "/uploads/default/original/1X/test.jpg",
+ original_filename: "test.jpg",
+ )
+
+ script = <<~JS
+ function invoke(params) {
+ return upload.getUrl(params.short_url);
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "short_url" => upload.short_url }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+
+ expect(result).to eq(GlobalPath.full_cdn_url(upload.url))
+ end
+
+ it "returns null for invalid upload short URLs" do
+ script = <<~JS
+ function invoke(params) {
+ return upload.getUrl(params.short_url);
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner = tool.runner({ "short_url" => "upload://invalid" }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+
+ expect(result).to be_nil
+ end
+
+ it "returns null for non-existent uploads" do
+ script = <<~JS
+ function invoke(params) {
+ return upload.getUrl(params.short_url);
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ { "short_url" => "upload://hwmUkTAL9mwhQuRMLsXw6tvDi5C.jpeg" },
+ llm: nil,
+ bot_user: nil,
+ )
+
+ result = runner.invoke
+
+ expect(result).to be_nil
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner_spec.rb
index eba9302a410..cbd0fce74cd 100644
--- a/plugins/discourse-ai/spec/lib/agents/tool_runner_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner_spec.rb
@@ -17,17 +17,9 @@ RSpec.describe DiscourseAi::Agents::ToolRunner do
end
fab!(:llm_model)
fab!(:ai_secret)
- fab!(:tag1) { Fabricate(:tag, name: "tag1") }
- fab!(:tag2) { Fabricate(:tag, name: "tag2") }
- fab!(:category) { Fabricate(:category, name: "Test Category", slug: "test-category") }
- fab!(:topic) { Fabricate(:topic, category: category) }
- fab!(:pm_topic, :private_message_topic)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model.id) }
- before do
- enable_current_plugin
- SiteSetting.tagging_enabled = true
- end
+ before { enable_current_plugin }
describe "#invoke" do
it "can execute a simple script" do
@@ -95,723 +87,6 @@ RSpec.describe DiscourseAi::Agents::ToolRunner do
expect(result["key"]).to eq(ai_secret.secret)
end
-
- it "can set tags on a topic" do
- tool.update!(
- script:
- "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['tag1', 'tag2'] }); }",
- )
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["tags"]).to contain_exactly("tag1", "tag2")
- expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
- end
-
- it "can get a topic with tags and first_post_id" do
- Fabricate(:post, topic: topic)
- tag = Fabricate(:tag, name: "test_tag")
- topic.tags << tag
- tool.update!(
- script:
- "function invoke(params) { const t = discourse.getTopic(params.topic_id); return { tags: t.tags, first_post_id: t.first_post_id }; }",
- )
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["tags"]).to contain_exactly("test_tag")
- expect(result["first_post_id"]).to eq(topic.first_post.id)
- end
-
- it "can append tags on a topic" do
- old_tag = Fabricate(:tag, name: "old_tag")
- topic.tags << old_tag
- Fabricate(:tag, name: "new_tag")
- tool.update!(
- script:
- "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['new_tag'] }, { append: true }); }",
- )
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(topic.reload.tags.pluck(:name)).to contain_exactly("old_tag", "new_tag")
- end
-
- it "can set tags as a specific user" do
- tool.update!(
- script:
- "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['tag1'] }, { username: 'system' }); }",
- )
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["tags"]).to eq(["tag1"])
- expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1")
- end
-
- it "publishes to MessageBus when setting tags" do
- topic = Fabricate(:topic)
- Fabricate(:post, topic: topic)
- Fabricate(:tag, name: "msgbus_tag")
- tool.update!(
- script:
- "function invoke(params) { return discourse.setTags(params.topic_id, ['msgbus_tag']); }",
- )
-
- messages =
- MessageBus.track_publish("/topic/#{topic.id}") do
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- end
-
- expect(messages).not_to be_empty
- expect(messages.first.data[:type]).to eq(:revised)
- end
-
- it "can edit a post" do
- post = Fabricate(:post)
- tool.update!(
- script:
- "function invoke(params) { return discourse.editPost(params.post_id, 'new raw content', { edit_reason: 'AI edit' }); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(post.reload.raw).to eq("new raw content")
- expect(post.edit_reason).to eq("AI edit")
- expect(post.last_editor_id).to eq(bot_user.id)
- end
-
- it "can edit a post as a specific user" do
- other_user = Fabricate(:user, admin: true)
- post = Fabricate(:post)
- tool.update!(
- script:
- "function invoke(params) { return discourse.editPost(params.post_id, 'new raw content', { username: '#{other_user.username}' }); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(post.reload.last_editor_id).to eq(other_user.id)
- end
-
- it "denies editing a post when the user lacks permission" do
- post_author = Fabricate(:user)
- unprivileged_user = Fabricate(:user)
- post = Fabricate(:post, user: post_author)
- original_raw = post.raw
- tool.update!(
- script:
- "function invoke(params) { return discourse.editPost(params.post_id, 'hacked content', { username: '#{unprivileged_user.username}' }); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- expect { runner.invoke }.to raise_error(/Permission denied/)
- expect(post.reload.raw).to eq(original_raw)
- end
-
- it "can generate JSON from LLM" do
- tool.update!(script: "function invoke() { return llm.generate('test', { json: true }); }")
-
- DiscourseAi::Completions::Llm.with_prepared_responses(
- ['{"key": "value"}'],
- ) do |_, _, _, prompt_options|
- runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
- result = runner.invoke
- expect(result).to eq({ "key" => "value" })
-
- expect(prompt_options.last[:response_format]).to eq({ "type" => "json_object" })
- end
- end
-
- it "can get a topic with category info" do
- tool.update!(script: <<~JS)
- function invoke(params) {
- const t = discourse.getTopic(params.topic_id);
- return {
- category_id: t.category_id,
- category_name: t.category_name,
- category_slug: t.category_slug
- };
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["category_id"]).to eq(category.id)
- expect(result["category_name"]).to eq("Test Category")
- expect(result["category_slug"]).to eq("test-category")
- end
-
- it "can set category on a topic by slug" do
- new_category = Fabricate(:category, slug: "new-category")
- tool.update!(script: <<~JS)
- function invoke(params) {
- return discourse.editTopic(params.topic_id, { category: "new-category" });
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["category_id"]).to eq(new_category.id)
- expect(topic.reload.category_id).to eq(new_category.id)
- end
-
- it "can set category on a topic by ID" do
- new_category = Fabricate(:category)
- tool.update!(script: <<~JS)
- function invoke(params) {
- return discourse.editTopic(params.topic_id, { category: params.category_id });
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- category_id: new_category.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["category_id"]).to eq(new_category.id)
- expect(topic.reload.category_id).to eq(new_category.id)
- end
-
- it "returns error when setting category on private message" do
- tool.update!(script: <<~JS)
- function invoke(params) {
- try {
- return discourse.editTopic(params.topic_id, { category: params.category_id });
- } catch(e) {
- return { error: e.message };
- }
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: pm_topic.id,
- category_id: category.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["error"]).to include("private")
- end
-
- it "can unlist a topic" do
- tool.update!(script: <<~JS)
- function invoke(params) {
- return discourse.editTopic(params.topic_id, { visible: false });
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["visible"]).to eq(false)
- expect(topic.reload.visible).to eq(false)
- expect(topic.visibility_reason_id).to eq(Topic.visibility_reasons[:manually_unlisted])
- end
-
- it "can relist a topic" do
- topic.update!(visible: false)
- tool.update!(script: <<~JS)
- function invoke(params) {
- return discourse.editTopic(params.topic_id, { visible: true });
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["visible"]).to eq(true)
- expect(topic.reload.visible).to eq(true)
- expect(topic.visibility_reason_id).to eq(Topic.visibility_reasons[:manually_relisted])
- end
-
- it "editTopic throws error for non-existent topic" do
- tool.update!(script: <<~JS)
- function invoke(params) {
- try {
- return discourse.editTopic(999999, { tags: ['tag1'] });
- } catch(e) {
- return { thrown: true, message: e.message };
- }
- }
- JS
- runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
- result = runner.invoke
- expect(result["thrown"]).to eq(true)
- expect(result["message"]).to include("not found")
- end
-
- it "can edit multiple topic properties at once" do
- new_category = Fabricate(:category, slug: "multi-edit")
- tool.update!(script: <<~JS)
- function invoke(params) {
- return discourse.editTopic(params.topic_id, {
- category: "multi-edit",
- tags: ['tag1', 'tag2'],
- visible: false
- });
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["category_id"]).to eq(new_category.id)
- expect(result["topic"]["tags"]).to contain_exactly("tag1", "tag2")
- expect(result["topic"]["visible"]).to eq(false)
- topic.reload
- expect(topic.category_id).to eq(new_category.id)
- expect(topic.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
- expect(topic.visible).to eq(false)
- end
-
- it "can set category on a topic by name" do
- new_category = Fabricate(:category, name: "New Category Name", slug: "different-slug")
- tool.update!(script: <<~JS)
- function invoke(params) {
- return discourse.editTopic(params.topic_id, { category: "New Category Name" });
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["topic"]["category_id"]).to eq(new_category.id)
- expect(topic.reload.category_id).to eq(new_category.id)
- end
-
- it "returns error when user cannot move topic to category" do
- regular_user = Fabricate(:user)
- new_category = Fabricate(:category)
- new_category.set_permissions(staff: :full)
- new_category.save!
- tool.update!(script: <<~JS)
- function invoke(params) {
- try {
- return discourse.editTopic(params.topic_id, { category: params.category_id }, { username: params.username });
- } catch(e) {
- return { error: e.message };
- }
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- category_id: new_category.id,
- username: regular_user.username,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["error"]).to include("Permission denied")
- end
-
- it "returns error when user cannot toggle topic visibility" do
- regular_user = Fabricate(:user)
- tool.update!(script: <<~JS)
- function invoke(params) {
- try {
- return discourse.editTopic(params.topic_id, { visible: false }, { username: params.username });
- } catch(e) {
- return { error: e.message };
- }
- }
- JS
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- username: regular_user.username,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["error"]).to include("Permission denied")
- end
-
- it "setTags alias works for backwards compatibility" do
- tool.update!(
- script:
- "function invoke(params) { return discourse.setTags(params.topic_id, ['tag1', 'tag2']); }",
- )
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
- end
-
- describe "guardian permission checks" do
- fab!(:private_category) do
- Fabricate(:category).tap do |c|
- c.set_permissions(staff: :full)
- c.save!
- end
- end
- fab!(:private_topic) { Fabricate(:topic, category: private_category) }
-
- def run_tool(script, parameters)
- tool.update!(script: script)
- described_class.new(parameters: parameters, llm: llm, bot_user: bot_user, tool: tool).invoke
- end
-
- it "denies regular user access to restricted topics and categories" do
- params = { username: user.username }
-
- expect {
- run_tool(
- "function invoke(params) { return discourse.editTopic(params.topic_id, { visible: false }, { username: params.username }); }",
- params.merge(topic_id: private_topic.id),
- )
- }.to raise_error(MiniRacer::RuntimeError, /Permission denied/)
-
- expect {
- run_tool(
- 'function invoke(params) { return discourse.createTopic({ title: "Test title", raw: "Test body", category_id: params.category_id, username: params.username }); }',
- params.merge(category_id: private_category.id),
- )
- }.to raise_error(MiniRacer::RuntimeError, /Permission denied/)
-
- expect {
- run_tool(
- 'function invoke(params) { return discourse.createPost({ topic_id: params.topic_id, raw: "Test reply", username: params.username }); }',
- params.merge(topic_id: private_topic.id),
- )
- }.to raise_error(MiniRacer::RuntimeError, /Permission denied/)
- end
-
- it "defaults to bot_user when no username is provided" do
- new_category = Fabricate(:category)
- result =
- run_tool(
- 'function invoke(params) { return discourse.createTopic({ title: "Bot topic title here", raw: "Bot topic body content", category_id: params.category_id }); }',
- { category_id: new_category.id },
- )
- expect(result["success"]).to eq(true)
- expect(Topic.find(result["topic_id"]).user_id).to eq(bot_user.id)
-
- result =
- run_tool(
- 'function invoke(params) { return discourse.createPost({ topic_id: params.topic_id, raw: "Bot reply content" }); }',
- { topic_id: topic.id },
- )
- expect(result["success"]).to eq(true)
- expect(Post.find(result["post_id"]).user_id).to eq(bot_user.id)
-
- result =
- run_tool(
- "function invoke(params) { return discourse.editTopic(params.topic_id, { visible: false }); }",
- { topic_id: topic.id },
- )
- expect(result["success"]).to eq(true)
- expect(topic.reload.visible).to eq(false)
- end
-
- it "allows moderator to toggle visibility on a topic" do
- mod = Fabricate(:moderator)
- result =
- run_tool(
- "function invoke(params) { return discourse.editTopic(params.topic_id, { visible: false }, { username: params.username }); }",
- { topic_id: topic.id, username: mod.username },
- )
- expect(result["success"]).to eq(true)
- expect(topic.reload.visible).to eq(false)
- end
-
- it "allows user to createTopic in a permitted category" do
- result =
- run_tool(
- 'function invoke(params) { return discourse.createTopic({ title: "A valid topic title here", raw: "Some body content for the topic", category_id: params.category_id, username: params.username }); }',
- { category_id: category.id, username: user.username },
- )
- expect(result["success"]).to eq(true)
- expect(result["topic_id"]).to be_present
- end
-
- it "allows user to createPost in a permitted topic" do
- result =
- run_tool(
- 'function invoke(params) { return discourse.createPost({ topic_id: params.topic_id, raw: "A reply to the topic", username: params.username }); }',
- { topic_id: topic.id, username: user.username },
- )
- expect(result["success"]).to eq(true)
- expect(result["post_id"]).to be_present
- end
- end
-
- describe "custom fields" do
- it "can get a custom field from a post" do
- post = Fabricate(:post)
- post.custom_fields["test_key"] = "test_value"
- post.save_custom_fields
-
- tool.update!(
- script:
- "function invoke(params) { return discourse.getCustomField('post', params.post_id, 'test_key'); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result).to eq("test_value")
- end
-
- it "can set a custom field on a post" do
- post = Fabricate(:post)
-
- tool.update!(
- script:
- "function invoke(params) { return discourse.setCustomField('post', params.post_id, 'ai_processed', 'yes'); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
-
- expect(result["success"]).to eq(true)
- expect(post.reload.custom_fields["ai_processed"]).to eq("yes")
- end
-
- it "returns null for non-existent custom field" do
- post = Fabricate(:post)
-
- tool.update!(
- script:
- "function invoke(params) { return discourse.getCustomField('post', params.post_id, 'nonexistent'); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result).to be_nil
- end
-
- it "works with topic custom fields" do
- topic = Fabricate(:topic)
-
- tool.update!(
- script:
- "function invoke(params) { discourse.setCustomField('topic', params.topic_id, 'processed', 'true'); return discourse.getCustomField('topic', params.topic_id, 'processed'); }",
- )
- runner =
- described_class.new(
- parameters: {
- topic_id: topic.id,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
- expect(result).to eq("true")
- end
-
- it "throws error for invalid type in setCustomField" do
- tool.update!(
- script:
- "function invoke(params) { return discourse.setCustomField('invalid', 1, 'key', 'val'); }",
- )
- runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
- expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Invalid type/)
- end
-
- it "throws error for invalid type in getCustomField" do
- tool.update!(
- script:
- "function invoke(params) { return discourse.getCustomField('invalid', 1, 'key'); }",
- )
- runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
- expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Invalid type/)
- end
-
- it "throws error for key too long" do
- post = Fabricate(:post)
- long_key = "k" * (described_class::MAX_CUSTOM_FIELD_KEY_LENGTH + 1)
-
- tool.update!(
- script:
- "function invoke(params) { return discourse.setCustomField('post', params.post_id, params.key, 'val'); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- key: long_key,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Key too long/)
- end
-
- it "throws error for value too long" do
- post = Fabricate(:post)
- long_value = "v" * (described_class::MAX_CUSTOM_FIELD_VALUE_LENGTH + 1)
-
- tool.update!(
- script:
- "function invoke(params) { return discourse.setCustomField('post', params.post_id, 'key', params.value); }",
- )
- runner =
- described_class.new(
- parameters: {
- post_id: post.id,
- value: long_value,
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Value too long/)
- end
- end
end
describe "#has_custom_system_message?" do
@@ -858,105 +133,4 @@ RSpec.describe DiscourseAi::Agents::ToolRunner do
expect(runner.custom_system_message).to be_nil
end
end
-
- describe "#rag_get_file" do
- before { SiteSetting.authorized_extensions = "md|txt" }
-
- it "returns full file content in fragment order" do
- upload = Fabricate(:upload, original_filename: "skill.md")
- UploadReference.create!(upload: upload, target: tool)
-
- RagDocumentFragment.create!(
- target: tool,
- upload: upload,
- fragment: "Part 2",
- fragment_number: 2,
- )
- RagDocumentFragment.create!(
- target: tool,
- upload: upload,
- fragment: "Part 1",
- fragment_number: 1,
- )
- RagDocumentFragment.create!(
- target: tool,
- upload: upload,
- fragment: "Part 3",
- fragment_number: 3,
- )
-
- tool.update!(
- script: "function invoke(params) { return { content: index.getFile(params.filename) }; }",
- )
-
- runner =
- described_class.new(
- parameters: {
- "filename" => "skill.md",
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
-
- expect(result["content"]).to eq("Part 1\nPart 2\nPart 3")
- end
-
- it "returns null for non-existent file" do
- tool.update!(
- script: "function invoke(params) { return { content: index.getFile(params.filename) }; }",
- )
-
- runner =
- described_class.new(
- parameters: {
- "filename" => "nonexistent.md",
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
-
- expect(result["content"]).to be_nil
- end
-
- it "picks the latest upload when duplicate filenames exist" do
- old_upload = Fabricate(:upload, original_filename: "skill.md")
- new_upload = Fabricate(:upload, original_filename: "skill.md")
- UploadReference.create!(upload: old_upload, target: tool)
- UploadReference.create!(upload: new_upload, target: tool)
-
- RagDocumentFragment.create!(
- target: tool,
- upload: old_upload,
- fragment: "old content",
- fragment_number: 1,
- )
- RagDocumentFragment.create!(
- target: tool,
- upload: new_upload,
- fragment: "new content",
- fragment_number: 1,
- )
-
- tool.update!(
- script: "function invoke(params) { return { content: index.getFile(params.filename) }; }",
- )
-
- runner =
- described_class.new(
- parameters: {
- "filename" => "skill.md",
- },
- llm: llm,
- bot_user: bot_user,
- tool: tool,
- )
- result = runner.invoke
-
- expect(result["content"]).to eq("new content")
- end
- end
end
diff --git a/plugins/discourse-ai/spec/models/ai_tool_spec.rb b/plugins/discourse-ai/spec/models/ai_tool_spec.rb
index 3ceff90ed92..ea229377496 100644
--- a/plugins/discourse-ai/spec/models/ai_tool_spec.rb
+++ b/plugins/discourse-ai/spec/models/ai_tool_spec.rb
@@ -3,8 +3,6 @@
RSpec.describe AiTool do
fab!(:llm_model) { Fabricate(:llm_model, name: "claude-2") }
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
- fab!(:topic)
- fab!(:post) { Fabricate(:post, topic: topic, raw: "bananas are a tasty fruit") }
fab!(:bot_user) { Discourse.system_user }
def create_tool(
@@ -72,255 +70,6 @@ RSpec.describe AiTool do
expect(tool.missing_secret_aliases).to eq([])
end
- it "can base64 encode binary HTTP responses" do
- # Create binary data with all possible byte values (0-255)
- binary_data = (0..255).map(&:chr).join
- expected_base64 = Base64.strict_encode64(binary_data)
-
- script = <<~JS
- function invoke(params) {
- const result = http.post("https://example.com/binary", {
- body: "test",
- base64Encode: true
- });
- return result.body;
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({}, llm: nil, bot_user: nil)
-
- stub_request(:post, "https://example.com/binary").to_return(
- status: 200,
- body: binary_data,
- headers: {
- },
- )
-
- result = runner.invoke
-
- expect(result).to eq(expected_base64)
- # Verify we can decode back to original binary data
- expect(Base64.strict_decode64(result).bytes).to eq((0..255).to_a)
- end
-
- it "can base64 encode binary GET responses" do
- # Create binary data with all possible byte values (0-255)
- binary_data = (0..255).map(&:chr).join
- expected_base64 = Base64.strict_encode64(binary_data)
-
- script = <<~JS
- function invoke(params) {
- const result = http.get("https://example.com/binary", {
- base64Encode: true
- });
- return result.body;
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({}, llm: nil, bot_user: nil)
-
- stub_request(:get, "https://example.com/binary").to_return(
- status: 200,
- body: binary_data,
- headers: {
- },
- )
-
- result = runner.invoke
-
- expect(result).to eq(expected_base64)
- # Verify we can decode back to original binary data
- expect(Base64.strict_decode64(result).bytes).to eq((0..255).to_a)
- end
-
- it "can perform HTTP requests with various verbs" do
- %i[post put delete patch].each do |verb|
- script = <<~JS
- function invoke(params) {
- result = http.#{verb}("https://example.com/api",
- {
- headers: { TestHeader: "TestValue" },
- body: JSON.stringify({ data: params.data })
- }
- );
-
- return result.body;
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "data" => "test data" }, llm: nil, bot_user: nil)
-
- stub_request(verb, "https://example.com/api").with(
- body: "{\"data\":\"test data\"}",
- headers: {
- "Accept" => "*/*",
- "Testheader" => "TestValue",
- "User-Agent" => "Discourse AI Bot 1.0 (https://www.discourse.org)",
- },
- ).to_return(status: 200, body: "Success", headers: {})
-
- result = runner.invoke
-
- expect(result).to eq("Success")
- end
- end
-
- it "can perform GET HTTP requests, with 1 param" do
- script = <<~JS
- function invoke(params) {
- result = http.get("https://example.com/" + params.query);
- return result.body;
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
-
- stub_request(:get, "https://example.com/test").with(
- headers: {
- "Accept" => "*/*",
- "User-Agent" => "Discourse AI Bot 1.0 (https://www.discourse.org)",
- },
- ).to_return(status: 200, body: "Hello World", headers: {})
-
- result = runner.invoke
-
- expect(result).to eq("Hello World")
- end
-
- it "is limited to MAX http requests" do
- script = <<~JS
- function invoke(params) {
- let i = 0;
- while (i < 21) {
- http.get("https://example.com/");
- i += 1;
- }
- return "will not happen";
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({}, llm: nil, bot_user: nil)
-
- stub_request(:get, "https://example.com/").to_return(
- status: 200,
- body: "Hello World",
- headers: {
- },
- )
-
- expect { runner.invoke }.to raise_error(DiscourseAi::Agents::ToolRunner::TooManyRequestsError)
- end
-
- it "can perform GET HTTP requests" do
- script = <<~JS
- function invoke(params) {
- result = http.get("https://example.com/" + params.query,
- { headers: { TestHeader: "TestValue" } }
- );
-
- return result.body;
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
-
- stub_request(:get, "https://example.com/test").with(
- headers: {
- "Accept" => "*/*",
- "Testheader" => "TestValue",
- "User-Agent" => "Discourse AI Bot 1.0 (https://www.discourse.org)",
- },
- ).to_return(status: 200, body: "Hello World", headers: {})
-
- result = runner.invoke
-
- expect(result).to eq("Hello World")
- end
-
- it "will not timeout on slow HTTP reqs" do
- script = <<~JS
- function invoke(params) {
- result = http.get("https://example.com/" + params.query,
- { headers: { TestHeader: "TestValue" } }
- );
-
- return result.body;
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
-
- stub_request(:get, "https://example.com/test").to_return do
- sleep 0.01
- { status: 200, body: "Hello World", headers: {} }
- end
-
- tool = create_tool(script: script)
- runner = tool.runner({ "query" => "test" }, llm: nil, bot_user: nil)
-
- runner.timeout = 10
-
- result = runner.invoke
-
- expect(result).to eq("Hello World")
- end
-
- it "has access to llm truncation tools" do
- script = <<~JS
- function invoke(params) {
- return llm.truncate("Hello World", 1);
- }
- JS
-
- tool = create_tool(script: script)
-
- runner = tool.runner({}, llm: llm, bot_user: nil)
- result = runner.invoke
-
- expect(result).to eq("Hello")
- end
-
- it "is able to run llm completions" do
- script = <<~JS
- function invoke(params) {
- return llm.generate("question two") + llm.generate(
- { messages: [
- { type: "system", content: "system message" },
- { type: "user", content: "user message" }
- ]}
- );
- }
- JS
-
- tool = create_tool(script: script)
-
- result = nil
- prompts = nil
- responses = ["Hello ", "World"]
-
- DiscourseAi::Completions::Llm.with_prepared_responses(responses) do |_, _, _prompts|
- runner = tool.runner({}, llm: llm, bot_user: nil)
- result = runner.invoke
- prompts = _prompts
- end
-
- prompt =
- DiscourseAi::Completions::Prompt.new(
- "system message",
- messages: [{ type: :user, content: "user message" }],
- )
- expect(result).to eq("Hello World")
- expect(prompts[0]).to eq("question two")
- expect(prompts[1]).to eq(prompt)
- end
-
it "can timeout slow JS" do
script = <<~JS
function invoke(params) {
@@ -337,435 +86,6 @@ RSpec.describe AiTool do
expect(result[:error]).to eq("Script terminated due to timeout")
end
- context "when defining RAG fragments" do
- fab!(:cloudflare_embedding_def)
-
- before do
- SiteSetting.authorized_extensions = "txt"
- SiteSetting.ai_embeddings_selected_model = cloudflare_embedding_def.id
- SiteSetting.ai_embeddings_enabled = true
- Jobs.run_immediately!
- end
-
- def create_upload(content, filename)
- upload = nil
- Tempfile.create(filename) do |file|
- file.write(content)
- file.rewind
-
- upload = UploadCreator.new(file, filename).create_for(Discourse.system_user.id)
- end
- upload
- end
-
- def stub_embeddings
- # this is a trick, we get ever increasing embeddings, this gives us in turn
- # 100% consistent search results
- @counter = 0
- stub_request(:post, cloudflare_embedding_def.url).to_return(
- status: 200,
- body: lambda { |req| { result: { data: [([@counter += 2] * 1024)] } }.to_json },
- headers: {
- },
- )
- end
-
- it "allows search within uploads" do
- stub_embeddings
-
- upload1 = create_upload(<<~TXT, "test.txt")
- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
- TXT
-
- upload2 = create_upload(<<~TXT, "test.txt")
- 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
- TXT
-
- tool = create_tool(rag_chunk_tokens: 10, rag_chunk_overlap_tokens: 4, script: <<~JS)
- function invoke(params) {
- let result1 = index.search("testing a search", { limit: 1 });
- let result2 = index.search("testing another search", { limit: 3, filenames: ["test.txt"] });
-
- return [result1, result2];
- }
- JS
-
- RagDocumentFragment.link_target_and_uploads(tool, [upload1.id, upload2.id])
-
- result = tool.runner({}, llm: nil, bot_user: nil).invoke
-
- expected = [
- [{ "fragment" => "44 45 46 47 48 49 50", "metadata" => nil }],
- [
- { "fragment" => "44 45 46 47 48 49 50", "metadata" => nil },
- { "fragment" => "36 37 38 39 40 41 42 43 44 45", "metadata" => nil },
- { "fragment" => "30 31 32 33 34 35 36 37", "metadata" => nil },
- ],
- ]
-
- expect(result).to eq(expected)
-
- # will force a reindex
- tool.rag_chunk_tokens = 5
- tool.rag_chunk_overlap_tokens = 2
- tool.save!
-
- # this part of the API is a bit awkward, maybe we should do it
- # automatically
- RagDocumentFragment.update_target_uploads(tool, [upload1.id, upload2.id])
- result = tool.runner({}, llm: nil, bot_user: nil).invoke
-
- # this is flaking, it is not critical cause it relies on vector search
- # that may not be 100% deterministic
-
- # expected = [
- # [{ "fragment" => "48 49 50", "metadata" => nil }],
- # [
- # { "fragment" => "48 49 50", "metadata" => nil },
- # { "fragment" => "45 46 47", "metadata" => nil },
- # { "fragment" => "42 43 44", "metadata" => nil },
- # ],
- # ]
-
- expect(result.length).to eq(2)
- expect(result[0][0]["fragment"].length).to eq(8)
- expect(result[1].length).to eq(3)
- end
- end
-
- context "when using the topic API" do
- it "can fetch topic details" do
- script = <<~JS
- function invoke(params) {
- return discourse.getTopic(params.topic_id);
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "topic_id" => topic.id }, llm: nil, bot_user: nil)
-
- result = runner.invoke
-
- expect(result["id"]).to eq(topic.id)
- expect(result["title"]).to eq(topic.title)
- expect(result["archetype"]).to eq("regular")
- expect(result["posts_count"]).to eq(1)
- end
- end
-
- context "when using the post API" do
- it "can fetch post details" do
- script = <<~JS
- function invoke(params) {
- const post = discourse.getPost(params.post_id);
- return {
- post: post,
- topic: post.topic
- }
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "post_id" => post.id }, llm: nil, bot_user: nil)
-
- result = runner.invoke
- post_hash = result["post"]
- topic_hash = result["topic"]
-
- expect(post_hash["id"]).to eq(post.id)
- expect(post_hash["topic_id"]).to eq(topic.id)
- expect(post_hash["raw"]).to eq(post.raw)
-
- expect(topic_hash["id"]).to eq(topic.id)
- end
- end
-
- context "when using the search API" do
- before { SearchIndexer.enable }
- after { SearchIndexer.disable }
-
- it "can perform a discourse search" do
- SearchIndexer.index(topic, force: true)
- SearchIndexer.index(post, force: true)
-
- script = <<~JS
- function invoke(params) {
- return discourse.search({ search_query: params.query });
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "query" => "banana" }, llm: nil, bot_user: nil)
-
- result = runner.invoke
-
- expect(result["rows"].length).to be > 0
- expect(result["rows"].first["title"]).to eq(topic.title)
- end
- end
-
- context "when using the chat API" do
- before(:each) do
- skip "Chat plugin tests skipped because Chat module is not defined." unless defined?(Chat)
- SiteSetting.chat_enabled = true
- end
-
- fab!(:chat_user, :user)
- fab!(:chat_channel) do
- Fabricate(:chat_channel).tap do |channel|
- Fabricate(
- :user_chat_channel_membership,
- user: chat_user,
- chat_channel: channel,
- following: true,
- )
- end
- end
-
- it "can create a chat message" do
- script = <<~JS
- function invoke(params) {
- return discourse.createChatMessage({
- channel_name: params.channel_name,
- username: params.username,
- message: params.message
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- {
- "channel_name" => chat_channel.name,
- "username" => chat_user.username,
- "message" => "Hello from the tool!",
- },
- llm: nil,
- bot_user: bot_user, # The user *running* the tool doesn't affect sender
- )
-
- initial_message_count = Chat::Message.count
- result = runner.invoke
-
- expect(result["success"]).to eq(true), "Tool invocation failed: #{result["error"]}"
- expect(result["message"]).to eq("Hello from the tool!")
- expect(result["created_at"]).to be_present
- expect(result).not_to have_key("error")
-
- # Verify message was actually created in the database
- expect(Chat::Message.count).to eq(initial_message_count + 1)
- created_message = Chat::Message.find_by(id: result["message_id"])
-
- expect(created_message).not_to be_nil
- expect(created_message.message).to eq("Hello from the tool!")
- expect(created_message.user_id).to eq(chat_user.id) # Message is sent AS the specified user
- expect(created_message.chat_channel_id).to eq(chat_channel.id)
- end
-
- it "can create a chat message using channel slug" do
- chat_channel.update!(name: "My Test Channel", slug: "my-test-channel")
- expect(chat_channel.slug).to eq("my-test-channel")
-
- script = <<~JS
- function invoke(params) {
- return discourse.createChatMessage({
- channel_name: params.channel_slug, // Using slug here
- username: params.username,
- message: params.message
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- {
- "channel_slug" => chat_channel.slug,
- "username" => chat_user.username,
- "message" => "Hello via slug!",
- },
- llm: nil,
- bot_user: bot_user,
- )
-
- result = runner.invoke
-
- expect(result["success"]).to eq(true), "Tool invocation failed: #{result["error"]}"
- # see: https://github.com/rubyjs/mini_racer/issues/348
- # expect(result["message_id"]).to be_a(Integer)
-
- created_message = Chat::Message.find_by(id: result["message_id"])
- expect(created_message).not_to be_nil
- expect(created_message.message).to eq("Hello via slug!")
- expect(created_message.chat_channel_id).to eq(chat_channel.id)
- end
-
- it "returns an error if the channel is not found" do
- script = <<~JS
- function invoke(params) {
- return discourse.createChatMessage({
- channel_name: "non_existent_channel",
- username: params.username,
- message: params.message
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { "username" => chat_user.username, "message" => "Test" },
- llm: nil,
- bot_user: bot_user,
- )
-
- initial_message_count = Chat::Message.count
- expect { runner.invoke }.to raise_error(
- MiniRacer::RuntimeError,
- /Channel not found: non_existent_channel/,
- )
-
- expect(Chat::Message.count).to eq(initial_message_count) # Verify no message created
- end
-
- it "returns an error if the user is not found" do
- script = <<~JS
- function invoke(params) {
- return discourse.createChatMessage({
- channel_name: params.channel_name,
- username: "non_existent_user",
- message: params.message
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { "channel_name" => chat_channel.name, "message" => "Test" },
- llm: nil,
- bot_user: bot_user,
- )
-
- initial_message_count = Chat::Message.count
- expect { runner.invoke }.to raise_error(
- MiniRacer::RuntimeError,
- /User not found: non_existent_user/,
- )
-
- expect(Chat::Message.count).to eq(initial_message_count) # Verify no message created
- end
- end
-
- context "when updating agents" do
- fab!(:ai_agent) { Fabricate(:ai_agent, name: "TestAgent", system_prompt: "Original prompt") }
-
- it "can update a agent with proper permissions" do
- script = <<~JS
- function invoke(params) {
- return discourse.updateAgent(params.agent_name, {
- system_prompt: params.new_prompt,
- temperature: 0.7,
- top_p: 0.9
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { agent_name: "TestAgent", new_prompt: "Updated system prompt" },
- llm: nil,
- bot_user: bot_user,
- )
-
- result = runner.invoke
- expect(result["success"]).to eq(true)
- expect(result["agent"]["system_prompt"]).to eq("Updated system prompt")
- expect(result["agent"]["temperature"]).to eq(0.7)
-
- ai_agent.reload
- expect(ai_agent.system_prompt).to eq("Updated system prompt")
- expect(ai_agent.temperature).to eq(0.7)
- expect(ai_agent.top_p).to eq(0.9)
- end
- end
-
- context "when fetching agent information" do
- fab!(:ai_agent) do
- Fabricate(
- :ai_agent,
- name: "TestAgent",
- description: "Test description",
- system_prompt: "Test system prompt",
- temperature: 0.8,
- top_p: 0.9,
- vision_enabled: true,
- tools: ["Search", ["WebSearch", { param: "value" }, true]],
- )
- end
-
- it "can fetch a agent by name" do
- script = <<~JS
- function invoke(params) {
- const agent = discourse.getAgent(params.agent_name);
- return agent;
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ agent_name: "TestAgent" }, llm: nil, bot_user: bot_user)
-
- result = runner.invoke
-
- expect(result["id"]).to eq(ai_agent.id)
- expect(result["name"]).to eq("TestAgent")
- expect(result["description"]).to eq("Test description")
- expect(result["system_prompt"]).to eq("Test system prompt")
- expect(result["temperature"]).to eq(0.8)
- expect(result["top_p"]).to eq(0.9)
- expect(result["vision_enabled"]).to eq(true)
- expect(result["tools"]).to include("Search")
- expect(result["tools"][1]).to be_a(Array)
- end
-
- it "raises an error when the agent doesn't exist" do
- script = <<~JS
- function invoke(params) {
- return discourse.getAgent("NonExistentAgent");
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({}, llm: nil, bot_user: bot_user)
-
- expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Agent not found/)
- end
-
- it "can update a agent after fetching it" do
- script = <<~JS
- function invoke(params) {
- const agent = discourse.getAgent("TestAgent");
- return agent.update({
- system_prompt: "Updated through getAgent().update()",
- temperature: 0.5
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({}, llm: nil, bot_user: bot_user)
-
- result = runner.invoke
- expect(result["success"]).to eq(true)
-
- ai_agent.reload
- expect(ai_agent.system_prompt).to eq("Updated through getAgent().update()")
- expect(ai_agent.temperature).to eq(0.5)
- end
- end
-
it "can use sleep function with limits" do
script = <<~JS
function invoke(params) {
@@ -786,424 +106,6 @@ RSpec.describe AiTool do
expect(result).to eq([{ "slept" => 1 }, { "slept" => 1 }, { "slept" => 1 }])
end
- let(:jpg) { plugin_file_from_fixtures("1x1.jpg") }
-
- describe "upload base64 encoding" do
- it "can get base64 data from upload ID and short URL" do
- upload = UploadCreator.new(jpg, "1x1.jpg").create_for(Discourse.system_user.id)
-
- # Test with upload ID
- script_id = <<~JS
- function invoke(params) {
- return upload.getBase64(params.upload_id, params.max_pixels);
- }
- JS
-
- tool = create_tool(script: script_id)
- runner =
- tool.runner(
- { "upload_id" => upload.id, "max_pixels" => 1_000_000 },
- llm: nil,
- bot_user: nil,
- )
- result_id = runner.invoke
-
- expect(result_id).to be_present
- expect(result_id).to be_a(String)
- expect(result_id.length).to be > 0
-
- # Test with short URL
- script_url = <<~JS
- function invoke(params) {
- return upload.getBase64(params.short_url, params.max_pixels);
- }
- JS
-
- tool = create_tool(script: script_url)
- runner =
- tool.runner(
- { "short_url" => upload.short_url, "max_pixels" => 1_000_000 },
- llm: nil,
- bot_user: nil,
- )
- result_url = runner.invoke
-
- expect(result_url).to be_present
- expect(result_url).to be_a(String)
- expect(result_url).to eq(result_id) # Should return same base64 data
-
- # Test with invalid upload ID
- script_invalid = <<~JS
- function invoke(params) {
- return upload.getBase64(99999);
- }
- JS
-
- tool = create_tool(script: script_invalid)
- runner = tool.runner({}, llm: nil, bot_user: nil)
- result_invalid = runner.invoke
-
- expect(result_invalid).to be_nil
- end
- end
-
- describe "upload URL resolution" do
- it "can resolve upload short URLs to public URLs" do
- upload =
- Fabricate(
- :upload,
- sha1: "abcdef1234567890abcdef1234567890abcdef12",
- url: "/uploads/default/original/1X/test.jpg",
- original_filename: "test.jpg",
- )
-
- script = <<~JS
- function invoke(params) {
- return upload.getUrl(params.short_url);
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "short_url" => upload.short_url }, llm: nil, bot_user: nil)
-
- result = runner.invoke
-
- expect(result).to eq(GlobalPath.full_cdn_url(upload.url))
- end
-
- it "returns null for invalid upload short URLs" do
- script = <<~JS
- function invoke(params) {
- return upload.getUrl(params.short_url);
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ "short_url" => "upload://invalid" }, llm: nil, bot_user: nil)
-
- result = runner.invoke
-
- expect(result).to be_nil
- end
-
- it "returns null for non-existent uploads" do
- script = <<~JS
- function invoke(params) {
- return upload.getUrl(params.short_url);
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { "short_url" => "upload://hwmUkTAL9mwhQuRMLsXw6tvDi5C.jpeg" },
- llm: nil,
- bot_user: nil,
- )
-
- result = runner.invoke
-
- expect(result).to be_nil
- end
- end
-
- context "when creating staged users" do
- it "can create a staged user" do
- script = <<~JS
- function invoke(params) {
- return discourse.createStagedUser({
- email: params.email,
- username: params.username,
- name: params.name
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { email: "[email protected]", username: "testuser123", name: "Test User" },
- llm: nil,
- bot_user: nil,
- )
-
- result = runner.invoke
-
- expect(result["success"]).to eq(true)
- expect(result["username"]).to eq("testuser123")
- expect(result["email"]).to eq("[email protected]")
-
- user = User.find_by(id: result["user_id"])
- expect(user).not_to be_nil
- expect(user.staged).to eq(true)
- expect(user.username).to eq("testuser123")
- expect(user.email).to eq("[email protected]")
- expect(user.name).to eq("Test User")
- end
-
- it "returns an error if user already exists" do
- existing_user = Fabricate(:user, email: "[email protected]", username: "existinguser")
-
- script = <<~JS
- function invoke(params) {
- try {
- return discourse.createStagedUser({
- email: params.email,
- username: params.username
- });
- } catch (e) {
- return { error: e.message };
- }
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { email: existing_user.email, username: "newusername" },
- llm: nil,
- bot_user: nil,
- )
-
- result = runner.invoke
-
- expect(result["error"]).to eq("User already exists")
- end
- end
-
- context "when creating topics" do
- fab!(:category)
- fab!(:user, :admin)
-
- it "can create a topic" do
- script = <<~JS
- function invoke(params) {
- return discourse.createTopic({
- category_id: params.category_id,
- title: params.title,
- raw: params.raw,
- username: params.username,
- tags: params.tags
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- {
- category_id: category.id,
- title: "Test Topic Title",
- raw: "This is the content of the test topic",
- username: user.username,
- tags: %w[test example],
- },
- llm: nil,
- bot_user: nil,
- )
-
- result = runner.invoke
-
- expect(result["success"]).to eq(true)
- expect(result["topic_id"]).to be_present
- expect(result["post_id"]).to be_present
-
- topic = Topic.find_by(id: result["topic_id"])
- expect(topic).not_to be_nil
- expect(topic.title).to eq("Test Topic Title")
- expect(topic.category_id).to eq(category.id)
- expect(topic.user_id).to eq(user.id)
- expect(topic.archetype).to eq("regular")
- expect(topic.tags.pluck(:name)).to contain_exactly("test", "example")
-
- post = Post.find_by(id: result["post_id"])
- expect(post).not_to be_nil
- expect(post.raw).to eq("This is the content of the test topic")
- end
-
- it "can create a topic without username (uses system user)" do
- script = <<~JS
- function invoke(params) {
- return discourse.createTopic({
- category_id: params.category_id,
- title: params.title,
- raw: params.raw
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { category_id: category.id, title: "System User Topic", raw: "Created by system" },
- llm: nil,
- bot_user: nil,
- )
-
- result = runner.invoke
-
- expect(result["success"]).to eq(true)
-
- topic = Topic.find_by(id: result["topic_id"])
- expect(topic.user_id).to eq(Discourse.system_user.id)
- end
-
- it "returns an error for invalid category" do
- script = <<~JS
- function invoke(params) {
- return discourse.createTopic({
- category_id: 99999,
- title: "Test",
- raw: "Test"
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({}, llm: nil, bot_user: nil)
-
- expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Category not found/)
- end
- end
-
- context "when creating posts" do
- fab!(:topic) { Fabricate(:post).topic }
- fab!(:user)
-
- it "can create a post in a topic" do
- script = <<~JS
- function invoke(params) {
- return discourse.createPost({
- topic_id: params.topic_id,
- raw: params.raw,
- username: params.username
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { topic_id: topic.id, raw: "This is a reply to the topic", username: user.username },
- llm: nil,
- bot_user: nil,
- )
-
- result = runner.invoke
-
- expect(result["success"]).to eq(true)
- expect(result["post_id"]).to be_present
- expect(result["post_number"]).to be > 1
-
- post = Post.find_by(id: result["post_id"])
- expect(post).not_to be_nil
- expect(post.raw).to eq("This is a reply to the topic")
- expect(post.topic_id).to eq(topic.id)
- expect(post.user_id).to eq(user.id)
- end
-
- it "can create a reply to a specific post" do
- _original_post = Fabricate(:post, topic: topic, post_number: 2)
-
- script = <<~JS
- function invoke(params) {
- return discourse.createPost({
- topic_id: params.topic_id,
- raw: params.raw,
- reply_to_post_number: params.reply_to_post_number
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner =
- tool.runner(
- { topic_id: topic.id, raw: "This is a reply to post #2", reply_to_post_number: 2 },
- llm: nil,
- bot_user: nil,
- )
-
- result = runner.invoke
-
- expect(result["success"]).to eq(true)
-
- post = Post.find_by(id: result["post_id"])
- expect(post.reply_to_post_number).to eq(2)
- end
-
- it "returns an error for invalid topic" do
- script = <<~JS
- function invoke(params) {
- return discourse.createPost({
- topic_id: 99999,
- raw: "Test"
- });
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({}, llm: nil, bot_user: nil)
-
- expect { runner.invoke }.to raise_error(MiniRacer::RuntimeError, /Topic not found/)
- end
- end
-
- context "when seeding a category with topics" do
- fab!(:category)
-
- it "can seed a category with a topic and post" do
- script = <<~JS
- function invoke(params) {
- // Create a staged user
- const user = discourse.createStagedUser({
- email: '[email protected]',
- username: 'testuser',
- name: 'Test User'
- });
-
- // Create a topic
- const topic = discourse.createTopic({
- category_name: params.category_name,
- title: 'Test Topic 123 123 123',
- raw: 'This is the initial post content.',
- username: user.username
- });
-
- // Add an extra post to the topic
- const post = discourse.createPost({
- topic_id: topic.topic_id,
- raw: 'This is a reply to the topic.',
- username: user.username
- });
-
- return {
- success: true,
- user: user,
- topic: topic,
- post: post
- };
- }
- JS
-
- tool = create_tool(script: script)
- runner = tool.runner({ category_name: category.name }, llm: nil, bot_user: nil)
-
- result = runner.invoke
-
- expect(result["success"]).to eq(true)
-
- user = User.find_by(username: "testuser")
- expect(user).not_to be_nil
- expect(user.staged).to eq(true)
-
- topic = Topic.find_by(id: result["topic"]["topic_id"])
- expect(topic).not_to be_nil
- expect(topic.category_id).to eq(category.id)
-
- expect(topic.posts.count).to eq(2)
- end
- end
-
describe "#set_image_generation_tool_flag" do
it "sets flag to true when tool has all required characteristics" do
tool =