0
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-08-14 13:58:53 +08:00
discourse/plugins/discourse-ai/plugin.rb
Joffrey JAFFEUX 0914b9fb32
FEATURE: discourse-workflows (#40374)
Discourse Workflows is a visual automation plugin for admins. A workflow
is a
versioned graph made of trigger, condition, action, and utility nodes.

## Architecture

The plugin has three main responsibilities:

- Store and version workflow graphs.
- Render an admin editor from node metadata.
- Execute published workflow versions and record their results.

The graph is stored as workflow nodes plus connections. Each node has a
stable
type, a type version, editor position, configuration parameters,
optional
credential references, and direct runtime settings. Published workflows
create immutable versions that executions can safely use even after the
draft changes.

## Runtime Flow

A normal execution follows this path:

1. A trigger produces initial data from a Discourse event, schedule,
webhook, or
   manual run.
2. Trigger data is wrapped as workflow items.
3. The executor queues downstream nodes from the graph connections.
4. Each node receives input items and returns one array per output.
5. The executor records the step, stores node output for expressions,
and routes
   each output array to connected downstream nodes.
6. The execution finishes, fails, or enters a waiting state.

Waiting nodes persist enough execution context to resume later. Resume
requests
continue from the waiting node using the workflow snapshot saved with
the
execution, not the latest draft.

Expressions are resolved at runtime against the current item, node
parameters,
workflow variables, previous node outputs, and execution context. The
editor
stores expression values in parameters; node code should read them
through the
execution context instead of parsing parameter values directly.

## Adding nodes

- Workflow nodes, registered with
`DiscoursePluginRegistry.register_discourse_workflows_node`.

Core nodes live in `lib/discourse_workflows/nodes` and are registered
during
plugin initialization. Other plugins can add their own nodes when
`DiscourseWorkflows` is loaded.

## Node API

Nodes inherit from `DiscourseWorkflows::NodeType`. A node class is
responsible
for two things:

- Declaring its contract with `description(...)`.
- Implementing the runtime entry point for its node kind.

The description is the public contract between the node, editor,
validator, and
runtime. It should include:

- `name`: stable identifier, usually prefixed by `trigger:`, `action:`,
`condition:`, or `flow:`.
- `version`: implementation version used by stored workflow nodes.
- `defaults`: editor metadata such as icon and color.
- `group`: palette category.
- `inputs` and `outputs`: graph ports.
- `properties`: configuration fields rendered by the property engine.
- `credentials`: credential slots the node can use.
- `webhooks`: public or resume webhook declarations.
- `events`: Discourse events that should activate a trigger node.
- `capabilities`: feature flags such as manual triggering, waiting, or
current
  user access.
- `available`: optional availability gate for nodes backed by another
plugin or
  site setting.

Description data should stay declarative. Put business logic in the
runtime
entry point or helper classes.

### Action, Condition, And Flow Nodes

Action-like nodes implement `execute(exec_ctx)`. They receive input
items through
the execution context and return positional output arrays. A one-output
node
returns one outer array; a branching node returns one inner array per
branch.

### Trigger Nodes

Trigger nodes start executions. Event triggers declare `events` and
usually
implement:

- `valid?` to ignore events that should not run workflows.
- `matches?(trigger_ctx)` to compare event data with node configuration.
- `output` to produce the initial workflow item data.

### Webhook And Waiting Nodes

Webhook trigger nodes declare webhook metadata and produce initial data
from the
incoming request. Waiting nodes pause an execution and resume it through
a later
interaction or webhook.

### Dynamic Options

Nodes can provide dynamic property options with
`self.load_options_context(context)`. Use the context object to access
current
parameters, filtered credentials, the search filter, the current user,
guardian,
and shared helpers.

### Errors And Logs

Raise `DiscourseWorkflows::NodeError` for failures admins can act on,
such as
invalid configuration or missing Discourse records. Unexpected
exceptions fail
the current execution.

---------

---------

Co-authored-by: Renato Atilio <3530+renato@users.noreply.github.com>
Co-authored-by: Martin Brennan <martin@discourse.org>
Co-authored-by: Jordan Vidrine <30537603+jordanvidrine@users.noreply.github.com>
2026-05-28 19:44:50 +02:00

204 lines
7 KiB
Ruby
Vendored

# frozen_string_literal: true
# name: discourse-ai
# about: Enables integration between AI modules and features in Discourse
# meta_topic_id: 259214
# version: 0.0.1
# authors: Discourse
# url: https://github.com/discourse/discourse/tree/main/plugins/discourse-ai
require "tokenizers"
require "tiktoken_ruby"
require "discourse_ai/tokenizers"
require "ed25519"
enabled_site_setting :discourse_ai_enabled
register_asset "stylesheets/common/streaming.scss"
register_asset "stylesheets/common/ai-blinking-animation.scss"
register_asset "stylesheets/common/ai-user-settings.scss"
register_asset "stylesheets/common/ai-features.scss"
register_asset "stylesheets/admin/ai-features-editor.scss", :admin
register_asset "stylesheets/modules/translation/admin/translations.scss", :admin
register_asset "stylesheets/modules/ai-helper/common/ai-helper.scss"
register_asset "stylesheets/modules/ai-helper/desktop/ai-helper-fk-modals.scss", :desktop
register_asset "stylesheets/modules/ai-helper/mobile/ai-helper.scss", :mobile
register_asset "stylesheets/modules/summarization/common/ai-summary.scss"
register_asset "stylesheets/modules/summarization/desktop/ai-summary.scss", :desktop
register_asset "stylesheets/modules/summarization/common/ai-gists.scss"
register_asset "stylesheets/modules/ai-bot/common/bot-replies.scss"
register_asset "stylesheets/modules/ai-bot/common/ai-agent.scss"
register_asset "stylesheets/modules/ai-bot/common/ai-discobot-discoveries.scss"
register_asset "stylesheets/modules/ai-bot/mobile/ai-agent.scss", :mobile
register_asset "stylesheets/modules/ai-bot-conversations/common.scss"
register_asset "stylesheets/modules/ai-bot-conversations/docked-composer.scss"
register_asset "stylesheets/modules/embeddings/common/semantic-related-topics.scss"
register_asset "stylesheets/modules/embeddings/common/semantic-search.scss"
register_asset "stylesheets/modules/sentiment/common/dashboard.scss"
register_asset "stylesheets/modules/llms/common/ai-llms-editor.scss"
register_asset "stylesheets/modules/llms/common/ai-secret-selector.scss"
register_asset "stylesheets/modules/embeddings/common/ai-embedding-editor.scss"
register_asset "stylesheets/modules/llms/common/usage.scss"
register_asset "stylesheets/modules/llms/common/spam.scss"
register_asset "stylesheets/modules/llms/common/ai-llm-quotas.scss"
register_asset "stylesheets/modules/llms/common/ai-credit-bar.scss"
register_asset "stylesheets/modules/ai-bot/common/ai-tools.scss"
register_asset "stylesheets/modules/ai-bot/common/ai-artifact.scss"
module ::DiscourseAi
PLUGIN_NAME = "discourse-ai"
def self.public_asset_path(name)
File.expand_path(File.join(__dir__, "public", name))
end
end
Rails.autoloaders.main.push_dir(File.join(__dir__, "lib"), namespace: DiscourseAi)
require_relative "lib/engine"
require_relative "lib/configuration/module"
require_relative "lib/mcp/oauth_token_store"
require_relative "lib/mcp/oauth_discovery"
require_relative "lib/mcp/oauth_client_registration"
require_relative "lib/mcp/oauth_flow"
# Other plugins can register features through this register.
DiscoursePluginRegistry.define_filtered_register(:external_ai_features)
DiscourseAi::Configuration::Module::NAMES.each do |module_name|
register_site_setting_area("ai-features/#{module_name}")
end
after_initialize do
if defined?(Rack::MiniProfiler)
Rack::MiniProfiler.config.skip_paths << "/discourse-ai/ai-bot/artifacts"
end
# Avoid a mini_sql warning ("no type cast defined") by registering a halfvec text decoder.
if !GlobalSetting.skip_db?
if halfvec_oid = DB.query_single("SELECT oid FROM pg_type WHERE typname = 'halfvec'").first
DB.type_map.add_coder(PG::TextDecoder::String.new(oid: halfvec_oid))
end
end
# do not autoload this cause we may have no namespace
require_relative "discourse_automation/llm_triage"
require_relative "discourse_automation/llm_report"
require_relative "discourse_automation/ai_tool_action"
require_relative "discourse_automation/llm_agent_triage"
require_relative "discourse_automation/llm_tagger"
if respond_to?(:register_discourse_workflows_node)
register_discourse_workflows_node do
require_relative "discourse_workflows/nodes/ai_agent/v1"
DiscourseWorkflows::Nodes::AiAgent::V1
end
end
add_admin_route("discourse_ai.title", "discourse-ai", { use_new_show_route: true })
register_seedfu_fixtures(Rails.root.join("plugins/discourse-ai/db/fixtures/agents"))
[
DiscourseAi::Embeddings::EntryPoint.new,
DiscourseAi::Sentiment::EntryPoint.new,
DiscourseAi::AiHelper::EntryPoint.new,
DiscourseAi::Summarization::EntryPoint.new,
DiscourseAi::AiBot::EntryPoint.new,
DiscourseAi::AiModeration::EntryPoint.new,
DiscourseAi::Translation::EntryPoint.new,
DiscourseAi::Discover::EntryPoint.new,
].each { |a_module| a_module.inject_into(self) }
register_problem_check ProblemCheck::AiLlmStatus
#register_problem_check ProblemCheck::AiCreditSoftLimit
#register_problem_check ProblemCheck::AiCreditHardLimit
register_reviewable_type ReviewableAiChatMessage
register_reviewable_type ReviewableAiPost
register_reviewable_type ReviewableAiToolAction
on(:reviewable_transitioned_to) do |new_status, reviewable|
ModelAccuracy.adjust_model_accuracy(new_status, reviewable)
if DiscourseAi::AiModeration::SpamScanner.enabled?
DiscourseAi::AiModeration::SpamMetric.update(new_status, reviewable)
end
end
if Rails.env.test?
require_relative "spec/support/embeddings_generation_stubs"
require_relative "spec/support/fake_external_agent"
end
reloadable_patch do |plugin|
Guardian.prepend DiscourseAi::GuardianExtensions
Topic.prepend DiscourseAi::TopicExtensions
Post.prepend DiscourseAi::PostExtensions
end
# AI bots reply via `skip_guardian: true`, so the reachability warning is misleading.
register_modifier(:composer_mention_user_reason) do |reason, user|
DiscourseAi::AiBot::EntryPoint.all_bot_ids.include?(user.id) ? nil : reason
end
register_modifier(:post_should_secure_uploads?) do |_, _, topic|
if topic.private_message? && SharedAiConversation.exists?(target: topic)
false
else
# revert to default behavior
# even though this can be shortened this is the clearest way to express it
nil
end
end
add_api_key_scope(:ai, { update_agents: { actions: %w[discourse_ai/admin/ai_agents#update] } })
add_api_key_scope(
:ai,
{
manage_artifacts: {
actions: %w[
discourse_ai/admin/ai_artifacts#index
discourse_ai/admin/ai_artifacts#show
discourse_ai/admin/ai_artifacts#create
discourse_ai/admin/ai_artifacts#update
discourse_ai/admin/ai_artifacts#destroy
],
},
},
)
plugin_icons = %w[
chart-column
spell-check
language
images
far-copy
robot
info
bars-staggered
far-circle-question
face-smile
face-meh
face-angry
circle-info
]
plugin_icons.each { |icon| register_svg_icon(icon) }
add_model_callback(DiscourseAutomation::Automation, :after_save) do
DiscourseAi::Configuration::Feature.feature_cache.flush!
end
end