use serde_json::Value;
use std::time::Instant;
pub const MAX_HOPS: u8 = 8;
pub const MAX_FANOUT: usize = 64;
pub const SYNC_TIMEOUT_MS: u32 = 16;
pub const SYNC_TIMEOUT_MAX_MS: u32 = 50;
pub const QUEUE_LEN: usize = 1024;
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Origin {
Host,
Plugin { name: String, session: String },
Mcp { client: String },
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Event {
pub seq: u64,
pub ts_us: u64,
pub tab: Option<u32>,
pub name: String,
pub payload: Value,
pub origin: Origin,
pub cause: Option<u64>,
pub hops: u8,
pub synthetic: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum Delivery {
#[default]
Async,
Sync { timeout_ms: u32 },
Responder,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Coalesce {
Latest,
Sum,
Batch { max_ms: u32 },
}
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct Filter {
pub mode_active: bool,
pub active_tab: bool,
pub mime: Option<String>,
pub from_self: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Listener {
pub event: String,
pub filter: Option<Filter>,
pub delivery: Delivery,
pub coalesce: Option<Coalesce>,
pub max_rate_hz: Option<u16>,
}
impl Listener {
pub fn on(event: &str) -> Self {
Self { event: event.into(), filter: None, delivery: Delivery::Async, coalesce: None, max_rate_hz: None }
}
pub fn matches(&self, name: &str) -> bool {
matches(&self.event, name)
}
pub fn hears_self(&self) -> bool {
self.filter.as_ref().and_then(|f| f.from_self).unwrap_or(true)
}
}
pub fn matches(pattern: &str, name: &str) -> bool {
match pattern.strip_suffix('*') {
Some("") => true,
Some(prefix) => prefix.ends_with('.') && name.starts_with(prefix),
None => pattern == name,
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EventDecl {
pub name: String,
pub schema: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum EmitResult {
Accepted {
delivered: u32,
},
Throttled,
Denied(String),
Loop,
}
pub const HOST_FACTS: &[&str] = &["shell.", "term.", "agent.", "approval.", "tab.", "plugin.", "models.", "frame.", "fs.", "proc."];
pub const SELF_INPUT: &[&str] = &["input.key", "input.text", "ui.action", "input.scroll", "timer.fired"];
pub fn may_emit(plugin: &str, declared: &[EventDecl], name: &str, into: Option<&str>, granted: &[String]) -> Result<(), String> {
if HOST_FACTS.iter().any(|p| name.starts_with(p)) {
return Err(format!("{name} is a host event; plugins can't emit it"));
}
if SELF_INPUT.contains(&name) {
return match into {
None => Ok(()),
Some(t) if t == plugin => Ok(()),
Some(t) if granted.iter().any(|g| *g == format!("events.inject:{t}")) => Ok(()),
Some(t) => Err(format!("injecting {name} into {t} needs events.inject:{t}")),
};
}
let own = name.strip_prefix(plugin).is_some_and(|r| r.starts_with('.'));
if !own {
return Err(format!("{name} is outside {plugin}'s namespace"));
}
if !declared.iter().any(|d| d.name == name) {
return Err(format!("{name} was not declared in emits"));
}
Ok(())
}
pub fn next_hops(cause_hops: u8) -> Option<u8> {
let h = cause_hops.saturating_add(1);
(h <= MAX_HOPS).then_some(h)
}
#[derive(Debug, Clone)]
pub struct RateLimit {
tokens: f64,
rate: f64,
burst: f64,
last: Instant,
}
impl RateLimit {
pub fn new(now: Instant) -> Self {
Self::with(200.0, 1000.0, now)
}
pub fn with(rate: f64, burst: f64, now: Instant) -> Self {
Self { tokens: burst, rate, burst, last: now }
}
pub fn take(&mut self, now: Instant) -> bool {
let dt = now.saturating_duration_since(self.last).as_secs_f64();
self.last = now;
self.tokens = (self.tokens + dt * self.rate).min(self.burst);
if self.tokens >= 1.0 {
self.tokens -= 1.0;
true
} else {
false
}
}
}