Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

feat(plugins): route declared chat commands (#5043)

Gabe Kangas297b6d6d248a
diff --git a/pluginhost/pluginevents.go b/pluginhost/pluginevents.go
index 634b7893c7..4c0fff5d8c 100644
--- a/pluginhost/pluginevents.go
+++ b/pluginhost/pluginevents.go
@@ -18,19 +18,9 @@ import (
// TypeScript interfaces (ChatMessage, User, …) so a plugin's typed
// handlers receive exactly the documented JSON.
-// pluginChatMessage is the chat.message.received (and chat.filter) payload.
-// It carries the full sender identity as a nested object plus the originating
-// connection's clientId so plugins can do reliable per-user state and
-// moderation (e.g. gate on scopes) and reply privately to the sender via
-// owncast.chat.sendTo / replyTo. User is nil for the rare message with no
-// associated account.
-type pluginChatMessage struct {
- ID string `json:"id"`
- User *plugins.HostUser `json:"user,omitempty"`
- ClientID uint `json:"clientId,omitempty"`
- Body string `json:"body"`
- Timestamp string `json:"timestamp"`
-}
+// pluginChatMessage aliases the shared wire type used by chat notifications,
+// filters, command events, and chat history.
+type pluginChatMessage = plugins.HostChatMessage
// The user wire shape lives once, as plugins.HostUser (the type chat.history()
// and the users.list()/get() directory also return). These event payloads
@@ -88,7 +78,7 @@ func newPluginChatFilter(pluginDispatcher *plugins.Dispatcher) dispatcher.Filter
if !msg.Timestamp.IsZero() {
timestamp = msg.Timestamp.UTC().Format(time.RFC3339Nano)
}
- final, allowed, _ := pluginDispatcher.Filter(ctx, plugins.EventChatMessageReceived, pluginChatMessage{ID: msg.ID, User: toHostUserPtr(msg.User), ClientID: msg.ClientID, Body: msg.Body, Timestamp: timestamp})
+ final, allowed, _ := pluginDispatcher.Filter(ctx, plugins.EventChatMessageReceived, pluginChatMessage{ID: msg.ID, User: toHostUserPtr(msg.User), ClientID: uint64(msg.ClientID), Body: msg.Body, Timestamp: timestamp})
if !allowed {
return false
}
@@ -128,16 +118,9 @@ func filteredBody(final any, fallback string) string {
return fallback
}
-// moderatorScope is the user scope that grants moderator privileges; mod-only
-// commands are hidden from non-moderators in the help listing.
-const moderatorScope = "MODERATOR"
-
-// newHelpResponder returns a dispatcher.Listener that answers the unified
-// `!help` chat command. The host owns !help (no plugin implements it): it
-// aggregates command metadata across all loaded plugins — which no single
-// sandboxed plugin could see — and posts the list as a system message via
-// `post`. snapshot yields the current loaded plugins; post sends a system
-// chat message.
+// newHelpResponder returns a listener for Owncast's built-in `!help` response.
+// The same message continues through ordinary chat and command dispatch, so
+// plugins may add their own responses.
func newHelpResponder(snapshot func() []*plugins.Loaded, post func(text string)) dispatcher.Listener {
return func(ctx context.Context, e dispatcher.Event) {
webhookEvent, ok := e.Payload.(webhooks.WebhookEvent)
@@ -159,7 +142,7 @@ func newHelpResponder(snapshot func() []*plugins.Loaded, post func(text string))
isMod := false
if data.User != nil {
for _, s := range data.User.Scopes {
- if s == moderatorScope {
+ if s == models.ModeratorScopeKey {
isMod = true
break
}
@@ -192,7 +175,14 @@ func newPluginEventListener(pluginDispatcher *plugins.Dispatcher) dispatcher.Lis
// here would re-run every plugin's on_filter on a message
// that already survived once, doubling work and double-
// triggering rate-limit logic (slow-mode, etc.).
- go pluginDispatcher.Notify(ctx, pe.eventType, pe.payload)
+ go func(pe pluginEvent) {
+ pluginDispatcher.Notify(ctx, pe.eventType, pe.payload)
+ if pe.eventType == plugins.EventChatMessageReceived {
+ if msg, ok := pe.payload.(pluginChatMessage); ok {
+ pluginDispatcher.DispatchCommands(ctx, msg)
+ }
+ }
+ }(pe)
}
}
}
@@ -355,7 +345,7 @@ func chatMessageEvent(evt webhooks.WebhookEvent) []pluginEvent {
msg := pluginChatMessage{
ID: data.ID,
User: toHostUserPtr(data.User),
- ClientID: data.ClientID,
+ ClientID: uint64(data.ClientID),
Body: data.RawBody,
Timestamp: formatTimePtr(data.Timestamp),
}
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.go
index 4be458079a..9123db3abc 100644
--- a/pluginhost/pluginhost.go
+++ b/pluginhost/pluginhost.go
@@ -648,9 +648,9 @@ func New(ctx context.Context, deps Deps) (*Host, error) {
deps.Events.AddListener(newPluginEventListener(pluginDispatcher))
deps.Events.AddFilter(newPluginChatFilter(pluginDispatcher))
- // Host-owned `!help`: list every plugin's chat commands (no single plugin
- // can see across the sandbox, so the host aggregates and answers). Posts a
- // system message — works even when no plugin holds chat.send.
+ // Built-in `!help`: aggregate every plugin's declarations into a system
+ // message. The original message also reaches ordinary chat and matching
+ // plugin command handlers.
deps.Events.AddListener(newHelpResponder(manager.Snapshot, func(text string) {
if err := deps.Chat.SendSystemMessage(text, false); err != nil {
log.Errorln("plugin !help:", err)
diff --git a/services/plugins/commands.go b/services/plugins/commands.go
new file mode 100644
index 0000000000..9017fe49fb
--- /dev/null
+++ b/services/plugins/commands.go
@@ -0,0 +1,176 @@
+package plugins
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+type commandCooldownKey struct {
+ command string
+ user string
+}
+
+const (
+ commandCooldownSweepIntervalMs int64 = 60_000
+ commandModeratorScope = "MODERATOR"
+)
+
+type commandTarget struct {
+ plugin *Loaded
+ event CommandEvent
+}
+
+// DispatchCommands matches an accepted human chat message against every loaded
+// plugin's command declarations and delivers chat.command directly to each
+// match. Duplicate declarations across plugins intentionally all receive it.
+func (d *Dispatcher) DispatchCommands(ctx context.Context, msg HostChatMessage) {
+ targets := d.commandTargets(msg)
+
+ var wg sync.WaitGroup
+ for _, target := range targets {
+ wg.Add(1)
+ go func(target commandTarget) {
+ defer wg.Done()
+ deliverCommand(ctx, target.plugin, target.event)
+ }(target)
+ }
+ wg.Wait()
+}
+
+func (d *Dispatcher) commandTargets(msg HostChatMessage) []commandTarget {
+ var targets []commandTarget
+ for _, p := range d.snapshot() {
+ if p == nil || p.Manifest == nil {
+ continue
+ }
+ for _, command := range p.Manifest.Commands {
+ event, matched := matchCommand(msg, command)
+ if !matched || !commandAllowed(msg, command) || !commandCooldownReady(p, msg, command) {
+ continue
+ }
+ targets = append(targets, commandTarget{plugin: p, event: event})
+ }
+ }
+ return targets
+}
+
+func matchCommand(msg HostChatMessage, command CommandInfo) (CommandEvent, bool) {
+ prefix := command.Prefix
+ if prefix == "" {
+ prefix = DefaultCommandPrefix
+ }
+ if !strings.HasPrefix(msg.Body, prefix) {
+ return CommandEvent{}, false
+ }
+
+ rest := strings.TrimSpace(strings.TrimPrefix(msg.Body, prefix))
+ parts := strings.Fields(rest)
+ if len(parts) == 0 {
+ return CommandEvent{}, false
+ }
+ invokedAs := parts[0]
+ if !commandNameMatches(invokedAs, command.Name, command.CaseSensitive) {
+ matchedAlias := false
+ for _, alias := range command.Aliases {
+ if commandNameMatches(invokedAs, alias, command.CaseSensitive) {
+ matchedAlias = true
+ break
+ }
+ }
+ if !matchedAlias {
+ return CommandEvent{}, false
+ }
+ }
+
+ return CommandEvent{
+ Message: msg,
+ Command: command.Name,
+ InvokedAs: invokedAs,
+ Args: parts[1:],
+ ArgString: strings.TrimSpace(rest[len(invokedAs):]),
+ }, true
+}
+
+func commandNameMatches(called, declared string, caseSensitive bool) bool {
+ if caseSensitive {
+ return called == declared
+ }
+ return strings.EqualFold(called, declared)
+}
+
+func commandAllowed(msg HostChatMessage, command CommandInfo) bool {
+ if !command.ModOnly || msg.User == nil {
+ return !command.ModOnly
+ }
+ for _, scope := range msg.User.Scopes {
+ if scope == commandModeratorScope {
+ return true
+ }
+ }
+ return false
+}
+
+func commandCooldownReady(p *Loaded, msg HostChatMessage, command CommandInfo) bool {
+ if command.CooldownMs <= 0 {
+ return true
+ }
+ now, err := time.Parse(time.RFC3339Nano, msg.Timestamp)
+ if err != nil {
+ return true
+ }
+
+ nowMs := now.UnixMilli()
+ key := commandCooldownKey{command: command.Name, user: commandUserKey(msg)}
+ p.commandCooldownMu.Lock()
+ defer p.commandCooldownMu.Unlock()
+ if p.commandCooldowns == nil {
+ p.commandCooldowns = make(map[commandCooldownKey]int64)
+ }
+ if p.commandCooldownSweep == 0 || nowMs-p.commandCooldownSweep >= commandCooldownSweepIntervalMs {
+ for existing, expiresAt := range p.commandCooldowns {
+ if expiresAt <= nowMs {
+ delete(p.commandCooldowns, existing)
+ }
+ }
+ p.commandCooldownSweep = nowMs
+ }
+ if expiresAt, ok := p.commandCooldowns[key]; ok && nowMs < expiresAt {
+ return false
+ }
+ expiresAt := int64(math.MaxInt64)
+ if nowMs <= math.MaxInt64-command.CooldownMs {
+ expiresAt = nowMs + command.CooldownMs
+ }
+ p.commandCooldowns[key] = expiresAt
+ return true
+}
+
+func commandUserKey(msg HostChatMessage) string {
+ if msg.User != nil && msg.User.ID != "" {
+ return msg.User.ID
+ }
+ if msg.ClientID != 0 {
+ return "client:" + strconv.FormatUint(msg.ClientID, 10)
+ }
+ return "anonymous"
+}
+
+func deliverCommand(ctx context.Context, p *Loaded, event CommandEvent) {
+ envelope, err := json.Marshal(Envelope{EventType: EventChatCommand, Payload: event})
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "plugin %s: marshal command event failed: %v\n", p.Manifest.Slug, err)
+ return
+ }
+ if err := callOnEvent(ctx, p, envelope); err != nil &&
+ !errors.Is(err, errPluginNotLoaded) && !errors.Is(err, errPluginNoSuchExport) {
+ fmt.Fprintf(os.Stderr, "plugin %s: on_event(%s) failed: %v\n", p.Manifest.Slug, EventChatCommand, err)
+ }
+}
diff --git a/services/plugins/commands_test.go b/services/plugins/commands_test.go
new file mode 100644
index 0000000000..c854162db9
--- /dev/null
+++ b/services/plugins/commands_test.go
@@ -0,0 +1,112 @@
+package plugins
+
+import (
+ "math"
+ "reflect"
+ "testing"
+)
+
+func TestMatchCommand(t *testing.T) {
+ msg := HostChatMessage{Body: "?PING one two"}
+ command := CommandInfo{Name: "ping", Prefix: "?", Aliases: []string{"p"}}
+
+ event, matched := matchCommand(msg, command)
+ if !matched {
+ t.Fatal("case-insensitive command should match")
+ }
+ if event.Command != "ping" || event.InvokedAs != "PING" {
+ t.Fatalf("unexpected command identity: %+v", event)
+ }
+ if !reflect.DeepEqual(event.Args, []string{"one", "two"}) || event.ArgString != "one two" {
+ t.Fatalf("unexpected arguments: %+v", event)
+ }
+
+ command.CaseSensitive = true
+ if _, matched := matchCommand(msg, command); matched {
+ t.Fatal("case-sensitive command should reject different casing")
+ }
+ if _, matched := matchCommand(HostChatMessage{Body: "?unknown"}, command); matched {
+ t.Fatal("unknown command should not match")
+ }
+}
+
+func TestCommandTargetsAllowDuplicatesAndIgnoreUnknown(t *testing.T) {
+ first := &Loaded{Manifest: &Manifest{Slug: "first", Commands: []CommandInfo{{Name: "ping"}}}}
+ second := &Loaded{Manifest: &Manifest{Slug: "second", Commands: []CommandInfo{{Name: "ping"}}}}
+ dispatcher := NewDispatcher([]*Loaded{first, second})
+
+ targets := dispatcher.commandTargets(HostChatMessage{Body: "!ping"})
+ if len(targets) != 2 {
+ t.Fatalf("duplicate declarations should both match, got %d targets", len(targets))
+ }
+ if targets[0].plugin != first || targets[1].plugin != second {
+ t.Fatalf("unexpected command targets: %+v", targets)
+ }
+ if targets := dispatcher.commandTargets(HostChatMessage{Body: "!unknown"}); len(targets) != 0 {
+ t.Fatalf("unknown command should be silent, got %d targets", len(targets))
+ }
+ first.Manifest.Commands = append(first.Manifest.Commands, CommandInfo{Name: "help"})
+ if targets := dispatcher.commandTargets(HostChatMessage{Body: HelpCommand}); len(targets) != 1 || targets[0].plugin != first {
+ t.Fatalf("built-in help command should remain available to plugins: %+v", targets)
+ }
+}
+
+func TestCommandModeratorGate(t *testing.T) {
+ command := CommandInfo{Name: "announce", ModOnly: true}
+ if commandAllowed(HostChatMessage{}, command) {
+ t.Fatal("anonymous sender must not pass moderator gate")
+ }
+ viewer := HostChatMessage{User: &HostUser{ID: "viewer"}}
+ if commandAllowed(viewer, command) {
+ t.Fatal("viewer must not pass moderator gate")
+ }
+ moderator := HostChatMessage{User: &HostUser{ID: "mod", Scopes: []string{commandModeratorScope}}}
+ if !commandAllowed(moderator, command) {
+ t.Fatal("moderator should pass moderator gate")
+ }
+}
+
+func TestCommandCooldownIsolation(t *testing.T) {
+ loaded := &Loaded{}
+ command := CommandInfo{Name: "ping", CooldownMs: 1_000}
+ message := func(user, timestamp string) HostChatMessage {
+ return HostChatMessage{User: &HostUser{ID: user}, Timestamp: timestamp}
+ }
+
+ if !commandCooldownReady(loaded, message("u1", "2026-01-01T00:00:00Z"), command) {
+ t.Fatal("first invocation should run")
+ }
+ if commandCooldownReady(loaded, message("u1", "2026-01-01T00:00:00.500Z"), command) {
+ t.Fatal("same user and command should be cooling down")
+ }
+ if !commandCooldownReady(loaded, message("u2", "2026-01-01T00:00:00.500Z"), command) {
+ t.Fatal("cooldown must be isolated by user")
+ }
+ other := CommandInfo{Name: "other", CooldownMs: 1_000}
+ if !commandCooldownReady(loaded, message("u1", "2026-01-01T00:00:00.500Z"), other) {
+ t.Fatal("cooldown must be isolated by command")
+ }
+ if !commandCooldownReady(loaded, message("u1", "2026-01-01T00:00:01Z"), command) {
+ t.Fatal("invocation should run when cooldown expires")
+ }
+
+ if !commandCooldownReady(loaded, message("u3", "2026-01-01T00:02:00Z"), command) {
+ t.Fatal("later invocation should run")
+ }
+ if len(loaded.commandCooldowns) != 1 {
+ t.Fatalf("expired cooldown entries were not pruned: %+v", loaded.commandCooldowns)
+ }
+}
+
+func TestCommandCooldownOverflow(t *testing.T) {
+ loaded := &Loaded{}
+ command := CommandInfo{Name: "ping", CooldownMs: math.MaxInt64}
+ first := HostChatMessage{User: &HostUser{ID: "u1"}, Timestamp: "2026-01-01T00:00:00Z"}
+ if !commandCooldownReady(loaded, first, command) {
+ t.Fatal("first invocation should run")
+ }
+ second := HostChatMessage{User: &HostUser{ID: "u1"}, Timestamp: "2026-01-01T00:00:01Z"}
+ if commandCooldownReady(loaded, second, command) {
+ t.Fatal("overflowing cooldown must remain active")
+ }
+}
diff --git a/services/plugins/contract_test.go b/services/plugins/contract_test.go
index 18f559dae2..cf1194aede 100644
--- a/services/plugins/contract_test.go
+++ b/services/plugins/contract_test.go
@@ -15,21 +15,13 @@ import (
"testing"
)
-// This guards against this vendored copy of the plugin runtime silently
-// drifting from the upstream SDK's wire contract. services/plugins is a copy
-// of github.com/owncast/plugin-sdk's host-runtime/plugin package; the
-// implementation is allowed to fork for Owncast integration, but the *wire
-// contract* (host-function names, permission identifiers, serialized type
-// shapes) must stay identical, or plugins and the TypeScript SDK break.
+// This guards the plugin wire contract against accidental drift. hostfns.go is
+// the Go source of truth for host-function names, permission identifiers, and
+// serialized type shapes. The TypeScript SDK and wire-protocol documentation
+// mirror it.
//
-// plugin-contract.json is the SDK's published contract, copied in verbatim.
-// This test re-derives the contract from THIS repo's hostfns.go and compares.
-// If it fails, this copy has fallen behind (or ahead of) the SDK — re-sync the
-// runtime and copy the SDK's host-runtime/plugin/plugin-contract.json here.
-//
-// The extractor below is a verbatim copy of the SDK's
-// host-runtime/plugin/contract_test.go extractor; keep it identical so the
-// produced contract is comparable byte-for-byte.
+// plugin-contract.json is the generated fingerprint. Regenerate it only for an
+// intentional contract change by running this test with UPDATE_CONTRACT=1.
// hostFnNameRe matches an actual host-function name exactly — not the error
// strings ("owncast_x from %s: ...") that also begin with the prefix.
@@ -178,27 +170,29 @@ func TestPluginContractMatchesSDK(t *testing.T) {
t.Fatalf("read hostfns.go: %v", err)
}
gotJSON := marshalContract(t, buildContractFromSource(t, string(src)))
+ contractPath := filepath.Join(repoRoot, "services/plugins/plugin-contract.json")
+ if os.Getenv("UPDATE_CONTRACT") == "1" {
+ if err := os.WriteFile(contractPath, gotJSON, 0o644); err != nil {
+ t.Fatalf("update plugin-contract.json: %v", err)
+ }
+ return
+ }
- want, err := os.ReadFile(filepath.Join(repoRoot, "services/plugins/plugin-contract.json"))
+ want, err := os.ReadFile(contractPath)
if err != nil {
t.Fatalf("read plugin-contract.json: %v", err)
}
if string(normalizeNewlines(gotJSON)) != string(normalizeNewlines(want)) {
- t.Errorf(`Owncast's bundled plugin runtime is out of sync with the plugin SDK.
+ t.Errorf(`The plugin wire contract snapshot is stale.
+
+The host functions, permissions, or data shapes derived from
+services/plugins/hostfns.go no longer match plugin-contract.json.
-The plugin host functions, permissions, or data shapes in services/plugins no
-longer match what the SDK (github.com/owncast/plugin-sdk) publishes, so plugins
-built against the SDK may not work correctly against this build of Owncast.
+If the change is intentional, regenerate the snapshot:
-This usually means a change landed in the SDK but wasn't copied here yet (or a
-change was made here without updating the SDK). To fix:
+ UPDATE_CONTRACT=1 go test ./services/plugins/ -run TestPluginContractMatchesSDK
- 1. Make the change in the SDK first and regenerate its snapshot there:
- UPDATE_CONTRACT=1 go test ./plugin/ -run TestPluginContract
- 2. Copy the SDK's host-runtime/plugin/plugin-contract.json over
- services/plugins/plugin-contract.json here, and bring
- services/plugins/hostfns.go in line with the SDK.
- 3. Re-run this test — it passes once the two sides match.`)
+Then rerun this test without UPDATE_CONTRACT.`)
}
}
diff --git a/services/plugins/dispatcher_test.go b/services/plugins/dispatcher_test.go
index 09f6aea4fc..149a3d54dd 100644
--- a/services/plugins/dispatcher_test.go
+++ b/services/plugins/dispatcher_test.go
@@ -15,7 +15,7 @@ import (
func TestReservedEventTypes_CoversCoreEvents(t *testing.T) {
for _, e := range []string{
EventChatMessageReceived, EventChatUserJoined, EventChatUserParted,
- EventChatUserRenamed, EventChatMessageModerated, EventStreamStarted,
+ EventChatUserRenamed, EventChatMessageModerated, EventChatCommand, EventStreamStarted,
EventStreamStopped, EventStreamTitleChanged, EventSSEConnect,
EventSSEDisconnect, EventTick, EventTimerFire, EventFediverseFollow,
EventFediverseLike, EventFediverseRepost, EventFediverseMention,
diff --git a/services/plugins/engines/javascript/engine.wasm b/services/plugins/engines/javascript/engine.wasm
index 27be298e18..975052828f 100644
Binary files a/services/plugins/engines/javascript/engine.wasm and b/services/plugins/engines/javascript/engine.wasm differ
diff --git a/services/plugins/engines/python/engine.wasm b/services/plugins/engines/python/engine.wasm
index fe6d11baf2..6e796a5dc7 100644
Binary files a/services/plugins/engines/python/engine.wasm and b/services/plugins/engines/python/engine.wasm differ
diff --git a/services/plugins/events.go b/services/plugins/events.go
index f9fd622037..b79766a79a 100644
--- a/services/plugins/events.go
+++ b/services/plugins/events.go
@@ -11,6 +11,11 @@ const (
EventChatUserRenamed = "chat.user.renamed"
EventChatMessageModerated = "chat.message.moderated"
+ // EventChatCommand is delivered directly to each plugin whose registered
+ // command matches an accepted chat message. Internal: the guest SDK maps
+ // the canonical command name back to the author's handler.
+ EventChatCommand = "chat.command"
+
// Stream lifecycle events.
EventStreamStarted = "stream.started"
EventStreamStopped = "stream.stopped"
@@ -54,6 +59,7 @@ var reservedEventTypes = map[string]bool{
EventChatUserParted: true,
EventChatUserRenamed: true,
EventChatMessageModerated: true,
+ EventChatCommand: true,
EventStreamStarted: true,
EventStreamStopped: true,
EventStreamTitleChanged: true,
diff --git a/services/plugins/help.go b/services/plugins/help.go
index 2edc322954..59371482ff 100644
--- a/services/plugins/help.go
+++ b/services/plugins/help.go
@@ -5,15 +5,17 @@ import (
"strings"
)
-// HelpCommand is the chat command that triggers the unified command listing.
-// The host owns it (no plugin needs to implement it); a plugin can't shadow it.
-const HelpCommand = "!help"
+const (
+ DefaultCommandPrefix = "!"
+ HelpCommand = DefaultCommandPrefix + "help"
+ HelpCommandAlias = DefaultCommandPrefix + "commands"
+)
// IsHelpCommand reports whether a chat message body is the help command. Matched
// case-insensitively and trim-tolerant; "!commands" is accepted as an alias.
func IsHelpCommand(body string) bool {
b := strings.ToLower(strings.TrimSpace(body))
- return b == HelpCommand || b == "!commands"
+ return b == HelpCommand || b == HelpCommandAlias
}
// BuildHelpMessage renders the unified command list aggregated across the given
@@ -48,7 +50,7 @@ func BuildHelpMessage(loaded []*Loaded, isModerator bool) string {
}
prefix := c.Prefix
if prefix == "" {
- prefix = "!"
+ prefix = DefaultCommandPrefix
}
// Markdown: backticked command, em-dash description. System
// messages are rendered (RenderBody), so this becomes a code span
diff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.go
index dc805fb92c..ec1a74829a 100644
--- a/services/plugins/hostfns.go
+++ b/services/plugins/hostfns.go
@@ -191,6 +191,19 @@ type FediversePayload struct {
Link string `json:"link,omitempty"`
}
+// CommandInfo is one command declared by a plugin. The host uses this
+// registration data to match chat messages and dispatch command events.
+type CommandInfo struct {
+ Name string `json:"name"`
+ Prefix string `json:"prefix,omitempty"`
+ Description string `json:"description,omitempty"`
+ Usage string `json:"usage,omitempty"`
+ Aliases []string `json:"aliases,omitempty"`
+ ModOnly bool `json:"modOnly,omitempty"`
+ CaseSensitive bool `json:"caseSensitive,omitempty"`
+ CooldownMs int64 `json:"cooldownMs,omitempty"`
+}
+
// HostChatMessage is the shape returned by ChatHistory. It matches the
// onChatMessage / chat.message.received event payload: User is the full User
// object (nil for the rare message with no associated account), not a bare
@@ -199,10 +212,21 @@ type FediversePayload struct {
type HostChatMessage struct {
ID string `json:"id"`
User *HostUser `json:"user,omitempty"`
+ ClientID uint64 `json:"clientId,omitempty"`
Body string `json:"body"`
Timestamp string `json:"timestamp"`
}
+// CommandEvent is the internal chat.command payload delivered by the host to
+// every plugin whose declared command matches an accepted chat message.
+type CommandEvent struct {
+ Message HostChatMessage `json:"message"`
+ Command string `json:"command"`
+ InvokedAs string `json:"invokedAs"`
+ Args []string `json:"args"`
+ ArgString string `json:"argString"`
+}
+
// BrowserPushPayload is what a plugin asks Owncast to send via the
// configured browser push channel.
type BrowserPushPayload struct {
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index 64dfd9b2d7..e9b51f2ab8 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -58,11 +58,14 @@ type Loaded struct {
// releaseEngine drops this instance's reference on its shared compiled
// engine (nil for legacy self-contained wasm). Called exactly once by
// Close, after the instance itself is closed.
- releaseEngine func()
- mu sync.Mutex
- failureMu sync.Mutex
- filterFails int
- disabled atomic.Bool
+ releaseEngine func()
+ mu sync.Mutex
+ failureMu sync.Mutex
+ filterFails int
+ disabled atomic.Bool
+ commandCooldownMu sync.Mutex
+ commandCooldowns map[commandCooldownKey]int64
+ commandCooldownSweep int64
// pkgCloser holds the file-backed zip reader for .ocpkg plugins so the
// underlying file stays open for PublicFS / AssetsFS reads. nil for
// loose-files plugins. Closed by Loaded.Close.
@@ -1537,9 +1540,9 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
return nil, fail(err)
}
manifest.Subscriptions = runtime.Subscriptions
- // Command metadata is derived by the SDK and reported via register() (like
- // subscriptions); the host aggregates it for !help. Informational only, so
- // it isn't part of AgreesWith's security checks.
+ // Command registrations are derived by the SDK. They have no sidecar
+ // counterpart for AgreesWith to compare. Core uses them for matching,
+ // dispatch, gating, cooldowns, and help.
manifest.Commands = runtime.Commands
var adminGlobs []glob.Glob
diff --git a/services/plugins/manifest.go b/services/plugins/manifest.go
index a9d2617b38..1484f8fa12 100644
--- a/services/plugins/manifest.go
+++ b/services/plugins/manifest.go
@@ -27,18 +27,6 @@ type Subscriptions struct {
Filter []Subscription `json:"filter,omitempty"`
}
-// CommandInfo is one chat command a plugin advertises for the unified !help.
-// Reported by the SDK in register() output; purely informational (the plugin's
-// own router does the actual matching).
-type CommandInfo struct {
- Name string `json:"name"`
- Prefix string `json:"prefix,omitempty"`
- Description string `json:"description,omitempty"`
- Usage string `json:"usage,omitempty"`
- Aliases []string `json:"aliases,omitempty"`
- ModOnly bool `json:"modOnly,omitempty"`
-}
-
type ConfigField struct {
Type string `json:"type"`
Default any `json:"default,omitempty"`
@@ -78,10 +66,9 @@ type Manifest struct {
Description string `json:"description,omitempty"`
Bot BotConfig `json:"bot,omitempty"`
Subscriptions Subscriptions `json:"subscriptions"`
- // Commands is the plugin's chat-command metadata, derived by the SDK from
- // its defineCommands/plugin.commands table and reported via register() (not
- // authored in the sidecar manifest). The host aggregates these across
- // plugins to answer a unified !help.
+ // Commands is the plugin's command registration table, derived by the SDK
+ // and reported via register(). The host routes matching chat commands and
+ // aggregates the same declarations for !help.
Commands []CommandInfo `json:"commands,omitempty"`
Permissions []string `json:"permissions,omitempty"`
Config map[string]ConfigField `json:"config,omitempty"`
diff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.json
index 50403e4ccf..6e738005c1 100644
--- a/services/plugins/plugin-contract.json
+++ b/services/plugins/plugin-contract.json
@@ -75,6 +75,23 @@
"title": "string",
"url": "string"
},
+ "CommandEvent": {
+ "argString": "string",
+ "args": "[]string",
+ "command": "string",
+ "invokedAs": "string",
+ "message": "HostChatMessage"
+ },
+ "CommandInfo": {
+ "aliases": "[]string",
+ "caseSensitive": "bool",
+ "cooldownMs": "int64",
+ "description": "string",
+ "modOnly": "bool",
+ "name": "string",
+ "prefix": "string",
+ "usage": "string"
+ },
"Emote": {
"name": "string",
"url": "string"
@@ -105,6 +122,7 @@
},
"HostChatMessage": {
"body": "string",
+ "clientId": "uint64",
"id": "string",
"timestamp": "string",
"user": "*HostUser"
diff --git a/services/plugins/shared_engine_test.go b/services/plugins/shared_engine_test.go
index afbccd0a32..d76a37b3b1 100644
--- a/services/plugins/shared_engine_test.go
+++ b/services/plugins/shared_engine_test.go
@@ -305,33 +305,60 @@ module.exports = definePlugin({
}
}
-// TestSharedEngineReportsCommands verifies command metadata declared in a
-// plugin's command table flows SDK → engine register() → host manifest, so the
-// host can build !help.
-func TestSharedEngineReportsCommands(t *testing.T) {
+// TestSharedEngineReportsAndDispatchesCommands verifies that JS and Python
+// declarations reach core registration, avoid broad chat subscriptions, and
+// receive the targeted command event.
+func TestSharedEngineReportsAndDispatchesCommands(t *testing.T) {
ctx := context.Background()
compiledEngines.resetForTest(ctx)
t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
- env, _, _ := captureEnv()
+ env, sends, mu := captureEnv()
jsScript := `
const { definePlugin } = require("@owncast/plugin-sdk");
module.exports = definePlugin({
- commands: { uptime: { description: "Stream uptime", run: () => {} } },
+ commands: { uptime: { description: "Stream uptime", aliases: ["up"], run: (ctx) => ctx.reply("js:" + ctx.invokedAs + ":" + ctx.args.join(",")) } },
});`
- js := loadShared(t, ctx, env, RuntimeJavaScript, "js-cmds", jsScript, []string{})
+ js := loadShared(t, ctx, env, RuntimeJavaScript, "js-cmds", jsScript, []string{PermChatSend})
defer js.Close(ctx)
assertHasCommand(t, js, "uptime", "Stream uptime")
pyScript := `
-plugin.commands({"uptime": {"description": "Stream uptime", "run": lambda ctx: None}})
+plugin.commands({"uptime": {"description": "Stream uptime", "aliases": ["up"], "run": lambda ctx: ctx.reply("py:" + ctx.invoked_as + ":" + ",".join(ctx.args))}})
`
- py := loadShared(t, ctx, env, RuntimePython, "py-cmds", pyScript, []string{})
+ py := loadShared(t, ctx, env, RuntimePython, "py-cmds", pyScript, []string{PermChatSend})
defer py.Close(ctx)
assertHasCommand(t, py, "uptime", "Stream uptime")
- // And the host can render a unified help listing from it.
+ for _, loaded := range []*Loaded{js, py} {
+ if subscribed(loaded.Manifest.Subscriptions.Notify, EventChatMessageReceived) {
+ t.Errorf("%s: command declaration must not subscribe to ordinary chat", loaded.Manifest.Slug)
+ }
+ }
+
+ d := NewDispatcher([]*Loaded{js, py})
+ d.DispatchCommands(ctx, HostChatMessage{
+ ID: "m1",
+ User: &HostUser{ID: "u1", DisplayName: "alice"},
+ ClientID: 7,
+ Body: "!up one two",
+ Timestamp: "2026-01-01T00:00:00Z",
+ })
+
+ mu.Lock()
+ got := make(map[string]bool, len(*sends))
+ for _, send := range *sends {
+ got[send.Text] = true
+ }
+ mu.Unlock()
+ for _, want := range []string{"js:up:one,two", "py:up:one,two"} {
+ if !got[want] {
+ t.Errorf("duplicate command dispatch missing %q; got %+v", want, got)
+ }
+ }
+
+ // The host still aggregates the same registrations for its built-in help.
help := BuildHelpMessage([]*Loaded{js, py}, false)
if !strings.Contains(help, "`!uptime`") || !strings.Contains(help, "Stream uptime") {
t.Errorf("help should list the reported command:\n%s", help)