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