Skip to content

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

FEATURE: Add category definition filters and AI filterTopics binding (#39478)

Samadbb23fb011e
diff --git a/plugins/discourse-ai/lib/agents/tool_runner.rb b/plugins/discourse-ai/lib/agents/tool_runner.rb
index 9a3fb1c2be8..97fd870390b 100644
--- a/plugins/discourse-ai/lib/agents/tool_runner.rb
+++ b/plugins/discourse-ai/lib/agents/tool_runner.rb
@@ -219,6 +219,13 @@ module DiscourseAi
},
getPost: _discourse_get_post,
getTopic: _discourse_get_topic,
+ filterTopics: function(params) {
+ const result = _discourse_filter_topics(params || {});
+ if (result.error) {
+ throw new Error(result.error);
+ }
+ return result;
+ },
getUser: _discourse_get_user,
getAgent: function(name) {
const agentDetails = _discourse_get_agent(name);
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb b/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
index c758c914b67..19893066ddd 100644
--- a/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
+++ b/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
@@ -12,11 +12,12 @@ module DiscourseAi
# 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.
+ # 1. Read bindings (`getPost`, `getTopic`, `getUser`, `getAgent`) serialize
+ # with `system_guardian` and can return staff-visible data including PMs
+ # and staff-only fields (emails, IPs). `search` and `filterTopics`
+ # default to public visibility and only elevate when `with_private: true`
+ # is passed. Existing tools rely on these contracts — don't tighten or
+ # widen without a corresponding preamble doc change and migration plan.
#
# 2. `resolve_guardian` elevates staged users to `system_guardian`. This
# supports a seeding pattern exercised by the "can seed a category
@@ -62,16 +63,41 @@ module DiscourseAi
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
+ serialize_topic_for_tool(topic, scope: system_guardian)
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_filter_topics",
+ ->(params) do
+ in_attached_function do
+ return { error: "params must be an object" } if !params.respond_to?(:symbolize_keys)
+
+ params = (params || {}).symbolize_keys
+ query = params[:q].to_s
+ return { error: "Missing required parameter: q" } if query.blank?
+
+ page = params[:page].to_i
+ return { error: "page must be greater than or equal to 0" } if page.negative?
+
+ with_private = ActiveModel::Type::Boolean.new.cast(params[:with_private])
+ guardian = with_private ? system_guardian : Guardian.new
+
+ query_options = { guardian: guardian, q: query, page: page }
+ query_options[:per_page] = params[:limit].to_i if params.key?(:limit)
+
+ topic_list = TopicQuery.new(nil, **query_options).list_filter
+
+ {
+ query: query,
+ page: page,
+ limit: topic_list.per_page,
+ topics:
+ topic_list.topics.map do |topic|
+ serialize_topic_for_tool(topic, scope: guardian)
+ end,
+ }
end
end,
)
@@ -613,6 +639,19 @@ module DiscourseAi
end
end
+ def serialize_topic_for_tool(topic, scope:)
+ data = recursive_as_json(ListableTopicSerializer.new(topic, scope: scope, root: false))
+ data["url"] = topic.relative_url
+ data["tags"] = topic.tags.map(&: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["views"] = topic.views
+ data["like_count"] = topic.like_count
+ data
+ end
+
def find_model_by_type(type, id)
CUSTOM_FIELD_MODELS[type]&.find_by(id: id)
end
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
index b2ea02a3e1c..4c1b8146f94 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
@@ -150,12 +150,15 @@
* 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
+ * - Read ops (`getPost`, `getTopic`, `getUser`, `getAgent`) 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.
*
+ * - `search` and `filterTopics` default to public visibility. Pass
+ * `with_private: true` to elevate them to the SystemUser scope.
+ *
* - 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,
@@ -183,9 +186,24 @@
* discourse.search(params): Performs a Discourse search.
* Parameters:
* params (Object): Search parameters (e.g., { search_query: "keyword", with_private: true, max_results: 10 }).
- * `with_private: true` searches across all posts visible to the SystemUser. `result_style: 'detailed'` is used by default.
+ * By default this searches public content. `with_private: true` searches across all posts visible to the
+ * SystemUser. `result_style: 'detailed'` is used by default.
* Returns: Object (Discourse search results structure, includes posts, topics, users etc.)
*
+ * discourse.filterTopics(params): Filters topics using Discourse topic filter syntax.
+ * Parameters:
+ * params (Object): { q: string, limit?: number, page?: number, with_private?: boolean }
+ * `q` uses Discourse topic filter syntax (for example: "category:support order:created").
+ * By default this only returns topics visible publicly. Pass `with_private: true` to elevate to the
+ * SystemUser scope.
+ * Returns: Object { query, page, limit, topics }
+ * query (string): The filter query that was executed.
+ * page (number): The page number used.
+ * limit (number): The effective per-page limit used.
+ * topics (Array<Object>): Topic summaries — same shape as `getTopic` (ListableTopicSerializer plus
+ * `url`, `tags`, `first_post_id`, `category_id`, `category_name`,
+ * `category_slug`, `views`, `like_count`).
+ *
* discourse.getPost(post_id): Retrieves details for a specific post.
* Parameters:
* post_id (number): The ID of the post.
@@ -194,8 +212,9 @@
* discourse.getTopic(topic_id): Retrieves details for a specific topic.
* Parameters:
* topic_id (number): The ID of the topic.
- * Returns: Object (Topic details using ListableTopicSerializer structure, plus `tags`, `first_post_id`,
- * `category_id`, `category_name`, `category_slug`) or null if not found/accessible.
+ * Returns: Object (Topic details using ListableTopicSerializer structure, plus `url`, `tags`,
+ * `first_post_id`, `category_id`, `category_name`, `category_slug`, `views`, `like_count`)
+ * or null if not found/accessible.
*
* discourse.getUser(user_id_or_username): Retrieves details for a specific user.
* Parameters:
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
index 775fe06331d..87d6c1d3015 100644
--- a/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb
@@ -114,6 +114,106 @@ RSpec.describe DiscourseAi::Agents::ToolRunner do
end
end
+ context "when using the topic filter API" do
+ it "filters topics matching the query and returns serialized fields" do
+ matching_topic =
+ Fabricate(:topic, category: category, title: "NDA checklist guidance topic")
+ matching_post = Fabricate(:post, topic: matching_topic, raw: "NDA checklist details")
+ matching_topic.tags << tag1
+ other_matching_topic =
+ Fabricate(:topic, category: category, title: "How to review a contract safely")
+ other_matching_post =
+ Fabricate(:post, topic: other_matching_topic, raw: "Contract review details")
+ Fabricate(:topic, title: "Outside category knowledge topic")
+
+ script = <<~JS
+ function invoke(params) {
+ return discourse.filterTopics({
+ q: "category:" + params.category,
+ limit: params.limit
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner({ "category" => category.slug, "limit" => 10 }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+ topics = result["topics"]
+
+ expect(result["query"]).to eq("category:#{category.slug}")
+ expect(result["limit"]).to eq(10)
+ expect(topics.map { |topic| topic["id"] }).to contain_exactly(
+ matching_topic.id,
+ other_matching_topic.id,
+ )
+ expect(topics.map { |topic| topic["category_slug"] }.uniq).to eq([category.slug])
+ expect(topics.map { |topic| topic["first_post_id"] }).to contain_exactly(
+ matching_post.id,
+ other_matching_post.id,
+ )
+ expect(topics.find { |topic| topic["id"] == matching_topic.id }["tags"]).to contain_exactly(
+ tag1.name,
+ )
+ end
+
+ it "respects the limit parameter" do
+ 3.times do |i|
+ Fabricate(:topic, category: category, title: "Legal knowledge topic number #{i}")
+ end
+
+ script = <<~JS
+ function invoke(params) {
+ return discourse.filterTopics({ q: params.q, limit: params.limit });
+ }
+ JS
+
+ tool = create_tool(script: script)
+ runner =
+ tool.runner({ "q" => "category:#{category.slug}", "limit" => 2 }, llm: nil, bot_user: nil)
+
+ result = runner.invoke
+
+ expect(result["topics"].size).to eq(2)
+ end
+
+ it "requires with_private to include private categories" do
+ private_category =
+ Fabricate(
+ :private_category,
+ group: Fabricate(:group),
+ slug: "private-legal-kb",
+ name: "Private Legal KB",
+ )
+ private_topic =
+ Fabricate(:topic, category: private_category, title: "Private legal playbook topic")
+
+ script = <<~JS
+ function invoke(params) {
+ return discourse.filterTopics({
+ q: "category:" + params.category,
+ with_private: params.with_private
+ });
+ }
+ JS
+
+ tool = create_tool(script: script)
+
+ public_result =
+ tool.runner({ "category" => private_category.slug }, llm: nil, bot_user: nil).invoke
+ private_result =
+ tool.runner(
+ { "category" => private_category.slug, "with_private" => true },
+ llm: nil,
+ bot_user: nil,
+ ).invoke
+
+ expect(public_result["topics"]).to eq([])
+ expect(private_result["topics"].map { |topic| topic["id"] }).to eq([private_topic.id])
+ end
+ end
+
context "when using the post API" do
it "can fetch post details" do
script = <<~JS