1#![cfg_attr(not(test), forbid(unsafe_code))]
12
13pub mod normalize;
14pub use normalize::{Outcome as NormalizeOutcome, normalize_or_raw_sync};
15
16use anyhow::{Context, Result, anyhow};
17use serde_json::{Value, json};
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use tokio::io::{AsyncWriteExt, BufReader};
22use tokio::process::{Child, ChildStdin, Command};
23use tokio::sync::oneshot;
24
25pub const HOST_FILES: &[(&str, &str)] = &[
27 ("host.mjs", include_str!("host/host.mjs")),
28 ("native-assets.mjs", include_str!("host/native-assets.mjs")),
29 ("v2.mjs", include_str!("host/v2.mjs")),
30 (
31 "bun-sqlite-loader.mjs",
32 include_str!("host/bun-sqlite-loader.mjs"),
33 ),
34 (
35 "shim-bun-sqlite.mjs",
36 include_str!("host/shim-bun-sqlite.mjs"),
37 ),
38 (
39 "shim-bun-sqlite.cjs",
40 include_str!("host/shim-bun-sqlite.cjs"),
41 ),
42];
43
44pub const RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
46
47pub fn materialize_host(dir: &Path) -> Result<PathBuf> {
49 std::fs::create_dir_all(dir).with_context(|| format!("create host dir {}", dir.display()))?;
50 for (name, body) in HOST_FILES {
51 let path = dir.join(name);
52 std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
53 }
54 Ok(dir.join("host.mjs"))
55}
56
57pub fn resolve_entry(spec: &str, home: &Path) -> Result<PathBuf> {
66 if let Some(p) = file_url_path(spec) {
67 return entry_from_path(&p);
68 }
69 if let Some(rest) = spec.strip_prefix("~/") {
72 return entry_from_path(&home.join(rest));
73 }
74 if is_path_spec(spec) {
75 return entry_from_path(Path::new(spec));
76 }
77 let cache = home.join(".cache/opencode/packages");
78 let pkg_name = strip_version(spec);
79 let candidates = [
80 cache.join(format!("{spec}@latest")),
81 cache.join(spec),
82 cache.join(format!("{pkg_name}@latest")),
83 ];
84 for dir in &candidates {
85 if !dir.exists() {
86 continue;
87 }
88 let direct = dir.join("package.json");
90 if let Some(entry) = entry_from_package(&direct, dir, &pkg_name) {
91 return Ok(entry);
92 }
93 let nested = dir
94 .join("node_modules")
95 .join(&pkg_name)
96 .join("package.json");
97 if let Some(entry) = entry_from_package(&nested, nested.parent().unwrap_or(dir), &pkg_name)
98 {
99 return Ok(entry);
100 }
101 }
102 anyhow::bail!("plugin target not found in opencode cache: {spec}")
103}
104
105fn is_path_spec(spec: &str) -> bool {
108 let b = spec.as_bytes();
109 let drive = b.len() >= 3
110 && b[0].is_ascii_alphabetic()
111 && b[1] == b':'
112 && (b[2] == b'\\' || b[2] == b'/');
113 spec.starts_with('/')
114 || spec.starts_with("./")
115 || spec.starts_with("../")
116 || Path::new(spec).is_absolute()
117 || drive
118}
119
120fn entry_from_path(p: &Path) -> Result<PathBuf> {
123 let abs;
127 let p = if p.is_absolute() {
128 p
129 } else {
130 match std::env::current_dir() {
131 Ok(cwd) => {
132 abs = cwd.join(p);
133 &abs
134 }
135 Err(_) => p,
136 }
137 };
138 if p.is_file() {
139 return Ok(p.to_path_buf());
140 }
141 if p.is_dir() {
142 return dir_entry(p)
143 .ok_or_else(|| anyhow!("plugin directory has no entrypoint: {}", p.display()));
144 }
145 anyhow::bail!("plugin file not found: {}", p.display())
146}
147
148fn dir_entry(dir: &Path) -> Option<PathBuf> {
152 if let Some(entry) = entry_from_package(&dir.join("package.json"), dir, "") {
153 return Some(entry);
154 }
155 for name in [
156 "index.ts",
157 "index.tsx",
158 "index.js",
159 "index.mjs",
160 "index.cjs",
161 ] {
162 let p = dir.join(name);
163 if p.is_file() {
164 return Some(p);
165 }
166 }
167 None
168}
169
170fn file_url_path(spec: &str) -> Option<PathBuf> {
175 let rest = spec.strip_prefix("file://")?;
176 let rest = match rest.strip_prefix("localhost") {
178 Some(r) if r.starts_with('/') => r,
179 _ => rest,
180 };
181 if !rest.starts_with('/') {
182 return None;
183 }
184 let decoded = percent_decode(rest);
185 if decoded.is_empty() {
186 return None;
187 }
188 #[cfg(windows)]
189 let decoded = decoded.trim_start_matches('/').to_string();
190 Some(PathBuf::from(decoded))
191}
192
193fn percent_decode(s: &str) -> String {
194 let bytes = s.as_bytes();
195 let mut out = Vec::with_capacity(bytes.len());
196 let mut i = 0;
197 while i < bytes.len() {
198 if bytes[i] == b'%'
199 && i + 2 < bytes.len()
200 && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
201 {
202 out.push(hi * 16 + lo);
203 i += 3;
204 continue;
205 }
206 out.push(bytes[i]);
207 i += 1;
208 }
209 String::from_utf8_lossy(&out).into_owned()
210}
211
212fn hex_nibble(b: u8) -> Option<u8> {
213 match b {
214 b'0'..=b'9' => Some(b - b'0'),
215 b'a'..=b'f' => Some(b - b'a' + 10),
216 b'A'..=b'F' => Some(b - b'A' + 10),
217 _ => None,
218 }
219}
220
221pub fn discover_plugin_specs(config_dir: &Path) -> Vec<String> {
230 const MAX_DISCOVERED: usize = 64;
231 let mut out = Vec::new();
232 for sub in ["plugin", "plugins"] {
233 let dir = config_dir.join(sub);
234 let Ok(entries) = std::fs::read_dir(&dir) else {
235 continue;
236 };
237 let mut entries: Vec<_> = entries.flatten().collect();
238 entries.sort_by_key(|e| e.file_name());
239 for entry in entries {
240 if out.len() >= MAX_DISCOVERED {
241 break;
242 }
243 let path = entry.path();
244 let Ok(meta) = std::fs::metadata(&path) else {
247 continue;
248 };
249 let is_source = meta.is_file()
250 && matches!(
251 path.extension().and_then(|e| e.to_str()),
252 Some("ts") | Some("js")
253 );
254 if (is_source || meta.is_dir())
255 && let Some(s) = path.to_str()
256 {
257 out.push(s.to_string());
258 }
259 }
260 }
261 out.sort();
262 out.dedup();
263 out.truncate(MAX_DISCOVERED);
264 out
265}
266
267fn strip_version(spec: &str) -> String {
268 let bytes = spec.as_bytes();
270 let mut cut = None;
272 for (i, b) in bytes.iter().enumerate() {
273 if *b == b'@' && i > 0 {
274 cut = Some(i);
275 }
276 }
277 match cut {
278 Some(i) => spec[..i].to_string(),
279 None => spec.to_string(),
280 }
281}
282
283fn entry_from_package(pkg_json: &Path, base: &Path, _pkg_name: &str) -> Option<PathBuf> {
284 let text = std::fs::read_to_string(pkg_json).ok()?;
285 let v: Value = serde_json::from_str(&text).ok()?;
286 let mut rel: Option<&str> = None;
287 if let Some(exp) = v.get("exports") {
288 for key in [".", "./server"] {
292 let Some(dot) = exp.get(key) else { continue };
293 rel = match dot {
294 Value::String(s) => Some(s.as_str()),
295 Value::Object(_) => dot
296 .get("import")
297 .and_then(|x| x.as_str())
298 .or_else(|| dot.get("default").and_then(|x| x.as_str())),
299 _ => None,
300 };
301 if rel.is_some() {
302 break;
303 }
304 }
305 }
306 rel = rel.or_else(|| v.get("main").and_then(|x| x.as_str()));
307 rel = rel.or_else(|| v.get("module").and_then(|x| x.as_str()));
308 let rel = rel?;
309 let entry = base.join(rel);
310 let lex = lexically_normalize(&entry);
314 if !lex.starts_with(base)
315 && !std::fs::canonicalize(base)
316 .ok()
317 .is_some_and(|cb| lex.starts_with(&cb))
318 {
319 tracing::warn!("plugin entry {rel} escapes its package dir — refused");
320 return None;
321 }
322 lex.exists().then_some(lex)
323}
324
325fn lexically_normalize(p: &Path) -> PathBuf {
326 use std::path::Component;
327 let mut out = PathBuf::new();
328 for c in p.components() {
329 match c {
330 Component::ParentDir => {
331 out.pop();
332 }
333 Component::CurDir => {}
334 other => out.push(other.as_os_str()),
335 }
336 }
337 out
338}
339
340struct Pending {
341 tx: oneshot::Sender<Result<Value, String>>,
342}
343
344struct PendingGuard {
348 pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
349 id: i64,
350}
351
352impl PendingGuard {
353 fn new(pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>, id: i64) -> Self {
354 Self { pending, id }
355 }
356}
357
358impl Drop for PendingGuard {
359 fn drop(&mut self) {
360 self.pending.lock().remove(&self.id);
361 }
362}
363
364pub struct Inner {
378 stdin: tokio::sync::Mutex<ChildStdin>,
379 pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
381 next_id: std::sync::atomic::AtomicI64,
382 statuses: parking_lot::Mutex<HashMap<String, Value>>,
384 alive: Arc<std::sync::atomic::AtomicBool>,
386 poisoned: Arc<std::sync::atomic::AtomicBool>,
388 last_tools: parking_lot::Mutex<Option<Vec<Value>>>,
391}
392
393#[derive(Clone)]
395pub struct Handle(Arc<Inner>);
396
397impl Handle {
398 pub fn is_alive(&self) -> bool {
401 self.0.alive.load(std::sync::atomic::Ordering::Acquire)
402 }
403
404 pub fn registers(&self, hook: &str) -> bool {
407 self.0.statuses.lock().values().any(|v| {
408 v.get("hooks")
409 .and_then(|h| h.as_array())
410 .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(hook)))
411 })
412 }
413
414 pub fn any_loaded(&self) -> bool {
418 self.0
419 .statuses
420 .lock()
421 .values()
422 .any(|v| v.get("ok").and_then(|b| b.as_bool()).unwrap_or(false))
423 }
424
425 pub fn has_tools(&self) -> bool {
429 self.0.statuses.lock().values().any(|v| {
430 v.get("has_tools")
431 .and_then(|b| b.as_bool())
432 .unwrap_or(false)
433 })
434 }
435
436 pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
437 self.request_with_timeout(method, params, Some(RPC_TIMEOUT))
438 .await
439 }
440
441 pub async fn request_with_timeout(
442 &self,
443 method: &str,
444 params: Value,
445 timeout: Option<std::time::Duration>,
446 ) -> Result<Value> {
447 if !self.is_alive() {
448 anyhow::bail!("plugin host is down ({method}); a respawn is required");
449 }
450 let id = self
451 .0
452 .next_id
453 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
454 let (tx, rx) = oneshot::channel();
455 self.0.pending.lock().insert(id, Pending { tx });
456 let _guard = PendingGuard::new(Arc::clone(&self.0.pending), id);
457 let msg = json!({"id": id, "method": method, "params": params});
458 let mut line = msg.to_string();
459 line.push('\n');
460 let exchange = async {
465 {
466 let mut stdin = self.0.stdin.lock().await;
467 stdin.write_all(line.as_bytes()).await?;
468 stdin.flush().await?;
469 }
470 match rx.await {
471 Ok(res) => res.map_err(|e| anyhow!("plugin host {method}: {e}")),
472 Err(_) => Err(anyhow!("plugin host dropped response for {method}")),
473 }
474 };
475 match timeout {
476 None => exchange
477 .await
478 .map_err(|e| e.context("plugin host stdin write")),
479 Some(d) => match tokio::time::timeout(d, exchange).await {
480 Ok(res) => res,
481 Err(_) => {
482 self.0
483 .poisoned
484 .store(true, std::sync::atomic::Ordering::Release);
485 self.0
486 .alive
487 .store(false, std::sync::atomic::Ordering::Release);
488 ocserve_metrics::labeled_counter(
489 "ocserve_plugin_hook_timeout_total",
490 &format!("hook=\"{method}\""),
491 1,
492 );
493 Err(anyhow!(
494 "plugin host {method} timed out after {}ms (runaway hook?)",
495 d.as_millis()
496 ))
497 }
498 },
499 }
500 }
501}
502
503impl Handle {
504 pub async fn trigger_bounded(
505 &self,
506 name: &str,
507 input: Value,
508 mut output: Value,
509 budget: Option<std::time::Duration>,
510 ) -> Result<Value> {
511 let res = self
512 .request_with_timeout(
513 "trigger",
514 json!({"name": name, "input": input, "output": output}),
515 budget,
516 )
517 .await?;
518 if res.is_object() {
519 output = res;
520 }
521 Ok(output)
522 }
523
524 pub async fn trigger_v2_bounded(
525 &self,
526 domain: &str,
527 name: &str,
528 input: Value,
529 budget: Option<std::time::Duration>,
530 ) -> Result<Value> {
531 self.request_with_timeout(
532 "trigger_v2",
533 json!({"domain": domain, "name": name, "input": input}),
534 budget,
535 )
536 .await
537 }
538
539 pub async fn emit_event_bounded(
540 &self,
541 event: Value,
542 budget: Option<std::time::Duration>,
543 ) -> Result<Value> {
544 self.request_with_timeout("event", json!({"event": event}), budget)
545 .await
546 }
547}
548
549pub fn hook_budget(hook: &str) -> Option<std::time::Duration> {
556 match std::env::var("OCSERVE_HOOK_TIMEOUT_MS")
557 .ok()
558 .and_then(|v| v.parse::<u64>().ok())
559 {
560 Some(0) => None,
561 Some(ms) => Some(std::time::Duration::from_millis(ms)),
562 None => Some(std::time::Duration::from_secs(
563 if hook.contains("tool.execute") {
564 180
565 } else if hook.contains("transform")
566 || hook.contains("context")
567 || hook.contains("compact")
570 {
571 60
572 } else {
573 30
574 },
575 )),
576 }
577}
578
579impl Handle {
580 pub async fn rpc_call(&self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
582 self.request(
583 "rpc_call",
584 json!({"rpcID": rpc_id, "method": method, "input": input}),
585 )
586 .await
587 }
588
589 pub async fn v2_inventory(&self) -> Result<Value> {
592 self.request("v2_inventory", json!({})).await
593 }
594
595 pub async fn transform_commands(
597 &self,
598 commands: Vec<Value>,
599 ) -> Result<(Vec<Value>, Vec<Value>)> {
600 let r = self
601 .request("v2_transform_commands", json!({ "commands": commands }))
602 .await?;
603 let out = r["commands"]
604 .as_array()
605 .cloned()
606 .unwrap_or_default()
607 .into_iter()
608 .collect();
609 let failures = r["failures"].as_array().cloned().unwrap_or_default();
610 Ok((out, failures))
611 }
612}
613
614impl Handle {
615 pub async fn tools(&self) -> Result<Vec<Value>> {
623 if !self.any_loaded() {
630 return Ok(Vec::new());
631 }
632 match self.request("tools", json!({})).await {
633 Ok(res) => {
634 let list = res.as_array().cloned().unwrap_or_default();
635 *self.0.last_tools.lock() = Some(list.clone());
636 Ok(list)
637 }
638 Err(e) => {
639 if let Some(cached) = self.0.last_tools.lock().clone() {
640 tracing::warn!("plugin tools: {e:#} — serving the last known list");
641 return Ok(cached);
642 }
643 Err(e)
644 }
645 }
646 }
647
648 pub async fn execute_tool(&self, name: &str, input: Value, ctx: Value) -> Result<Value> {
651 self.request_with_timeout(
652 "tool_execute",
653 json!({"name": name, "input": input, "ctx": ctx}),
654 Some(std::time::Duration::from_secs(300)),
655 )
656 .await
657 }
658}
659
660pub struct Sidecar {
662 inner: Arc<Inner>,
663 child: Child,
664 server: (String, String),
666 args: SpawnArgs,
668 loads: Vec<(String, PathBuf, Value, Value)>,
673 normalize_root: Option<PathBuf>,
676 started_at: std::time::Instant,
680 recycled: bool,
684}
685
686#[derive(Debug, Clone, Copy, PartialEq, Eq)]
690pub enum PluginRuntime {
691 Bun,
692 Node,
693}
694
695impl PluginRuntime {
696 pub fn program(self) -> &'static str {
697 match self {
698 PluginRuntime::Bun => "bun",
699 PluginRuntime::Node => "node",
700 }
701 }
702}
703
704pub(crate) fn which(prog: &str) -> Option<PathBuf> {
707 let name = ocserve_store::platform::exe(prog);
711 if let Ok(path) = std::env::var("PATH") {
712 for dir in std::env::split_paths(&path) {
713 let cand = dir.join(&name);
714 if ocserve_store::platform::is_executable_file(&cand) {
715 return Some(cand);
716 }
717 }
718 }
719 for key in ["OCSERVE_HOME", "HOME", "USERPROFILE"] {
720 let Some(home) = std::env::var_os(key).filter(|v| !v.is_empty()) else {
721 continue;
722 };
723 let cand = Path::new(&home).join(".bun/bin").join(&name);
724 if ocserve_store::platform::is_executable_file(&cand) {
725 return Some(cand);
726 }
727 }
728 None
729}
730
731pub fn plugin_runtime() -> PluginRuntime {
732 match std::env::var("OCSERVE_PLUGIN_RUNTIME").as_deref() {
733 Ok("node") => return PluginRuntime::Node,
734 Ok("bun") => return PluginRuntime::Bun,
735 _ => {}
736 }
737 if which("bun").is_some() {
738 PluginRuntime::Bun
739 } else {
740 PluginRuntime::Node
741 }
742}
743
744#[derive(Clone)]
745struct SpawnArgs {
746 host_path: PathBuf,
747 server_url: String,
748 directory: String,
749}
750
751impl Sidecar {
752 pub async fn spawn(host_path: &Path, server_url: &str, directory: &str) -> Result<Self> {
753 let runtime = crate::plugin_runtime();
757 let program = which(runtime.program())
760 .map(|p| p.to_string_lossy().into_owned())
761 .unwrap_or_else(|| runtime.program().to_string());
762 let shape = ocserve_store::cgroup::contained(&program, "plugin");
766 let mut cmd = Command::new(&shape.program);
767 cmd.args(&shape.prefix);
768 cmd.env("OCSERVE_VERSION", env!("CARGO_PKG_VERSION"));
772 match &shape.cgroup {
773 Some(p) => {
774 cmd.env(ocserve_store::cgroup::ENV, p);
775 }
776 None => {
777 cmd.env_remove(ocserve_store::cgroup::ENV);
778 }
779 }
780 match runtime {
781 PluginRuntime::Bun => {
785 cmd.arg("--smol");
786 }
787 PluginRuntime::Node => {
794 cmd.arg(format!(
795 "--max-old-space-size={}",
796 std::env::var("OCSERVE_PLUGIN_HEAP_MB")
797 .ok()
798 .and_then(|v| v.parse().ok())
799 .unwrap_or(128)
800 ));
801 cmd.arg("--max-semi-space-size=2");
802 }
803 }
804 cmd.arg(host_path)
805 .stdin(std::process::Stdio::piped())
806 .stdout(std::process::Stdio::piped())
807 .stderr(std::process::Stdio::inherit())
808 .kill_on_drop(true);
809 let mut child = cmd
810 .spawn()
811 .with_context(|| format!("spawn {} plugin host", runtime.program()))?;
812 let stdin = child.stdin.take().context("host stdin")?;
813 let stdout = child.stdout.take().context("host stdout")?;
814 let pending = Arc::new(parking_lot::Mutex::new(HashMap::<i64, Pending>::new()));
815 let pending_task = Arc::clone(&pending);
816 let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
817 let alive_task = Arc::clone(&alive);
818 let poisoned = Arc::new(std::sync::atomic::AtomicBool::new(false));
819 let poisoned_task = Arc::clone(&poisoned);
820 tokio::spawn(async move {
821 const MAX_HOST_LINE: usize = 8 * 1024 * 1024;
826 let mut reader = BufReader::new(stdout);
827 let mut line = String::new();
828 loop {
829 line.clear();
830 use tokio::io::AsyncBufReadExt as _;
831 let n = {
832 let mut limited =
833 tokio::io::AsyncReadExt::take(&mut reader, MAX_HOST_LINE as u64 + 1);
834 limited.read_line(&mut line).await
835 };
836 match n {
837 Ok(0) | Err(_) => break,
838 Ok(_) if line.len() > MAX_HOST_LINE => {
841 tracing::warn!("plugin host: oversized line — child marked for respawn");
846 poisoned_task.store(true, std::sync::atomic::Ordering::Release);
847 break;
848 }
849 Ok(_) => {}
850 }
851 let trimmed = line.trim();
852 if trimmed.is_empty() {
853 continue;
854 }
855 match serde_json::from_str::<Value>(trimmed) {
856 Ok(v) => {
857 if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
858 let result = match v.get("error") {
859 Some(e) if !e.is_null() => {
860 Err(e["message"].as_str().unwrap_or("host error").to_string())
861 }
862 _ => Ok(v.get("result").cloned().unwrap_or(Value::Null)),
863 };
864 if let Some(p) = pending_task.lock().remove(&id) {
865 let _ = p.tx.send(result);
866 }
867 } else if v.get("event").and_then(|e| e.as_str()) == Some("plugin_error") {
868 ocserve_metrics::labeled_counter(
873 "ocserve_plugin_internal_error_total",
874 &format!(
875 "plugin=\"{}\",hook=\"{}\"",
876 v["plugin"].as_str().unwrap_or("?"),
877 v["hook"].as_str().unwrap_or("?")
878 ),
879 1,
880 );
881 tracing::warn!(
882 "plugin internal error: {} {}: {}",
883 v["plugin"].as_str().unwrap_or("?"),
884 v["hook"].as_str().unwrap_or("?"),
885 v["error"].as_str().unwrap_or("?")
886 );
887 }
888 }
890 Err(_) => {
891 let head: String = trimmed.chars().take(120).collect();
892 tracing::warn!("plugin host: unparsable line: {head}");
893 }
894 }
895 }
896 alive_task.store(false, std::sync::atomic::Ordering::Release);
899 for (_, p) in pending_task.lock().drain() {
900 let _ = p.tx.send(Err("plugin host exited".into()));
901 }
902 ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 0);
903 });
904 ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 1);
905 Ok(Self {
906 inner: Arc::new(Inner {
907 stdin: tokio::sync::Mutex::new(stdin),
908 pending,
909 next_id: std::sync::atomic::AtomicI64::new(1),
910 statuses: parking_lot::Mutex::new(HashMap::new()),
911 alive,
912 poisoned,
913 last_tools: parking_lot::Mutex::new(None),
914 }),
915 child,
916 server: (server_url.to_string(), directory.to_string()),
917 args: SpawnArgs {
918 host_path: host_path.to_path_buf(),
919 server_url: server_url.to_string(),
920 directory: directory.to_string(),
921 },
922 loads: Vec::new(),
923 normalize_root: None,
924 started_at: std::time::Instant::now(),
925 recycled: false,
926 })
927 }
928
929 pub fn in_flight(&self) -> usize {
932 self.inner.pending.lock().len()
933 }
934
935 pub fn uptime(&self) -> std::time::Duration {
937 self.started_at.elapsed()
938 }
939
940 pub fn recycle_child(&mut self) -> bool {
946 if self.child.try_wait().ok().flatten().is_some() {
947 return false;
948 }
949 let _ = self.child.start_kill();
950 self.inner
957 .alive
958 .store(false, std::sync::atomic::Ordering::Release);
959 self.recycled = true;
960 true
961 }
962
963 pub fn set_normalize_root(&mut self, root: PathBuf) {
967 self.normalize_root = Some(root);
968 }
969
970 pub async fn ensure_alive(&mut self) -> Result<()> {
975 if self
979 .inner
980 .poisoned
981 .load(std::sync::atomic::Ordering::Acquire)
982 {
983 let _ = self.child.start_kill();
984 self.inner
985 .alive
986 .store(false, std::sync::atomic::Ordering::Release);
987 } else if self.inner.alive.load(std::sync::atomic::Ordering::Acquire)
988 && let Ok(None) = self.child.try_wait()
989 {
990 return Ok(());
991 }
992 ocserve_metrics::labeled_counter(
993 "ocserve_plugin_sidecar_respawn_total",
994 if self.recycled {
995 "reason=\"recycle\""
996 } else {
997 "reason=\"exit\""
998 },
999 1,
1000 );
1001 let status = self.child.try_wait().ok().flatten();
1002 if std::mem::take(&mut self.recycled) {
1003 tracing::info!(
1004 "plugin sidecar recycled (L1, was {status:?}) — respawning + replaying hooks"
1005 );
1006 } else if let Some(status) = status {
1007 tracing::error!("plugin sidecar exited ({status}) — respawning");
1008 } else {
1009 tracing::warn!("plugin sidecar unresponsive — replacing the host");
1010 }
1011 let args = self.args.clone();
1012 let loads = std::mem::take(&mut self.loads);
1013 let mut fresh =
1018 match Sidecar::spawn(&args.host_path, &args.server_url, &args.directory).await {
1019 Ok(f) => f,
1020 Err(e) => {
1021 self.loads = loads;
1022 tracing::error!("plugin sidecar respawn failed: {e:#} — plugin set preserved");
1023 return Err(e);
1024 }
1025 };
1026 fresh.normalize_root = self.normalize_root.clone();
1029 for (spec, entry, input, options) in &loads {
1030 if let Err(e) = fresh.load_raw(spec, entry, input, options).await {
1031 tracing::warn!("plugin {spec} reload after respawn failed: {e:#}");
1032 }
1033 }
1034 *self = fresh;
1035 Ok(())
1036 }
1037
1038 pub fn child_pid(&self) -> u32 {
1040 self.child.id().unwrap_or(0)
1041 }
1042
1043 pub fn handle(&self) -> Handle {
1044 Handle(Arc::clone(&self.inner))
1045 }
1046
1047 pub async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
1048 self.ensure_alive().await?;
1049 self.handle().request(method, params).await
1050 }
1051
1052 pub async fn request_bounded(
1054 &mut self,
1055 method: &str,
1056 params: Value,
1057 timeout: Option<std::time::Duration>,
1058 ) -> Result<Value> {
1059 self.ensure_alive().await?;
1060 self.handle()
1061 .request_with_timeout(method, params, timeout)
1062 .await
1063 }
1064
1065 pub async fn load(
1069 &mut self,
1070 spec: &str,
1071 entry: &Path,
1072 input: &Value,
1073 options: &Value,
1074 ) -> Result<Vec<String>> {
1075 self.ensure_alive().await?;
1076 self.load_raw(spec, entry, input, options).await
1077 }
1078
1079 async fn load_raw(
1081 &mut self,
1082 spec: &str,
1083 entry: &Path,
1084 input: &Value,
1085 options: &Value,
1086 ) -> Result<Vec<String>> {
1087 let root = self.normalize_root.clone();
1090 let raw = entry.to_path_buf();
1091 let raw_for_spawn = raw.clone();
1092 let (load_path, outcome) = tokio::task::spawn_blocking(move || {
1093 crate::normalize::normalize_or_raw_sync(root.as_deref(), &raw_for_spawn)
1094 })
1095 .await
1096 .map_err(|e| anyhow!("normalize task: {e}"))?;
1097 ocserve_metrics::labeled_counter(
1098 "ocserve_plugin_normalize_total",
1099 &format!("result=\"{}\"", outcome.label()),
1100 1,
1101 );
1102 match &outcome {
1103 crate::normalize::Outcome::Built {
1104 path,
1105 ms,
1106 beside,
1107 rss_before_kb,
1108 rss_after_kb,
1109 } => tracing::info!(
1110 "plugin normalize {spec}: built {} ({}) in {ms}ms rss {rss_before_kb}→{rss_after_kb}kB",
1111 path.display(),
1112 if *beside { "beside-entry" } else { "data-dir" }
1113 ),
1114 crate::normalize::Outcome::Fallback { err, .. } => {
1115 tracing::warn!("plugin normalize {spec} failed, loading raw entry: {err}")
1116 }
1117 _ => {}
1118 }
1119 let mut input = input.clone();
1121 if input
1122 .get("serverUrl")
1123 .and_then(|v| v.as_str())
1124 .unwrap_or("")
1125 .is_empty()
1126 {
1127 input["serverUrl"] = json!(self.server.0);
1128 }
1129 if input
1130 .get("directory")
1131 .and_then(|v| v.as_str())
1132 .unwrap_or("")
1133 .is_empty()
1134 {
1135 input["directory"] = json!(self.server.1);
1136 }
1137 let params = json!({
1138 "spec": spec,
1139 "entry": load_path.to_string_lossy(),
1140 "origin": raw.to_string_lossy(),
1145 "input": input,
1146 "options": options,
1147 });
1148 let res = self.handle().request("load", params).await?;
1149 let hooks: Vec<String> = res["hooks"]
1150 .as_array()
1151 .map(|a| {
1152 a.iter()
1153 .filter_map(|h| h.as_str().map(String::from))
1154 .collect()
1155 })
1156 .unwrap_or_default();
1157 self.inner.statuses.lock().insert(
1158 spec.to_string(),
1159 json!({
1160 "ok": true,
1161 "hooks": hooks,
1162 "id": res["id"],
1163 "has_tools": res["has_tools"].as_bool().unwrap_or(false),
1167 }),
1168 );
1169 self.loads.push((
1170 spec.to_string(),
1171 entry.to_path_buf(),
1172 input,
1173 options.clone(),
1174 ));
1175 Ok(hooks)
1176 }
1177
1178 pub fn attempted(&self, spec: &str) -> bool {
1182 self.inner.statuses.lock().contains_key(spec)
1183 }
1184
1185 pub async fn load_discovered(&mut self, spec: &str, home: &Path) -> Result<Vec<String>> {
1190 if self.attempted(spec) {
1191 return Ok(Vec::new());
1192 }
1193 let entry = match resolve_entry(spec, home) {
1194 Ok(entry) => entry,
1195 Err(e) => {
1196 self.note_failure(spec, &e);
1197 return Err(e);
1198 }
1199 };
1200 self.ensure_alive().await?;
1201 let input = json!({
1202 "directory": self.server.1,
1203 "projectID": "global",
1204 "worktree": "/",
1205 "serverUrl": self.server.0,
1206 });
1207 match self.load(spec, &entry, &input, &json!({})).await {
1208 Ok(hooks) => Ok(hooks),
1209 Err(e) => {
1210 self.note_failure(spec, &e);
1211 Err(e)
1212 }
1213 }
1214 }
1215
1216 pub fn note_failure(&self, spec: &str, e: &anyhow::Error) {
1220 self.inner.statuses.lock().insert(
1221 spec.to_string(),
1222 json!({"ok": false, "hooks": [], "error": format!("{e:#}")}),
1223 );
1224 }
1225
1226 pub async fn trigger(&mut self, name: &str, input: Value, mut output: Value) -> Result<Value> {
1228 let params = json!({"name": name, "input": input, "output": output});
1229 let res = self.request("trigger", params).await?;
1230 if res.is_object() {
1231 output = res;
1232 }
1233 Ok(output)
1234 }
1235
1236 pub async fn emit_event(&mut self, event: Value) -> Result<Value> {
1239 self.request("event", json!({"event": event})).await
1240 }
1241
1242 pub async fn trigger_v2(&mut self, domain: &str, name: &str, input: Value) -> Result<Value> {
1246 self.request(
1247 "trigger_v2",
1248 json!({"domain": domain, "name": name, "input": input}),
1249 )
1250 .await
1251 }
1252
1253 pub async fn rpc_call(&mut self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
1257 self.ensure_alive().await?;
1258 self.handle().rpc_call(rpc_id, method, input).await
1259 }
1260
1261 pub async fn v2_inventory(&mut self) -> Result<Value> {
1264 self.ensure_alive().await?;
1265 self.handle().v2_inventory().await
1266 }
1267
1268 pub async fn transform_commands(
1282 &mut self,
1283 commands: Vec<Value>,
1284 ) -> Result<(Vec<Value>, Vec<Value>)> {
1285 self.ensure_alive().await?;
1286 self.handle().transform_commands(commands).await
1287 }
1288
1289 pub async fn config(&mut self, cfg: Value) -> Result<Value> {
1290 self.request("config", json!({"config": cfg})).await
1291 }
1292
1293 pub fn statuses(&self) -> Value {
1294 let mut out = serde_json::Map::new();
1295 for (spec, v) in self.inner.statuses.lock().iter() {
1296 out.insert(spec.clone(), v.clone());
1297 }
1298 Value::Object(out)
1299 }
1300
1301 pub async fn shutdown(&mut self) {
1302 let _ = self.request("dispose", json!({})).await;
1303 let _ = self.child.start_kill();
1304 }
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309 use super::*;
1310
1311 #[test]
1312 fn strip_version_cases() {
1313 assert_eq!(strip_version("context-mode"), "context-mode");
1314 assert_eq!(strip_version("context-mode@latest"), "context-mode");
1315 assert_eq!(
1316 strip_version("@cortexkit/opencode-magic-context@latest"),
1317 "@cortexkit/opencode-magic-context"
1318 );
1319 assert_eq!(
1320 strip_version("@iam-brain/opencode-codex-auth@latest"),
1321 "@iam-brain/opencode-codex-auth"
1322 );
1323 }
1324
1325 #[test]
1326 fn entry_from_package_shapes() {
1327 let dir = tempfile::tempdir().unwrap();
1328 std::fs::write(
1330 dir.path().join("package.json"),
1331 r#"{"exports": {".": "./dist/index.js"}}"#,
1332 )
1333 .unwrap();
1334 std::fs::create_dir(dir.path().join("dist")).unwrap();
1335 std::fs::write(dir.path().join("dist/index.js"), "//").unwrap();
1336 let e = entry_from_package(&dir.path().join("package.json"), dir.path(), "x")
1337 .expect("exports dot");
1338 assert!(e.ends_with("dist/index.js"));
1339 std::fs::write(
1341 dir.path().join("package.json"),
1342 r#"{"main": "./lib/main.js"}"#,
1343 )
1344 .unwrap();
1345 std::fs::create_dir(dir.path().join("lib")).unwrap();
1346 std::fs::write(dir.path().join("lib/main.js"), "//").unwrap();
1347 let e =
1348 entry_from_package(&dir.path().join("package.json"), dir.path(), "x").expect("main");
1349 assert!(e.ends_with("lib/main.js"));
1350 }
1351
1352 #[test]
1353 fn resolve_entry_accepts_file_urls_and_directories() {
1354 let dir = tempfile::tempdir().unwrap();
1355 let file = dir.path().join("bridge.mjs");
1357 std::fs::write(&file, "//").unwrap();
1358 let url = format!("file://{}", file.display());
1359 assert_eq!(resolve_entry(&url, dir.path()).unwrap(), file);
1360 let spaced = dir.path().join("bridge copy.mjs");
1362 std::fs::write(&spaced, "//").unwrap();
1363 let encoded = format!("file://{}", spaced.display()).replace(' ', "%20");
1364 assert_eq!(resolve_entry(&encoded, dir.path()).unwrap(), spaced);
1365 let pkg = dir.path().join("managed-bridge");
1369 std::fs::create_dir_all(pkg.join("dist")).unwrap();
1370 std::fs::write(
1371 pkg.join("package.json"),
1372 r#"{"name":"paseo-managed-bridge","type":"module","exports":{"./server":"./dist/main.mjs"}}"#,
1373 )
1374 .unwrap();
1375 std::fs::write(pkg.join("dist/main.mjs"), "//").unwrap();
1376 assert_eq!(
1377 resolve_entry(pkg.to_str().unwrap(), dir.path()).unwrap(),
1378 pkg.join("dist/main.mjs")
1379 );
1380 let plain = dir.path().join("plain");
1382 std::fs::create_dir_all(&plain).unwrap();
1383 std::fs::write(plain.join("index.ts"), "//").unwrap();
1384 assert_eq!(
1385 resolve_entry(plain.to_str().unwrap(), dir.path()).unwrap(),
1386 plain.join("index.ts")
1387 );
1388 let empty = dir.path().join("empty");
1390 std::fs::create_dir_all(&empty).unwrap();
1391 let err = resolve_entry(empty.to_str().unwrap(), dir.path()).unwrap_err();
1392 assert!(err.to_string().contains("no entrypoint"), "{err}");
1393 }
1394
1395 #[test]
1396 fn resolve_entry_negative_control_still_rejects_unknown_packages() {
1397 let dir = tempfile::tempdir().unwrap();
1398 let err = resolve_entry("no-such-plugin-package", dir.path()).unwrap_err();
1399 assert!(err.to_string().contains("plugin target not found"), "{err}");
1400 }
1401
1402 #[test]
1403 fn discover_plugin_specs_matches_upstream_layout() {
1404 let dir = tempfile::tempdir().unwrap();
1405 std::fs::create_dir_all(dir.path().join("plugin")).unwrap();
1406 std::fs::create_dir_all(dir.path().join("plugins/managed-bridge")).unwrap();
1407 std::fs::write(dir.path().join("plugin/a.js"), "//").unwrap();
1408 std::fs::write(dir.path().join("plugin/b.mjs"), "//").unwrap(); std::fs::write(dir.path().join("plugins/readme.txt"), "x").unwrap();
1410 let got = discover_plugin_specs(dir.path());
1411 assert!(
1412 got.iter().any(|s| s.ends_with("/plugin/a.js")),
1413 "a .js source file is discovered: {got:?}"
1414 );
1415 assert!(
1416 got.iter().any(|s| s.ends_with("/plugins/managed-bridge")),
1417 "a package DIRECTORY is discovered: {got:?}"
1418 );
1419 assert!(
1420 !got.iter().any(|s| s.ends_with("b.mjs")),
1421 "upstream does not discover .mjs by glob: {got:?}"
1422 );
1423 assert!(!got.iter().any(|s| s.ends_with("readme.txt")));
1424 assert_eq!(got.len(), 2, "{got:?}");
1427 }
1428
1429 #[tokio::test]
1433 async fn v2_tool_transform_registers_and_executes() -> anyhow::Result<()> {
1434 if !runtime_available() {
1435 panic!(
1436 "plugin-runtime binary ({}) required for plugin-host tests",
1437 crate::plugin_runtime().program()
1438 );
1439 }
1440 let dir = tempfile::tempdir().unwrap();
1441 std::fs::write(
1442 dir.path().join("tools.mjs"),
1443 r#"export default {
1444 id: "toolshop",
1445 setup: async (ctx) => {
1446 await ctx.tool.transform((editor) => {
1447 editor.add({
1448 name: "echo",
1449 description: "echo the input",
1450 input: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
1451 async execute(input, call) {
1452 return {
1453 content: [{ type: "text", text: `hi ${input.text} ${call.sessionID}` }],
1454 metadata: { tag: "v2" },
1455 };
1456 },
1457 });
1458 });
1459 },
1460};"#,
1461 )
1462 .unwrap();
1463 let host = materialize_host(&dir.path().join("host"))?;
1464 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1465 sc.load(
1466 "toolshop",
1467 &dir.path().join("tools.mjs"),
1468 &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1469 &json!({}),
1470 )
1471 .await?;
1472 assert!(sc.handle().has_tools(), "load must report has_tools");
1473 let tools = sc.handle().tools().await?;
1474 let tool = tools
1475 .iter()
1476 .find(|t| t["name"] == "echo")
1477 .expect("v2 tool advertised");
1478 assert_eq!(tool["parameters"]["properties"]["text"]["type"], "string");
1479 let res = sc
1480 .handle()
1481 .execute_tool("echo", json!({"text": "x"}), json!({"sessionID": "s1"}))
1482 .await?;
1483 assert_eq!(res["ok"], true, "{res}");
1484 assert_eq!(res["output"], "hi x s1", "{res}");
1485 assert_eq!(res["metadata"]["tag"], "v2", "{res}");
1486 let missing = sc
1488 .handle()
1489 .execute_tool("nope", json!({}), json!({}))
1490 .await?;
1491 assert_eq!(missing["ok"], false, "{missing}");
1492 sc.shutdown().await;
1493 Ok(())
1494 }
1495
1496 #[tokio::test]
1500 async fn v2_tool_added_after_load_is_advertised() -> anyhow::Result<()> {
1501 if !runtime_available() {
1502 panic!(
1503 "plugin-runtime binary ({}) required for plugin-host tests",
1504 crate::plugin_runtime().program()
1505 );
1506 }
1507 let dir = tempfile::tempdir().unwrap();
1508 std::fs::write(
1509 dir.path().join("late.mjs"),
1510 r#"export default {
1511 id: "late",
1512 setup: async (ctx) => {
1513 await ctx.rpc.register(
1514 { id: "late.rpc", methods: { add: { input: {}, output: {} } }, events: {} },
1515 {
1516 add: async () => {
1517 await ctx.tool.transform((editor) => {
1518 editor.add({
1519 name: "late_tool",
1520 description: "added by rpc",
1521 input: { type: "object", properties: {} },
1522 async execute() { return { content: [{ type: "text", text: "late-ok" }] }; },
1523 });
1524 });
1525 return {};
1526 },
1527 },
1528 );
1529 },
1530};"#,
1531 )
1532 .unwrap();
1533 let host = materialize_host(&dir.path().join("host"))?;
1534 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1535 let hooks = sc
1536 .load(
1537 "late",
1538 &dir.path().join("late.mjs"),
1539 &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1540 &json!({}),
1541 )
1542 .await?;
1543 assert!(hooks.is_empty(), "no hooks at load: {hooks:?}");
1544 assert!(
1545 sc.handle().tools().await?.is_empty(),
1546 "no tools before bind"
1547 );
1548 let out = sc.rpc_call("late.rpc", "add", json!({})).await?;
1549 assert!(out.get("output").is_some(), "{out}");
1550 let tools = sc.handle().tools().await?;
1551 assert!(
1552 tools.iter().any(|t| t["name"] == "late_tool"),
1553 "tool added after load must be advertised: {tools:?}"
1554 );
1555 sc.shutdown().await;
1556 Ok(())
1557 }
1558
1559 #[tokio::test]
1560 async fn sidecar_load_trigger_roundtrip() -> anyhow::Result<()> {
1561 if !runtime_available() {
1562 panic!(
1563 "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1564 crate::plugin_runtime().program()
1565 );
1566 }
1567 let dir = tempfile::tempdir().unwrap();
1568 std::fs::write(
1570 dir.path().join("plug.mjs"),
1571 r#"
1572export const PluginModule = {
1573 id: "synthetic",
1574 server: async () => ({
1575 "tool.execute.after": async (input, output) => { output.seen = input.tool; },
1576 "chat.message": async (input, output) => { output.touched = true; },
1577 "event": async (payload) => {
1578 if (!payload.event || !payload.event.type) throw new Error("bad event shape");
1579 if (payload.event.type === "boom.type") throw new Error("event boom");
1580 },
1581 }),
1582};
1583export default PluginModule.server;
1584"#,
1585 )
1586 .unwrap();
1587 let host = materialize_host(&dir.path().join("host"))?;
1588 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work")
1589 .await
1590 .expect("spawn node");
1591 let ping = sc.request("ping", json!({})).await.expect("ping");
1592 assert_eq!(ping, "pong");
1593
1594 let input =
1595 json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
1596 let hooks = sc
1597 .load(
1598 "synthetic",
1599 &dir.path().join("plug.mjs"),
1600 &input,
1601 &Value::Null,
1602 )
1603 .await
1604 .expect("load");
1605 assert_eq!(
1606 hooks,
1607 vec![
1608 "tool.execute.after".to_string(),
1609 "chat.message".to_string(),
1610 "event".to_string()
1611 ],
1612 "hook names registered in declaration order"
1613 );
1614
1615 let out = sc
1617 .trigger(
1618 "tool.execute.after",
1619 json!({"tool": "write", "args": {"filePath": "/x"}}),
1620 json!({}),
1621 )
1622 .await
1623 .expect("trigger");
1624 assert_eq!(
1625 out["seen"], "write",
1626 "hook observed input and mutated output"
1627 );
1628 let out2 = sc
1630 .trigger("permission.ask", json!({}), json!({"keep": 1}))
1631 .await
1632 .expect("trigger2");
1633 assert_eq!(out2["keep"], 1);
1634
1635 let ev = sc
1640 .emit_event(json!({"id": "e1", "type": "session.created", "properties": {}}))
1641 .await
1642 .expect("emit_event");
1643 assert_eq!(ev["delivered"], 1, "event hook must receive exact shape");
1644 let ev2 = sc
1645 .emit_event(json!({"id": "e2", "type": "boom.type", "properties": {}}))
1646 .await
1647 .expect("emit_event fail-open");
1648 assert_eq!(ev2["delivered"], 0, "throwing event hook must not count");
1649
1650 let st = sc.statuses();
1651 assert_eq!(st["synthetic"]["ok"], true);
1652 assert_eq!(st["synthetic"]["hooks"][0], "tool.execute.after");
1653
1654 sc.shutdown().await;
1655 Ok(())
1656 }
1657
1658 #[tokio::test]
1659 async fn sidecar_resolves_bun_pty_library_from_original_package_tree() -> anyhow::Result<()> {
1660 if !runtime_available() {
1661 panic!(
1662 "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1663 crate::plugin_runtime().program()
1664 );
1665 }
1666
1667 #[cfg(target_os = "macos")]
1668 let library_name = if cfg!(target_arch = "aarch64") {
1669 "librust_pty_arm64.dylib"
1670 } else {
1671 "librust_pty.dylib"
1672 };
1673 #[cfg(target_os = "linux")]
1674 let library_name = if cfg!(target_arch = "aarch64") {
1675 "librust_pty_arm64.so"
1676 } else {
1677 "librust_pty.so"
1678 };
1679 #[cfg(target_os = "windows")]
1680 let library_name = "rust_pty.dll";
1681 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
1682 let library_name = "librust_pty.so";
1683
1684 let dir = tempfile::tempdir()?;
1685 let package = dir.path().join("opencode-pty");
1686 let entry = package.join("index.mjs");
1687 let library = package
1688 .join("node_modules/bun-pty/rust-pty/target/release")
1689 .join(library_name);
1690 std::fs::create_dir_all(library.parent().expect("library has parent"))?;
1691 std::fs::write(&library, b"synthetic native library path fixture")?;
1692 let expected = serde_json::to_string(&library.to_string_lossy())?;
1693 std::fs::write(
1694 &entry,
1695 format!(
1696 r#"
1697const expected = {expected};
1698if (process.env.BUN_PTY_LIB !== expected) throw new Error("native library path was not resolved from plugin origin");
1699export const PluginModule = {{
1700 id: "native-asset-probe",
1701 server: async () => ({{ "chat.message": async (_input, output) => {{ output.resolved = true; }} }}),
1702}};
1703export default PluginModule.server;
1704"#
1705 ),
1706 )?;
1707
1708 let host = materialize_host(&dir.path().join("host"))?;
1709 assert!(
1712 std::env::var_os("BUN_PTY_LIB").is_none(),
1713 "unset BUN_PTY_LIB to run this test"
1714 );
1715 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1716 let hooks = sc
1717 .load("opencode-pty", &entry, &json!({}), &Value::Null)
1718 .await?;
1719 assert_eq!(hooks, vec!["chat.message"]);
1720 let output = sc.trigger("chat.message", json!({}), json!({})).await?;
1721 assert_eq!(output["resolved"], true);
1722 sc.shutdown().await;
1723 Ok(())
1724 }
1725
1726 #[tokio::test]
1727 async fn sidecar_respawns_after_death_and_reloads_plugins() -> anyhow::Result<()> {
1728 if !runtime_available() {
1729 panic!(
1730 "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1731 crate::plugin_runtime().program()
1732 );
1733 }
1734 let dir = tempfile::tempdir().unwrap();
1735 std::fs::write(
1736 dir.path().join("plug.mjs"),
1737 r#"
1738export const PluginModule = {
1739 id: "reaper",
1740 server: async () => ({
1741 "chat.message": async (_i, output) => { output.alive = true; },
1742 }),
1743};
1744export default PluginModule.server;
1745"#,
1746 )
1747 .unwrap();
1748 let host = materialize_host(&dir.path().join("host"))?;
1749 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1750 sc.load(
1751 "reaper",
1752 &dir.path().join("plug.mjs"),
1753 &json!({}),
1754 &Value::Null,
1755 )
1756 .await
1757 .expect("load");
1758 let pid = sc.child_pid();
1759 std::process::Command::new("kill")
1762 .arg("-9")
1763 .arg(pid.to_string())
1764 .status()
1765 .expect("kill -9");
1766 tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1767
1768 let out = sc
1770 .trigger("chat.message", json!({"sessionID": "s"}), json!({}))
1771 .await
1772 .expect("trigger after respawn");
1773 assert_eq!(out["alive"], true, "hook must fire after respawn");
1774 assert_ne!(sc.child_pid(), pid, "child process must be replaced");
1775 let st = sc.statuses();
1776 assert_eq!(
1777 st["reaper"]["ok"], true,
1778 "previously loaded plugins must be reloaded"
1779 );
1780 sc.shutdown().await;
1781 Ok(())
1782 }
1783
1784 #[tokio::test]
1790 async fn v2_battery_promise_and_effect_dialects() -> anyhow::Result<()> {
1791 if !runtime_available() {
1792 panic!(
1793 "plugin-runtime binary ({}) required for plugin-host tests",
1794 crate::plugin_runtime().program()
1795 );
1796 }
1797 let dir = tempfile::tempdir().unwrap();
1798 std::fs::write(
1799 dir.path().join("p_v2_promise.mjs"),
1800 r#"export default {
1801 id: "v2promise",
1802 setup: async (ctx) => {
1803 await ctx.session.hook("context", (ev) => { ev.promiseTouched = true; });
1804 await ctx.tool.hook("execute.after", (ev) => { ev.result = "mutated-by-promise"; });
1805 await ctx.rpc.register({ id: "sample" }, {
1806 hello: async (input) => ({ echoed: input, from: "promise" }),
1807 });
1808 await ctx.storage.set("k", 41);
1809 if ((await ctx.storage.get("k")) !== 41) throw new Error("storage broke");
1810 },
1811};"#,
1812 )
1813 .unwrap();
1814 let eff = dir
1815 .path()
1816 .join("p_v2_effect")
1817 .join("node_modules")
1818 .join("effect");
1819 std::fs::create_dir_all(eff.join("lib")).unwrap();
1820 std::fs::write(
1821 eff.join("package.json"),
1822 r#"{"name":"effect","version":"3.0.0","type":"module","exports":{".":"./lib/index.js"}}"#,
1823 )
1824 .unwrap();
1825 std::fs::write(
1826 eff.join("lib/index.js"),
1827 "export const Effect = { scoped: (p) => p, runPromise: async (p) => { await p; } };\nexport const Scope = {};\n",
1828 )
1829 .unwrap();
1830 std::fs::write(
1831 dir.path().join("p_v2_effect").join("plug.mjs"),
1832 r#"export default {
1833 id: "v2effect",
1834 effect: (ctx) => (async () => {
1835 await ctx.tool.hook("execute.before", (ev) => { ev.input.before = "effect"; });
1836 })(),
1837};"#,
1838 )
1839 .unwrap();
1840
1841 let host = materialize_host(&dir.path().join("host"))?;
1842 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1843 let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
1844
1845 let h1 = sc
1846 .load(
1847 "v2promise",
1848 &dir.path().join("p_v2_promise.mjs"),
1849 &input,
1850 &Value::Null,
1851 )
1852 .await?;
1853 assert!(
1854 h1.contains(&"session.context".to_string()),
1855 "promise hooks: {h1:?}"
1856 );
1857 assert!(h1.contains(&"tool.execute.after".to_string()));
1858 let h2 = sc
1859 .load(
1860 "v2effect",
1861 &dir.path().join("p_v2_effect").join("plug.mjs"),
1862 &input,
1863 &Value::Null,
1864 )
1865 .await?;
1866 assert!(
1867 h2.contains(&"tool.execute.before".to_string()),
1868 "effect hooks: {h2:?}"
1869 );
1870
1871 let out = sc.trigger_v2("session", "context", json!({})).await?;
1872 assert_eq!(out["matched"], 1);
1873 assert_eq!(out["output"]["promiseTouched"], true);
1874 let after = sc
1875 .trigger_v2(
1876 "tool",
1877 "execute.after",
1878 json!({"tool": "read", "result": "orig"}),
1879 )
1880 .await?;
1881 assert_eq!(after["output"]["result"], "mutated-by-promise");
1882 let before = sc
1883 .trigger_v2(
1884 "tool",
1885 "execute.before",
1886 json!({"tool": "read", "input": {}}),
1887 )
1888 .await?;
1889 assert_eq!(before["output"]["input"]["before"], "effect");
1890
1891 let rpc = sc.rpc_call("sample", "hello", json!({"n": 7})).await?;
1892 assert_eq!(rpc["output"]["echoed"]["n"], 7);
1893 let miss = sc.rpc_call("sample", "nope", json!({})).await?;
1894 assert_eq!(miss["error"]["type"], "rpc.method_not_found");
1895 let unreg = sc.rpc_call("ghost", "hello", json!({})).await?;
1896 assert_eq!(unreg["error"]["type"], "rpc.unavailable");
1897
1898 let inv = sc.v2_inventory().await?;
1899 assert_eq!(inv["plugins"].as_array().unwrap().len(), 2, "{inv}");
1900 assert!(
1901 inv["rpcs"]
1902 .as_array()
1903 .unwrap()
1904 .iter()
1905 .any(|r| r == "sample")
1906 );
1907
1908 sc.shutdown().await;
1909 Ok(())
1910 }
1911
1912 #[tokio::test]
1918 async fn v2_accepts_every_declared_hook_at_registration() -> anyhow::Result<()> {
1919 if !runtime_available() {
1920 panic!(
1921 "plugin-runtime binary ({}) required for plugin-host tests",
1922 crate::plugin_runtime().program()
1923 );
1924 }
1925 let dir = tempfile::tempdir().unwrap();
1926 let surface: serde_json::Value =
1928 serde_json::from_str(include_str!("../tests/fixtures/v2-hooks.json"))?;
1929 let mut body =
1930 String::from("export default {\n id: \"v2allhooks\",\n setup: async (ctx) => {\n");
1931 for (domain, hooks) in surface.as_object().unwrap() {
1932 for hook in hooks.as_array().unwrap() {
1933 let hook = hook.as_str().unwrap();
1934 body.push_str(&format!(
1935 " await ctx.{domain}.hook(\"{hook}\", () => {{}});\n"
1936 ));
1937 }
1938 }
1939 body.push_str(" await ctx.event.subscribe(() => {});\n },\n};\n");
1940 std::fs::write(dir.path().join("all_hooks.mjs"), body).unwrap();
1941 let host = materialize_host(&dir.path().join("host"))?;
1942 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1943 let h = sc
1944 .load(
1945 "v2allhooks",
1946 &dir.path().join("all_hooks.mjs"),
1947 &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1948 &Value::Null,
1949 )
1950 .await
1951 .expect("every declared hook must register without failing setup");
1952 for d in ["session", "tool", "permission", "shell"] {
1953 assert!(
1954 h.iter().any(|x| x == d || x.starts_with(&format!("{d}."))),
1955 "no {d} hook registered: {h:?}"
1956 );
1957 }
1958 sc.shutdown().await;
1959 Ok(())
1960 }
1961
1962 #[tokio::test]
1977 async fn v2_unbridged_transform_registers_instead_of_failing_setup() -> anyhow::Result<()> {
1978 if !runtime_available() {
1979 panic!(
1980 "plugin-runtime binary ({}) required for plugin-host tests",
1981 crate::plugin_runtime().program()
1982 );
1983 }
1984 let dir = tempfile::tempdir().unwrap();
1985 std::fs::write(
1986 dir.path().join("p_v2_edit.mjs"),
1987 r#"export default {
1988 id: "v2edit",
1989 setup: async (ctx) => {
1990 // A transform on a domain ocserve does not bridge (upstream's registration
1991 // form, so this is what real plugins do).
1992 await ctx.tool.transform((editor) => { editor.remove("bash"); });
1993 await ctx.integration.transform(() => {});
1994 // The common transform -> reload -> list sequence: reload must resolve.
1995 await ctx.provider.reload();
1996 // The hooks we DO bridge must survive.
1997 await ctx.session.hook("context", (ev) => { ev.survived = true; });
1998 },
1999};"#,
2000 )
2001 .unwrap();
2002
2003 let host = materialize_host(&dir.path().join("host"))?;
2004 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2005 let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
2006
2007 let hooks = sc
2008 .load(
2009 "v2edit",
2010 &dir.path().join("p_v2_edit.mjs"),
2011 &input,
2012 &Value::Null,
2013 )
2014 .await
2015 .expect("a transform on an unbridged domain must not fail setup");
2016
2017 assert!(
2019 hooks.contains(&"session.context".to_string()),
2020 "the bridged hook must survive: {hooks:?}"
2021 );
2022 let out = sc.trigger_v2("session", "context", json!({})).await?;
2023 assert_eq!(out["matched"], 1);
2024 assert_eq!(out["output"]["survived"], true);
2025
2026 let inv = sc.v2_inventory().await?;
2030 let unbridged: Vec<String> = inv["unbridged_transforms"]
2031 .as_array()
2032 .expect("inventory must list unbridged transforms")
2033 .iter()
2034 .map(|v| v.as_str().unwrap_or_default().to_string())
2035 .collect();
2036 assert!(!unbridged.contains(&"tool".to_string()), "{inv}");
2037 assert!(unbridged.contains(&"integration".to_string()), "{inv}");
2038
2039 std::fs::write(
2042 dir.path().join("p_v2_use.mjs"),
2043 r#"export default {
2044 id: "v2use",
2045 setup: async (ctx) => { await ctx.vcs.apply({}); },
2046};"#,
2047 )
2048 .unwrap();
2049 let err = sc
2050 .load(
2051 "v2use",
2052 &dir.path().join("p_v2_use.mjs"),
2053 &input,
2054 &Value::Null,
2055 )
2056 .await
2057 .expect_err("using an unbridged domain must still fail loudly");
2058 let text = format!("{err:#}");
2059 assert!(text.contains("D-V2-DOMAIN"), "{text}");
2060 assert!(text.contains("vcs"), "{text}");
2061
2062 sc.shutdown().await;
2063 Ok(())
2064 }
2065
2066 #[tokio::test]
2075 async fn v2_domain_rest_methods_bind_real_routes() -> anyhow::Result<()> {
2076 if !runtime_available() {
2077 panic!(
2078 "plugin-runtime binary ({}) required for plugin-host tests",
2079 crate::plugin_runtime().program()
2080 );
2081 }
2082 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2085 let port = listener.local_addr().unwrap().port();
2086 std::thread::spawn(move || {
2087 for stream in listener.incoming() {
2088 let Ok(mut s) = stream else { continue };
2089 use std::io::{Read, Write};
2090 let mut buf = [0u8; 2048];
2091 let _ = s.read(&mut buf);
2092 let body = br#"{"id":"ses_bound","title":"bound-route"}"#;
2093 let _ = s.write_all(
2094 format!(
2095 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
2096 body.len()
2097 )
2098 .as_bytes(),
2099 );
2100 let _ = s.write_all(body);
2101 }
2102 });
2103
2104 let dir = tempfile::tempdir().unwrap();
2105 std::fs::write(
2108 dir.path().join("rest.mjs"),
2109 r#"export default {
2110 id: "restprobe",
2111 setup: async (ctx) => {
2112 const results = {};
2113 // plugin.list must return the REAL inventory, not [].
2114 results.pluginList = await ctx.plugin.list();
2115 // session.get must reach the bound route.
2116 try {
2117 const s = await ctx.session.get("ses_bound");
2118 results.sessionGet = { ok: true, id: s && s.id };
2119 } catch (e) { results.sessionGet = { ok: false, err: String(e && e.message || e) }; }
2120 // An UNBOUND verb must throw the NAMED divergence, not a TypeError.
2121 try { await ctx.session.notARealVerb("x"); results.unbound = { threw: false }; }
2122 catch (e) { results.unbound = { threw: true, msg: String(e && e.message || e) }; }
2123 await ctx.rpc.register({ id: "probe" }, { results: async () => results });
2124 },
2125};"#,
2126 )
2127 .unwrap();
2128
2129 let host = materialize_host(&dir.path().join("host"))?;
2130 let mut sc = Sidecar::spawn(&host, &format!("http://127.0.0.1:{port}"), "/work").await?;
2131 let input = json!({"directory": "/work", "serverUrl": format!("http://127.0.0.1:{port}")});
2132 sc.load(
2133 "restprobe",
2134 &dir.path().join("rest.mjs"),
2135 &input,
2136 &Value::Null,
2137 )
2138 .await?;
2139
2140 let r = sc.rpc_call("probe", "results", json!({})).await?;
2141 let out = &r["output"];
2142
2143 let listed = out["pluginList"].as_array().cloned().unwrap_or_default();
2145 assert!(
2146 listed.iter().any(|p| p["id"] == "restprobe"),
2147 "ctx.plugin.list() must report the loaded plugin: {out}"
2148 );
2149
2150 assert_eq!(
2152 out["sessionGet"]["ok"], true,
2153 "ctx.session.get must reach /api/session/{{id}}: {out}"
2154 );
2155 assert_eq!(out["sessionGet"]["id"], "ses_bound");
2156
2157 assert_eq!(
2160 out["unbound"]["threw"], true,
2161 "unbound verb must throw: {out}"
2162 );
2163 let msg = out["unbound"]["msg"].as_str().unwrap_or_default();
2164 assert!(
2165 msg.contains("D-V2-DOMAIN"),
2166 "unbound verb must name the divergence (D-V2-DOMAIN), got: {msg}"
2167 );
2168
2169 sc.shutdown().await;
2170 Ok(())
2171 }
2172
2173 #[tokio::test]
2186 async fn v2_command_transform_pulls_into_the_served_list() -> anyhow::Result<()> {
2187 if !runtime_available() {
2188 panic!(
2189 "plugin-runtime binary ({}) required for plugin-host tests",
2190 crate::plugin_runtime().program()
2191 );
2192 }
2193 let dir = tempfile::tempdir().unwrap();
2194 std::fs::write(
2195 dir.path().join("tx.mjs"),
2196 r#"export default {
2197 id: "tx",
2198 setup: async (ctx) => {
2199 // upstream shape: ctx.command.transform((editor) => editor.add({...}))
2200 await ctx.command.transform((editor) => {
2201 editor.add({ name: "plugin-cmd", description: "added by plugin" });
2202 });
2203 await ctx.skill.transform((editor) => {
2204 editor.update("demo-skill", (s) => { s.description = "rewritten by plugin"; });
2205 editor.add({ name: "plugin-skill", description: "skill from plugin", source: "skill" });
2206 });
2207 await ctx.command.reload();
2208 const listed = await ctx.command.list();
2209 await ctx.rpc.register({ id: "probe" }, {
2210 afterSetup: async () => ({ listed }),
2211 });
2212 },
2213};"#,
2214 )
2215 .unwrap();
2216
2217 let host = materialize_host(&dir.path().join("host"))?;
2218 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
2219 let input = json!({"directory": "/work"});
2220 sc.load("tx", &dir.path().join("tx.mjs"), &input, &Value::Null)
2221 .await?;
2222
2223 let pristine = vec![
2226 json!({"name": "demo-skill", "description": "original", "source": "skill"}),
2227 json!({"name": "review", "description": "config command", "source": "config"}),
2228 ];
2229 let (edited, failures) = sc.transform_commands(pristine.clone()).await?;
2230
2231 assert!(
2232 failures.is_empty(),
2233 "no transform should have failed: {failures:?}"
2234 );
2235 let added = edited
2237 .iter()
2238 .find(|c| c["name"] == "plugin-cmd")
2239 .expect("plugin command must be present");
2240 assert_eq!(added["description"], "added by plugin");
2241 let skill = edited
2243 .iter()
2244 .find(|c| c["name"] == "demo-skill")
2245 .expect("demo-skill must still be present");
2246 assert_eq!(
2247 skill["description"], "rewritten by plugin",
2248 "skill.transform must reach the vector skill_entries() reads"
2249 );
2250 assert!(
2252 edited
2253 .iter()
2254 .any(|c| c["name"] == "plugin-skill" && c["source"] == "skill"),
2255 "plugin skill must carry source=skill or skill_entries() drops it: {edited:?}"
2256 );
2257 assert!(edited.iter().any(|c| c["name"] == "review"));
2259
2260 let (again, _) = sc.transform_commands(pristine.clone()).await?;
2263 assert_eq!(
2264 serde_json::to_value(&again).unwrap(),
2265 serde_json::to_value(&edited).unwrap(),
2266 "a reload must not accumulate duplicates"
2267 );
2268
2269 let (kept, _) = sc
2272 .transform_commands(vec![json!({"name": "keepme"})])
2273 .await?;
2274 assert!(kept.iter().any(|c| c["name"] == "keepme"));
2275
2276 sc.shutdown().await;
2277 Ok(())
2278 }
2279
2280 #[tokio::test]
2285 async fn v2_command_transform_failure_keeps_the_list() -> anyhow::Result<()> {
2286 if !runtime_available() {
2287 panic!(
2288 "plugin-runtime binary ({}) required for plugin-host tests",
2289 crate::plugin_runtime().program()
2290 );
2291 }
2292 let dir = tempfile::tempdir().unwrap();
2293 std::fs::write(
2294 dir.path().join("boom.mjs"),
2295 r#"export default {
2296 id: "boom",
2297 setup: async (ctx) => {
2298 await ctx.command.transform(() => { throw new Error("transform exploded"); });
2299 await ctx.command.transform((editor) => { editor.add({ name: "survivor" }); });
2300 },
2301};"#,
2302 )
2303 .unwrap();
2304
2305 let host = materialize_host(&dir.path().join("host"))?;
2306 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
2307 let input = json!({"directory": "/work"});
2308 sc.load("boom", &dir.path().join("boom.mjs"), &input, &Value::Null)
2309 .await?;
2310
2311 let (kept, failures) = sc
2312 .transform_commands(vec![json!({"name": "existing"})])
2313 .await?;
2314 assert!(
2316 kept.iter().any(|c| c["name"] == "survivor"),
2317 "a throwing transform must not stop the others: {kept:?}"
2318 );
2319 assert!(kept.iter().any(|c| c["name"] == "existing"));
2320 assert_eq!(failures.len(), 1, "the throwing transform must be reported");
2322 assert!(
2323 failures[0]["message"]
2324 .as_str()
2325 .unwrap_or_default()
2326 .contains("transform exploded"),
2327 "{failures:?}"
2328 );
2329
2330 sc.shutdown().await;
2331 Ok(())
2332 }
2333
2334 #[tokio::test]
2338 async fn config_hook_is_dispatched() -> anyhow::Result<()> {
2339 if !runtime_available() {
2340 panic!(
2341 "plugin-runtime binary ({}) required for plugin-host tests",
2342 crate::plugin_runtime().program()
2343 );
2344 }
2345 let dir = tempfile::tempdir().unwrap();
2346 std::fs::write(
2347 dir.path().join("cfg.mjs"),
2348 r#"export const PluginModule = {
2349 id: "cfg",
2350 server: async () => ({
2351 config: async (cfg) => {
2352 if (typeof cfg !== "object" || cfg === null) throw new Error("config not object");
2353 },
2354 "chat.message": async () => {},
2355 }),
2356};
2357export default PluginModule.server;"#,
2358 )
2359 .unwrap();
2360 let host = materialize_host(&dir.path().join("host"))?;
2361 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2362 sc.load("cfg", &dir.path().join("cfg.mjs"), &json!({}), &Value::Null)
2363 .await?;
2364 let r = sc.config(json!({"model": "x"})).await?;
2365 assert_eq!(r["matched"], 1, "config hook must be dispatched: {r}");
2366 sc.shutdown().await;
2367 Ok(())
2368 }
2369
2370 fn runtime_available() -> bool {
2372 crate::which(crate::plugin_runtime().program()).is_some()
2373 }
2374
2375 #[tokio::test]
2382 async fn battery_all_authoring_forms_and_options() -> anyhow::Result<()> {
2383 if !runtime_available() {
2384 panic!(
2385 "plugin-runtime binary ({}) required for plugin-host tests",
2386 crate::plugin_runtime().program()
2387 );
2388 }
2389 let dir = tempfile::tempdir().unwrap();
2390 std::fs::write(
2392 dir.path().join("p_module.mjs"),
2393 r#"export const PluginModule = {
2394 id: "m",
2395 server: async () => ({ "chat.message": async (_i, o) => { o.module = true; } }),
2396};"#,
2397 )
2398 .unwrap();
2399 std::fs::write(
2401 dir.path().join("p_default_obj.mjs"),
2402 r#"export default { server: async () => ({ "chat.params": async (_i, o) => { o.defaultobj = true; } }) };"#,
2403 )
2404 .unwrap();
2405 std::fs::write(
2407 dir.path().join("p_default_fn.mjs"),
2408 r#"export default async () => ({ "tool.execute.after": async (_i, o) => { o.defaultfn = true; } });"#,
2409 )
2410 .unwrap();
2411 std::fs::write(
2413 dir.path().join("p_named.mjs"),
2414 r#"export async function MyPlugin() { return { "event": async () => {} }; }"#,
2415 )
2416 .unwrap();
2417 std::fs::write(
2419 dir.path().join("p_options.mjs"),
2420 r#"export const PluginModule = {
2421 id: "opts",
2422 server: async (_input, options) => ({
2423 "chat.message": async (_i, o) => { o.sawOptions = options; },
2424 }),
2425};"#,
2426 )
2427 .unwrap();
2428
2429 let host = materialize_host(&dir.path().join("host"))?;
2430 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2431 let input =
2432 json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
2433
2434 let h1 = sc
2435 .load("m", &dir.path().join("p_module.mjs"), &input, &Value::Null)
2436 .await?;
2437 assert_eq!(h1, vec!["chat.message"], "PluginModule.server form");
2438 let h2 = sc
2439 .load(
2440 "dobj",
2441 &dir.path().join("p_default_obj.mjs"),
2442 &input,
2443 &Value::Null,
2444 )
2445 .await?;
2446 assert_eq!(h2, vec!["chat.params"], "default object with .server form");
2447 let h3 = sc
2448 .load(
2449 "dfn",
2450 &dir.path().join("p_default_fn.mjs"),
2451 &input,
2452 &Value::Null,
2453 )
2454 .await?;
2455 assert_eq!(
2456 h3,
2457 vec!["tool.execute.after"],
2458 "default function (legacy) form"
2459 );
2460 let h4 = sc
2461 .load(
2462 "named",
2463 &dir.path().join("p_named.mjs"),
2464 &input,
2465 &Value::Null,
2466 )
2467 .await?;
2468 assert_eq!(h4, vec!["event"], "named function export form");
2469
2470 let opts = json!({"token": "abc", "n": 3});
2471 let h5 = sc
2472 .load("opts", &dir.path().join("p_options.mjs"), &input, &opts)
2473 .await?;
2474 assert_eq!(
2475 h5,
2476 vec!["chat.message"],
2477 "options-tuple form registers same hook"
2478 );
2479
2480 let out = sc.trigger("chat.message", json!({}), json!({})).await?;
2482 assert_eq!(out["module"], true, "form 1 hook fired");
2483 assert_eq!(out["sawOptions"], opts, "factory saw the tuple options");
2485 let out2 = sc.trigger("chat.params", json!({}), json!({})).await?;
2486 assert_eq!(out2["defaultobj"], true, "form 2 hook fired");
2487 let out3 = sc
2488 .trigger("tool.execute.after", json!({}), json!({}))
2489 .await?;
2490 assert_eq!(out3["defaultfn"], true, "form 3 hook fired");
2491
2492 let st = sc.statuses();
2494 for spec in ["m", "dobj", "dfn", "named", "opts"] {
2495 assert_eq!(st[spec]["ok"], true, "status for {spec}");
2496 }
2497 sc.shutdown().await;
2498 Ok(())
2499 }
2500}
2501
2502#[cfg(test)]
2503mod runtime_selection_tests {
2504 #[test]
2508 fn runtime_override_and_default_preference() {
2509 let has_bun = crate::which("bun").is_some();
2510 let has_node = crate::which("node").is_some();
2511 if !has_node {
2512 panic!("node required for the fallback leg (test environment gate)");
2513 }
2514
2515 unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "node") };
2517 assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
2518
2519 if has_bun {
2520 unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "bun") };
2521 assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Bun);
2522 unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2523 assert_eq!(
2524 crate::plugin_runtime(),
2525 crate::PluginRuntime::Bun,
2526 "bun present + no override → bun preferred (upstream fidelity)"
2527 );
2528 } else {
2529 unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2530 assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
2531 }
2532
2533 unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "deno") };
2535 let _ = crate::plugin_runtime();
2536 unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2537 }
2538}
2539
2540#[cfg(test)]
2541mod oom_wrapper_tests {
2542 #[cfg(target_os = "linux")]
2545 #[test]
2546 fn wrapper_raises_child_oom_score_adj() {
2547 let out = std::process::Command::new("sh")
2548 .arg("-c")
2549 .arg(ocserve_store::cgroup::WRAPPER)
2550 .arg("sh")
2551 .arg("cat")
2552 .arg("/proc/self/oom_score_adj")
2553 .output()
2554 .expect("wrapper spawns");
2555 assert!(
2556 out.status.success(),
2557 "wrapper failed: {}",
2558 String::from_utf8_lossy(&out.stderr)
2559 );
2560 assert_eq!(
2561 String::from_utf8_lossy(&out.stdout).trim(),
2562 "500",
2563 "child must run at adj=500"
2564 );
2565 }
2566}
2567
2568#[cfg(test)]
2569mod plugin_tool_schema_tests {
2570 use super::*;
2571
2572 #[tokio::test]
2578 async fn plugin_tool_schema_is_valid_json_schema() -> anyhow::Result<()> {
2579 let dir = tempfile::tempdir()?;
2580 let entry = dir.path().join("p_schema.mjs");
2581 std::fs::write(
2582 &entry,
2583 r#"import { z } from "zod";
2584export const hook = async () => ({
2585 tool: {
2586 ztool: {
2587 description: "zod args",
2588 args: {
2589 text: z.string(),
2590 count: z.number(),
2591 },
2592 execute: async () => "ok",
2593 },
2594 },
2595});"#,
2596 )?;
2597 std::fs::create_dir_all(dir.path().join("node_modules/zod"))?;
2599 std::fs::write(
2600 dir.path().join("node_modules/zod/package.json"),
2601 r#"{"name":"zod","version":"4.0.0","main":"./index.cjs","exports":{".":"./index.cjs","./v4":"./index.cjs"}}"#,
2602 )?;
2603 std::fs::write(
2604 dir.path().join("node_modules/zod/index.cjs"),
2605 "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'] });",
2606 )?;
2607 let host = materialize_host(&dir.path().join("host"))?;
2608 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2609 sc.load(
2610 "schema-fixture",
2611 &entry,
2612 &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
2613 &Value::Null,
2614 )
2615 .await?;
2616 let tools = sc.handle().tools().await?;
2617 let tool = tools
2618 .iter()
2619 .find(|t| t["name"] == "ztool")
2620 .expect("ztool advertised");
2621 let params = &tool["parameters"];
2622 assert_eq!(params["type"], "object", "{params}");
2623 assert_eq!(params["properties"]["text"]["type"], "string", "{params}");
2624 assert!(
2625 params["properties"]["text"].get("~standard").is_none()
2626 && params["properties"]["text"].get("def").is_none(),
2627 "a raw Zod object must never reach the provider: {params}"
2628 );
2629 sc.shutdown().await;
2630 Ok(())
2631 }
2632}