Skip to content

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

FEATURE: add customSystemMessage hook and index.getFile API for AI tools (#38229)

Sam70ce4579e786
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
index f9f83585360..403a0ebed30 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
@@ -22,6 +22,21 @@
* return `Browsed: <a href="${lastUrl}">${lastUrl}</a>`;
* }
*
+ * customSystemMessage(): Optional function. Called during prompt assembly (not during tool invocation).
+ * Runs each time a prompt is built, before the LLM sees any messages.
+ * Returns a string that is appended to the system prompt, or null/undefined to skip.
+ * Use this to inject persistent instructions into the AI's system prompt based on state
+ * (e.g., active skills stored via discourse.setCustomField).
+ * Has access to `context`, `discourse`, and `index` objects.
+ * Example:
+ * function customSystemMessage() {
+ * if (!context || !context.topic_id) return null;
+ * var skill = discourse.getCustomField("topic", context.topic_id, "active_skill");
+ * if (!skill) return null;
+ * var content = index.getFile(skill + ".md");
+ * return content ? "## Active Skill\n\n" + content : null;
+ * }
+ *
* Provided Objects & Functions
*
* 1. http
@@ -74,6 +89,12 @@
* limit (number): Maximum number of fragments to return (default: 10, max: 200).
* Returns: Array<{ fragment: string, metadata: string | null }> - Ordered by relevance.
*
+ * index.getFile(filename): Retrieves the full content of an uploaded RAG file by its exact filename.
+ * Parameters:
+ * filename (string): The original filename of the uploaded file (e.g., "my_skill.md").
+ * Returns: string (all fragments joined in order) or null if file not found.
+ * Use case: When you need the complete, ordered content of a file rather than semantic search fragments.
+ *
* 4. upload
* Handles file uploads within Discourse.
*
diff --git a/plugins/discourse-ai/lib/personas/tool_runner.rb b/plugins/discourse-ai/lib/personas/tool_runner.rb
index 4aca2e979ce..a5de365322a 100644
--- a/plugins/discourse-ai/lib/personas/tool_runner.rb
+++ b/plugins/discourse-ai/lib/personas/tool_runner.rb
@@ -129,6 +129,7 @@ module DiscourseAi
const index = {
search: _index_search,
+ getFile: _index_get_file,
}
const upload = {
@@ -334,6 +335,30 @@ module DiscourseAi
nil
end
+ def has_custom_system_message?
+ mini_racer_context.eval(tool.script)
+ mini_racer_context.eval("typeof customSystemMessage === 'function'")
+ rescue StandardError
+ false
+ end
+
+ def custom_system_message
+ mini_racer_context.eval(tool.script)
+ result = eval_with_timeout("customSystemMessage()")
+ return result if result.is_a?(String)
+ if result.present?
+ Rails.logger.warn(
+ "customSystemMessage for tool #{tool.id} (#{tool.name}) returned #{result.class}, expected String",
+ )
+ end
+ nil
+ rescue StandardError => e
+ Rails.logger.warn(
+ "customSystemMessage failed for tool #{tool.id} (#{tool.name}): #{e.class} - #{e.message}",
+ )
+ nil
+ end
+
private
def preload_secrets(bindings)
@@ -350,6 +375,7 @@ module DiscourseAi
end
MAX_FRAGMENTS = 200
+ MAX_GET_FILE_CHARS = 500_000
def rag_search(query, filenames: nil, limit: 10)
limit = limit.to_i
@@ -394,6 +420,35 @@ module DiscourseAi
fragment_ids.take(limit).map { |fragment_id| mapped[fragment_id] }
end
+ def rag_get_file(filename)
+ return nil if filename.blank?
+
+ upload_refs =
+ UploadReference.where(target_id: tool.id, target_type: "AiTool").pluck(:upload_id)
+ upload_id =
+ Upload.where(id: upload_refs, original_filename: filename).order(id: :desc).pick(:id)
+ return nil if upload_id.nil?
+
+ fragments =
+ RagDocumentFragment
+ .where(target_id: tool.id, target_type: "AiTool", upload_id: upload_id)
+ .order(:fragment_number)
+ .pluck(:fragment)
+
+ return nil if fragments.empty?
+
+ result = +""
+ fragments.each do |fragment|
+ if result.length + fragment.length + 1 > MAX_GET_FILE_CHARS
+ result << "\n[truncated]"
+ break
+ end
+ result << "\n" unless result.empty?
+ result << fragment
+ end
+ result
+ end
+
def attach_truncate(mini_racer_context)
mini_racer_context.attach(
"_llm_truncate",
@@ -471,6 +526,11 @@ module DiscourseAi
end
end,
)
+
+ mini_racer_context.attach(
+ "_index_get_file",
+ ->(filename) { in_attached_function { rag_get_file(filename) } },
+ )
end
def attach_chain(mini_racer_context)
diff --git a/plugins/discourse-ai/lib/personas/tools/custom.rb b/plugins/discourse-ai/lib/personas/tools/custom.rb
index a11bbc2b9c2..c1fa27cac1f 100644
--- a/plugins/discourse-ai/lib/personas/tools/custom.rb
+++ b/plugins/discourse-ai/lib/personas/tools/custom.rb
@@ -47,15 +47,44 @@ module DiscourseAi
@has_custom_context
end
+ def self.has_custom_system_message?
+ # cached safely - persona cache is bumped when an ai tool is saved, expiring this class
+ return @has_custom_system_message if defined?(@has_custom_system_message)
+
+ @has_custom_system_message = false
+ ai_tool = AiTool.find_by(id: tool_id)
+ if ai_tool&.script&.include?("customSystemMessage")
+ runner = ai_tool.runner({}, llm: nil, bot_user: nil, context: nil)
+ @has_custom_system_message = runner.has_custom_system_message?
+ end
+
+ @has_custom_system_message
+ end
+
def self.inject_prompt(prompt:, context:, persona:)
- if has_custom_context?
- ai_tool = AiTool.find_by(id: tool_id)
- if ai_tool
- runner = ai_tool.runner({}, llm: nil, bot_user: nil, context: context)
- custom_context = runner.custom_context
- if custom_context.present?
- last_message = prompt.messages.last
- last_message[:content] = "#{custom_context}\n\n#{last_message[:content]}"
+ needs_context = has_custom_context?
+ needs_system_message = has_custom_system_message?
+ return unless needs_context || needs_system_message
+
+ ai_tool = AiTool.find_by(id: tool_id)
+ return unless ai_tool
+
+ runner = ai_tool.runner({}, llm: nil, bot_user: nil, context: context)
+
+ if needs_context
+ custom_context = runner.custom_context
+ if custom_context.present?
+ last_message = prompt.messages.last
+ last_message[:content] = "#{custom_context}\n\n#{last_message[:content]}"
+ end
+ end
+
+ if needs_system_message
+ system_msg = runner.custom_system_message
+ if system_msg.is_a?(String) && system_msg.present?
+ system_message = prompt.messages.first
+ if system_message && system_message[:type] == :system
+ system_message[:content] = "#{system_message[:content]}\n#{system_msg}"
end
end
end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
index 88dc0ab5763..a1f2f5a0081 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
@@ -1332,6 +1332,96 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
end
+ describe "custom tool system message injection" do
+ let!(:custom_tool) do
+ AiTool.create!(
+ name: "system_msg_tool",
+ tool_name: "system_msg_tool",
+ summary: "tool with custom system message",
+ description: "A test custom tool that injects into system prompt",
+ parameters: [{ name: "query", type: "string", description: "Input" }],
+ script: <<~JS,
+ function invoke(params) {
+ return 'Tool result: ' + params.query;
+ }
+
+ function customSystemMessage() {
+ return "You must always respond in haiku format.";
+ }
+ JS
+ created_by: user,
+ )
+ end
+
+ let!(:ai_persona) { Fabricate(:ai_persona, tools: ["custom-#{custom_tool.id}"]) }
+ let(:bot) { DiscourseAi::Personas::Bot.as(bot_user, persona: ai_persona.class_instance.new) }
+ let(:playground) { DiscourseAi::AiBot::Playground.new(bot) }
+
+ it "injects custom system message into the system prompt" do
+ prompts = nil
+ response = "I received the system instructions"
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([response]) do |_, _, _prompts|
+ new_post = Fabricate(:post, raw: "Hello bot")
+ playground.reply_to(new_post)
+ prompts = _prompts
+ end
+
+ system_message = prompts[0].messages.first
+ expect(system_message[:type]).to eq(:system)
+ expect(system_message[:content]).to include("You must always respond in haiku format.")
+ end
+ end
+
+ describe "custom tool with both context and system message hooks" do
+ let!(:custom_tool) do
+ AiTool.create!(
+ name: "dual_hook_tool",
+ tool_name: "dual_hook_tool",
+ summary: "tool with both hooks",
+ description: "A test custom tool with both customContext and customSystemMessage",
+ parameters: [{ name: "query", type: "string", description: "Input" }],
+ script: <<~JS,
+ function invoke(params) {
+ return 'result';
+ }
+
+ function customContext() {
+ return "Context from the tool";
+ }
+
+ function customSystemMessage() {
+ return "System instructions from the tool";
+ }
+ JS
+ created_by: user,
+ )
+ end
+
+ let!(:ai_persona) { Fabricate(:ai_persona, tools: ["custom-#{custom_tool.id}"]) }
+ let(:bot) { DiscourseAi::Personas::Bot.as(bot_user, persona: ai_persona.class_instance.new) }
+ let(:playground) { DiscourseAi::AiBot::Playground.new(bot) }
+
+ it "injects both hooks into the correct prompt locations" do
+ prompts = nil
+ response = "I received both injections"
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([response]) do |_, _, _prompts|
+ new_post = Fabricate(:post, raw: "Hello bot")
+ playground.reply_to(new_post)
+ prompts = _prompts
+ end
+
+ system_message = prompts[0].messages.first
+ expect(system_message[:type]).to eq(:system)
+ expect(system_message[:content]).to include("System instructions from the tool")
+
+ user_message = prompts[0].messages.last
+ expect(user_message[:content]).to include("Context from the tool")
+ expect(user_message[:content]).to include("Hello bot")
+ end
+ end
+
it "does not raise 'can't modify frozen attributes' when retrying a reply with thinking" do
thinking_progress =
DiscourseAi::Completions::Thinking.new(message: "I should say hello", partial: true)
diff --git a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
index a2c2050b606..c99e5214e33 100644
--- a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
+++ b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
@@ -813,4 +813,150 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
end
end
end
+
+ describe "#has_custom_system_message?" do
+ it "returns true when script defines customSystemMessage function" do
+ tool.update!(script: <<~JS)
+ function invoke(params) { return {}; }
+ function customSystemMessage() { return "extra system instructions"; }
+ JS
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ expect(runner.has_custom_system_message?).to eq(true)
+ end
+
+ it "returns false when script does not define customSystemMessage" do
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ expect(runner.has_custom_system_message?).to eq(false)
+ end
+ end
+
+ describe "#custom_system_message" do
+ it "returns the string from customSystemMessage()" do
+ tool.update!(script: <<~JS)
+ function invoke(params) { return {}; }
+ function customSystemMessage() { return "You are a coding assistant"; }
+ JS
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ expect(runner.custom_system_message).to eq("You are a coding assistant")
+ end
+
+ it "returns nil when customSystemMessage returns null" do
+ tool.update!(script: <<~JS)
+ function invoke(params) { return {}; }
+ function customSystemMessage() { return null; }
+ JS
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ expect(runner.custom_system_message).to be_nil
+ end
+
+ it "returns nil when script errors" do
+ tool.update!(script: <<~JS)
+ function invoke(params) { return {}; }
+ function customSystemMessage() { throw new Error("oops"); }
+ JS
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ 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