A platform for community discussion. Free, open, simple.
FEATURE: triage using tool directly (#37136)
Sam165e13af6259
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 0d14c78aa07..6de5737c2fe 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -110,14 +110,14 @@ en:label: "Persona"description: "AI Persona to use for report generation"- llm_tool_triage:+ ai_tool_action:fields:- model:- label: "Model"- description: "The default language model used for triage"tool:- label: "Tool"- description: "Tool to use for triage (tool must have no parameters defined)"+ label: "AI Tool"+ description: "The AI tool to execute when the automation triggers"+ llm_model:+ label: "LLM Model"+ description: "Language model for tools that use llm.generate() (optional)"llm_persona_triage:fields:diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex e7e9b278775..f601f7bf742 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -21,9 +21,9 @@ en:spam: "Flag as spam and hide post"spam_silence: "Flag as spam, hide post and silence user"scriptables:- llm_tool_triage:- title: Triage posts using AI Tool- description: "Triage posts using custom logic in an AI tool"+ ai_tool_action:+ title: AI Tool Action+ description: Execute an AI tool when the automation triggersllm_persona_triage:title: Triage posts using AI Personadescription: "Respond to posts using a specific AI persona"diff --git a/plugins/discourse-ai/discourse_automation/ai_tool_action.rb b/plugins/discourse-ai/discourse_automation/ai_tool_action.rbnew file mode 100644index 00000000000..7f2da14e341--- /dev/null+++ b/plugins/discourse-ai/discourse_automation/ai_tool_action.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++if defined?(DiscourseAutomation)+ DiscourseAutomation::Scriptable.add("ai_tool_action") do+ version 1+ run_in_background++ triggerables %i[post_created_edited]++ # Select which AI tool to run+ field :tool,+ component: :choices,+ required: true,+ extra: {+ content: DiscourseAi::Automation.available_tools_all,+ }++ # Optional LLM for tools that call llm.generate()+ field :llm_model,+ component: :choices,+ extra: {+ content: DiscourseAi::Automation.available_models,+ }++ script do |context, fields, automation|+ post = context["post"]+ next if post.blank? || post.user&.bot?++ begin+ [+ ["ai_tool_action_#{post.id}", SiteSetting.ai_automation_max_triage_per_post_per_minute],+ ["ai_tool_action", SiteSetting.ai_automation_max_triage_per_minute],+ ].each do |key, limit|+ RateLimiter.new(Discourse.system_user, key, limit, 1.minute).performed!+ end++ DiscourseAi::Automation::AiToolAction.handle(+ post: post,+ tool_id: fields.dig("tool", "value"),+ llm_model_id: fields.dig("llm_model", "value"),+ automation: automation,+ )+ rescue => e+ Discourse.warn_exception(e, message: "ai_tool_action: failed on post #{post.id}")+ raise e if Rails.env.test?+ end+ end+ end+enddiff --git a/plugins/discourse-ai/discourse_automation/llm_tool_triage.rb b/plugins/discourse-ai/discourse_automation/llm_tool_triage.rbdeleted file mode 100644index 885f81fbed6..00000000000--- a/plugins/discourse-ai/discourse_automation/llm_tool_triage.rb+++ /dev/null@@ -1,49 +0,0 @@-# frozen_string_literal: true--# TODO: this is still highly experimental and subject to a lot of change-# leaving it off in production for now Sam-if defined?(DiscourseAutomation) && !Rails.env.production?- DiscourseAutomation::Scriptable.add("llm_tool_triage") do- version 1- run_in_background-- triggerables %i[post_created_edited]-- field :tool,- component: :choices,- required: true,- extra: {- content: DiscourseAi::Automation.available_custom_tools,- }-- script do |context, fields|- tool_id = fields["tool"]["value"]- post = context["post"]- return if post&.user&.bot?-- begin- RateLimiter.new(- Discourse.system_user,- "llm_tool_triage_#{post.id}",- SiteSetting.ai_automation_max_triage_per_post_per_minute,- 1.minute,- ).performed!-- RateLimiter.new(- Discourse.system_user,- "llm_tool_triage",- SiteSetting.ai_automation_max_triage_per_minute,- 1.minute,- ).performed!-- DiscourseAi::Automation::LlmToolTriage.handle(- post: post,- tool_id: tool_id,- automation: self.automation,- )- rescue => e- Discourse.warn_exception(e, message: "llm_tool_triage: skipped triage on post #{post.id}")- end- end- end-enddiff --git a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.jsindex 5044f171944..a5fea9fe1f2 100644--- a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js@@ -177,17 +177,88 @@* username (string): The username of the user performing the action.* Returns: { success: boolean, post_id: number }*+ * discourse.getCustomField(type, id, key): Reads a custom field value from a post, topic, or user.+ * Parameters:+ * type (string): The model type - "post", "topic", or "user".+ * id (number): The ID of the post, topic, or user.+ * key (string): The custom field key to read.+ * Returns: string | null (the custom field value, or null if not set)+ * Use case: Check if a post has already been processed by the tool.+ * Example:+ * const processed = discourse.getCustomField("post", context.post_id, "ai_processed");+ * if (processed) return { skipped: true };+ *+ * discourse.setCustomField(type, id, key, value): Sets a custom field value on a post, topic, or user.+ * Parameters:+ * type (string): The model type - "post", "topic", or "user".+ * id (number): The ID of the post, topic, or user.+ * key (string): The custom field key (max 256 characters).+ * value (string): The value to set (max 1024 characters).+ * Returns: { success: boolean, key: string, value: string }+ * Throws: Error if type is invalid, key/value too long, or model not found.+ * Use case: Mark a post as processed to prevent duplicate processing.+ * Example:+ * discourse.setCustomField("post", context.post_id, "ai_processed", Date.now().toString());+ ** 7. context* An object containing information about the environment where the tool is being run.- * Available properties depend on the invocation context, but may include:- * post_id (number): ID of the post triggering the tool (if in a Post context).- * topic_id (number): ID of the topic (if in a Post context).- * private_message (boolean): Whether the context is a private message (in Post context).- * message_id (number): ID of the chat message triggering the tool (if in Chat context).- * channel_id (number): ID of the chat channel (if in Chat context).- * user (Object): Details of the user invoking the tool/persona (structure may vary, often null or SystemUser details unless explicitly passed).- * participants (string): Comma-separated list of usernames in a PM (if applicable).- * // ... other potential context-specific properties added by the calling environment.+ * Tools can be invoked from multiple contexts - understanding where your tool is running+ * helps you access the right data and take appropriate actions.+ *+ * Invocation Contexts:+ *+ * A) AI Bot Conversation (Post context):+ * When a user mentions an AI persona in a topic or PM, tools run with:+ * context.post_id (number): The post that triggered the persona.+ * context.topic_id (number): The topic containing the post.+ * context.private_message (boolean): Whether this is a PM.+ * context.participants (string): Comma-separated usernames (in PMs).+ * context.username (string): The user who triggered the tool.+ * context.user_id (number): The user's ID.+ *+ * B) Chat Context:+ * When a user mentions an AI persona in a chat channel:+ * context.message_id (number): The chat message that triggered the tool.+ * context.channel_id (number): The chat channel ID.+ * context.username (string): The user who sent the message.+ *+ * C) Automation Context (ai_tool_action):+ * When a tool runs via Discourse Automation (e.g., on post_created_edited trigger):+ * context.post_id (number): The post that triggered the automation.+ * context.topic_id (number): The topic containing the post.+ * context.username (string): The post author's username.+ * context.user_id (number): The post author's ID.+ * context.feature_name (string): "ai_tool_action" - identifies automation context.+ * context.feature_context (Object): { automation_id, automation_name } - the automation details.+ *+ * Common Properties (available in most contexts):+ * context.site_url (string): The base URL of the Discourse site.+ * context.site_title (string): The site's title.+ * context.site_description (string): The site's description.+ *+ * Accessing Full Data:+ * The context provides IDs - use the discourse API to fetch full objects:+ * const post = discourse.getPost(context.post_id); // Full post with raw content+ * const topic = discourse.getTopic(context.topic_id); // Full topic with tags, category+ * const user = discourse.getUser(context.username); // Full user profile+ *+ * Example - Automation Tool Pattern:+ * function invoke(params) {+ * // Skip if not first post or already processed+ * const post = discourse.getPost(context.post_id);+ * if (post.post_number !== 1) return { skipped: "not first post" };+ *+ * const processed = discourse.getCustomField("post", context.post_id, "ai_processed");+ * if (processed) return { skipped: "already processed" };+ *+ * // Do work (e.g., auto-tag, summarize, moderate)+ * const topic = discourse.getTopic(context.topic_id);+ * // ... your logic here ...+ *+ * // Mark as processed to prevent re-running+ * discourse.setCustomField("post", context.post_id, "ai_processed", Date.now().toString());+ * return { success: true };+ * }** Constraints*diff --git a/plugins/discourse-ai/lib/automation.rb b/plugins/discourse-ai/lib/automation.rbindex 08c2a80ddec..70935fcc33b 100644--- a/plugins/discourse-ai/lib/automation.rb+++ b/plugins/discourse-ai/lib/automation.rb@@ -30,11 +30,20 @@ module DiscourseAienddef self.available_custom_tools- AiTool- .where(enabled: true)- .where("parameters = '[]'::jsonb")- .pluck(:id, :name, :description)- .map { |id, name, description| { id: id, translated_name: name, description: description } }+ available_tools(+ scope: AiTool.where(enabled: true).where("parameters = '[]'::jsonb"),+ description_field: :description,+ )+ end++ def self.available_tools_all+ available_tools(description_field: :summary)+ end++ def self.available_tools(scope: AiTool.where(enabled: true), description_field: :description)+ scope+ .pluck(:id, :name, description_field)+ .map { |id, name, desc| { id: id, translated_name: name, description: desc } }enddef self.available_modelsdiff --git a/plugins/discourse-ai/lib/automation/ai_tool_action.rb b/plugins/discourse-ai/lib/automation/ai_tool_action.rbnew file mode 100644index 00000000000..73ef56821ac--- /dev/null+++ b/plugins/discourse-ai/lib/automation/ai_tool_action.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++module DiscourseAi+ module Automation+ module AiToolAction+ def self.handle(post:, tool_id:, llm_model_id: nil, automation: nil)+ tool = ::AiTool.find_by(id: tool_id, enabled: true)+ return if !tool++ llm =+ LlmModel.find_by(id: llm_model_id)&.then { |m| DiscourseAi::Completions::Llm.proxy(m) }+ context =+ DiscourseAi::Personas::BotContext.new(+ post: post,+ feature_name: "ai_tool_action",+ feature_context: {+ automation_id: automation&.id,+ automation_name: automation&.name,+ },+ )++ runner = tool.runner({}, llm: llm, bot_user: Discourse.system_user, context: context)+ runner.invoke+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/automation/llm_tool_triage.rb b/plugins/discourse-ai/lib/automation/llm_tool_triage.rbdeleted file mode 100644index e8206da401b..00000000000--- a/plugins/discourse-ai/lib/automation/llm_tool_triage.rb+++ /dev/null@@ -1,17 +0,0 @@-# frozen_string_literal: true-module DiscourseAi- module Automation- module LlmToolTriage- def self.handle(post:, tool_id:, automation: nil)- tool = AiTool.find_by(id: tool_id)- return if !tool- return if tool.parameters.present?-- context = DiscourseAi::Personas::BotContext.new(post: post)-- runner = tool.runner({}, llm: nil, bot_user: Discourse.system_user, context: context)- runner.invoke- end- end- end-enddiff --git a/plugins/discourse-ai/lib/personas/tool_runner.rb b/plugins/discourse-ai/lib/personas/tool_runner.rbindex aa3b4fe4ab7..787d1b728d1 100644--- a/plugins/discourse-ai/lib/personas/tool_runner.rb+++ b/plugins/discourse-ai/lib/personas/tool_runner.rb@@ -16,6 +16,11 @@ module DiscourseAiMAX_SLEEP_CALLS = 30MAX_SLEEP_DURATION_MS = 60_000+ MAX_CUSTOM_FIELD_KEY_LENGTH = 256+ MAX_CUSTOM_FIELD_VALUE_LENGTH = 1024++ CUSTOM_FIELD_MODELS = { "post" => Post, "topic" => Topic, "user" => User }.freeze+def initialize(parameters:, llm:, bot_user:, context: nil, tool:, timeout: nil)if context && !context.is_a?(DiscourseAi::Personas::BotContext)raise ArgumentError, "context must be a BotContext object"@@ -207,6 +212,16 @@ module DiscourseAisetTags: function(topic_id, tags, options) {return this.editTopic(topic_id, { tags: tags }, options);},+ getCustomField: function(type, id, key) {+ return _discourse_get_custom_field(type, id, key);+ },+ setCustomField: function(type, id, key, value) {+ const result = _discourse_set_custom_field(type, id, key, value);+ if (result.error) {+ throw new Error(result.error);+ }+ return result;+ },};const context = #{JSON.generate(@context.to_json)};@@ -918,11 +933,9 @@ module DiscourseAiendvisibility_reason =- if updates["visible"]- Topic.visibility_reasons[:manually_relisted]- else- Topic.visibility_reasons[:manually_unlisted]- end+ Topic.visibility_reasons[+ updates["visible"] ? :manually_relisted : :manually_unlisted+ ]topic.update_status("visible",@@ -942,6 +955,7 @@ module DiscourseAi)return { error: "Failed to apply tags", details: topic.errors.full_messages }end+ topic.first_post&.publish_change_to_clients!(:revised)end{@@ -959,6 +973,41 @@ module DiscourseAiendend,)++ mini_racer_context.attach(+ "_discourse_get_custom_field",+ ->(type, id, key) do+ in_attached_function do+ 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,+ )enddef attach_upload(mini_racer_context)@@ -1131,6 +1180,10 @@ module DiscourseAiendend+ def find_model_by_type(type, id)+ CUSTOM_FIELD_MODELS[type]&.find_by(id: id)+ end+def in_attached_functionself.running_attached_function = trueyielddiff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rbindex 25aa578fa21..14bbb99ffc0 100644--- a/plugins/discourse-ai/plugin.rb+++ b/plugins/discourse-ai/plugin.rb@@ -81,7 +81,7 @@ after_initialize do# do not autoload this cause we may have no namespacerequire_relative "discourse_automation/llm_triage"require_relative "discourse_automation/llm_report"- require_relative "discourse_automation/llm_tool_triage"+ require_relative "discourse_automation/ai_tool_action"require_relative "discourse_automation/llm_persona_triage"require_relative "discourse_automation/llm_tagger"diff --git a/plugins/discourse-ai/spec/lib/discourse_automation/ai_tool_action_spec.rb b/plugins/discourse-ai/spec/lib/discourse_automation/ai_tool_action_spec.rbnew file mode 100644index 00000000000..323a9440bca--- /dev/null+++ b/plugins/discourse-ai/spec/lib/discourse_automation/ai_tool_action_spec.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Automation::AiToolAction do+ fab!(:user)+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:post) { Fabricate(:post, topic: topic, user: user, raw: "Test post content") }+ fab!(:llm_model)++ fab!(:context_tool) do+ AiTool.create!(+ name: "Context Reader",+ tool_name: "context_reader",+ description: "Reads data from context",+ parameters: [],+ script: <<~JS,+ function invoke(params) {+ const post = discourse.getPost(context.post_id);+ return {+ post_id: context.post_id,+ raw: post.raw,+ username: context.username+ };+ }+ JS+ created_by_id: Discourse.system_user.id,+ summary: "Reads context",+ enabled: true,+ )+ end++ before do+ SiteSetting.ai_bot_enabled = true+ SiteSetting.discourse_ai_enabled = true+ end++ it "executes tool that reads from context" do+ result = described_class.handle(post: post, tool_id: context_tool.id)+ expect(result["post_id"]).to eq(post.id)+ expect(result["raw"]).to eq("Test post content")+ expect(result["username"]).to eq(user.username)+ end++ it "skips disabled tools" do+ context_tool.update!(enabled: false)+ result = described_class.handle(post: post, tool_id: context_tool.id)+ expect(result).to be_nil+ end++ it "skips non-existent tools" do+ result = described_class.handle(post: post, tool_id: -999)+ expect(result).to be_nil+ end++ context "with LLM configured" do+ fab!(:llm_tool) do+ AiTool.create!(+ name: "LLM Tool",+ tool_name: "llm_tool",+ description: "Uses LLM to generate",+ parameters: [],+ script: <<~JS,+ function invoke(params) {+ const result = llm.truncate("test string", 5);+ return { truncated: result };+ }+ JS+ created_by_id: Discourse.system_user.id,+ summary: "Uses LLM",+ enabled: true,+ )+ end++ it "passes LLM when specified" do+ result = described_class.handle(post: post, tool_id: llm_tool.id, llm_model_id: llm_model.id)+ expect(result["truncated"]).to be_present+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/discourse_automation/llm_tool_triage_spec.rb b/plugins/discourse-ai/spec/lib/discourse_automation/llm_tool_triage_spec.rbdeleted file mode 100644index f7981ab33b5..00000000000--- a/plugins/discourse-ai/spec/lib/discourse_automation/llm_tool_triage_spec.rb+++ /dev/null@@ -1,111 +0,0 @@-# frozen_string_literal: true--RSpec.describe DiscourseAi::Automation::LlmToolTriage do- fab!(:solver, :user)- fab!(:new_user) { Fabricate(:user, trust_level: TrustLevel[0], created_at: 1.day.ago) }- fab!(:topic) { Fabricate(:topic, user: new_user) }- fab!(:post) { Fabricate(:post, topic: topic, user: new_user, raw: "How do I reset my password?") }- fab!(:llm_model)- fab!(:ai_persona) do- persona = Fabricate(:ai_persona, default_llm: llm_model)- persona.create_user- persona- end-- fab!(:tool) do- tool_script = <<~JS- function invoke(params) {- const postId = context.post_id;- const post = discourse.getPost(postId);- const user = discourse.getUser(post.user_id);-- if (user.trust_level > 0) {- return {- processed: false,- reason: "User is not new"- };- }-- const helper = discourse.getPersona("#{ai_persona.name}");- const answer = helper.respondTo({ post_id: post.id });-- return {- answer: answer,- processed: true,- reason: "answered question"- };- }- JS-- AiTool.create!(- name: "New User Question Answerer",- tool_name: "new_user_question_answerer",- description: "Automatically answers questions from new users when possible",- parameters: [], # No parameters as required by llm_tool_triage- script: tool_script,- created_by_id: Discourse.system_user.id,- summary: "Answers new user questions",- enabled: true,- )- end-- before do- enable_current_plugin- SiteSetting.ai_bot_enabled = true- end-- it "It is able to answer new user questions" do- result = nil- DiscourseAi::Completions::Llm.with_prepared_responses(- ["this is how you reset your password"],- ) { result = described_class.handle(post: post, tool_id: tool.id) }- expect(result["processed"]).to eq(true)- response = post.topic.reload.posts.order(:post_number).last- expect(response.raw).to eq("this is how you reset your password")- end-- it "Is able to respond as a whisper if instructed" do- # Create a tool with a script that explicitly requests a whisper response- whisper_tool =- AiTool.create!(- name: "Whisper Triage Tool",- tool_name: "whisper_triage_tool",- description: "Responds with whispers to moderation issues",- parameters: [],- script: <<~JS,- function invoke(params) {- const postId = context.post_id;- const post = discourse.getPost(postId);-- const helper = discourse.getPersona("#{ai_persona.name}");- // Pass instructions to make response a whisper- const answer = helper.respondTo({- post_id: post.id,- instructions: "Respond as a whisper for moderators only",- whisper: true- });-- return {- answer: answer,- processed: true,- reason: "responded with whisper"- };- }- JS- created_by_id: Discourse.system_user.id,- summary: "Responds with whispers",- enabled: true,- )-- result = nil- DiscourseAi::Completions::Llm.with_prepared_responses(- ["This moderation note is only visible to staff"],- ) { result = described_class.handle(post: post, tool_id: whisper_tool.id) }-- expect(result["processed"]).to eq(true)- response = post.topic.reload.posts.order(:post_number).last- expect(response.raw).to eq("This moderation note is only visible to staff")- # Check that the response is indeed a whisper- expect(response.post_type).to eq(Post.types[:whisper])- end-enddiff --git a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rbindex 8f542581fc6..7a959cf4152 100644--- a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb+++ b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb@@ -126,6 +126,34 @@ RSpec.describe DiscourseAi::Personas::ToolRunner doexpect(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" dopost = Fabricate(:post)tool.update!(@@ -464,5 +492,142 @@ RSpec.describe DiscourseAi::Personas::ToolRunner doexpect(result["success"]).to eq(true)expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")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" 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 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+ endendend