use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use dashmap::DashMap;
use nexo_broker::{AnyBroker, BrokerHandle, Event, Message, StdioBridgeBroker};
use nexo_microapp_sdk::plugin::{PluginAdapter, ToolInvocation, ToolInvocationError};
use once_cell::sync::Lazy;
use tokio::sync::{Mutex, OnceCell};
use nexo_plugin_browser::{
browser_tool_defs,
dispatch::{dispatch_browser_tool, resolve_plugin_or_legacy_gated},
env_config::browser_config_from_env,
profile::{sanitize_id, user_data_dir_for},
profile_decoration::decorate_profile_dir,
profile_limits::{read_profile_limits, ProfileLimits},
BrowserPlugin,
};
const MANIFEST: &str = include_str!("../nexo-plugin.toml");
static BRIDGE: Lazy<OnceCell<Arc<StdioBridgeBroker>>> = Lazy::new(OnceCell::new);
struct ProfileEntry {
plugin: Arc<BrowserPlugin>,
last_active_at: Mutex<Instant>,
}
static PROFILES: Lazy<DashMap<String, ProfileEntry>> = Lazy::new(DashMap::new);
async fn shared_plugin_for(
agent_id: &str,
limits: ProfileLimits,
) -> Result<Arc<BrowserPlugin>, ToolInvocationError> {
let key = if !limits.multi_profile_enabled || agent_id.is_empty() {
"default".to_string()
} else {
sanitize_id(agent_id)
.map_err(|e| ToolInvocationError::ArgumentInvalid(e.to_string()))?
};
if let Some(entry) = PROFILES.get(&key) {
return Ok(entry.plugin.clone());
}
if PROFILES.len() >= limits.max_profiles {
return Err(ToolInvocationError::Unavailable(format!(
"max profiles reached: {}; close idle agents or raise NEXO_PLUGIN_BROWSER_MAX_PROFILES",
limits.max_profiles
)));
}
let mut cfg = {
let guard = nexo_plugin_browser::configured_state().read().await;
if let Some(vec) = guard.as_ref() {
if let Some(c) = vec.first() {
c.clone()
} else {
drop(guard);
browser_config_from_env()
}
} else {
drop(guard);
browser_config_from_env()
}
};
if limits.multi_profile_enabled && key != "default" {
let base: PathBuf = cfg.user_data_dir.clone().into();
let derived = user_data_dir_for(&base, &key);
cfg.user_data_dir = derived.to_string_lossy().into_owned();
if let Err(e) = decorate_profile_dir(Path::new(&cfg.user_data_dir), &key).await {
tracing::warn!(
agent_id = %key,
user_data_dir = %cfg.user_data_dir,
error = %e,
"decoration failed; continuing without profile chip badge"
);
}
}
tracing::info!(
target: "plugin.browser",
agent_id = %key,
user_data_dir = %cfg.user_data_dir,
max_profiles = limits.max_profiles,
"boot Chrome for agent profile"
);
let plugin = Arc::new(BrowserPlugin::new(cfg));
let entry_ref = PROFILES
.entry(key)
.or_insert_with(|| ProfileEntry {
plugin: plugin.clone(),
last_active_at: Mutex::new(Instant::now()),
});
Ok(entry_ref.plugin.clone())
}
fn spawn_idle_eviction_loop(idle_secs: u64) {
if idle_secs == 0 {
tracing::debug!(
target: "plugin.browser",
"idle eviction disabled (NEXO_PLUGIN_BROWSER_PROFILE_IDLE_SECS=0)"
);
return;
}
let threshold = Duration::from_secs(idle_secs);
tokio::spawn(async move {
let interval = Duration::from_secs(30);
loop {
tokio::time::sleep(interval).await;
let now = Instant::now();
let mut to_evict: Vec<String> = Vec::new();
for entry in PROFILES.iter() {
let last = *entry.value().last_active_at.lock().await;
if now.duration_since(last) >= threshold {
to_evict.push(entry.key().clone());
}
}
for key in to_evict {
if let Some((_, entry)) = PROFILES.remove(&key) {
entry.plugin.shutdown_chrome().await;
tracing::info!(
target: "plugin.browser",
agent_id = %key,
idle_secs,
"evicted idle Chrome for agent profile"
);
}
}
}
});
}
async fn auto_discovery_broker() -> anyhow::Result<AnyBroker> {
let kind = std::env::var("NEXO_BROKER_KIND").unwrap_or_else(|_| "nats".to_string());
if kind == "stdio_bridge" {
let bridge = BRIDGE
.get()
.ok_or_else(|| anyhow::anyhow!("BRIDGE not initialized"))?;
return Ok(AnyBroker::stdio_bridge((**bridge).clone()));
}
let url = std::env::var("NEXO_BROKER_URL")
.map_err(|_| anyhow::anyhow!("NEXO_BROKER_URL not set"))?;
let inner = nexo_config::types::broker::BrokerInner {
kind: if url.starts_with("nats://") {
nexo_config::types::broker::BrokerKind::Nats
} else {
nexo_config::types::broker::BrokerKind::Local
},
url,
auth: nexo_config::types::broker::BrokerAuthConfig::default(),
persistence: nexo_config::types::broker::BrokerPersistenceConfig::default(),
limits: nexo_config::types::broker::BrokerLimitsConfig::default(),
fallback: nexo_config::types::broker::BrokerFallbackConfig::default(),
};
AnyBroker::from_config(&inner)
.await
.map_err(|e| anyhow::anyhow!("broker connect failed: {e}"))
}
fn spawn_auto_discovery_subscribers(broker: AnyBroker) {
use nexo_plugin_browser::auto_discovery as ad;
spawn_one(
broker.clone(),
"plugin.browser.pairing.normalize_sender",
|_b, p| async move { ad::pairing_normalize_sender(&p) },
);
spawn_one(
broker.clone(),
"plugin.browser.pairing.send_reply",
|_b, p| async move { ad::pairing_send_reply(&p).await },
);
spawn_one(
broker.clone(),
"plugin.browser.pairing.send_qr_image",
|_b, p| async move { ad::pairing_send_qr_image(&p).await },
);
spawn_one(
broker.clone(),
"plugin.browser.http.request",
|_b, p| async move { ad::http_request(&p).await },
);
spawn_one(
broker.clone(),
"plugin.browser.metrics.scrape",
|_b, p| async move { ad::metrics_scrape(&p).await },
);
spawn_one(broker, "plugin.browser.admin.>", |_b, p| async move {
ad::admin_handle(&p).await
});
}
fn spawn_one<F, Fut>(broker: AnyBroker, topic: &'static str, handler: F)
where
F: Fn(AnyBroker, serde_json::Value) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = serde_json::Value> + Send + 'static,
{
tokio::spawn(async move {
let mut sub = match broker.subscribe(topic).await {
Ok(s) => s,
Err(e) => {
tracing::warn!(
target = "browser.auto_discovery",
topic,
error = %e,
"subscribe failed; topic will not receive requests"
);
return;
}
};
tracing::info!(target = "browser.auto_discovery", topic, "subscriber up");
while let Some(event) = sub.next().await {
let Ok(msg) = serde_json::from_value::<Message>(event.payload) else {
continue;
};
let Some(reply_to) = msg.reply_to.clone() else {
continue;
};
let reply_payload = handler(broker.clone(), msg.payload.clone()).await;
let reply_msg = Message::new(reply_to.clone(), reply_payload);
let reply_event = Event::new(
reply_to.clone(),
"browser",
match serde_json::to_value(&reply_msg) {
Ok(v) => v,
Err(_) => continue,
},
);
if let Err(e) = broker.publish(&reply_to, reply_event).await {
tracing::warn!(
target = "browser.auto_discovery",
topic,
reply_to = %reply_to,
error = %e,
"failed to publish reply"
);
}
}
tracing::debug!(
target = "browser.auto_discovery",
topic,
"subscriber stream ended"
);
});
}
#[tokio::main]
async fn main() -> nexo_microapp_sdk::Result<()> {
nexo_microapp_sdk::init_logging_from_env("nexo-plugin-browser");
let _ = rustls::crypto::ring::default_provider().install_default();
let limits = read_profile_limits();
tracing::info!(
target: "plugin.browser",
max_profiles = limits.max_profiles,
idle_secs = limits.idle_secs,
multi_profile_enabled = limits.multi_profile_enabled,
"browser-plugin: profile limits resolved"
);
spawn_idle_eviction_loop(limits.idle_secs);
let adapter = PluginAdapter::new(MANIFEST)?
.declare_tools(browser_tool_defs())
.on_configure(|value: serde_yaml::Value| async move {
nexo_plugin_browser::boot::apply_configure(value).await
})
.on_tool(move |inv: ToolInvocation| async move {
let agent_id = inv.agent_id.as_deref().unwrap_or("");
let legacy = shared_plugin_for(agent_id, limits).await?;
let plugin = resolve_plugin_or_legacy_gated(
&inv.args,
agent_id,
legacy.clone(),
limits.legacy_per_agent_enabled,
)?;
let touch_key = if !limits.multi_profile_enabled || agent_id.is_empty() {
"default".to_string()
} else {
sanitize_id(agent_id).unwrap_or_else(|_| "default".into())
};
let dispatched_against_legacy = std::sync::Arc::ptr_eq(&plugin, &legacy);
let instance_label = if dispatched_against_legacy {
"legacy".to_string()
} else {
plugin
.config_snapshot()
.instance
.clone()
.unwrap_or_else(|| "default".into())
};
let tool_name_for_metrics = inv.tool_name.clone();
let start = Instant::now();
let result = dispatch_browser_tool(plugin, &inv.tool_name, inv.args).await;
nexo_plugin_browser::metrics::record_invocation(
&instance_label,
&tool_name_for_metrics,
result.is_ok(),
start.elapsed().as_secs_f64(),
);
if result.is_ok() && dispatched_against_legacy {
if let Some(entry) = PROFILES.get(&touch_key) {
*entry.value().last_active_at.lock().await = Instant::now();
}
}
result
});
let adapter = if std::env::var("NEXO_BROKER_KIND").as_deref() == Ok("stdio_bridge") {
let (adapter, bridge) = adapter.with_stdio_bridge_broker();
BRIDGE
.set(bridge.clone())
.map_err(|_| {
nexo_microapp_sdk::Error::Internal(
"BRIDGE already initialized (this should not happen)".into(),
)
})?;
tracing::info!(
target = "nexo_plugin_browser",
"stdio_bridge broker wired (daemon broker = Local)"
);
adapter
} else {
adapter
};
match auto_discovery_broker().await {
Ok(broker) => spawn_auto_discovery_subscribers(broker),
Err(e) => tracing::warn!(
target = "nexo_plugin_browser",
error = %e,
"auto-discovery broker unavailable; subscribers not spawned (tool.invoke path unaffected)"
),
}
adapter.run_stdio().await
}