1use serde_json::Value;
8use std::time::Instant;
9
10pub const MAX_HOPS: u8 = 8;
12pub const MAX_FANOUT: usize = 64;
14pub const SYNC_TIMEOUT_MS: u32 = 16;
16pub const SYNC_TIMEOUT_MAX_MS: u32 = 50;
17pub 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#[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 pub name: String,
35 pub payload: Value,
36 pub origin: Origin,
37 pub cause: Option<u64>,
39 pub hops: u8,
41 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 Sync { timeout_ms: u32 },
51 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 pub mode_active: bool,
66 pub active_tab: bool,
67 pub mime: Option<String>,
68 pub from_self: Option<bool>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
73pub struct Listener {
74 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
96pub 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#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
107pub struct EventDecl {
108 pub name: String,
109 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 Loop,
122}
123
124pub const HOST_FACTS: &[&str] =
126 &["shell.", "term.", "agent.", "approval.", "tab.", "plugin.", "models.", "frame.", "fs.", "proc.", "view.", "media."];
127
128pub const SELF_INPUT: &[&str] = &["input.key", "input.text", "ui.action", "input.scroll", "timer.fired"];
130
131pub 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
156pub 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#[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 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}