Skip to main content

mouser_mode_api/
events.rs

1//! Events and listeners (EVENTS.md sections 3, 4, 8 and 11). Host events and
2//! plugin-emitted events go through one dispatcher with the same matching,
3//! permissions and ordering; a plugin hears its own emits unless a listener
4//! opts out. The rules a dispatcher enforces live here so host and tests
5//! share them.
6
7use serde_json::Value;
8use std::time::Instant;
9
10/// Emits deeper than this in one cause chain are dropped.
11pub const MAX_HOPS: u8 = 8;
12/// One emit reaches at most this many listeners.
13pub const MAX_FANOUT: usize = 64;
14/// Sync listener timeout: default and the most a listener may ask for.
15pub const SYNC_TIMEOUT_MS: u32 = 16;
16pub const SYNC_TIMEOUT_MAX_MS: u32 = 50;
17/// Bounded per-plugin outbound queue.
18pub const QUEUE_LEN: usize = 1024;
19
20#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub enum Origin {
22    Host,
23    Plugin { name: String, session: String },
24    Mcp { client: String },
25}
26
27/// Every event, from the host or emitted by a plugin or MCP client.
28#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
29pub struct Event {
30    pub seq: u64,
31    pub ts_us: u64,
32    pub tab: Option<u32>,
33    /// `shell.cwd_changed`, `input.key`, `commander.selection` ...
34    pub name: String,
35    pub payload: Value,
36    pub origin: Origin,
37    /// Seq of the event whose handler emitted this one.
38    pub cause: Option<u64>,
39    /// 0 for host input; +1 per emit made while handling an event.
40    pub hops: u8,
41    /// Emitted by a plugin or MCP client rather than observed by the host.
42    pub synthetic: bool,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
46pub enum Delivery {
47    #[default]
48    Async,
49    /// May answer `Handled`/`Pass` within `timeout_ms` (≤ 50).
50    Sync { timeout_ms: u32 },
51    /// Answers `EmitRequest`s.
52    Responder,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
56pub enum Coalesce {
57    Latest,
58    Sum,
59    Batch { max_ms: u32 },
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
63pub struct Filter {
64    /// Only while this plugin's mode is active.
65    pub mode_active: bool,
66    pub active_tab: bool,
67    pub mime: Option<String>,
68    /// Hear this plugin's own emits (default true).
69    pub from_self: Option<bool>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
73pub struct Listener {
74    /// Exact `shell.cwd_changed` or a trailing glob `input.*`.
75    pub event: String,
76    pub filter: Option<Filter>,
77    pub delivery: Delivery,
78    pub coalesce: Option<Coalesce>,
79    pub max_rate_hz: Option<u16>,
80}
81
82impl Listener {
83    pub fn on(event: &str) -> Self {
84        Self { event: event.into(), filter: None, delivery: Delivery::Async, coalesce: None, max_rate_hz: None }
85    }
86
87    pub fn matches(&self, name: &str) -> bool {
88        matches(&self.event, name)
89    }
90
91    pub fn hears_self(&self) -> bool {
92        self.filter.as_ref().and_then(|f| f.from_self).unwrap_or(true)
93    }
94}
95
96/// `pattern` is exact, `*`, or ends in `.*` (any name below that prefix).
97pub fn matches(pattern: &str, name: &str) -> bool {
98    match pattern.strip_suffix('*') {
99        Some("") => true,
100        Some(prefix) => prefix.ends_with('.') && name.starts_with(prefix),
101        None => pattern == name,
102    }
103}
104
105/// A custom event a plugin declares in `Hello.emits`.
106#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
107pub struct EventDecl {
108    pub name: String,
109    /// JSON schema of the payload, shown by MCP `events_list`.
110    pub schema: Option<Value>,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
114pub enum EmitResult {
115    Accepted {
116        delivered: u32,
117    },
118    Throttled,
119    Denied(String),
120    /// Over [`MAX_HOPS`].
121    Loop,
122}
123
124/// Facts only the host can assert: never emitted by a plugin or MCP client.
125pub const HOST_FACTS: &[&str] =
126    &["shell.", "term.", "agent.", "approval.", "tab.", "plugin.", "models.", "frame.", "fs.", "proc.", "view.", "media."];
127
128/// Input-style events a plugin may synthesize into its own mode.
129pub const SELF_INPUT: &[&str] = &["input.key", "input.text", "ui.action", "input.scroll", "timer.fired"];
130
131/// Whether `plugin` (which declared `declared`) may emit `name`. `into`
132/// names the mode a synthetic input event targets (`None`: own mode);
133/// `granted` holds `events.inject:<plugin>` grants.
134pub fn may_emit(plugin: &str, declared: &[EventDecl], name: &str, into: Option<&str>, granted: &[String]) -> Result<(), String> {
135    if HOST_FACTS.iter().any(|p| name.starts_with(p)) {
136        return Err(format!("{name} is a host event; plugins can't emit it"));
137    }
138    if SELF_INPUT.contains(&name) {
139        return match into {
140            None => Ok(()),
141            Some(t) if t == plugin => Ok(()),
142            Some(t) if granted.iter().any(|g| *g == format!("events.inject:{t}")) => Ok(()),
143            Some(t) => Err(format!("injecting {name} into {t} needs events.inject:{t}")),
144        };
145    }
146    let own = name.strip_prefix(plugin).is_some_and(|r| r.starts_with('.'));
147    if !own {
148        return Err(format!("{name} is outside {plugin}'s namespace"));
149    }
150    if !declared.iter().any(|d| d.name == name) {
151        return Err(format!("{name} was not declared in emits"));
152    }
153    Ok(())
154}
155
156/// Hop count for an emit made while handling `cause`, or `None` (a loop).
157pub fn next_hops(cause_hops: u8) -> Option<u8> {
158    let h = cause_hops.saturating_add(1);
159    (h <= MAX_HOPS).then_some(h)
160}
161
162/// Emit rate per plugin: 200/s sustained, bursts of 1000.
163#[derive(Debug, Clone)]
164pub struct RateLimit {
165    tokens: f64,
166    rate: f64,
167    burst: f64,
168    last: Instant,
169}
170
171impl RateLimit {
172    pub fn new(now: Instant) -> Self {
173        Self::with(200.0, 1000.0, now)
174    }
175
176    pub fn with(rate: f64, burst: f64, now: Instant) -> Self {
177        Self { tokens: burst, rate, burst, last: now }
178    }
179
180    /// Take a token; false: throttled.
181    pub fn take(&mut self, now: Instant) -> bool {
182        let dt = now.saturating_duration_since(self.last).as_secs_f64();
183        self.last = now;
184        self.tokens = (self.tokens + dt * self.rate).min(self.burst);
185        if self.tokens >= 1.0 {
186            self.tokens -= 1.0;
187            true
188        } else {
189            false
190        }
191    }
192}