#![cfg_attr(not(test), forbid(unsafe_code))]
pub mod normalize;
pub use normalize::{Outcome as NormalizeOutcome, normalize_or_raw_sync};
use anyhow::{Context, Result, anyhow};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, Command};
use tokio::sync::oneshot;
pub const HOST_FILES: &[(&str, &str)] = &[
("host.mjs", include_str!("host/host.mjs")),
("native-assets.mjs", include_str!("host/native-assets.mjs")),
("v2.mjs", include_str!("host/v2.mjs")),
(
"bun-sqlite-loader.mjs",
include_str!("host/bun-sqlite-loader.mjs"),
),
(
"shim-bun-sqlite.mjs",
include_str!("host/shim-bun-sqlite.mjs"),
),
(
"shim-bun-sqlite.cjs",
include_str!("host/shim-bun-sqlite.cjs"),
),
];
pub const RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
pub fn materialize_host(dir: &Path) -> Result<PathBuf> {
std::fs::create_dir_all(dir).with_context(|| format!("create host dir {}", dir.display()))?;
for (name, body) in HOST_FILES {
let path = dir.join(name);
std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
}
Ok(dir.join("host.mjs"))
}
pub fn resolve_entry(spec: &str, home: &Path) -> Result<PathBuf> {
if let Some(p) = file_url_path(spec) {
return entry_from_path(&p);
}
if let Some(rest) = spec.strip_prefix("~/") {
return entry_from_path(&home.join(rest));
}
if is_path_spec(spec) {
return entry_from_path(Path::new(spec));
}
let cache = home.join(".cache/opencode/packages");
let pkg_name = strip_version(spec);
let candidates = [
cache.join(format!("{spec}@latest")),
cache.join(spec),
cache.join(format!("{pkg_name}@latest")),
];
for dir in &candidates {
if !dir.exists() {
continue;
}
let direct = dir.join("package.json");
if let Some(entry) = entry_from_package(&direct, dir, &pkg_name) {
return Ok(entry);
}
let nested = dir
.join("node_modules")
.join(&pkg_name)
.join("package.json");
if let Some(entry) = entry_from_package(&nested, nested.parent().unwrap_or(dir), &pkg_name)
{
return Ok(entry);
}
}
anyhow::bail!("plugin target not found in opencode cache: {spec}")
}
fn is_path_spec(spec: &str) -> bool {
let b = spec.as_bytes();
let drive = b.len() >= 3
&& b[0].is_ascii_alphabetic()
&& b[1] == b':'
&& (b[2] == b'\\' || b[2] == b'/');
spec.starts_with('/')
|| spec.starts_with("./")
|| spec.starts_with("../")
|| Path::new(spec).is_absolute()
|| drive
}
fn entry_from_path(p: &Path) -> Result<PathBuf> {
let abs;
let p = if p.is_absolute() {
p
} else {
match std::env::current_dir() {
Ok(cwd) => {
abs = cwd.join(p);
&abs
}
Err(_) => p,
}
};
if p.is_file() {
return Ok(p.to_path_buf());
}
if p.is_dir() {
return dir_entry(p)
.ok_or_else(|| anyhow!("plugin directory has no entrypoint: {}", p.display()));
}
anyhow::bail!("plugin file not found: {}", p.display())
}
fn dir_entry(dir: &Path) -> Option<PathBuf> {
if let Some(entry) = entry_from_package(&dir.join("package.json"), dir, "") {
return Some(entry);
}
for name in [
"index.ts",
"index.tsx",
"index.js",
"index.mjs",
"index.cjs",
] {
let p = dir.join(name);
if p.is_file() {
return Some(p);
}
}
None
}
fn file_url_path(spec: &str) -> Option<PathBuf> {
let rest = spec.strip_prefix("file://")?;
let rest = match rest.strip_prefix("localhost") {
Some(r) if r.starts_with('/') => r,
_ => rest,
};
if !rest.starts_with('/') {
return None;
}
let decoded = percent_decode(rest);
if decoded.is_empty() {
return None;
}
#[cfg(windows)]
let decoded = decoded.trim_start_matches('/').to_string();
Some(PathBuf::from(decoded))
}
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
{
out.push(hi * 16 + lo);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn hex_nibble(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
pub fn discover_plugin_specs(config_dir: &Path) -> Vec<String> {
const MAX_DISCOVERED: usize = 64;
let mut out = Vec::new();
for sub in ["plugin", "plugins"] {
let dir = config_dir.join(sub);
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
if out.len() >= MAX_DISCOVERED {
break;
}
let path = entry.path();
let Ok(meta) = std::fs::metadata(&path) else {
continue;
};
let is_source = meta.is_file()
&& matches!(
path.extension().and_then(|e| e.to_str()),
Some("ts") | Some("js")
);
if (is_source || meta.is_dir())
&& let Some(s) = path.to_str()
{
out.push(s.to_string());
}
}
}
out.sort();
out.dedup();
out.truncate(MAX_DISCOVERED);
out
}
fn strip_version(spec: &str) -> String {
let bytes = spec.as_bytes();
let mut cut = None;
for (i, b) in bytes.iter().enumerate() {
if *b == b'@' && i > 0 {
cut = Some(i);
}
}
match cut {
Some(i) => spec[..i].to_string(),
None => spec.to_string(),
}
}
fn entry_from_package(pkg_json: &Path, base: &Path, _pkg_name: &str) -> Option<PathBuf> {
let text = std::fs::read_to_string(pkg_json).ok()?;
let v: Value = serde_json::from_str(&text).ok()?;
let mut rel: Option<&str> = None;
if let Some(exp) = v.get("exports") {
for key in [".", "./server"] {
let Some(dot) = exp.get(key) else { continue };
rel = match dot {
Value::String(s) => Some(s.as_str()),
Value::Object(_) => dot
.get("import")
.and_then(|x| x.as_str())
.or_else(|| dot.get("default").and_then(|x| x.as_str())),
_ => None,
};
if rel.is_some() {
break;
}
}
}
rel = rel.or_else(|| v.get("main").and_then(|x| x.as_str()));
rel = rel.or_else(|| v.get("module").and_then(|x| x.as_str()));
let rel = rel?;
let entry = base.join(rel);
let lex = lexically_normalize(&entry);
if !lex.starts_with(base)
&& !std::fs::canonicalize(base)
.ok()
.is_some_and(|cb| lex.starts_with(&cb))
{
tracing::warn!("plugin entry {rel} escapes its package dir — refused");
return None;
}
lex.exists().then_some(lex)
}
fn lexically_normalize(p: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
other => out.push(other.as_os_str()),
}
}
out
}
struct Pending {
tx: oneshot::Sender<Result<Value, String>>,
}
struct PendingGuard {
pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
id: i64,
}
impl PendingGuard {
fn new(pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>, id: i64) -> Self {
Self { pending, id }
}
}
impl Drop for PendingGuard {
fn drop(&mut self) {
self.pending.lock().remove(&self.id);
}
}
pub struct Inner {
stdin: tokio::sync::Mutex<ChildStdin>,
pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
next_id: std::sync::atomic::AtomicI64,
statuses: parking_lot::Mutex<HashMap<String, Value>>,
alive: Arc<std::sync::atomic::AtomicBool>,
poisoned: Arc<std::sync::atomic::AtomicBool>,
last_tools: parking_lot::Mutex<Option<Vec<Value>>>,
}
#[derive(Clone)]
pub struct Handle(Arc<Inner>);
impl Handle {
pub fn is_alive(&self) -> bool {
self.0.alive.load(std::sync::atomic::Ordering::Acquire)
}
pub fn registers(&self, hook: &str) -> bool {
self.0.statuses.lock().values().any(|v| {
v.get("hooks")
.and_then(|h| h.as_array())
.is_some_and(|a| a.iter().any(|x| x.as_str() == Some(hook)))
})
}
pub fn any_loaded(&self) -> bool {
self.0
.statuses
.lock()
.values()
.any(|v| v.get("ok").and_then(|b| b.as_bool()).unwrap_or(false))
}
pub fn has_tools(&self) -> bool {
self.0.statuses.lock().values().any(|v| {
v.get("has_tools")
.and_then(|b| b.as_bool())
.unwrap_or(false)
})
}
pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
self.request_with_timeout(method, params, Some(RPC_TIMEOUT))
.await
}
pub async fn request_with_timeout(
&self,
method: &str,
params: Value,
timeout: Option<std::time::Duration>,
) -> Result<Value> {
if !self.is_alive() {
anyhow::bail!("plugin host is down ({method}); a respawn is required");
}
let id = self
.0
.next_id
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (tx, rx) = oneshot::channel();
self.0.pending.lock().insert(id, Pending { tx });
let _guard = PendingGuard::new(Arc::clone(&self.0.pending), id);
let msg = json!({"id": id, "method": method, "params": params});
let mut line = msg.to_string();
line.push('\n');
let exchange = async {
{
let mut stdin = self.0.stdin.lock().await;
stdin.write_all(line.as_bytes()).await?;
stdin.flush().await?;
}
match rx.await {
Ok(res) => res.map_err(|e| anyhow!("plugin host {method}: {e}")),
Err(_) => Err(anyhow!("plugin host dropped response for {method}")),
}
};
match timeout {
None => exchange
.await
.map_err(|e| e.context("plugin host stdin write")),
Some(d) => match tokio::time::timeout(d, exchange).await {
Ok(res) => res,
Err(_) => {
self.0
.poisoned
.store(true, std::sync::atomic::Ordering::Release);
self.0
.alive
.store(false, std::sync::atomic::Ordering::Release);
ocserve_metrics::labeled_counter(
"ocserve_plugin_hook_timeout_total",
&format!("hook=\"{method}\""),
1,
);
Err(anyhow!(
"plugin host {method} timed out after {}ms (runaway hook?)",
d.as_millis()
))
}
},
}
}
}
impl Handle {
pub async fn trigger_bounded(
&self,
name: &str,
input: Value,
mut output: Value,
budget: Option<std::time::Duration>,
) -> Result<Value> {
let res = self
.request_with_timeout(
"trigger",
json!({"name": name, "input": input, "output": output}),
budget,
)
.await?;
if res.is_object() {
output = res;
}
Ok(output)
}
pub async fn trigger_v2_bounded(
&self,
domain: &str,
name: &str,
input: Value,
budget: Option<std::time::Duration>,
) -> Result<Value> {
self.request_with_timeout(
"trigger_v2",
json!({"domain": domain, "name": name, "input": input}),
budget,
)
.await
}
pub async fn emit_event_bounded(
&self,
event: Value,
budget: Option<std::time::Duration>,
) -> Result<Value> {
self.request_with_timeout("event", json!({"event": event}), budget)
.await
}
}
pub fn hook_budget(hook: &str) -> Option<std::time::Duration> {
match std::env::var("OCSERVE_HOOK_TIMEOUT_MS")
.ok()
.and_then(|v| v.parse::<u64>().ok())
{
Some(0) => None,
Some(ms) => Some(std::time::Duration::from_millis(ms)),
None => Some(std::time::Duration::from_secs(
if hook.contains("tool.execute") {
180
} else if hook.contains("transform")
|| hook.contains("context")
|| hook.contains("compact")
{
60
} else {
30
},
)),
}
}
impl Handle {
pub async fn rpc_call(&self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
self.request(
"rpc_call",
json!({"rpcID": rpc_id, "method": method, "input": input}),
)
.await
}
pub async fn v2_inventory(&self) -> Result<Value> {
self.request("v2_inventory", json!({})).await
}
pub async fn transform_commands(
&self,
commands: Vec<Value>,
) -> Result<(Vec<Value>, Vec<Value>)> {
let r = self
.request("v2_transform_commands", json!({ "commands": commands }))
.await?;
let out = r["commands"]
.as_array()
.cloned()
.unwrap_or_default()
.into_iter()
.collect();
let failures = r["failures"].as_array().cloned().unwrap_or_default();
Ok((out, failures))
}
}
impl Handle {
pub async fn tools(&self) -> Result<Vec<Value>> {
if !self.any_loaded() {
return Ok(Vec::new());
}
match self.request("tools", json!({})).await {
Ok(res) => {
let list = res.as_array().cloned().unwrap_or_default();
*self.0.last_tools.lock() = Some(list.clone());
Ok(list)
}
Err(e) => {
if let Some(cached) = self.0.last_tools.lock().clone() {
tracing::warn!("plugin tools: {e:#} — serving the last known list");
return Ok(cached);
}
Err(e)
}
}
}
pub async fn execute_tool(&self, name: &str, input: Value, ctx: Value) -> Result<Value> {
self.request_with_timeout(
"tool_execute",
json!({"name": name, "input": input, "ctx": ctx}),
Some(std::time::Duration::from_secs(300)),
)
.await
}
}
pub struct Sidecar {
inner: Arc<Inner>,
child: Child,
server: (String, String),
args: SpawnArgs,
loads: Vec<(String, PathBuf, Value, Value)>,
normalize_root: Option<PathBuf>,
started_at: std::time::Instant,
recycled: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginRuntime {
Bun,
Node,
}
impl PluginRuntime {
pub fn program(self) -> &'static str {
match self {
PluginRuntime::Bun => "bun",
PluginRuntime::Node => "node",
}
}
}
pub(crate) fn which(prog: &str) -> Option<PathBuf> {
let name = ocserve_store::platform::exe(prog);
if let Ok(path) = std::env::var("PATH") {
for dir in std::env::split_paths(&path) {
let cand = dir.join(&name);
if ocserve_store::platform::is_executable_file(&cand) {
return Some(cand);
}
}
}
for key in ["OCSERVE_HOME", "HOME", "USERPROFILE"] {
let Some(home) = std::env::var_os(key).filter(|v| !v.is_empty()) else {
continue;
};
let cand = Path::new(&home).join(".bun/bin").join(&name);
if ocserve_store::platform::is_executable_file(&cand) {
return Some(cand);
}
}
None
}
pub fn plugin_runtime() -> PluginRuntime {
match std::env::var("OCSERVE_PLUGIN_RUNTIME").as_deref() {
Ok("node") => return PluginRuntime::Node,
Ok("bun") => return PluginRuntime::Bun,
_ => {}
}
if which("bun").is_some() {
PluginRuntime::Bun
} else {
PluginRuntime::Node
}
}
#[derive(Clone)]
struct SpawnArgs {
host_path: PathBuf,
server_url: String,
directory: String,
}
impl Sidecar {
pub async fn spawn(host_path: &Path, server_url: &str, directory: &str) -> Result<Self> {
let runtime = crate::plugin_runtime();
let program = which(runtime.program())
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| runtime.program().to_string());
let shape = ocserve_store::cgroup::contained(&program, "plugin");
let mut cmd = Command::new(&shape.program);
cmd.args(&shape.prefix);
cmd.env("OCSERVE_VERSION", env!("CARGO_PKG_VERSION"));
match &shape.cgroup {
Some(p) => {
cmd.env(ocserve_store::cgroup::ENV, p);
}
None => {
cmd.env_remove(ocserve_store::cgroup::ENV);
}
}
match runtime {
PluginRuntime::Bun => {
cmd.arg("--smol");
}
PluginRuntime::Node => {
cmd.arg(format!(
"--max-old-space-size={}",
std::env::var("OCSERVE_PLUGIN_HEAP_MB")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(128)
));
cmd.arg("--max-semi-space-size=2");
}
}
cmd.arg(host_path)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.kill_on_drop(true);
let mut child = cmd
.spawn()
.with_context(|| format!("spawn {} plugin host", runtime.program()))?;
let stdin = child.stdin.take().context("host stdin")?;
let stdout = child.stdout.take().context("host stdout")?;
let pending = Arc::new(parking_lot::Mutex::new(HashMap::<i64, Pending>::new()));
let pending_task = Arc::clone(&pending);
let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
let alive_task = Arc::clone(&alive);
let poisoned = Arc::new(std::sync::atomic::AtomicBool::new(false));
let poisoned_task = Arc::clone(&poisoned);
tokio::spawn(async move {
const MAX_HOST_LINE: usize = 8 * 1024 * 1024;
let mut reader = BufReader::new(stdout);
let mut line = String::new();
loop {
line.clear();
use tokio::io::AsyncBufReadExt as _;
let n = {
let mut limited =
tokio::io::AsyncReadExt::take(&mut reader, MAX_HOST_LINE as u64 + 1);
limited.read_line(&mut line).await
};
match n {
Ok(0) | Err(_) => break,
Ok(_) if line.len() > MAX_HOST_LINE => {
tracing::warn!("plugin host: oversized line — child marked for respawn");
poisoned_task.store(true, std::sync::atomic::Ordering::Release);
break;
}
Ok(_) => {}
}
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
match serde_json::from_str::<Value>(trimmed) {
Ok(v) => {
if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
let result = match v.get("error") {
Some(e) if !e.is_null() => {
Err(e["message"].as_str().unwrap_or("host error").to_string())
}
_ => Ok(v.get("result").cloned().unwrap_or(Value::Null)),
};
if let Some(p) = pending_task.lock().remove(&id) {
let _ = p.tx.send(result);
}
} else if v.get("event").and_then(|e| e.as_str()) == Some("plugin_error") {
ocserve_metrics::labeled_counter(
"ocserve_plugin_internal_error_total",
&format!(
"plugin=\"{}\",hook=\"{}\"",
v["plugin"].as_str().unwrap_or("?"),
v["hook"].as_str().unwrap_or("?")
),
1,
);
tracing::warn!(
"plugin internal error: {} {}: {}",
v["plugin"].as_str().unwrap_or("?"),
v["hook"].as_str().unwrap_or("?"),
v["error"].as_str().unwrap_or("?")
);
}
}
Err(_) => {
let head: String = trimmed.chars().take(120).collect();
tracing::warn!("plugin host: unparsable line: {head}");
}
}
}
alive_task.store(false, std::sync::atomic::Ordering::Release);
for (_, p) in pending_task.lock().drain() {
let _ = p.tx.send(Err("plugin host exited".into()));
}
ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 0);
});
ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 1);
Ok(Self {
inner: Arc::new(Inner {
stdin: tokio::sync::Mutex::new(stdin),
pending,
next_id: std::sync::atomic::AtomicI64::new(1),
statuses: parking_lot::Mutex::new(HashMap::new()),
alive,
poisoned,
last_tools: parking_lot::Mutex::new(None),
}),
child,
server: (server_url.to_string(), directory.to_string()),
args: SpawnArgs {
host_path: host_path.to_path_buf(),
server_url: server_url.to_string(),
directory: directory.to_string(),
},
loads: Vec::new(),
normalize_root: None,
started_at: std::time::Instant::now(),
recycled: false,
})
}
pub fn in_flight(&self) -> usize {
self.inner.pending.lock().len()
}
pub fn uptime(&self) -> std::time::Duration {
self.started_at.elapsed()
}
pub fn recycle_child(&mut self) -> bool {
if self.child.try_wait().ok().flatten().is_some() {
return false;
}
let _ = self.child.start_kill();
self.inner
.alive
.store(false, std::sync::atomic::Ordering::Release);
self.recycled = true;
true
}
pub fn set_normalize_root(&mut self, root: PathBuf) {
self.normalize_root = Some(root);
}
pub async fn ensure_alive(&mut self) -> Result<()> {
if self
.inner
.poisoned
.load(std::sync::atomic::Ordering::Acquire)
{
let _ = self.child.start_kill();
self.inner
.alive
.store(false, std::sync::atomic::Ordering::Release);
} else if self.inner.alive.load(std::sync::atomic::Ordering::Acquire)
&& let Ok(None) = self.child.try_wait()
{
return Ok(());
}
ocserve_metrics::labeled_counter(
"ocserve_plugin_sidecar_respawn_total",
if self.recycled {
"reason=\"recycle\""
} else {
"reason=\"exit\""
},
1,
);
let status = self.child.try_wait().ok().flatten();
if std::mem::take(&mut self.recycled) {
tracing::info!(
"plugin sidecar recycled (L1, was {status:?}) — respawning + replaying hooks"
);
} else if let Some(status) = status {
tracing::error!("plugin sidecar exited ({status}) — respawning");
} else {
tracing::warn!("plugin sidecar unresponsive — replacing the host");
}
let args = self.args.clone();
let loads = std::mem::take(&mut self.loads);
let mut fresh =
match Sidecar::spawn(&args.host_path, &args.server_url, &args.directory).await {
Ok(f) => f,
Err(e) => {
self.loads = loads;
tracing::error!("plugin sidecar respawn failed: {e:#} — plugin set preserved");
return Err(e);
}
};
fresh.normalize_root = self.normalize_root.clone();
for (spec, entry, input, options) in &loads {
if let Err(e) = fresh.load_raw(spec, entry, input, options).await {
tracing::warn!("plugin {spec} reload after respawn failed: {e:#}");
}
}
*self = fresh;
Ok(())
}
pub fn child_pid(&self) -> u32 {
self.child.id().unwrap_or(0)
}
pub fn handle(&self) -> Handle {
Handle(Arc::clone(&self.inner))
}
pub async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
self.ensure_alive().await?;
self.handle().request(method, params).await
}
pub async fn request_bounded(
&mut self,
method: &str,
params: Value,
timeout: Option<std::time::Duration>,
) -> Result<Value> {
self.ensure_alive().await?;
self.handle()
.request_with_timeout(method, params, timeout)
.await
}
pub async fn load(
&mut self,
spec: &str,
entry: &Path,
input: &Value,
options: &Value,
) -> Result<Vec<String>> {
self.ensure_alive().await?;
self.load_raw(spec, entry, input, options).await
}
async fn load_raw(
&mut self,
spec: &str,
entry: &Path,
input: &Value,
options: &Value,
) -> Result<Vec<String>> {
let root = self.normalize_root.clone();
let raw = entry.to_path_buf();
let raw_for_spawn = raw.clone();
let (load_path, outcome) = tokio::task::spawn_blocking(move || {
crate::normalize::normalize_or_raw_sync(root.as_deref(), &raw_for_spawn)
})
.await
.map_err(|e| anyhow!("normalize task: {e}"))?;
ocserve_metrics::labeled_counter(
"ocserve_plugin_normalize_total",
&format!("result=\"{}\"", outcome.label()),
1,
);
match &outcome {
crate::normalize::Outcome::Built {
path,
ms,
beside,
rss_before_kb,
rss_after_kb,
} => tracing::info!(
"plugin normalize {spec}: built {} ({}) in {ms}ms rss {rss_before_kb}→{rss_after_kb}kB",
path.display(),
if *beside { "beside-entry" } else { "data-dir" }
),
crate::normalize::Outcome::Fallback { err, .. } => {
tracing::warn!("plugin normalize {spec} failed, loading raw entry: {err}")
}
_ => {}
}
let mut input = input.clone();
if input
.get("serverUrl")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty()
{
input["serverUrl"] = json!(self.server.0);
}
if input
.get("directory")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty()
{
input["directory"] = json!(self.server.1);
}
let params = json!({
"spec": spec,
"entry": load_path.to_string_lossy(),
"origin": raw.to_string_lossy(),
"input": input,
"options": options,
});
let res = self.handle().request("load", params).await?;
let hooks: Vec<String> = res["hooks"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|h| h.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
self.inner.statuses.lock().insert(
spec.to_string(),
json!({
"ok": true,
"hooks": hooks,
"id": res["id"],
"has_tools": res["has_tools"].as_bool().unwrap_or(false),
}),
);
self.loads.push((
spec.to_string(),
entry.to_path_buf(),
input,
options.clone(),
));
Ok(hooks)
}
pub fn attempted(&self, spec: &str) -> bool {
self.inner.statuses.lock().contains_key(spec)
}
pub async fn load_discovered(&mut self, spec: &str, home: &Path) -> Result<Vec<String>> {
if self.attempted(spec) {
return Ok(Vec::new());
}
let entry = match resolve_entry(spec, home) {
Ok(entry) => entry,
Err(e) => {
self.note_failure(spec, &e);
return Err(e);
}
};
self.ensure_alive().await?;
let input = json!({
"directory": self.server.1,
"projectID": "global",
"worktree": "/",
"serverUrl": self.server.0,
});
match self.load(spec, &entry, &input, &json!({})).await {
Ok(hooks) => Ok(hooks),
Err(e) => {
self.note_failure(spec, &e);
Err(e)
}
}
}
pub fn note_failure(&self, spec: &str, e: &anyhow::Error) {
self.inner.statuses.lock().insert(
spec.to_string(),
json!({"ok": false, "hooks": [], "error": format!("{e:#}")}),
);
}
pub async fn trigger(&mut self, name: &str, input: Value, mut output: Value) -> Result<Value> {
let params = json!({"name": name, "input": input, "output": output});
let res = self.request("trigger", params).await?;
if res.is_object() {
output = res;
}
Ok(output)
}
pub async fn emit_event(&mut self, event: Value) -> Result<Value> {
self.request("event", json!({"event": event})).await
}
pub async fn trigger_v2(&mut self, domain: &str, name: &str, input: Value) -> Result<Value> {
self.request(
"trigger_v2",
json!({"domain": domain, "name": name, "input": input}),
)
.await
}
pub async fn rpc_call(&mut self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
self.ensure_alive().await?;
self.handle().rpc_call(rpc_id, method, input).await
}
pub async fn v2_inventory(&mut self) -> Result<Value> {
self.ensure_alive().await?;
self.handle().v2_inventory().await
}
pub async fn transform_commands(
&mut self,
commands: Vec<Value>,
) -> Result<(Vec<Value>, Vec<Value>)> {
self.ensure_alive().await?;
self.handle().transform_commands(commands).await
}
pub async fn config(&mut self, cfg: Value) -> Result<Value> {
self.request("config", json!({"config": cfg})).await
}
pub fn statuses(&self) -> Value {
let mut out = serde_json::Map::new();
for (spec, v) in self.inner.statuses.lock().iter() {
out.insert(spec.clone(), v.clone());
}
Value::Object(out)
}
pub async fn shutdown(&mut self) {
let _ = self.request("dispose", json!({})).await;
let _ = self.child.start_kill();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strip_version_cases() {
assert_eq!(strip_version("context-mode"), "context-mode");
assert_eq!(strip_version("context-mode@latest"), "context-mode");
assert_eq!(
strip_version("@cortexkit/opencode-magic-context@latest"),
"@cortexkit/opencode-magic-context"
);
assert_eq!(
strip_version("@iam-brain/opencode-codex-auth@latest"),
"@iam-brain/opencode-codex-auth"
);
}
#[test]
fn entry_from_package_shapes() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("package.json"),
r#"{"exports": {".": "./dist/index.js"}}"#,
)
.unwrap();
std::fs::create_dir(dir.path().join("dist")).unwrap();
std::fs::write(dir.path().join("dist/index.js"), "//").unwrap();
let e = entry_from_package(&dir.path().join("package.json"), dir.path(), "x")
.expect("exports dot");
assert!(e.ends_with("dist/index.js"));
std::fs::write(
dir.path().join("package.json"),
r#"{"main": "./lib/main.js"}"#,
)
.unwrap();
std::fs::create_dir(dir.path().join("lib")).unwrap();
std::fs::write(dir.path().join("lib/main.js"), "//").unwrap();
let e =
entry_from_package(&dir.path().join("package.json"), dir.path(), "x").expect("main");
assert!(e.ends_with("lib/main.js"));
}
#[test]
fn resolve_entry_accepts_file_urls_and_directories() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("bridge.mjs");
std::fs::write(&file, "//").unwrap();
let url = format!("file://{}", file.display());
assert_eq!(resolve_entry(&url, dir.path()).unwrap(), file);
let spaced = dir.path().join("bridge copy.mjs");
std::fs::write(&spaced, "//").unwrap();
let encoded = format!("file://{}", spaced.display()).replace(' ', "%20");
assert_eq!(resolve_entry(&encoded, dir.path()).unwrap(), spaced);
let pkg = dir.path().join("managed-bridge");
std::fs::create_dir_all(pkg.join("dist")).unwrap();
std::fs::write(
pkg.join("package.json"),
r#"{"name":"paseo-managed-bridge","type":"module","exports":{"./server":"./dist/main.mjs"}}"#,
)
.unwrap();
std::fs::write(pkg.join("dist/main.mjs"), "//").unwrap();
assert_eq!(
resolve_entry(pkg.to_str().unwrap(), dir.path()).unwrap(),
pkg.join("dist/main.mjs")
);
let plain = dir.path().join("plain");
std::fs::create_dir_all(&plain).unwrap();
std::fs::write(plain.join("index.ts"), "//").unwrap();
assert_eq!(
resolve_entry(plain.to_str().unwrap(), dir.path()).unwrap(),
plain.join("index.ts")
);
let empty = dir.path().join("empty");
std::fs::create_dir_all(&empty).unwrap();
let err = resolve_entry(empty.to_str().unwrap(), dir.path()).unwrap_err();
assert!(err.to_string().contains("no entrypoint"), "{err}");
}
#[test]
fn resolve_entry_negative_control_still_rejects_unknown_packages() {
let dir = tempfile::tempdir().unwrap();
let err = resolve_entry("no-such-plugin-package", dir.path()).unwrap_err();
assert!(err.to_string().contains("plugin target not found"), "{err}");
}
#[test]
fn discover_plugin_specs_matches_upstream_layout() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("plugin")).unwrap();
std::fs::create_dir_all(dir.path().join("plugins/managed-bridge")).unwrap();
std::fs::write(dir.path().join("plugin/a.js"), "//").unwrap();
std::fs::write(dir.path().join("plugin/b.mjs"), "//").unwrap(); std::fs::write(dir.path().join("plugins/readme.txt"), "x").unwrap();
let got = discover_plugin_specs(dir.path());
assert!(
got.iter().any(|s| s.ends_with("/plugin/a.js")),
"a .js source file is discovered: {got:?}"
);
assert!(
got.iter().any(|s| s.ends_with("/plugins/managed-bridge")),
"a package DIRECTORY is discovered: {got:?}"
);
assert!(
!got.iter().any(|s| s.ends_with("b.mjs")),
"upstream does not discover .mjs by glob: {got:?}"
);
assert!(!got.iter().any(|s| s.ends_with("readme.txt")));
assert_eq!(got.len(), 2, "{got:?}");
}
#[tokio::test]
async fn v2_tool_transform_registers_and_executes() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("tools.mjs"),
r#"export default {
id: "toolshop",
setup: async (ctx) => {
await ctx.tool.transform((editor) => {
editor.add({
name: "echo",
description: "echo the input",
input: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
async execute(input, call) {
return {
content: [{ type: "text", text: `hi ${input.text} ${call.sessionID}` }],
metadata: { tag: "v2" },
};
},
});
});
},
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
sc.load(
"toolshop",
&dir.path().join("tools.mjs"),
&json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
&json!({}),
)
.await?;
assert!(sc.handle().has_tools(), "load must report has_tools");
let tools = sc.handle().tools().await?;
let tool = tools
.iter()
.find(|t| t["name"] == "echo")
.expect("v2 tool advertised");
assert_eq!(tool["parameters"]["properties"]["text"]["type"], "string");
let res = sc
.handle()
.execute_tool("echo", json!({"text": "x"}), json!({"sessionID": "s1"}))
.await?;
assert_eq!(res["ok"], true, "{res}");
assert_eq!(res["output"], "hi x s1", "{res}");
assert_eq!(res["metadata"]["tag"], "v2", "{res}");
let missing = sc
.handle()
.execute_tool("nope", json!({}), json!({}))
.await?;
assert_eq!(missing["ok"], false, "{missing}");
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn v2_tool_added_after_load_is_advertised() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("late.mjs"),
r#"export default {
id: "late",
setup: async (ctx) => {
await ctx.rpc.register(
{ id: "late.rpc", methods: { add: { input: {}, output: {} } }, events: {} },
{
add: async () => {
await ctx.tool.transform((editor) => {
editor.add({
name: "late_tool",
description: "added by rpc",
input: { type: "object", properties: {} },
async execute() { return { content: [{ type: "text", text: "late-ok" }] }; },
});
});
return {};
},
},
);
},
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
let hooks = sc
.load(
"late",
&dir.path().join("late.mjs"),
&json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
&json!({}),
)
.await?;
assert!(hooks.is_empty(), "no hooks at load: {hooks:?}");
assert!(
sc.handle().tools().await?.is_empty(),
"no tools before bind"
);
let out = sc.rpc_call("late.rpc", "add", json!({})).await?;
assert!(out.get("output").is_some(), "{out}");
let tools = sc.handle().tools().await?;
assert!(
tools.iter().any(|t| t["name"] == "late_tool"),
"tool added after load must be advertised: {tools:?}"
);
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn sidecar_load_trigger_roundtrip() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("plug.mjs"),
r#"
export const PluginModule = {
id: "synthetic",
server: async () => ({
"tool.execute.after": async (input, output) => { output.seen = input.tool; },
"chat.message": async (input, output) => { output.touched = true; },
"event": async (payload) => {
if (!payload.event || !payload.event.type) throw new Error("bad event shape");
if (payload.event.type === "boom.type") throw new Error("event boom");
},
}),
};
export default PluginModule.server;
"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work")
.await
.expect("spawn node");
let ping = sc.request("ping", json!({})).await.expect("ping");
assert_eq!(ping, "pong");
let input =
json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
let hooks = sc
.load(
"synthetic",
&dir.path().join("plug.mjs"),
&input,
&Value::Null,
)
.await
.expect("load");
assert_eq!(
hooks,
vec![
"tool.execute.after".to_string(),
"chat.message".to_string(),
"event".to_string()
],
"hook names registered in declaration order"
);
let out = sc
.trigger(
"tool.execute.after",
json!({"tool": "write", "args": {"filePath": "/x"}}),
json!({}),
)
.await
.expect("trigger");
assert_eq!(
out["seen"], "write",
"hook observed input and mutated output"
);
let out2 = sc
.trigger("permission.ask", json!({}), json!({"keep": 1}))
.await
.expect("trigger2");
assert_eq!(out2["keep"], 1);
let ev = sc
.emit_event(json!({"id": "e1", "type": "session.created", "properties": {}}))
.await
.expect("emit_event");
assert_eq!(ev["delivered"], 1, "event hook must receive exact shape");
let ev2 = sc
.emit_event(json!({"id": "e2", "type": "boom.type", "properties": {}}))
.await
.expect("emit_event fail-open");
assert_eq!(ev2["delivered"], 0, "throwing event hook must not count");
let st = sc.statuses();
assert_eq!(st["synthetic"]["ok"], true);
assert_eq!(st["synthetic"]["hooks"][0], "tool.execute.after");
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn sidecar_resolves_bun_pty_library_from_original_package_tree() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
crate::plugin_runtime().program()
);
}
#[cfg(target_os = "macos")]
let library_name = if cfg!(target_arch = "aarch64") {
"librust_pty_arm64.dylib"
} else {
"librust_pty.dylib"
};
#[cfg(target_os = "linux")]
let library_name = if cfg!(target_arch = "aarch64") {
"librust_pty_arm64.so"
} else {
"librust_pty.so"
};
#[cfg(target_os = "windows")]
let library_name = "rust_pty.dll";
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
let library_name = "librust_pty.so";
let dir = tempfile::tempdir()?;
let package = dir.path().join("opencode-pty");
let entry = package.join("index.mjs");
let library = package
.join("node_modules/bun-pty/rust-pty/target/release")
.join(library_name);
std::fs::create_dir_all(library.parent().expect("library has parent"))?;
std::fs::write(&library, b"synthetic native library path fixture")?;
let expected = serde_json::to_string(&library.to_string_lossy())?;
std::fs::write(
&entry,
format!(
r#"
const expected = {expected};
if (process.env.BUN_PTY_LIB !== expected) throw new Error("native library path was not resolved from plugin origin");
export const PluginModule = {{
id: "native-asset-probe",
server: async () => ({{ "chat.message": async (_input, output) => {{ output.resolved = true; }} }}),
}};
export default PluginModule.server;
"#
),
)?;
let host = materialize_host(&dir.path().join("host"))?;
assert!(
std::env::var_os("BUN_PTY_LIB").is_none(),
"unset BUN_PTY_LIB to run this test"
);
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
let hooks = sc
.load("opencode-pty", &entry, &json!({}), &Value::Null)
.await?;
assert_eq!(hooks, vec!["chat.message"]);
let output = sc.trigger("chat.message", json!({}), json!({})).await?;
assert_eq!(output["resolved"], true);
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn sidecar_respawns_after_death_and_reloads_plugins() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("plug.mjs"),
r#"
export const PluginModule = {
id: "reaper",
server: async () => ({
"chat.message": async (_i, output) => { output.alive = true; },
}),
};
export default PluginModule.server;
"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
sc.load(
"reaper",
&dir.path().join("plug.mjs"),
&json!({}),
&Value::Null,
)
.await
.expect("load");
let pid = sc.child_pid();
std::process::Command::new("kill")
.arg("-9")
.arg(pid.to_string())
.status()
.expect("kill -9");
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let out = sc
.trigger("chat.message", json!({"sessionID": "s"}), json!({}))
.await
.expect("trigger after respawn");
assert_eq!(out["alive"], true, "hook must fire after respawn");
assert_ne!(sc.child_pid(), pid, "child process must be replaced");
let st = sc.statuses();
assert_eq!(
st["reaper"]["ok"], true,
"previously loaded plugins must be reloaded"
);
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn v2_battery_promise_and_effect_dialects() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("p_v2_promise.mjs"),
r#"export default {
id: "v2promise",
setup: async (ctx) => {
await ctx.session.hook("context", (ev) => { ev.promiseTouched = true; });
await ctx.tool.hook("execute.after", (ev) => { ev.result = "mutated-by-promise"; });
await ctx.rpc.register({ id: "sample" }, {
hello: async (input) => ({ echoed: input, from: "promise" }),
});
await ctx.storage.set("k", 41);
if ((await ctx.storage.get("k")) !== 41) throw new Error("storage broke");
},
};"#,
)
.unwrap();
let eff = dir
.path()
.join("p_v2_effect")
.join("node_modules")
.join("effect");
std::fs::create_dir_all(eff.join("lib")).unwrap();
std::fs::write(
eff.join("package.json"),
r#"{"name":"effect","version":"3.0.0","type":"module","exports":{".":"./lib/index.js"}}"#,
)
.unwrap();
std::fs::write(
eff.join("lib/index.js"),
"export const Effect = { scoped: (p) => p, runPromise: async (p) => { await p; } };\nexport const Scope = {};\n",
)
.unwrap();
std::fs::write(
dir.path().join("p_v2_effect").join("plug.mjs"),
r#"export default {
id: "v2effect",
effect: (ctx) => (async () => {
await ctx.tool.hook("execute.before", (ev) => { ev.input.before = "effect"; });
})(),
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
let h1 = sc
.load(
"v2promise",
&dir.path().join("p_v2_promise.mjs"),
&input,
&Value::Null,
)
.await?;
assert!(
h1.contains(&"session.context".to_string()),
"promise hooks: {h1:?}"
);
assert!(h1.contains(&"tool.execute.after".to_string()));
let h2 = sc
.load(
"v2effect",
&dir.path().join("p_v2_effect").join("plug.mjs"),
&input,
&Value::Null,
)
.await?;
assert!(
h2.contains(&"tool.execute.before".to_string()),
"effect hooks: {h2:?}"
);
let out = sc.trigger_v2("session", "context", json!({})).await?;
assert_eq!(out["matched"], 1);
assert_eq!(out["output"]["promiseTouched"], true);
let after = sc
.trigger_v2(
"tool",
"execute.after",
json!({"tool": "read", "result": "orig"}),
)
.await?;
assert_eq!(after["output"]["result"], "mutated-by-promise");
let before = sc
.trigger_v2(
"tool",
"execute.before",
json!({"tool": "read", "input": {}}),
)
.await?;
assert_eq!(before["output"]["input"]["before"], "effect");
let rpc = sc.rpc_call("sample", "hello", json!({"n": 7})).await?;
assert_eq!(rpc["output"]["echoed"]["n"], 7);
let miss = sc.rpc_call("sample", "nope", json!({})).await?;
assert_eq!(miss["error"]["type"], "rpc.method_not_found");
let unreg = sc.rpc_call("ghost", "hello", json!({})).await?;
assert_eq!(unreg["error"]["type"], "rpc.unavailable");
let inv = sc.v2_inventory().await?;
assert_eq!(inv["plugins"].as_array().unwrap().len(), 2, "{inv}");
assert!(
inv["rpcs"]
.as_array()
.unwrap()
.iter()
.any(|r| r == "sample")
);
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn v2_accepts_every_declared_hook_at_registration() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
let surface: serde_json::Value =
serde_json::from_str(include_str!("../tests/fixtures/v2-hooks.json"))?;
let mut body =
String::from("export default {\n id: \"v2allhooks\",\n setup: async (ctx) => {\n");
for (domain, hooks) in surface.as_object().unwrap() {
for hook in hooks.as_array().unwrap() {
let hook = hook.as_str().unwrap();
body.push_str(&format!(
" await ctx.{domain}.hook(\"{hook}\", () => {{}});\n"
));
}
}
body.push_str(" await ctx.event.subscribe(() => {});\n },\n};\n");
std::fs::write(dir.path().join("all_hooks.mjs"), body).unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
let h = sc
.load(
"v2allhooks",
&dir.path().join("all_hooks.mjs"),
&json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
&Value::Null,
)
.await
.expect("every declared hook must register without failing setup");
for d in ["session", "tool", "permission", "shell"] {
assert!(
h.iter().any(|x| x == d || x.starts_with(&format!("{d}."))),
"no {d} hook registered: {h:?}"
);
}
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn v2_unbridged_transform_registers_instead_of_failing_setup() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("p_v2_edit.mjs"),
r#"export default {
id: "v2edit",
setup: async (ctx) => {
// A transform on a domain ocserve does not bridge (upstream's registration
// form, so this is what real plugins do).
await ctx.tool.transform((editor) => { editor.remove("bash"); });
await ctx.integration.transform(() => {});
// The common transform -> reload -> list sequence: reload must resolve.
await ctx.provider.reload();
// The hooks we DO bridge must survive.
await ctx.session.hook("context", (ev) => { ev.survived = true; });
},
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
let hooks = sc
.load(
"v2edit",
&dir.path().join("p_v2_edit.mjs"),
&input,
&Value::Null,
)
.await
.expect("a transform on an unbridged domain must not fail setup");
assert!(
hooks.contains(&"session.context".to_string()),
"the bridged hook must survive: {hooks:?}"
);
let out = sc.trigger_v2("session", "context", json!({})).await?;
assert_eq!(out["matched"], 1);
assert_eq!(out["output"]["survived"], true);
let inv = sc.v2_inventory().await?;
let unbridged: Vec<String> = inv["unbridged_transforms"]
.as_array()
.expect("inventory must list unbridged transforms")
.iter()
.map(|v| v.as_str().unwrap_or_default().to_string())
.collect();
assert!(!unbridged.contains(&"tool".to_string()), "{inv}");
assert!(unbridged.contains(&"integration".to_string()), "{inv}");
std::fs::write(
dir.path().join("p_v2_use.mjs"),
r#"export default {
id: "v2use",
setup: async (ctx) => { await ctx.vcs.apply({}); },
};"#,
)
.unwrap();
let err = sc
.load(
"v2use",
&dir.path().join("p_v2_use.mjs"),
&input,
&Value::Null,
)
.await
.expect_err("using an unbridged domain must still fail loudly");
let text = format!("{err:#}");
assert!(text.contains("D-V2-DOMAIN"), "{text}");
assert!(text.contains("vcs"), "{text}");
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn v2_domain_rest_methods_bind_real_routes() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut s) = stream else { continue };
use std::io::{Read, Write};
let mut buf = [0u8; 2048];
let _ = s.read(&mut buf);
let body = br#"{"id":"ses_bound","title":"bound-route"}"#;
let _ = s.write_all(
format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
body.len()
)
.as_bytes(),
);
let _ = s.write_all(body);
}
});
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("rest.mjs"),
r#"export default {
id: "restprobe",
setup: async (ctx) => {
const results = {};
// plugin.list must return the REAL inventory, not [].
results.pluginList = await ctx.plugin.list();
// session.get must reach the bound route.
try {
const s = await ctx.session.get("ses_bound");
results.sessionGet = { ok: true, id: s && s.id };
} catch (e) { results.sessionGet = { ok: false, err: String(e && e.message || e) }; }
// An UNBOUND verb must throw the NAMED divergence, not a TypeError.
try { await ctx.session.notARealVerb("x"); results.unbound = { threw: false }; }
catch (e) { results.unbound = { threw: true, msg: String(e && e.message || e) }; }
await ctx.rpc.register({ id: "probe" }, { results: async () => results });
},
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, &format!("http://127.0.0.1:{port}"), "/work").await?;
let input = json!({"directory": "/work", "serverUrl": format!("http://127.0.0.1:{port}")});
sc.load(
"restprobe",
&dir.path().join("rest.mjs"),
&input,
&Value::Null,
)
.await?;
let r = sc.rpc_call("probe", "results", json!({})).await?;
let out = &r["output"];
let listed = out["pluginList"].as_array().cloned().unwrap_or_default();
assert!(
listed.iter().any(|p| p["id"] == "restprobe"),
"ctx.plugin.list() must report the loaded plugin: {out}"
);
assert_eq!(
out["sessionGet"]["ok"], true,
"ctx.session.get must reach /api/session/{{id}}: {out}"
);
assert_eq!(out["sessionGet"]["id"], "ses_bound");
assert_eq!(
out["unbound"]["threw"], true,
"unbound verb must throw: {out}"
);
let msg = out["unbound"]["msg"].as_str().unwrap_or_default();
assert!(
msg.contains("D-V2-DOMAIN"),
"unbound verb must name the divergence (D-V2-DOMAIN), got: {msg}"
);
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn v2_command_transform_pulls_into_the_served_list() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("tx.mjs"),
r#"export default {
id: "tx",
setup: async (ctx) => {
// upstream shape: ctx.command.transform((editor) => editor.add({...}))
await ctx.command.transform((editor) => {
editor.add({ name: "plugin-cmd", description: "added by plugin" });
});
await ctx.skill.transform((editor) => {
editor.update("demo-skill", (s) => { s.description = "rewritten by plugin"; });
editor.add({ name: "plugin-skill", description: "skill from plugin", source: "skill" });
});
await ctx.command.reload();
const listed = await ctx.command.list();
await ctx.rpc.register({ id: "probe" }, {
afterSetup: async () => ({ listed }),
});
},
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
let input = json!({"directory": "/work"});
sc.load("tx", &dir.path().join("tx.mjs"), &input, &Value::Null)
.await?;
let pristine = vec![
json!({"name": "demo-skill", "description": "original", "source": "skill"}),
json!({"name": "review", "description": "config command", "source": "config"}),
];
let (edited, failures) = sc.transform_commands(pristine.clone()).await?;
assert!(
failures.is_empty(),
"no transform should have failed: {failures:?}"
);
let added = edited
.iter()
.find(|c| c["name"] == "plugin-cmd")
.expect("plugin command must be present");
assert_eq!(added["description"], "added by plugin");
let skill = edited
.iter()
.find(|c| c["name"] == "demo-skill")
.expect("demo-skill must still be present");
assert_eq!(
skill["description"], "rewritten by plugin",
"skill.transform must reach the vector skill_entries() reads"
);
assert!(
edited
.iter()
.any(|c| c["name"] == "plugin-skill" && c["source"] == "skill"),
"plugin skill must carry source=skill or skill_entries() drops it: {edited:?}"
);
assert!(edited.iter().any(|c| c["name"] == "review"));
let (again, _) = sc.transform_commands(pristine.clone()).await?;
assert_eq!(
serde_json::to_value(&again).unwrap(),
serde_json::to_value(&edited).unwrap(),
"a reload must not accumulate duplicates"
);
let (kept, _) = sc
.transform_commands(vec![json!({"name": "keepme"})])
.await?;
assert!(kept.iter().any(|c| c["name"] == "keepme"));
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn v2_command_transform_failure_keeps_the_list() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("boom.mjs"),
r#"export default {
id: "boom",
setup: async (ctx) => {
await ctx.command.transform(() => { throw new Error("transform exploded"); });
await ctx.command.transform((editor) => { editor.add({ name: "survivor" }); });
},
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
let input = json!({"directory": "/work"});
sc.load("boom", &dir.path().join("boom.mjs"), &input, &Value::Null)
.await?;
let (kept, failures) = sc
.transform_commands(vec![json!({"name": "existing"})])
.await?;
assert!(
kept.iter().any(|c| c["name"] == "survivor"),
"a throwing transform must not stop the others: {kept:?}"
);
assert!(kept.iter().any(|c| c["name"] == "existing"));
assert_eq!(failures.len(), 1, "the throwing transform must be reported");
assert!(
failures[0]["message"]
.as_str()
.unwrap_or_default()
.contains("transform exploded"),
"{failures:?}"
);
sc.shutdown().await;
Ok(())
}
#[tokio::test]
async fn config_hook_is_dispatched() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("cfg.mjs"),
r#"export const PluginModule = {
id: "cfg",
server: async () => ({
config: async (cfg) => {
if (typeof cfg !== "object" || cfg === null) throw new Error("config not object");
},
"chat.message": async () => {},
}),
};
export default PluginModule.server;"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
sc.load("cfg", &dir.path().join("cfg.mjs"), &json!({}), &Value::Null)
.await?;
let r = sc.config(json!({"model": "x"})).await?;
assert_eq!(r["matched"], 1, "config hook must be dispatched: {r}");
sc.shutdown().await;
Ok(())
}
fn runtime_available() -> bool {
crate::which(crate::plugin_runtime().program()).is_some()
}
#[tokio::test]
async fn battery_all_authoring_forms_and_options() -> anyhow::Result<()> {
if !runtime_available() {
panic!(
"plugin-runtime binary ({}) required for plugin-host tests",
crate::plugin_runtime().program()
);
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("p_module.mjs"),
r#"export const PluginModule = {
id: "m",
server: async () => ({ "chat.message": async (_i, o) => { o.module = true; } }),
};"#,
)
.unwrap();
std::fs::write(
dir.path().join("p_default_obj.mjs"),
r#"export default { server: async () => ({ "chat.params": async (_i, o) => { o.defaultobj = true; } }) };"#,
)
.unwrap();
std::fs::write(
dir.path().join("p_default_fn.mjs"),
r#"export default async () => ({ "tool.execute.after": async (_i, o) => { o.defaultfn = true; } });"#,
)
.unwrap();
std::fs::write(
dir.path().join("p_named.mjs"),
r#"export async function MyPlugin() { return { "event": async () => {} }; }"#,
)
.unwrap();
std::fs::write(
dir.path().join("p_options.mjs"),
r#"export const PluginModule = {
id: "opts",
server: async (_input, options) => ({
"chat.message": async (_i, o) => { o.sawOptions = options; },
}),
};"#,
)
.unwrap();
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
let input =
json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
let h1 = sc
.load("m", &dir.path().join("p_module.mjs"), &input, &Value::Null)
.await?;
assert_eq!(h1, vec!["chat.message"], "PluginModule.server form");
let h2 = sc
.load(
"dobj",
&dir.path().join("p_default_obj.mjs"),
&input,
&Value::Null,
)
.await?;
assert_eq!(h2, vec!["chat.params"], "default object with .server form");
let h3 = sc
.load(
"dfn",
&dir.path().join("p_default_fn.mjs"),
&input,
&Value::Null,
)
.await?;
assert_eq!(
h3,
vec!["tool.execute.after"],
"default function (legacy) form"
);
let h4 = sc
.load(
"named",
&dir.path().join("p_named.mjs"),
&input,
&Value::Null,
)
.await?;
assert_eq!(h4, vec!["event"], "named function export form");
let opts = json!({"token": "abc", "n": 3});
let h5 = sc
.load("opts", &dir.path().join("p_options.mjs"), &input, &opts)
.await?;
assert_eq!(
h5,
vec!["chat.message"],
"options-tuple form registers same hook"
);
let out = sc.trigger("chat.message", json!({}), json!({})).await?;
assert_eq!(out["module"], true, "form 1 hook fired");
assert_eq!(out["sawOptions"], opts, "factory saw the tuple options");
let out2 = sc.trigger("chat.params", json!({}), json!({})).await?;
assert_eq!(out2["defaultobj"], true, "form 2 hook fired");
let out3 = sc
.trigger("tool.execute.after", json!({}), json!({}))
.await?;
assert_eq!(out3["defaultfn"], true, "form 3 hook fired");
let st = sc.statuses();
for spec in ["m", "dobj", "dfn", "named", "opts"] {
assert_eq!(st[spec]["ok"], true, "status for {spec}");
}
sc.shutdown().await;
Ok(())
}
}
#[cfg(test)]
mod runtime_selection_tests {
#[test]
fn runtime_override_and_default_preference() {
let has_bun = crate::which("bun").is_some();
let has_node = crate::which("node").is_some();
if !has_node {
panic!("node required for the fallback leg (test environment gate)");
}
unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "node") };
assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
if has_bun {
unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "bun") };
assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Bun);
unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
assert_eq!(
crate::plugin_runtime(),
crate::PluginRuntime::Bun,
"bun present + no override → bun preferred (upstream fidelity)"
);
} else {
unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
}
unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "deno") };
let _ = crate::plugin_runtime();
unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
}
}
#[cfg(test)]
mod oom_wrapper_tests {
#[cfg(target_os = "linux")]
#[test]
fn wrapper_raises_child_oom_score_adj() {
let out = std::process::Command::new("sh")
.arg("-c")
.arg(ocserve_store::cgroup::WRAPPER)
.arg("sh")
.arg("cat")
.arg("/proc/self/oom_score_adj")
.output()
.expect("wrapper spawns");
assert!(
out.status.success(),
"wrapper failed: {}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(
String::from_utf8_lossy(&out.stdout).trim(),
"500",
"child must run at adj=500"
);
}
}
#[cfg(test)]
mod plugin_tool_schema_tests {
use super::*;
#[tokio::test]
async fn plugin_tool_schema_is_valid_json_schema() -> anyhow::Result<()> {
let dir = tempfile::tempdir()?;
let entry = dir.path().join("p_schema.mjs");
std::fs::write(
&entry,
r#"import { z } from "zod";
export const hook = async () => ({
tool: {
ztool: {
description: "zod args",
args: {
text: z.string(),
count: z.number(),
},
execute: async () => "ok",
},
},
});"#,
)?;
std::fs::create_dir_all(dir.path().join("node_modules/zod"))?;
std::fs::write(
dir.path().join("node_modules/zod/package.json"),
r#"{"name":"zod","version":"4.0.0","main":"./index.cjs","exports":{".":"./index.cjs","./v4":"./index.cjs"}}"#,
)?;
std::fs::write(
dir.path().join("node_modules/zod/index.cjs"),
"exports.object = (shape) => ({ shape }); exports.z = { object: (shape) => ({ shape }), string: () => ({ _zod: 1, type: 'string' }), number: () => ({ _zod: 1, type: 'number' }) }; exports.toJSONSchema = () => ({ type: 'object', properties: { text: { type: 'string' }, count: { type: 'integer' } }, required: ['text'] });",
)?;
let host = materialize_host(&dir.path().join("host"))?;
let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
sc.load(
"schema-fixture",
&entry,
&json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
&Value::Null,
)
.await?;
let tools = sc.handle().tools().await?;
let tool = tools
.iter()
.find(|t| t["name"] == "ztool")
.expect("ztool advertised");
let params = &tool["parameters"];
assert_eq!(params["type"], "object", "{params}");
assert_eq!(params["properties"]["text"]["type"], "string", "{params}");
assert!(
params["properties"]["text"].get("~standard").is_none()
&& params["properties"]["text"].get("def").is_none(),
"a raw Zod object must never reach the provider: {params}"
);
sc.shutdown().await;
Ok(())
}
}