Skip to content

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

FEATURE: add credential bindings for AI tools (#37891)

Sam10d109e4c816
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjs
index 30d6d400a2e..6ba9d4cdae0 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjs
@@ -73,6 +73,14 @@ export default class AiSecretsListEditor extends Component {
{{usage.name}}
</LinkTo>
({{i18n "discourse_ai.secrets.embedding"}})
+ {{else if (eq usage.type "tool")}}
+ <LinkTo
+ @route="adminPlugins.show.discourse-ai-tools.edit"
+ @model={{usage.id}}
+ >
+ {{usage.name}}
+ </LinkTo>
+ ({{i18n "discourse_ai.secrets.tool"}})
{{else}}
<LinkTo
@route="adminPlugins.show.discourse-ai-llms.edit"
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjs
index dc2422f2141..c34434a2baa 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjs
@@ -11,6 +11,7 @@ import DButton from "discourse/components/d-button";
import DPageSubheader from "discourse/components/d-page-subheader";
import DropdownMenu from "discourse/components/dropdown-menu";
import DMenu from "discourse/float-kit/components/d-menu";
+import icon from "discourse/helpers/d-icon";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
@@ -84,6 +85,23 @@ export default class AiToolListEditor extends Component {
);
}
+ credentialStatus(tool) {
+ const contracts = tool.secret_contracts || [];
+ if (contracts.length === 0) {
+ return [];
+ }
+
+ const bindings = tool.secret_bindings || [];
+ const boundAliases = new Set(
+ bindings.filter((b) => b.alias && b.ai_secret_id).map((b) => b.alias)
+ );
+
+ return contracts.map((contract) => ({
+ alias: contract.alias,
+ bound: boundAliases.has(contract.alias),
+ }));
+ }
+
@action
importTool() {
// Create a hidden file input and click it
@@ -273,6 +291,32 @@ export default class AiToolListEditor extends Component {
<div class="ai-tool-list__description">
{{tool.description}}
</div>
+ {{#if tool.secret_contracts.length}}
+ <div class="ai-tool-list__credentials">
+ {{#each (this.credentialStatus tool) as |cred|}}
+ <span
+ class="ai-tool-list__credential-badge
+ {{if
+ cred.bound
+ 'ai-tool-list__credential-badge--bound'
+ 'ai-tool-list__credential-badge--missing'
+ }}"
+ >
+ {{#if cred.bound}}
+ {{icon "check"}}
+ {{else}}
+ {{icon "triangle-exclamation"}}
+ {{/if}}
+ {{cred.alias}}
+ {{#unless cred.bound}}
+ <span class="ai-tool-list__credential-not-set">
+ {{i18n "discourse_ai.tools.credential_not_set"}}
+ </span>
+ {{/unless}}
+ </span>
+ {{/each}}
+ </div>
+ {{/if}}
</div>
</td>
<td class="d-admin-row__controls">
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.js
index d2f503d69ff..e5ad4b29a93 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.js
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.js
@@ -15,6 +15,7 @@ export default class DiscourseAiToolsEditRoute extends DiscourseRoute {
controller.set("allTools", toolsModel);
controller.set("presets", toolsModel.resultSetMeta.presets);
controller.set("llms", toolsModel.resultSetMeta.llms);
+ controller.set("secrets", toolsModel.resultSetMeta.ai_secrets);
controller.set("settings", toolsModel.resultSetMeta.settings);
}
}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js
index e32b9e89f4d..2cb5177f9bc 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js
@@ -19,6 +19,7 @@ export default class DiscourseAiToolsNewRoute extends DiscourseRoute {
controller.set("allTools", toolsModel);
controller.set("presets", toolsModel.resultSetMeta.presets);
controller.set("llms", toolsModel.resultSetMeta.llms);
+ controller.set("secrets", toolsModel.resultSetMeta.ai_secrets);
controller.set("settings", toolsModel.resultSetMeta.settings);
controller.set("selectedPreset", this.preset);
}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/edit.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/edit.gjs
index 089ad99d9c3..152c21d72db 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/edit.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/edit.gjs
@@ -7,6 +7,7 @@ export default <template>
@model={{@controller.model}}
@presets={{@controller.presets}}
@llms={{@controller.llms}}
+ @secrets={{@controller.secrets}}
@settings={{@controller.settings}}
/>
</section>
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/new.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/new.gjs
index 8a31c505fe8..7c4cf2c761d 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/new.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/new.gjs
@@ -7,6 +7,7 @@ export default <template>
@model={{@controller.model}}
@presets={{@controller.presets}}
@llms={{@controller.llms}}
+ @secrets={{@controller.secrets}}
@settings={{@controller.settings}}
@selectedPreset={{@controller.selectedPreset}}
/>
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rb
index 1ad218fdabd..874ce3dd7c3 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rb
@@ -6,7 +6,11 @@ module DiscourseAi
requires_plugin PLUGIN_NAME
def index
- secrets = AiSecret.all.includes(:llm_models, :embedding_definitions).order(:name)
+ secrets =
+ AiSecret
+ .all
+ .includes(:llm_models, :embedding_definitions, ai_tool_secret_bindings: :ai_tool)
+ .order(:name)
render json: {
ai_secrets:
@@ -19,7 +23,12 @@ module DiscourseAi
end
def show
- secret = AiSecret.includes(:llm_models, :embedding_definitions).find(params[:id])
+ secret =
+ AiSecret.includes(
+ :llm_models,
+ :embedding_definitions,
+ ai_tool_secret_bindings: :ai_tool,
+ ).find(params[:id])
render json: AiSecretSerializer.new(secret, scope: { unmask: true })
end
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_tools_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_tools_controller.rb
index 4e2e5487122..72dcff4f415 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_tools_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_tools_controller.rb
@@ -8,7 +8,7 @@ module DiscourseAi
before_action :find_ai_tool, only: %i[test edit update destroy export]
def index
- ai_tools = AiTool.all
+ ai_tools = AiTool.includes(:secret_bindings)
render_serialized({ ai_tools: ai_tools }, AiCustomToolListSerializer, root: false)
end
@@ -23,7 +23,7 @@ module DiscourseAi
ai_tool = AiTool.new(ai_tool_params)
ai_tool.created_by_id = current_user.id
- if ai_tool.save
+ if save_tool_with_optional_bindings(ai_tool)
RagDocumentFragment.link_target_and_uploads(ai_tool, attached_upload_ids)
log_ai_tool_creation(ai_tool)
render_serialized(ai_tool, AiCustomToolSerializer, status: :created)
@@ -36,7 +36,13 @@ module DiscourseAi
response.headers[
"Content-Disposition"
] = "attachment; filename=\"#{@ai_tool.tool_name}.json\""
- render_serialized(@ai_tool, AiCustomToolSerializer)
+ render_serialized(
+ @ai_tool,
+ AiCustomToolSerializer,
+ scope: {
+ include_secret_bindings: false,
+ },
+ )
end
def import
@@ -52,7 +58,7 @@ module DiscourseAi
if existing_tool && force_update
initial_attributes = existing_tool.attributes.dup
- if existing_tool.update(ai_tool_params)
+ if update_tool_with_optional_bindings(existing_tool)
log_ai_tool_update(existing_tool, initial_attributes)
render_serialized(existing_tool, AiCustomToolSerializer)
else
@@ -62,7 +68,7 @@ module DiscourseAi
ai_tool = AiTool.new(ai_tool_params)
ai_tool.created_by_id = current_user.id
- if ai_tool.save
+ if save_tool_with_optional_bindings(ai_tool)
log_ai_tool_creation(ai_tool)
render_serialized(ai_tool, AiCustomToolSerializer, status: :created)
else
@@ -74,7 +80,7 @@ module DiscourseAi
def update
initial_attributes = @ai_tool.attributes.dup
- if @ai_tool.update(ai_tool_params)
+ if update_tool_with_optional_bindings(@ai_tool)
RagDocumentFragment.update_target_uploads(@ai_tool, attached_upload_ids)
log_ai_tool_update(@ai_tool, initial_attributes)
render_serialized(@ai_tool, AiCustomToolSerializer)
@@ -100,19 +106,30 @@ module DiscourseAi
end
def test
+ # Mutate the in-memory model with unsaved edits (script, parameters, contracts)
+ # so the test run reflects the form state without persisting anything.
@ai_tool.assign_attributes(ai_tool_params) if params[:ai_tool]
parameters = params[:parameters]&.to_unsafe_h || {}
+ test_bindings = secret_bindings_supplied? ? secret_bindings_params : nil
# we need an llm so we have a tokenizer
# but will do without if none is available
llm = LlmModel.first&.to_llm
- runner = @ai_tool.runner(parameters, llm: llm, bot_user: current_user)
+ runner =
+ @ai_tool.runner(
+ parameters,
+ llm: llm,
+ bot_user: current_user,
+ secret_bindings: test_bindings,
+ )
result = runner.invoke
if result.is_a?(Hash) && result[:error]
render_json_error result[:error]
else
- render json: { output: result }
+ response = { output: result }
+ response[:custom_raw] = runner.custom_raw if runner.custom_raw.present?
+ render json: response
end
rescue ActiveRecord::RecordNotFound => e
render_json_error e.message, status: 400
@@ -127,7 +144,7 @@ module DiscourseAi
end
def find_ai_tool
- @ai_tool = AiTool.find(params[:id].to_i)
+ @ai_tool = AiTool.includes(:secret_bindings).find(params[:id].to_i)
end
def ai_tool_params
@@ -144,6 +161,7 @@ module DiscourseAi
:rag_llm_model_id,
rag_uploads: [:id],
parameters: [:name, :type, :description, :required, enum: []],
+ secret_contracts: [:alias],
)
.except(:rag_uploads)
end
@@ -172,9 +190,74 @@ module DiscourseAi
parameters: {
type: :large_text,
},
+ secret_contracts: {
+ type: :large_text,
+ },
}
end
+ def save_tool_with_optional_bindings(ai_tool)
+ AiTool.transaction do
+ ai_tool.save!
+ apply_secret_bindings!(ai_tool) if secret_bindings_supplied?
+ end
+ true
+ rescue ActiveRecord::RecordInvalid => e
+ collect_tool_errors(ai_tool, e.record)
+ false
+ rescue ArgumentError => e
+ ai_tool.errors.add(:base, e.message)
+ false
+ end
+
+ def update_tool_with_optional_bindings(ai_tool)
+ AiTool.transaction do
+ ai_tool.update!(ai_tool_params)
+ if secret_bindings_supplied?
+ apply_secret_bindings!(ai_tool)
+ else
+ prune_orphan_bindings!(ai_tool)
+ end
+ end
+ true
+ rescue ActiveRecord::RecordInvalid => e
+ collect_tool_errors(ai_tool, e.record)
+ false
+ rescue ArgumentError => e
+ ai_tool.errors.add(:base, e.message)
+ false
+ end
+
+ def collect_tool_errors(ai_tool, record)
+ return if record.blank?
+
+ return if record == ai_tool
+
+ record.errors.full_messages.each { |message| ai_tool.errors.add(:base, message) }
+ end
+
+ def apply_secret_bindings!(ai_tool)
+ ai_tool.replace_secret_bindings!(secret_bindings_params, created_by: current_user)
+ end
+
+ def prune_orphan_bindings!(ai_tool)
+ ai_tool.prune_orphan_bindings!
+ end
+
+ def secret_bindings_supplied?
+ return false if params[:ai_tool].blank?
+
+ params[:ai_tool].key?(:secret_bindings) || params[:ai_tool].key?("secret_bindings")
+ end
+
+ def secret_bindings_params
+ Array(
+ params.require(:ai_tool).permit(secret_bindings: %i[alias ai_secret_id])[
+ :secret_bindings
+ ],
+ )
+ end
+
def log_ai_tool_creation(ai_tool)
logger = DiscourseAi::Utils::AiStaffActionLogger.new(current_user)
diff --git a/plugins/discourse-ai/app/models/ai_secret.rb b/plugins/discourse-ai/app/models/ai_secret.rb
index ffc1c7a47ee..0776352935a 100644
--- a/plugins/discourse-ai/app/models/ai_secret.rb
+++ b/plugins/discourse-ai/app/models/ai_secret.rb
@@ -8,9 +8,11 @@ class AiSecret < ActiveRecord::Base
has_many :llm_models, dependent: :nullify
has_many :embedding_definitions, dependent: :nullify
+ has_many :ai_tool_secret_bindings, dependent: :destroy
def in_use?
- llm_models.exists? || embedding_definitions.exists? || used_by_provider_params?
+ llm_models.exists? || embedding_definitions.exists? || used_by_provider_params? ||
+ ai_tool_secret_bindings.exists?
end
def used_by
@@ -22,6 +24,17 @@ class AiSecret < ActiveRecord::Base
provider_param_llms.each do |llm|
usage << { type: "llm_provider_param", name: llm.display_name, id: llm.id }
end
+ ai_tool_secret_bindings
+ .includes(:ai_tool)
+ .each do |binding|
+ next if binding.ai_tool.blank?
+
+ usage << {
+ type: "tool",
+ name: "#{binding.ai_tool.name} (#{binding[:alias]})",
+ id: binding.ai_tool.id,
+ }
+ end
usage
end
diff --git a/plugins/discourse-ai/app/models/ai_tool.rb b/plugins/discourse-ai/app/models/ai_tool.rb
index 322148dbb1f..ad783482f1a 100644
--- a/plugins/discourse-ai/app/models/ai_tool.rb
+++ b/plugins/discourse-ai/app/models/ai_tool.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
class AiTool < ActiveRecord::Base
+ SECRET_ALIAS_PATTERN = /\A[a-zA-Z0-9_]+\z/
+
validates :name, presence: true, length: { maximum: 100 }, uniqueness: true
validates :tool_name, presence: true, length: { maximum: 100 }
validates :description, presence: true, length: { maximum: 1000 }
@@ -12,6 +14,10 @@ class AiTool < ActiveRecord::Base
has_many :rag_document_fragments, dependent: :destroy, as: :target
has_many :upload_references, as: :target, dependent: :destroy
has_many :uploads, through: :upload_references
+ has_many :secret_bindings,
+ class_name: "AiToolSecretBinding",
+ dependent: :destroy,
+ inverse_of: :ai_tool
before_save :set_image_generation_tool_flag
before_update :regenerate_rag_fragments
@@ -24,6 +30,7 @@ class AiTool < ActiveRecord::Base
}
validate :validate_parameters_enum
+ validate :validate_secret_contracts
def signature
{
@@ -38,13 +45,14 @@ class AiTool < ActiveRecord::Base
tool_name.presence || name
end
- def runner(parameters, llm:, bot_user:, context: nil)
+ def runner(parameters, llm:, bot_user:, context: nil, secret_bindings: nil)
DiscourseAi::Personas::ToolRunner.new(
parameters: parameters,
llm: llm,
bot_user: bot_user,
context: context,
tool: self,
+ secret_bindings: secret_bindings,
)
end
@@ -64,8 +72,120 @@ class AiTool < ActiveRecord::Base
is_image_generation_tool
end
+ def secret_contract_for(alias_name)
+ return nil if alias_name.blank?
+
+ normalized_alias = alias_name.to_s
+ Array(secret_contracts).find do |contract|
+ contract.is_a?(Hash) && contract.fetch("alias", contract[:alias]) == normalized_alias
+ end
+ end
+
+ def secret_aliases
+ Array(secret_contracts).filter_map do |contract|
+ next if !contract.is_a?(Hash)
+
+ contract.fetch("alias", contract[:alias]).to_s
+ end
+ end
+
+ def missing_secret_aliases(bindings: nil)
+ source_bindings = bindings || secret_bindings
+ bound_aliases =
+ source_bindings.each_with_object(Set.new) do |binding, aliases|
+ alias_name =
+ if binding.respond_to?(:[])
+ binding[:alias] || binding["alias"]
+ else
+ binding.alias
+ end
+ secret_id =
+ if binding.respond_to?(:[])
+ binding[:ai_secret_id] || binding["ai_secret_id"]
+ else
+ binding.ai_secret_id
+ end
+ next if alias_name.blank? || secret_id.blank?
+
+ aliases << alias_name.to_s
+ end
+
+ secret_aliases.reject { |alias_name| bound_aliases.include?(alias_name) }
+ end
+
+ def resolve_secret(alias_name, bindings: nil, secrets_cache: nil)
+ normalized_alias = alias_name.to_s
+ contract = secret_contract_for(normalized_alias)
+ return nil, :alias_not_declared if contract.nil?
+
+ source_bindings = bindings || secret_bindings
+ binding =
+ source_bindings.find do |item|
+ if item.respond_to?(:[])
+ (item[:alias] || item["alias"]).to_s == normalized_alias
+ else
+ item.alias.to_s == normalized_alias
+ end
+ end
+
+ return nil, :missing_binding if binding.nil?
+
+ secret_id =
+ if binding.respond_to?(:[])
+ (binding[:ai_secret_id] || binding["ai_secret_id"]).to_i
+ else
+ binding.ai_secret_id.to_i
+ end
+ secret = secrets_cache ? secrets_cache[secret_id] : AiSecret.find_by(id: secret_id)
+ return nil, :secret_not_found if secret.nil?
+
+ [secret.secret, nil]
+ end
+
+ def prune_orphan_bindings!
+ valid = secret_aliases
+ secret_bindings.where.not(alias: valid).destroy_all
+ end
+
+ def replace_secret_bindings!(bindings, created_by: nil)
+ return if bindings.nil?
+
+ normalized_bindings = normalize_secret_bindings(bindings)
+
+ transaction do
+ secret_bindings.destroy_all
+
+ normalized_bindings.each do |binding|
+ next if binding[:ai_secret_id].blank?
+
+ secret_bindings.create!(
+ alias: binding[:alias],
+ ai_secret_id: binding[:ai_secret_id],
+ created_by: created_by,
+ )
+ end
+ end
+ end
+
private
+ def normalize_secret_bindings(bindings)
+ unless bindings.is_a?(Array)
+ raise ArgumentError, I18n.t("discourse_ai.tools.secret_bindings.invalid_payload")
+ end
+
+ bindings.map do |binding|
+ unless binding.respond_to?(:[])
+ raise ArgumentError, I18n.t("discourse_ai.tools.secret_bindings.invalid_payload")
+ end
+
+ alias_name = (binding[:alias] || binding["alias"]).to_s
+ secret_id = (binding[:ai_secret_id] || binding["ai_secret_id"]).presence
+
+ { alias: alias_name, ai_secret_id: secret_id&.to_i }
+ end
+ end
+
def set_image_generation_tool_flag
has_prompt_parameter = parameters.is_a?(Array) && parameters.any? { |p| p["name"] == "prompt" }
has_upload_create = script.include?("upload.create")
@@ -99,6 +219,60 @@ class AiTool < ActiveRecord::Base
end
end
+ def validate_secret_contracts
+ return if secret_contracts.blank?
+
+ unless secret_contracts.is_a?(Array)
+ errors.add(:secret_contracts, I18n.t("discourse_ai.tools.secret_contracts.invalid_payload"))
+ return
+ end
+
+ aliases = []
+
+ Array(secret_contracts).each_with_index do |contract, index|
+ unless contract.is_a?(Hash)
+ errors.add(
+ :secret_contracts,
+ I18n.t("discourse_ai.tools.secret_contracts.invalid_contract", index: index),
+ )
+ next
+ end
+
+ alias_name = contract.fetch("alias", contract[:alias]).to_s
+
+ if alias_name.blank?
+ errors.add(
+ :secret_contracts,
+ I18n.t("discourse_ai.tools.secret_contracts.alias_required", index: index),
+ )
+ next
+ end
+
+ if alias_name.length > 100
+ errors.add(
+ :secret_contracts,
+ I18n.t("discourse_ai.tools.secret_contracts.alias_too_long", alias: alias_name),
+ )
+ end
+
+ unless alias_name.match?(SECRET_ALIAS_PATTERN)
+ errors.add(
+ :secret_contracts,
+ I18n.t("discourse_ai.tools.secret_contracts.alias_invalid", alias: alias_name),
+ )
+ end
+
+ if aliases.include?(alias_name)
+ errors.add(
+ :secret_contracts,
+ I18n.t("discourse_ai.tools.secret_contracts.alias_not_unique", alias: alias_name),
+ )
+ else
+ aliases << alias_name
+ end
+ end
+ end
+
# Load a JavaScript file from the ai_tool_scripts directory
def self.load_script(filename)
path = File.join(__dir__, "../../lib/ai_tool_scripts", filename)
@@ -158,6 +332,7 @@ class AiTool < ActiveRecord::Base
description: "The stock symbol (e.g., AAPL, GOOGL)",
},
],
+ secret_contracts: [{ alias: "alphavantage_api_key" }],
script: "#{preamble}\n#{load_script("presets/stock_quote.js")}",
summary: "Get real-time stock quotes using AlphaVantage API",
},
@@ -215,6 +390,7 @@ class AiTool < ActiveRecord::Base
description: "Image size (1024x1024, 1792x1024, or 1024x1792)",
},
],
+ secret_contracts: [{ alias: "openai_api_key" }],
script: "#{preamble}\n#{load_script("presets/image_generation/openai.js")}",
summary: "Generate images with OpenAI GPT Image 1 model",
category: "image_generation",
@@ -234,6 +410,7 @@ class AiTool < ActiveRecord::Base
description: "The text prompt for image generation",
},
],
+ secret_contracts: [{ alias: "google_api_key" }],
script: "#{preamble}\n#{load_script("presets/image_generation/gemini.js")}",
summary: "Generate images with Gemini 2.5 Flash Image",
category: "image_generation",
@@ -260,6 +437,7 @@ class AiTool < ActiveRecord::Base
description: "Optional seed for random number generation",
},
],
+ secret_contracts: [{ alias: "together_api_key" }],
script: "#{preamble}\n#{load_script("presets/image_generation/flux_together.js")}",
summary: "Generate images with FLUX 1.1 Pro",
category: "image_generation",
@@ -286,6 +464,7 @@ class AiTool < ActiveRecord::Base
description: "Optional seed for reproducible results",
},
],
+ secret_contracts: [{ alias: "bfl_api_key" }],
script: "#{preamble}\n#{load_script("presets/image_generation/flux_2_bfl.js")}",
summary: "Generate and edit images with FLUX 2 Pro",
category: "image_generation",
@@ -307,6 +486,7 @@ end
# rag_chunk_overlap_tokens :integer default(10), not null
# rag_chunk_tokens :integer default(374), not null
# script :text not null
+# secret_contracts :jsonb not null
# summary :string not null
# tool_name :string(100) default(""), not null
# created_at :datetime not null
diff --git a/plugins/discourse-ai/app/models/ai_tool_secret_binding.rb b/plugins/discourse-ai/app/models/ai_tool_secret_binding.rb
new file mode 100644
index 00000000000..4e33d39017e
--- /dev/null
+++ b/plugins/discourse-ai/app/models/ai_tool_secret_binding.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+class AiToolSecretBinding < ActiveRecord::Base
+ belongs_to :ai_tool
+ belongs_to :ai_secret
+ belongs_to :created_by, class_name: "User", optional: true
+
+ validates :alias,
+ presence: true,
+ length: {
+ maximum: 100,
+ },
+ format: {
+ with: AiTool::SECRET_ALIAS_PATTERN,
+ message: I18n.t("discourse_ai.tools.name.characters"),
+ },
+ uniqueness: {
+ scope: :ai_tool_id,
+ }
+ validates :ai_secret_id, presence: true
+
+ validate :secret_exists
+ validate :alias_declared
+
+ private
+
+ def secret_exists
+ return if ai_secret_id.blank?
+ return if AiSecret.exists?(ai_secret_id)
+
+ errors.add(:ai_secret_id, I18n.t("discourse_ai.tools.secret_bindings.secret_not_found"))
+ end
+
+ def alias_declared
+ return if self[:alias].blank? || ai_tool.blank?
+ return if ai_tool.secret_contract_for(self[:alias]).present?
+
+ errors.add(
+ :alias,
+ I18n.t("discourse_ai.tools.secret_bindings.alias_not_declared", alias: self[:alias]),
+ )
+ end
+end
+
+# == Schema Information
+#
+# Table name: ai_tool_secret_bindings
+#
+# id :bigint not null, primary key
+# alias :string(100) not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# ai_secret_id :bigint not null
+# ai_tool_id :bigint not null
+# created_by_id :integer
+#
+# Indexes
+#
+# index_ai_tool_secret_bindings_on_ai_secret_id (ai_secret_id)
+# index_ai_tool_secret_bindings_on_ai_tool_id (ai_tool_id)
+# index_ai_tool_secret_bindings_on_ai_tool_id_and_alias (ai_tool_id,alias) UNIQUE
+#
diff --git a/plugins/discourse-ai/app/serializers/ai_custom_tool_list_serializer.rb b/plugins/discourse-ai/app/serializers/ai_custom_tool_list_serializer.rb
index 36642a68a03..a4844a1a89b 100644
--- a/plugins/discourse-ai/app/serializers/ai_custom_tool_list_serializer.rb
+++ b/plugins/discourse-ai/app/serializers/ai_custom_tool_list_serializer.rb
@@ -9,6 +9,7 @@ class AiCustomToolListSerializer < ApplicationSerializer
{
presets: AiTool.presets,
llms: DiscourseAi::Configuration::LlmEnumerator.values_for_serialization,
+ ai_secrets: AiSecret.order(:name).pluck(:id, :name).map { |id, name| { id: id, name: name } },
settings: {
rag_images_enabled: SiteSetting.ai_rag_images_enabled,
},
diff --git a/plugins/discourse-ai/app/serializers/ai_custom_tool_serializer.rb b/plugins/discourse-ai/app/serializers/ai_custom_tool_serializer.rb
index 2af1a89fcfc..0d0b7511534 100644
--- a/plugins/discourse-ai/app/serializers/ai_custom_tool_serializer.rb
+++ b/plugins/discourse-ai/app/serializers/ai_custom_tool_serializer.rb
@@ -8,6 +8,8 @@ class AiCustomToolSerializer < ApplicationSerializer
:summary,
:parameters,
:script,
+ :secret_contracts,
+ :secret_bindings,
:rag_chunk_tokens,
:rag_chunk_overlap_tokens,
:rag_llm_model_id,
@@ -22,4 +24,14 @@ class AiCustomToolSerializer < ApplicationSerializer
def rag_uploads
object.uploads
end
+
+ def include_secret_bindings?
+ return true if scope.blank? || !scope.is_a?(Hash)
+
+ scope[:include_secret_bindings] != false
+ end
+
+ def secret_bindings
+ object.secret_bindings.map { |binding| binding.slice(:alias, :ai_secret_id) }
+ end
end
diff --git a/plugins/discourse-ai/app/services/discourse_ai/persona_exporter.rb b/plugins/discourse-ai/app/services/discourse_ai/persona_exporter.rb
index 9beadc20422..adeb5c6c3e2 100644
--- a/plugins/discourse-ai/app/services/discourse_ai/persona_exporter.rb
+++ b/plugins/discourse-ai/app/services/discourse_ai/persona_exporter.rb
@@ -33,6 +33,7 @@ module DiscourseAi
description: tool.description,
tool_name: tool.tool_name,
parameters: tool.parameters,
+ secret_contracts: tool.secret_contracts,
summary: tool.summary,
script: tool.script,
}
diff --git a/plugins/discourse-ai/app/services/discourse_ai/persona_importer.rb b/plugins/discourse-ai/app/services/discourse_ai/persona_importer.rb
index 6fecc2ae65c..4925df33d50 100644
--- a/plugins/discourse-ai/app/services/discourse_ai/persona_importer.rb
+++ b/plugins/discourse-ai/app/services/discourse_ai/persona_importer.rb
@@ -120,10 +120,12 @@ module DiscourseAi
t.name = tool_data["name"]
t.description = tool_data["description"]
t.parameters = tool_data["parameters"]
+ t.secret_contracts = tool_data["secret_contracts"] || []
t.script = tool_data["script"]
t.summary = tool_data["summary"]
t.created_by ||= Discourse.system_user
t.save!
+ t.prune_orphan_bindings! if overwrite
end
map[tool.tool_name] = tool.id
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-tool.js b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-tool.js
index 4b9cdf7cccb..d712509c4a6 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-tool.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-tool.js
@@ -7,6 +7,8 @@ const CREATE_ATTRIBUTES = [
"tool_name",
"description",
"parameters",
+ "secret_contracts",
+ "secret_bindings",
"script",
"summary",
"rag_uploads",
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor-form.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor-form.gjs
index 3a6d9e9379e..c0e1b7091aa 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor-form.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor-form.gjs
@@ -10,6 +10,7 @@ import getURL from "discourse/lib/get-url";
import { and, gt } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
import { toPlainObject } from "../lib/utilities";
+import AiSecretSelector from "./ai-secret-selector";
import AiToolTestModal from "./modal/ai-tool-test-modal";
import RagOptionsFk from "./rag-options-fk";
import RagUploader from "./rag-uploader";
@@ -51,17 +52,36 @@ export default class AiToolEditorForm extends Component {
const plainRagUploads =
ragUploads.length > 0 ? toPlainObject(ragUploads) : [];
+ const secretBindingMap = Object.fromEntries(
+ (this.args.editingModel.secret_bindings || []).map((binding) => [
+ binding.alias,
+ binding.ai_secret_id,
+ ])
+ );
+ const secretContracts = (this.args.editingModel.secret_contracts ?? []).map(
+ (contract) => ({
+ ...contract,
+ ai_secret_id:
+ secretBindingMap[contract.alias] || contract.ai_secret_id || null,
+ })
+ );
+
return {
name: this.args.editingModel.name || "",
tool_name: this.args.editingModel.tool_name || "",
description: this.args.editingModel.description || "",
summary: this.args.editingModel.summary || "",
parameters,
+ secret_contracts: secretContracts,
script: this.args.editingModel.script || "",
rag_uploads: plainRagUploads,
};
}
+ get secretOptions() {
+ return this.args.secrets || [];
+ }
+
@action
toggleIsEnum(value, { name, parentName, set }) {
if (value) {
@@ -73,11 +93,7 @@ export default class AiToolEditorForm extends Component {
set(name, value);
}
- @action
- async save(data) {
- this.isSaving = true;
-
- // we injected a isEnum thing, we need to clean it up
+ cleanFormData(data) {
const copiedData = toPlainObject(data);
if (copiedData.parameters) {
copiedData.parameters.forEach((parameter) => {
@@ -88,6 +104,30 @@ export default class AiToolEditorForm extends Component {
});
}
+ if (copiedData.secret_contracts) {
+ copiedData.secret_bindings = copiedData.secret_contracts.map(
+ ({ alias, ai_secret_id }) => ({
+ alias,
+ ai_secret_id,
+ })
+ );
+ copiedData.secret_contracts = copiedData.secret_contracts.map(
+ ({ alias: contractAlias }) => ({
+ alias: contractAlias,
+ })
+ );
+ } else {
+ copiedData.secret_bindings = [];
+ }
+
+ return copiedData;
+ }
+
+ @action
+ async save(data) {
+ this.isSaving = true;
+ const copiedData = this.cleanFormData(data);
+
try {
await this.args.model.save(copiedData);
@@ -151,10 +191,13 @@ export default class AiToolEditorForm extends Component {
}
@action
- openTestModal() {
+ openTestModal(data) {
+ const toolData = this.cleanFormData(data);
+
this.modal.show(AiToolTestModal, {
model: {
- tool: this.args.editingModel,
+ toolId: this.args.editingModel.id,
+ toolData,
},
});
}
@@ -364,6 +407,66 @@ export default class AiToolEditorForm extends Component {
name="" type="string" description="" required=false isEnum=false
)
}}
+ class="btn-default"
+ />
+
+ {{! CREDENTIAL CONTRACTS }}
+ <form.Collection @name="secret_contracts" as |collection index|>
+ <form.Container class="ai-tool-secret-contract">
+ <form.Row as |row|>
+ <row.Col @size={{6}}>
+ <collection.Field
+ @name="alias"
+ @title={{i18n "discourse_ai.tools.secret_alias"}}
+ @validation="required|length:1,100"
+ @format="full"
+ @tooltip={{i18n "discourse_ai.tools.secret_alias_help"}}
+ as |field|
+ >
+ <field.Input />
+ </collection.Field>
+ </row.Col>
+
+ <row.Col @size={{6}}>
+ <collection.Field
+ @name="ai_secret_id"
+ @title={{i18n "discourse_ai.tools.secret_credential"}}
+ @format="full"
+ as |field|
+ >
+ <field.Custom>
+ <AiSecretSelector
+ @value={{field.value}}
+ @secrets={{this.secretOptions}}
+ @onChange={{field.set}}
+ />
+ </field.Custom>
+ </collection.Field>
+ </row.Col>
+ </form.Row>
+
+ <form.Row as |row|>
+ <row.Col class="ai-tool-secret-contract__actions">
+ <form.Button
+ @label="discourse_ai.tools.remove_secret_contract"
+ @icon="trash-can"
+ @action={{fn collection.remove index}}
+ class="btn-danger"
+ />
+ </row.Col>
+ </form.Row>
+ </form.Container>
+ </form.Collection>
+
+ <form.Button
+ @icon="plus"
+ @label="discourse_ai.tools.add_secret_contract"
+ @action={{fn
+ form.addItemToCollection
+ "secret_contracts"
+ (hash alias="" ai_secret_id=null)
+ }}
+ class="btn-default"
/>
{{! SCRIPT }}
@@ -404,16 +507,21 @@ export default class AiToolEditorForm extends Component {
{{/if}}
<form.Actions>
+ <form.Submit
+ @label="discourse_ai.tools.save"
+ class="ai-tool-editor__save"
+ />
+
{{#unless @isNew}}
<form.Button
@label="discourse_ai.tools.test"
- @action={{this.openTestModal}}
- class="ai-tool-editor__test-button"
+ @action={{fn this.openTestModal data}}
+ class="btn-default ai-tool-editor__test-button"
/>
<form.Button
@label="discourse_ai.tools.export"
@action={{this.exportTool}}
- class="ai-tool-editor__export"
+ class="btn-default ai-tool-editor__export"
/>
<form.Button
@label="discourse_ai.tools.delete"
@@ -422,11 +530,6 @@ export default class AiToolEditorForm extends Component {
class="btn-danger ai-tool-editor__delete"
/>
{{/unless}}
-
- <form.Submit
- @label="discourse_ai.tools.save"
- class="ai-tool-editor__save"
- />
</form.Actions>
</Form>
</template>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor.gjs
index 2489f5eab3b..69c34bf4ccb 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-editor.gjs
@@ -33,6 +33,7 @@ export default class AiToolEditor extends Component {
<AiToolEditorForm
@model={{@model}}
@tools={{@tools}}
+ @secrets={{@secrets}}
@editingModel={{this.editingModel}}
@isNew={{@model.isNew}}
@selectedPreset={{this.selectedPreset}}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-tool-test-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-tool-test-modal.gjs
index 24bf40b2a31..306d3d83455 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-tool-test-modal.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-tool-test-modal.gjs
@@ -3,6 +3,7 @@ import { tracked } from "@glimmer/tracking";
import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
+import CookText from "discourse/components/cook-text";
import DButton from "discourse/components/d-button";
import DModal from "discourse/components/d-modal";
import { ajax } from "discourse/lib/ajax";
@@ -12,6 +13,7 @@ import { jsonToHtml } from "../../lib/utilities";
export default class AiToolTestModal extends Component {
@tracked testResult;
+ @tracked customRaw;
@tracked isLoading = false;
parameterValues = {};
@@ -23,19 +25,22 @@ export default class AiToolTestModal extends Component {
@action
async runTest() {
this.isLoading = true;
+ this.testResult = null;
+ this.customRaw = null;
try {
const response = await ajax(
- `/admin/plugins/discourse-ai/ai-tools/${this.args.model.tool.id}/test.json`,
+ `/admin/plugins/discourse-ai/ai-tools/${this.args.model.toolId}/test.json`,
{
type: "POST",
data: JSON.stringify({
- ai_tool: this.args.model.tool,
+ ai_tool: this.args.model.toolData,
parameters: this.parameterValues,
}),
contentType: "application/json",
}
);
this.testResult = jsonToHtml(response.output);
+ this.customRaw = response.custom_raw;
} catch (error) {
popupAjaxError(error);
} finally {
@@ -51,7 +56,7 @@ export default class AiToolTestModal extends Component {
class="ai-tool-test-modal"
>
<:body>
- {{#each @model.tool.parameters as |param|}}
+ {{#each @model.toolData.parameters as |param|}}
<div class="control-group">
<label>{{param.name}}</label>
<input
@@ -68,13 +73,19 @@ export default class AiToolTestModal extends Component {
<div>{{this.testResult}}</div>
</div>
{{/if}}
+
+ {{#if this.customRaw}}
+ <div class="ai-tool-test-modal__custom-raw">
+ <CookText @rawText={{this.customRaw}} />
+ </div>
+ {{/if}}
</:body>
<:footer>
<DButton
@action={{this.runTest}}
@label="discourse_ai.tools.test_modal.run"
- @disabled={{this.isLoading}}
+ @isLoading={{this.isLoading}}
class="btn-primary ai-tool-test-modal__run-button"
/>
</:footer>
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss
index 0d1e7a0a953..3e7c40e9298 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss
@@ -13,6 +13,19 @@
}
}
+.ai-tool-secret-contract {
+ padding: 1.5em;
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-input-border-radius);
+ width: 100%;
+ box-sizing: border-box;
+
+ .form-kit__container-content {
+ flex-direction: column;
+ width: 100%;
+ }
+}
+
.ai-tool-parameter__enum-values {
margin-block: 1rem;
@@ -40,6 +53,12 @@
display: none;
}
}
+
+ .form-kit__actions {
+ .btn-danger {
+ margin-left: auto;
+ }
+ }
}
.ai-tool-test-modal {
@@ -48,6 +67,15 @@
padding-left: 1em;
}
}
+
+ &__custom-raw {
+ margin-top: 1em;
+
+ img {
+ max-width: 100%;
+ height: auto;
+ }
+ }
}
.ai-tool-list-editor {
@@ -63,6 +91,38 @@
}
}
+.ai-tool-list__credentials {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.35em;
+ margin-top: 0.35em;
+}
+
+.ai-tool-list__credential-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25em;
+ padding: 0.15em 0.5em;
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-2);
+ line-height: 1.4;
+
+ &--bound {
+ background-color: var(--success-low);
+ color: var(--success);
+ }
+
+ &--missing {
+ background-color: var(--danger-low);
+ color: var(--danger);
+ }
+}
+
+.ai-tool-list__credential-not-set {
+ font-style: italic;
+ margin-left: 0.15em;
+}
+
.ai-tool-editor__templates {
&-list {
display: grid;
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 0858c92d9fe..b83e8e037f7 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -665,8 +665,14 @@ en:
parameter_description: "Parameter description"
enum_value: "Enum value"
add_enum_value: "Add enum value"
+ secret_alias: "Credential alias"
+ secret_alias_help: "Alias referenced from scripts via secrets.get(\"alias_name\"). Use letters, numbers, and underscores."
+ secret_credential: "Credential"
+ add_secret_contract: "Add credential"
+ remove_secret_contract: "Remove credential"
+ credential_not_set: "(not set)"
edit: "Edit"
- test: "Run test"
+ test: "Test"
delete: "Delete"
saved: "Tool saved"
confirm_delete: "Are you sure you want to delete this tool?"
@@ -677,7 +683,7 @@ en:
secrets:
short_title: "Credentials"
- description: "Manage authentication credentials shared across LLMs and embeddings."
+ description: "Manage authentication credentials shared across LLMs, embeddings, and tools."
name: "Name"
secret: "Value"
select_secret: "Select a credential..."
@@ -697,6 +703,7 @@ en:
not_used: "Not in use"
embedding: "Embedding"
cannot_delete_in_use: "This credential cannot be deleted because it is in use by:"
+ tool: "Tool"
modal:
title: "Create new credential"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index f145d67123e..9051cf209c2 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -288,6 +288,23 @@ en:
name: "Start from blank..."
name:
characters: "must only include numbers, letters, and underscores"
+ secret_contracts:
+ invalid_payload: "Secret contracts must be an array."
+ invalid_contract: "Secret contract at index %{index} is invalid."
+ alias_required: "Secret contract at index %{index} must include an alias."
+ alias_too_long: "Secret alias `%{alias}` is too long."
+ alias_invalid: "Secret alias `%{alias}` must only include numbers, letters, and underscores."
+ alias_not_unique: "Secret alias `%{alias}` is duplicated."
+ secret_bindings:
+ invalid_payload: "Secret bindings must be an array."
+ secret_not_found: "The selected credential does not exist."
+ alias_not_declared: "Alias `%{alias}` is not declared in this tool."
+ secret_runtime:
+ alias_not_declared: "Credential alias `%{alias}` is not declared for this tool."
+ missing_binding: "Credential alias `%{alias}` is required but not bound."
+ missing_required_aliases: "Missing required credential bindings for aliases: %{aliases}."
+ secret_not_found: "Credential alias `%{alias}` is bound to a missing credential."
+ unknown_error: "Unable to resolve the requested credential."
ai_helper:
errors:
@@ -674,7 +691,7 @@ en:
model_test_failed: "We failed to generate a test embedding with this model. Check it's correctly configured."
secrets:
- delete_failed_in_use: "This credential is currently in use by one or more LLMs or embeddings and cannot be deleted."
+ delete_failed_in_use: "This credential is currently in use by one or more LLMs, embeddings, or tools and cannot be deleted."
llm_models:
missing_provider_param: "%{param} can't be blank"
diff --git a/plugins/discourse-ai/db/migrate/20260218000000_add_secret_contracts_to_ai_tools.rb b/plugins/discourse-ai/db/migrate/20260218000000_add_secret_contracts_to_ai_tools.rb
new file mode 100644
index 00000000000..2b25bdf1d3f
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260218000000_add_secret_contracts_to_ai_tools.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+class AddSecretContractsToAiTools < ActiveRecord::Migration[7.0]
+ def change
+ add_column :ai_tools, :secret_contracts, :jsonb, default: [], null: false
+
+ create_table :ai_tool_secret_bindings do |t|
+ t.bigint :ai_tool_id, null: false
+ t.string :alias, null: false, limit: 100
+ t.bigint :ai_secret_id, null: false
+ t.integer :created_by_id
+ t.timestamps
+ end
+
+ add_index :ai_tool_secret_bindings, :ai_tool_id
+ add_index :ai_tool_secret_bindings, :ai_secret_id
+ add_index :ai_tool_secret_bindings, %i[ai_tool_id alias], unique: true
+ 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 a5fea9fe1f2..f9f83585360 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
@@ -109,7 +109,18 @@
* raw (string): The raw Markdown content for the post.
* Returns: void
*
- * 6. discourse
+ * 6. secrets
+ * Accesses credentials bound to this tool by alias.
+ *
+ * secrets.get(alias): Returns the credential value bound to `alias`.
+ * Parameters:
+ * alias (string): Alias defined in the tool's credential contract.
+ * Returns: string
+ * Throws: Error if alias is undeclared, alias is unbound, or credential is missing.
+ * Example:
+ * const apiKey = secrets.get("openai_api_key");
+ *
+ * 7. discourse
* Interacts with Discourse specific features. Access is generally performed as the SystemUser.
*
* discourse.baseUrl: The base URL of the Discourse site (e.g., "https://meta.discourse.org").
@@ -200,7 +211,7 @@
* Example:
* discourse.setCustomField("post", context.post_id, "ai_processed", Date.now().toString());
*
- * 7. context
+ * 8. context
* An object containing information about the environment where the tool is being run.
* Tools can be invoked from multiple contexts - understanding where your tool is running
* helps you access the right data and take appropriate actions.
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_2_bfl.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_2_bfl.js
index 0f3912958bf..5c2ce79a0db 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_2_bfl.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_2_bfl.js
@@ -1,5 +1,5 @@
/* eslint-disable no-undef, no-unused-vars */
-const apiKey = "YOUR_BFL_API_KEY";
+const apiKey = secrets.get("bfl_api_key");
function invoke(params) {
const prompt = params.prompt;
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_together.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_together.js
index c1676dbb451..dc05f5836d8 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_together.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux_together.js
@@ -1,5 +1,5 @@
/* eslint-disable no-undef, no-unused-vars */
-const apiKey = "YOUR_KEY";
+const apiKey = secrets.get("together_api_key");
const model = "black-forest-labs/FLUX.1.1-pro";
function invoke(params) {
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/gemini.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/gemini.js
index 09073f4f32d..f84b87f1e46 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/gemini.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/gemini.js
@@ -1,5 +1,5 @@
/* eslint-disable no-undef, no-unused-vars */
-const apiKey = "YOUR_GOOGLE_API_KEY";
+const apiKey = secrets.get("google_api_key");
function invoke(params) {
const prompt = params.prompt;
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/openai.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/openai.js
index 6d00a723472..78942ee78e3 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/openai.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/openai.js
@@ -1,5 +1,5 @@
/* eslint-disable no-undef, no-unused-vars */
-const apiKey = "YOUR_OPENAI_API_KEY";
+const apiKey = secrets.get("openai_api_key");
function invoke(params) {
const prompt = params.prompt;
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/stock_quote.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/stock_quote.js
index 60bd065afdc..204002e0a7a 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/presets/stock_quote.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/stock_quote.js
@@ -1,6 +1,6 @@
/* eslint-disable no-undef, no-unused-vars */
function invoke(params) {
- const apiKey = "YOUR_ALPHAVANTAGE_API_KEY"; // Replace with your actual API key
+ const apiKey = secrets.get("alphavantage_api_key");
const url = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${params.symbol}&apikey=${apiKey}`;
const result = http.get(url);
diff --git a/plugins/discourse-ai/lib/automation/ai_tool_action.rb b/plugins/discourse-ai/lib/automation/ai_tool_action.rb
index 73ef56821ac..8d98c36d898 100644
--- a/plugins/discourse-ai/lib/automation/ai_tool_action.rb
+++ b/plugins/discourse-ai/lib/automation/ai_tool_action.rb
@@ -4,7 +4,7 @@ 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)
+ tool = ::AiTool.includes(:secret_bindings).find_by(id: tool_id, enabled: true)
return if !tool
llm =
diff --git a/plugins/discourse-ai/lib/personas/tool_runner.rb b/plugins/discourse-ai/lib/personas/tool_runner.rb
index 99ee52d4160..4aca2e979ce 100644
--- a/plugins/discourse-ai/lib/personas/tool_runner.rb
+++ b/plugins/discourse-ai/lib/personas/tool_runner.rb
@@ -21,7 +21,15 @@ module DiscourseAi
CUSTOM_FIELD_MODELS = { "post" => Post, "topic" => Topic, "user" => User }.freeze
- def initialize(parameters:, llm:, bot_user:, context: nil, tool:, timeout: nil)
+ def initialize(
+ parameters:,
+ llm:,
+ bot_user:,
+ context: nil,
+ tool:,
+ timeout: nil,
+ secret_bindings: nil
+ )
if context && !context.is_a?(DiscourseAi::Personas::BotContext)
raise ArgumentError, "context must be a BotContext object"
end
@@ -35,6 +43,7 @@ module DiscourseAi
@tool = tool
@timeout = timeout || DEFAULT_TIMEOUT
@running_attached_function = false
+ @secret_bindings = secret_bindings
@sleep_calls_made = 0
@http_requests_made = 0
@@ -84,6 +93,7 @@ module DiscourseAi
attach_index(ctx)
attach_upload(ctx)
attach_chain(ctx)
+ attach_secrets(ctx)
attach_sleep(ctx)
attach_discourse(ctx)
ctx.eval(framework_script)
@@ -134,6 +144,12 @@ module DiscourseAi
streamCustomRaw: _chain_stream_custom_raw,
};
+ const secrets = {
+ get: function(aliasName) {
+ return _secrets_get(aliasName);
+ },
+ };
+
const discourse = {
baseUrl: #{Discourse.base_url.to_json},
search: function(params) {
@@ -285,6 +301,17 @@ module DiscourseAi
def invoke(progress_callback: nil)
@progress_callback = progress_callback
+ source_bindings = @secret_bindings || tool.secret_bindings
+ missing_aliases = tool.missing_secret_aliases(bindings: source_bindings)
+ if missing_aliases.present?
+ raise Discourse::InvalidParameters.new(
+ I18n.t(
+ "discourse_ai.tools.secret_runtime.missing_required_aliases",
+ aliases: missing_aliases.join(", "),
+ ),
+ )
+ end
+ preload_secrets(source_bindings)
mini_racer_context.eval(tool.script)
eval_with_timeout("invoke(#{JSON.generate(parameters)})")
rescue MiniRacer::ScriptTerminatedError
@@ -309,6 +336,19 @@ module DiscourseAi
private
+ def preload_secrets(bindings)
+ secret_ids =
+ bindings.filter_map do |binding|
+ if binding.respond_to?(:[])
+ binding[:ai_secret_id] || binding["ai_secret_id"]
+ else
+ binding.ai_secret_id
+ end
+ end
+ secret_ids = secret_ids.map(&:to_i).uniq
+ @secrets_cache = secret_ids.present? ? AiSecret.where(id: secret_ids).index_by(&:id) : {}
+ end
+
MAX_FRAGMENTS = 200
def rag_search(query, filenames: nil, limit: 10)
@@ -444,6 +484,13 @@ module DiscourseAi
)
end
+ def attach_secrets(mini_racer_context)
+ mini_racer_context.attach(
+ "_secrets_get",
+ ->(alias_name) { in_attached_function { resolve_tool_secret!(alias_name) } },
+ )
+ end
+
# this is useful for polling apis
def attach_sleep(mini_racer_context)
mini_racer_context.attach(
@@ -1187,6 +1234,36 @@ module DiscourseAi
CUSTOM_FIELD_MODELS[type]&.find_by(id: id)
end
+ def resolve_tool_secret!(alias_name)
+ value, error =
+ tool.resolve_secret(
+ alias_name,
+ bindings: @secret_bindings || tool.secret_bindings,
+ secrets_cache: @secrets_cache,
+ )
+
+ case error
+ when nil
+ value
+ when :alias_not_declared
+ raise Discourse::InvalidParameters.new(
+ I18n.t("discourse_ai.tools.secret_runtime.alias_not_declared", alias: alias_name),
+ )
+ when :missing_binding
+ raise Discourse::InvalidParameters.new(
+ I18n.t("discourse_ai.tools.secret_runtime.missing_binding", alias: alias_name),
+ )
+ when :secret_not_found
+ raise Discourse::InvalidParameters.new(
+ I18n.t("discourse_ai.tools.secret_runtime.secret_not_found", alias: alias_name),
+ )
+ else
+ raise Discourse::InvalidParameters.new(
+ I18n.t("discourse_ai.tools.secret_runtime.unknown_error"),
+ )
+ end
+ end
+
def in_attached_function
self.running_attached_function = true
yield
diff --git a/plugins/discourse-ai/lib/personas/tools/custom.rb b/plugins/discourse-ai/lib/personas/tools/custom.rb
index c1a70ad40d5..a11bbc2b9c2 100644
--- a/plugins/discourse-ai/lib/personas/tools/custom.rb
+++ b/plugins/discourse-ai/lib/personas/tools/custom.rb
@@ -96,7 +96,7 @@ module DiscourseAi
end
def ai_tool
- @ai_tool ||= AiTool.find(self.class.tool_id)
+ @ai_tool ||= AiTool.includes(:secret_bindings).find(self.class.tool_id)
end
def summary
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 3966878c61f..a2c2050b606 100644
--- a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
+++ b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
@@ -16,6 +16,7 @@ RSpec.describe DiscourseAi::Personas::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") }
@@ -42,6 +43,59 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
expect(result["baseUrl"]).to eq(Discourse.base_url)
end
+ it "allows scripts to resolve configured secret aliases" do
+ tool.update!(
+ secret_contracts: [{ alias: "external_api_key" }],
+ script: "function invoke() { return { key: secrets.get('external_api_key') }; }",
+ )
+ AiToolSecretBinding.create!(
+ ai_tool: tool,
+ alias: "external_api_key",
+ ai_secret_id: ai_secret.id,
+ )
+
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ result = runner.invoke
+
+ expect(result["key"]).to eq(ai_secret.secret)
+ end
+
+ it "raises when secret alias is not bound" do
+ tool.update!(
+ secret_contracts: [{ alias: "external_api_key" }],
+ script: "function invoke() { return secrets.get('external_api_key'); }",
+ )
+
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+
+ expect { runner.invoke }.to raise_error(
+ Discourse::InvalidParameters,
+ /Missing required credential bindings/,
+ )
+ end
+
+ it "resolves secrets from in-flight secret_bindings override" do
+ tool.update!(
+ secret_contracts: [{ alias: "external_api_key" }],
+ script: "function invoke() { return { key: secrets.get('external_api_key') }; }",
+ )
+
+ bindings = [{ "alias" => "external_api_key", "ai_secret_id" => ai_secret.id }]
+
+ runner =
+ described_class.new(
+ parameters: {
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ secret_bindings: bindings,
+ )
+ result = runner.invoke
+
+ expect(result["key"]).to eq(ai_secret.secret)
+ end
+
it "can set tags on a topic" do
tool.update!(
script:
diff --git a/plugins/discourse-ai/spec/models/ai_secret_spec.rb b/plugins/discourse-ai/spec/models/ai_secret_spec.rb
index 957f786fd7c..b9f6c05a62f 100644
--- a/plugins/discourse-ai/spec/models/ai_secret_spec.rb
+++ b/plugins/discourse-ai/spec/models/ai_secret_spec.rb
@@ -82,6 +82,17 @@ RSpec.describe AiSecret do
)
expect(ai_secret.in_use?).to eq(false)
end
+
+ it "returns true when used by a tool binding" do
+ tool = Fabricate(:ai_tool, secret_contracts: [{ alias: "external_api_key" }])
+ AiToolSecretBinding.create!(
+ ai_tool: tool,
+ alias: "external_api_key",
+ ai_secret_id: ai_secret.id,
+ )
+
+ expect(ai_secret.in_use?).to eq(true)
+ end
end
describe "ai_secret_id existence validation" do
@@ -112,5 +123,21 @@ RSpec.describe AiSecret do
expect(usage.length).to eq(2)
expect(usage.map { |u| u[:type] }).to contain_exactly("llm", "embedding")
end
+
+ it "lists tools using this secret" do
+ tool =
+ Fabricate(:ai_tool, name: "Weather Tool", secret_contracts: [{ alias: "weather_api_key" }])
+ AiToolSecretBinding.create!(
+ ai_tool: tool,
+ alias: "weather_api_key",
+ ai_secret_id: ai_secret.id,
+ )
+
+ usage = ai_secret.used_by
+ tool_usage = usage.find { |u| u[:type] == "tool" }
+
+ expect(tool_usage).to be_present
+ expect(tool_usage[:name]).to include("Weather Tool")
+ 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 cf647d29852..b71638aa4b7 100644
--- a/plugins/discourse-ai/spec/models/ai_tool_spec.rb
+++ b/plugins/discourse-ai/spec/models/ai_tool_spec.rb
@@ -10,6 +10,7 @@ RSpec.describe AiTool do
def create_tool(
parameters: nil,
script: nil,
+ secret_contracts: nil,
rag_chunk_tokens: nil,
rag_chunk_overlap_tokens: nil
)
@@ -20,6 +21,7 @@ RSpec.describe AiTool do
parameters:
parameters || [{ name: "query", type: "string", description: "perform a search" }],
script: script || "function invoke(params) { return params; }",
+ secret_contracts: secret_contracts || [],
created_by_id: 1,
summary: "Test tool summary",
rag_chunk_tokens: rag_chunk_tokens || 374,
@@ -45,6 +47,31 @@ RSpec.describe AiTool do
expect(runner.invoke).to eq("query" => "test")
end
+ it "validates secret contracts" do
+ tool =
+ create_tool(
+ parameters: [{ name: "query", type: "string", description: "perform a search" }],
+ script: "function invoke(params) { return params; }",
+ )
+
+ tool.secret_contracts = [{ alias: "invalid alias" }, { alias: "invalid alias" }]
+
+ expect(tool).not_to be_valid
+ expect(tool.errors[:secret_contracts]).to be_present
+ end
+
+ it "can replace and resolve secret bindings by alias" do
+ tool = create_tool(secret_contracts: [{ alias: "weather_api_key" }])
+ secret = Fabricate(:ai_secret)
+
+ tool.replace_secret_bindings!([{ alias: "weather_api_key", ai_secret_id: secret.id }])
+
+ value, error = tool.resolve_secret("weather_api_key")
+ expect(error).to be_nil
+ expect(value).to eq(secret.secret)
+ 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
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_secrets_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_secrets_controller_spec.rb
index 115d4be155c..daba58f07dc 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_secrets_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_secrets_controller_spec.rb
@@ -21,6 +21,17 @@ RSpec.describe DiscourseAi::Admin::AiSecretsController do
expect(json["ai_secrets"][0]["secret"]).to eq("********")
end
+ it "includes tool usage in used_by" do
+ tool = Fabricate(:ai_tool, secret_contracts: [{ alias: "api_key" }])
+ AiToolSecretBinding.create!(ai_tool: tool, alias: "api_key", ai_secret_id: ai_secret.id)
+
+ get "/admin/plugins/discourse-ai/ai-secrets.json"
+
+ json = response.parsed_body
+ used_by = json["ai_secrets"][0]["used_by"]
+ expect(used_by.map { |item| item["type"] }).to include("tool")
+ end
+
it "requires admin" do
sign_in(user)
get "/admin/plugins/discourse-ai/ai-secrets.json"
@@ -116,5 +127,15 @@ RSpec.describe DiscourseAi::Admin::AiSecretsController do
expect(response.status).to eq(409)
expect(AiSecret.find_by(id: ai_secret.id)).to be_present
end
+
+ it "refuses to delete a secret used by a tool binding" do
+ tool = Fabricate(:ai_tool, secret_contracts: [{ alias: "api_key" }])
+ AiToolSecretBinding.create!(ai_tool: tool, alias: "api_key", ai_secret_id: ai_secret.id)
+
+ delete "/admin/plugins/discourse-ai/ai-secrets/#{ai_secret.id}.json"
+
+ expect(response.status).to eq(409)
+ expect(AiSecret.find_by(id: ai_secret.id)).to be_present
+ end
end
end
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_tools_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_tools_controller_spec.rb
index 9c81438517e..131314232f3 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_tools_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_tools_controller_spec.rb
@@ -3,6 +3,7 @@
RSpec.describe DiscourseAi::Admin::AiToolsController do
fab!(:llm_model)
fab!(:admin)
+ fab!(:ai_secret)
fab!(:ai_tool) do
AiTool.create!(
name: "Test Tool",
@@ -36,6 +37,7 @@ RSpec.describe DiscourseAi::Admin::AiToolsController do
expect(response.parsed_body["ai_tools"].length).to eq(AiTool.count)
expect(response.parsed_body["meta"]["presets"].length).to be > 0
expect(response.parsed_body["meta"]["llms"].length).to be > 0
+ expect(response.parsed_body["meta"]["ai_secrets"].length).to be > 0
end
end
@@ -66,6 +68,21 @@ RSpec.describe DiscourseAi::Admin::AiToolsController do
expect(response).to have_http_status(:not_found)
end
+
+ it "does not include secret bindings in export payload" do
+ ai_tool.update!(secret_contracts: [{ alias: "external_api_key" }])
+ AiToolSecretBinding.create!(
+ ai_tool: ai_tool,
+ alias: "external_api_key",
+ ai_secret_id: ai_secret.id,
+ )
+
+ get "/admin/plugins/discourse-ai/ai-tools/#{ai_tool.id}/export.json"
+
+ expect(response).to be_successful
+ expect(response.parsed_body["ai_tool"]["secret_contracts"]).to be_present
+ expect(response.parsed_body["ai_tool"]["secret_bindings"]).to be_nil
+ end
end
describe "POST #import" do
@@ -146,6 +163,35 @@ RSpec.describe DiscourseAi::Admin::AiToolsController do
expect(existing_tool.name).to eq("Imported Tool")
expect(existing_tool.description).to eq("An imported test tool")
end
+
+ it "prunes orphan bindings when force import changes contracts" do
+ existing_tool =
+ AiTool.create!(
+ name: "Existing Tool",
+ tool_name: "imported_tool",
+ description: "Existing tool",
+ script: "function invoke(params) { return 'existing'; }",
+ summary: "Existing summary",
+ created_by_id: admin.id,
+ secret_contracts: [{ alias: "old_key" }],
+ )
+ AiToolSecretBinding.create!(
+ ai_tool: existing_tool,
+ alias: "old_key",
+ ai_secret_id: ai_secret.id,
+ )
+
+ attrs = import_attributes.merge(secret_contracts: [{ alias: "new_key" }])
+
+ post "/admin/plugins/discourse-ai/ai-tools/import.json?force=true",
+ params: { ai_tool: attrs }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(AiToolSecretBinding.where(ai_tool: existing_tool).pluck(:alias)).to be_empty
+ end
end
describe "POST #create" do
@@ -174,6 +220,26 @@ RSpec.describe DiscourseAi::Admin::AiToolsController do
expect(response.parsed_body["ai_tool"]["tool_name"]).to eq("test_tool_1")
end
+ it "creates a new AiTool with secret bindings" do
+ attrs =
+ valid_attributes.merge(
+ secret_contracts: [{ alias: "weather_api_key" }],
+ secret_bindings: [{ alias: "weather_api_key", ai_secret_id: ai_secret.id }],
+ )
+
+ post "/admin/plugins/discourse-ai/ai-tools.json",
+ params: { ai_tool: attrs }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:created)
+ tool_id = response.parsed_body.dig("ai_tool", "id")
+ binding = AiToolSecretBinding.find_by(ai_tool_id: tool_id, alias: "weather_api_key")
+ expect(binding).to be_present
+ expect(binding.ai_secret_id).to eq(ai_secret.id)
+ end
+
it "logs the creation with StaffActionLogger" do
expect {
post "/admin/plugins/discourse-ai/ai-tools.json",
@@ -294,6 +360,21 @@ RSpec.describe DiscourseAi::Admin::AiToolsController do
expect(history.subject).to eq("Updated Tool")
end
+ it "prunes orphan bindings when contracts are removed" do
+ ai_tool.update!(secret_contracts: [{ alias: "old_key" }])
+ AiToolSecretBinding.create!(ai_tool: ai_tool, alias: "old_key", ai_secret_id: ai_secret.id)
+
+ put "/admin/plugins/discourse-ai/ai-tools/#{ai_tool.id}.json",
+ params: {
+ ai_tool: {
+ secret_contracts: [],
+ },
+ }
+
+ expect(response).to be_successful
+ expect(AiToolSecretBinding.where(ai_tool: ai_tool).count).to eq(0)
+ end
+
context "when updating an enum parameters" do
it "updates the enum fixed values" do
put "/admin/plugins/discourse-ai/ai-tools/#{ai_tool.id}.json",
@@ -406,5 +487,62 @@ RSpec.describe DiscourseAi::Admin::AiToolsController do
expect(response.status).to eq(400)
expect(response.parsed_body["errors"].to_s).to include("Error executing the tool")
end
+
+ it "fails when a required secret alias is missing" do
+ ai_tool.update!(
+ secret_contracts: [{ alias: "external_api_key" }],
+ script: "function invoke() { return secrets.get('external_api_key'); }",
+ )
+
+ post "/admin/plugins/discourse-ai/ai-tools/#{ai_tool.id}/test.json", params: {}
+
+ expect(response.status).to eq(400)
+ expect(response.parsed_body["errors"].to_s).to include("Missing required credential bindings")
+ end
+
+ it "returns custom_raw when the tool sets it" do
+ ai_tool.update!(
+ script:
+ "function invoke(params) { chain.setCustomRaw('![image](upload://abc123)'); return { status: 'ok' }; }",
+ )
+
+ post "/admin/plugins/discourse-ai/ai-tools/#{ai_tool.id}/test.json", params: {}
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["output"]).to eq("status" => "ok")
+ expect(response.parsed_body["custom_raw"]).to eq("![image](upload://abc123)")
+ end
+
+ it "does not include custom_raw when not set" do
+ post "/admin/plugins/discourse-ai/ai-tools/#{ai_tool.id}/test.json",
+ params: {
+ parameters: {
+ input: "test",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).not_to have_key("custom_raw")
+ end
+
+ it "uses in-flight secret_bindings for testing" do
+ ai_tool.update!(
+ secret_contracts: [{ alias: "external_api_key" }],
+ script: "function invoke() { return { key: secrets.get('external_api_key') }; }",
+ )
+
+ post "/admin/plugins/discourse-ai/ai-tools/#{ai_tool.id}/test.json",
+ params: {
+ ai_tool: {
+ secret_bindings: [{ alias: "external_api_key", ai_secret_id: ai_secret.id }],
+ },
+ }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["output"]["key"]).to eq(ai_secret.secret)
+ end
end
end
diff --git a/plugins/discourse-ai/spec/services/discourse_ai/persona_exporter_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/persona_exporter_spec.rb
index 8b35cc56ef4..e9c173272dc 100644
--- a/plugins/discourse-ai/spec/services/discourse_ai/persona_exporter_spec.rb
+++ b/plugins/discourse-ai/spec/services/discourse_ai/persona_exporter_spec.rb
@@ -19,6 +19,7 @@ RSpec.describe DiscourseAi::PersonaExporter do
custom_tool = export_json["custom_tools"].first
expect(custom_tool["identifier"]).to eq(ai_tool.tool_name)
expect(custom_tool["name"]).to eq(ai_tool.name)
+ expect(custom_tool["secret_contracts"]).to eq(ai_tool.secret_contracts)
end
end
diff --git a/plugins/discourse-ai/spec/services/discourse_ai/persona_importer_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/persona_importer_spec.rb
index 25b5b30b4ef..f6bcd05cd9f 100644
--- a/plugins/discourse-ai/spec/services/discourse_ai/persona_importer_spec.rb
+++ b/plugins/discourse-ai/spec/services/discourse_ai/persona_importer_spec.rb
@@ -5,7 +5,14 @@ RSpec.describe DiscourseAi::PersonaImporter do
describe "#import!" do
context "when importing a persona with a custom tool" do
- fab!(:ai_tool) { Fabricate(:ai_tool, name: "Giphy Searcher", tool_name: "giphy_search") }
+ fab!(:ai_tool) do
+ Fabricate(
+ :ai_tool,
+ name: "Giphy Searcher",
+ tool_name: "giphy_search",
+ secret_contracts: [{ alias: "giphy_api_key" }],
+ )
+ end
fab!(:ai_persona) { Fabricate(:ai_persona, tools: [["custom-#{ai_tool.id}", nil, false]]) }
let!(:export_json) { DiscourseAi::PersonaExporter.new(persona: ai_persona).export }
@@ -25,6 +32,7 @@ RSpec.describe DiscourseAi::PersonaImporter do
expect(imported_tool.tool_name).to eq("giphy_search")
expect(imported_tool.name).to eq("Giphy Searcher")
+ expect(imported_tool.secret_contracts).to eq([{ "alias" => "giphy_api_key" }])
end
end
@@ -135,6 +143,36 @@ RSpec.describe DiscourseAi::PersonaImporter do
existing_tool.reload
expect(existing_tool.name).to eq("Old Browser") # Name from export_json
end
+
+ it "prunes orphan secret bindings when contracts change on overwrite" do
+ secret = Fabricate(:ai_secret, name: "old_cred")
+ existing_tool.update!(
+ secret_contracts: [{ "alias" => "old_key" }, { "alias" => "new_key" }],
+ )
+ existing_tool.replace_secret_bindings!(
+ [
+ { alias: "old_key", ai_secret_id: secret.id },
+ { alias: "new_key", ai_secret_id: secret.id },
+ ],
+ created_by: Discourse.system_user,
+ )
+ expect(existing_tool.secret_bindings.count).to eq(2)
+
+ # The export payload only declares "new_key" in contracts, so "old_key" binding should be pruned
+ export_data = JSON.parse(export_json)
+ export_data["custom_tools"].each do |tool_data|
+ if tool_data["tool_name"] == "browse_web"
+ tool_data["secret_contracts"] = [{ "alias" => "new_key" }]
+ end
+ end
+
+ importer = described_class.new(json: export_data)
+ importer.import!(overwrite: true)
+
+ existing_tool.reload
+ expect(existing_tool.secret_contracts).to eq([{ "alias" => "new_key" }])
+ expect(existing_tool.secret_bindings.pluck(:alias)).to eq(["new_key"])
+ end
end
context "with invalid payload" do