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> {
63 if spec.starts_with('/') || spec.starts_with("./") || spec.starts_with("../") {
64 let p = PathBuf::from(spec);
65 if p.exists() {
66 return Ok(p);
67 }
68 anyhow::bail!("plugin file not found: {spec}");
69 }
70 let cache = home.join(".cache/opencode/packages");
71 let pkg_name = strip_version(spec);
72 let candidates = [
73 cache.join(format!("{spec}@latest")),
74 cache.join(spec),
75 cache.join(format!("{pkg_name}@latest")),
76 ];
77 for dir in &candidates {
78 if !dir.exists() {
79 continue;
80 }
81 let direct = dir.join("package.json");
83 if let Some(entry) = entry_from_package(&direct, dir, &pkg_name) {
84 return Ok(entry);
85 }
86 let nested = dir
87 .join("node_modules")
88 .join(&pkg_name)
89 .join("package.json");
90 if let Some(entry) = entry_from_package(&nested, nested.parent().unwrap_or(dir), &pkg_name)
91 {
92 return Ok(entry);
93 }
94 }
95 anyhow::bail!("plugin target not found in opencode cache: {spec}")
96}
97
98fn strip_version(spec: &str) -> String {
99 let bytes = spec.as_bytes();
101 let mut cut = None;
103 for (i, b) in bytes.iter().enumerate() {
104 if *b == b'@' && i > 0 {
105 cut = Some(i);
106 }
107 }
108 match cut {
109 Some(i) => spec[..i].to_string(),
110 None => spec.to_string(),
111 }
112}
113
114fn entry_from_package(pkg_json: &Path, base: &Path, _pkg_name: &str) -> Option<PathBuf> {
115 let text = std::fs::read_to_string(pkg_json).ok()?;
116 let v: Value = serde_json::from_str(&text).ok()?;
117 let mut rel: Option<&str> = None;
118 if let Some(exp) = v.get("exports")
119 && let Some(dot) = exp.get(".")
120 {
121 rel = match dot {
122 Value::String(s) => Some(s.as_str()),
123 Value::Object(_) => dot
124 .get("import")
125 .and_then(|x| x.as_str())
126 .or_else(|| dot.get("default").and_then(|x| x.as_str())),
127 _ => None,
128 };
129 }
130 rel = rel.or_else(|| v.get("main").and_then(|x| x.as_str()));
131 rel = rel.or_else(|| v.get("module").and_then(|x| x.as_str()));
132 let rel = rel?;
133 let entry = base.join(rel);
134 let lex = lexically_normalize(&entry);
138 if !lex.starts_with(base)
139 && !std::fs::canonicalize(base)
140 .ok()
141 .is_some_and(|cb| lex.starts_with(&cb))
142 {
143 tracing::warn!("plugin entry {rel} escapes its package dir — refused");
144 return None;
145 }
146 lex.exists().then_some(lex)
147}
148
149fn lexically_normalize(p: &Path) -> PathBuf {
150 use std::path::Component;
151 let mut out = PathBuf::new();
152 for c in p.components() {
153 match c {
154 Component::ParentDir => {
155 out.pop();
156 }
157 Component::CurDir => {}
158 other => out.push(other.as_os_str()),
159 }
160 }
161 out
162}
163
164struct Pending {
165 tx: oneshot::Sender<Result<Value, String>>,
166}
167
168struct PendingGuard {
172 pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
173 id: i64,
174}
175
176impl PendingGuard {
177 fn new(pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>, id: i64) -> Self {
178 Self { pending, id }
179 }
180}
181
182impl Drop for PendingGuard {
183 fn drop(&mut self) {
184 self.pending.lock().remove(&self.id);
185 }
186}
187
188pub struct Inner {
202 stdin: tokio::sync::Mutex<ChildStdin>,
203 pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
205 next_id: std::sync::atomic::AtomicI64,
206 statuses: parking_lot::Mutex<HashMap<String, Value>>,
208 alive: Arc<std::sync::atomic::AtomicBool>,
210 poisoned: Arc<std::sync::atomic::AtomicBool>,
212 last_tools: parking_lot::Mutex<Option<Vec<Value>>>,
215}
216
217#[derive(Clone)]
219pub struct Handle(Arc<Inner>);
220
221impl Handle {
222 pub fn is_alive(&self) -> bool {
225 self.0.alive.load(std::sync::atomic::Ordering::Acquire)
226 }
227
228 pub fn registers(&self, hook: &str) -> bool {
231 self.0.statuses.lock().values().any(|v| {
232 v.get("hooks")
233 .and_then(|h| h.as_array())
234 .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(hook)))
235 })
236 }
237
238 pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
239 self.request_with_timeout(method, params, Some(RPC_TIMEOUT))
240 .await
241 }
242
243 pub async fn request_with_timeout(
244 &self,
245 method: &str,
246 params: Value,
247 timeout: Option<std::time::Duration>,
248 ) -> Result<Value> {
249 if !self.is_alive() {
250 anyhow::bail!("plugin host is down ({method}); a respawn is required");
251 }
252 let id = self
253 .0
254 .next_id
255 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
256 let (tx, rx) = oneshot::channel();
257 self.0.pending.lock().insert(id, Pending { tx });
258 let _guard = PendingGuard::new(Arc::clone(&self.0.pending), id);
259 let msg = json!({"id": id, "method": method, "params": params});
260 let mut line = msg.to_string();
261 line.push('\n');
262 let exchange = async {
267 {
268 let mut stdin = self.0.stdin.lock().await;
269 stdin.write_all(line.as_bytes()).await?;
270 stdin.flush().await?;
271 }
272 match rx.await {
273 Ok(res) => res.map_err(|e| anyhow!("plugin host {method}: {e}")),
274 Err(_) => Err(anyhow!("plugin host dropped response for {method}")),
275 }
276 };
277 match timeout {
278 None => exchange
279 .await
280 .map_err(|e| e.context("plugin host stdin write")),
281 Some(d) => match tokio::time::timeout(d, exchange).await {
282 Ok(res) => res,
283 Err(_) => {
284 self.0
285 .poisoned
286 .store(true, std::sync::atomic::Ordering::Release);
287 self.0
288 .alive
289 .store(false, std::sync::atomic::Ordering::Release);
290 ocserve_metrics::labeled_counter(
291 "ocserve_plugin_hook_timeout_total",
292 &format!("hook=\"{method}\""),
293 1,
294 );
295 Err(anyhow!(
296 "plugin host {method} timed out after {}ms (runaway hook?)",
297 d.as_millis()
298 ))
299 }
300 },
301 }
302 }
303}
304
305impl Handle {
306 pub async fn trigger_bounded(
307 &self,
308 name: &str,
309 input: Value,
310 mut output: Value,
311 budget: Option<std::time::Duration>,
312 ) -> Result<Value> {
313 let res = self
314 .request_with_timeout(
315 "trigger",
316 json!({"name": name, "input": input, "output": output}),
317 budget,
318 )
319 .await?;
320 if res.is_object() {
321 output = res;
322 }
323 Ok(output)
324 }
325
326 pub async fn trigger_v2_bounded(
327 &self,
328 domain: &str,
329 name: &str,
330 input: Value,
331 budget: Option<std::time::Duration>,
332 ) -> Result<Value> {
333 self.request_with_timeout(
334 "trigger_v2",
335 json!({"domain": domain, "name": name, "input": input}),
336 budget,
337 )
338 .await
339 }
340
341 pub async fn emit_event_bounded(
342 &self,
343 event: Value,
344 budget: Option<std::time::Duration>,
345 ) -> Result<Value> {
346 self.request_with_timeout("event", json!({"event": event}), budget)
347 .await
348 }
349}
350
351pub fn hook_budget(hook: &str) -> Option<std::time::Duration> {
358 match std::env::var("OCSERVE_HOOK_TIMEOUT_MS")
359 .ok()
360 .and_then(|v| v.parse::<u64>().ok())
361 {
362 Some(0) => None,
363 Some(ms) => Some(std::time::Duration::from_millis(ms)),
364 None => Some(std::time::Duration::from_secs(
365 if hook.contains("tool.execute") {
366 180
367 } else if hook.contains("transform")
368 || hook.contains("context")
369 || hook.contains("compact")
372 {
373 60
374 } else {
375 30
376 },
377 )),
378 }
379}
380
381impl Handle {
382 pub async fn rpc_call(&self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
384 self.request(
385 "rpc_call",
386 json!({"rpcID": rpc_id, "method": method, "input": input}),
387 )
388 .await
389 }
390
391 pub async fn v2_inventory(&self) -> Result<Value> {
394 self.request("v2_inventory", json!({})).await
395 }
396
397 pub async fn transform_commands(
399 &self,
400 commands: Vec<Value>,
401 ) -> Result<(Vec<Value>, Vec<Value>)> {
402 let r = self
403 .request("v2_transform_commands", json!({ "commands": commands }))
404 .await?;
405 let out = r["commands"]
406 .as_array()
407 .cloned()
408 .unwrap_or_default()
409 .into_iter()
410 .collect();
411 let failures = r["failures"].as_array().cloned().unwrap_or_default();
412 Ok((out, failures))
413 }
414}
415
416impl Handle {
417 pub async fn tools(&self) -> Result<Vec<Value>> {
425 if !self.registers("tool") {
426 return Ok(Vec::new());
427 }
428 match self.request("tools", json!({})).await {
429 Ok(res) => {
430 let list = res.as_array().cloned().unwrap_or_default();
431 *self.0.last_tools.lock() = Some(list.clone());
432 Ok(list)
433 }
434 Err(e) => {
435 if let Some(cached) = self.0.last_tools.lock().clone() {
436 tracing::warn!("plugin tools: {e:#} — serving the last known list");
437 return Ok(cached);
438 }
439 Err(e)
440 }
441 }
442 }
443
444 pub async fn execute_tool(&self, name: &str, input: Value, ctx: Value) -> Result<Value> {
447 self.request_with_timeout(
448 "tool_execute",
449 json!({"name": name, "input": input, "ctx": ctx}),
450 Some(std::time::Duration::from_secs(300)),
451 )
452 .await
453 }
454}
455
456pub struct Sidecar {
458 inner: Arc<Inner>,
459 child: Child,
460 server: (String, String),
462 args: SpawnArgs,
464 loads: Vec<(String, PathBuf, Value, Value)>,
469 normalize_root: Option<PathBuf>,
472 started_at: std::time::Instant,
476 recycled: bool,
480}
481
482#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub enum PluginRuntime {
487 Bun,
488 Node,
489}
490
491impl PluginRuntime {
492 pub fn program(self) -> &'static str {
493 match self {
494 PluginRuntime::Bun => "bun",
495 PluginRuntime::Node => "node",
496 }
497 }
498}
499
500pub(crate) fn which(prog: &str) -> Option<PathBuf> {
503 let name = ocserve_store::platform::exe(prog);
507 if let Ok(path) = std::env::var("PATH") {
508 for dir in std::env::split_paths(&path) {
509 let cand = dir.join(&name);
510 if ocserve_store::platform::is_executable_file(&cand) {
511 return Some(cand);
512 }
513 }
514 }
515 for key in ["OCSERVE_HOME", "HOME", "USERPROFILE"] {
516 let Some(home) = std::env::var_os(key).filter(|v| !v.is_empty()) else {
517 continue;
518 };
519 let cand = Path::new(&home).join(".bun/bin").join(&name);
520 if ocserve_store::platform::is_executable_file(&cand) {
521 return Some(cand);
522 }
523 }
524 None
525}
526
527pub fn plugin_runtime() -> PluginRuntime {
528 match std::env::var("OCSERVE_PLUGIN_RUNTIME").as_deref() {
529 Ok("node") => return PluginRuntime::Node,
530 Ok("bun") => return PluginRuntime::Bun,
531 _ => {}
532 }
533 if which("bun").is_some() {
534 PluginRuntime::Bun
535 } else {
536 PluginRuntime::Node
537 }
538}
539
540#[derive(Clone)]
541struct SpawnArgs {
542 host_path: PathBuf,
543 server_url: String,
544 directory: String,
545}
546
547impl Sidecar {
548 pub async fn spawn(host_path: &Path, server_url: &str, directory: &str) -> Result<Self> {
549 let runtime = crate::plugin_runtime();
553 let program = which(runtime.program())
556 .map(|p| p.to_string_lossy().into_owned())
557 .unwrap_or_else(|| runtime.program().to_string());
558 let shape = ocserve_store::cgroup::contained(&program, "plugin");
562 let mut cmd = Command::new(&shape.program);
563 cmd.args(&shape.prefix);
564 cmd.env("OCSERVE_VERSION", env!("CARGO_PKG_VERSION"));
568 match &shape.cgroup {
569 Some(p) => {
570 cmd.env(ocserve_store::cgroup::ENV, p);
571 }
572 None => {
573 cmd.env_remove(ocserve_store::cgroup::ENV);
574 }
575 }
576 match runtime {
577 PluginRuntime::Bun => {
581 cmd.arg("--smol");
582 }
583 PluginRuntime::Node => {
590 cmd.arg(format!(
591 "--max-old-space-size={}",
592 std::env::var("OCSERVE_PLUGIN_HEAP_MB")
593 .ok()
594 .and_then(|v| v.parse().ok())
595 .unwrap_or(128)
596 ));
597 cmd.arg("--max-semi-space-size=2");
598 }
599 }
600 cmd.arg(host_path)
601 .stdin(std::process::Stdio::piped())
602 .stdout(std::process::Stdio::piped())
603 .stderr(std::process::Stdio::inherit())
604 .kill_on_drop(true);
605 let mut child = cmd
606 .spawn()
607 .with_context(|| format!("spawn {} plugin host", runtime.program()))?;
608 let stdin = child.stdin.take().context("host stdin")?;
609 let stdout = child.stdout.take().context("host stdout")?;
610 let pending = Arc::new(parking_lot::Mutex::new(HashMap::<i64, Pending>::new()));
611 let pending_task = Arc::clone(&pending);
612 let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
613 let alive_task = Arc::clone(&alive);
614 let poisoned = Arc::new(std::sync::atomic::AtomicBool::new(false));
615 let poisoned_task = Arc::clone(&poisoned);
616 tokio::spawn(async move {
617 const MAX_HOST_LINE: usize = 8 * 1024 * 1024;
622 let mut reader = BufReader::new(stdout);
623 let mut line = String::new();
624 loop {
625 line.clear();
626 use tokio::io::AsyncBufReadExt as _;
627 let n = {
628 let mut limited =
629 tokio::io::AsyncReadExt::take(&mut reader, MAX_HOST_LINE as u64 + 1);
630 limited.read_line(&mut line).await
631 };
632 match n {
633 Ok(0) | Err(_) => break,
634 Ok(_) if line.len() > MAX_HOST_LINE => {
637 tracing::warn!("plugin host: oversized line — child marked for respawn");
642 poisoned_task.store(true, std::sync::atomic::Ordering::Release);
643 break;
644 }
645 Ok(_) => {}
646 }
647 let trimmed = line.trim();
648 if trimmed.is_empty() {
649 continue;
650 }
651 match serde_json::from_str::<Value>(trimmed) {
652 Ok(v) => {
653 if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
654 let result = match v.get("error") {
655 Some(e) if !e.is_null() => {
656 Err(e["message"].as_str().unwrap_or("host error").to_string())
657 }
658 _ => Ok(v.get("result").cloned().unwrap_or(Value::Null)),
659 };
660 if let Some(p) = pending_task.lock().remove(&id) {
661 let _ = p.tx.send(result);
662 }
663 } else if v.get("event").and_then(|e| e.as_str()) == Some("plugin_error") {
664 ocserve_metrics::labeled_counter(
669 "ocserve_plugin_internal_error_total",
670 &format!(
671 "plugin=\"{}\",hook=\"{}\"",
672 v["plugin"].as_str().unwrap_or("?"),
673 v["hook"].as_str().unwrap_or("?")
674 ),
675 1,
676 );
677 tracing::warn!(
678 "plugin internal error: {} {}: {}",
679 v["plugin"].as_str().unwrap_or("?"),
680 v["hook"].as_str().unwrap_or("?"),
681 v["error"].as_str().unwrap_or("?")
682 );
683 }
684 }
686 Err(_) => {
687 let head: String = trimmed.chars().take(120).collect();
688 tracing::warn!("plugin host: unparsable line: {head}");
689 }
690 }
691 }
692 alive_task.store(false, std::sync::atomic::Ordering::Release);
695 for (_, p) in pending_task.lock().drain() {
696 let _ = p.tx.send(Err("plugin host exited".into()));
697 }
698 ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 0);
699 });
700 ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 1);
701 Ok(Self {
702 inner: Arc::new(Inner {
703 stdin: tokio::sync::Mutex::new(stdin),
704 pending,
705 next_id: std::sync::atomic::AtomicI64::new(1),
706 statuses: parking_lot::Mutex::new(HashMap::new()),
707 alive,
708 poisoned,
709 last_tools: parking_lot::Mutex::new(None),
710 }),
711 child,
712 server: (server_url.to_string(), directory.to_string()),
713 args: SpawnArgs {
714 host_path: host_path.to_path_buf(),
715 server_url: server_url.to_string(),
716 directory: directory.to_string(),
717 },
718 loads: Vec::new(),
719 normalize_root: None,
720 started_at: std::time::Instant::now(),
721 recycled: false,
722 })
723 }
724
725 pub fn in_flight(&self) -> usize {
728 self.inner.pending.lock().len()
729 }
730
731 pub fn uptime(&self) -> std::time::Duration {
733 self.started_at.elapsed()
734 }
735
736 pub fn recycle_child(&mut self) -> bool {
742 if self.child.try_wait().ok().flatten().is_some() {
743 return false;
744 }
745 let _ = self.child.start_kill();
746 self.inner
753 .alive
754 .store(false, std::sync::atomic::Ordering::Release);
755 self.recycled = true;
756 true
757 }
758
759 pub fn set_normalize_root(&mut self, root: PathBuf) {
763 self.normalize_root = Some(root);
764 }
765
766 pub async fn ensure_alive(&mut self) -> Result<()> {
771 if self
775 .inner
776 .poisoned
777 .load(std::sync::atomic::Ordering::Acquire)
778 {
779 let _ = self.child.start_kill();
780 self.inner
781 .alive
782 .store(false, std::sync::atomic::Ordering::Release);
783 } else if self.inner.alive.load(std::sync::atomic::Ordering::Acquire)
784 && let Ok(None) = self.child.try_wait()
785 {
786 return Ok(());
787 }
788 ocserve_metrics::labeled_counter(
789 "ocserve_plugin_sidecar_respawn_total",
790 if self.recycled {
791 "reason=\"recycle\""
792 } else {
793 "reason=\"exit\""
794 },
795 1,
796 );
797 let status = self.child.try_wait().ok().flatten();
798 if std::mem::take(&mut self.recycled) {
799 tracing::info!(
800 "plugin sidecar recycled (L1, was {status:?}) — respawning + replaying hooks"
801 );
802 } else if let Some(status) = status {
803 tracing::error!("plugin sidecar exited ({status}) — respawning");
804 } else {
805 tracing::warn!("plugin sidecar unresponsive — replacing the host");
806 }
807 let args = self.args.clone();
808 let loads = std::mem::take(&mut self.loads);
809 let mut fresh =
814 match Sidecar::spawn(&args.host_path, &args.server_url, &args.directory).await {
815 Ok(f) => f,
816 Err(e) => {
817 self.loads = loads;
818 tracing::error!("plugin sidecar respawn failed: {e:#} — plugin set preserved");
819 return Err(e);
820 }
821 };
822 fresh.normalize_root = self.normalize_root.clone();
825 for (spec, entry, input, options) in &loads {
826 if let Err(e) = fresh.load_raw(spec, entry, input, options).await {
827 tracing::warn!("plugin {spec} reload after respawn failed: {e:#}");
828 }
829 }
830 *self = fresh;
831 Ok(())
832 }
833
834 pub fn child_pid(&self) -> u32 {
836 self.child.id().unwrap_or(0)
837 }
838
839 pub fn handle(&self) -> Handle {
840 Handle(Arc::clone(&self.inner))
841 }
842
843 pub async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
844 self.ensure_alive().await?;
845 self.handle().request(method, params).await
846 }
847
848 pub async fn request_bounded(
850 &mut self,
851 method: &str,
852 params: Value,
853 timeout: Option<std::time::Duration>,
854 ) -> Result<Value> {
855 self.ensure_alive().await?;
856 self.handle()
857 .request_with_timeout(method, params, timeout)
858 .await
859 }
860
861 pub async fn load(
865 &mut self,
866 spec: &str,
867 entry: &Path,
868 input: &Value,
869 options: &Value,
870 ) -> Result<Vec<String>> {
871 self.ensure_alive().await?;
872 self.load_raw(spec, entry, input, options).await
873 }
874
875 async fn load_raw(
877 &mut self,
878 spec: &str,
879 entry: &Path,
880 input: &Value,
881 options: &Value,
882 ) -> Result<Vec<String>> {
883 let root = self.normalize_root.clone();
886 let raw = entry.to_path_buf();
887 let raw_for_spawn = raw.clone();
888 let (load_path, outcome) = tokio::task::spawn_blocking(move || {
889 crate::normalize::normalize_or_raw_sync(root.as_deref(), &raw_for_spawn)
890 })
891 .await
892 .map_err(|e| anyhow!("normalize task: {e}"))?;
893 ocserve_metrics::labeled_counter(
894 "ocserve_plugin_normalize_total",
895 &format!("result=\"{}\"", outcome.label()),
896 1,
897 );
898 match &outcome {
899 crate::normalize::Outcome::Built {
900 path,
901 ms,
902 beside,
903 rss_before_kb,
904 rss_after_kb,
905 } => tracing::info!(
906 "plugin normalize {spec}: built {} ({}) in {ms}ms rss {rss_before_kb}→{rss_after_kb}kB",
907 path.display(),
908 if *beside { "beside-entry" } else { "data-dir" }
909 ),
910 crate::normalize::Outcome::Fallback { err, .. } => {
911 tracing::warn!("plugin normalize {spec} failed, loading raw entry: {err}")
912 }
913 _ => {}
914 }
915 let mut input = input.clone();
917 if input
918 .get("serverUrl")
919 .and_then(|v| v.as_str())
920 .unwrap_or("")
921 .is_empty()
922 {
923 input["serverUrl"] = json!(self.server.0);
924 }
925 if input
926 .get("directory")
927 .and_then(|v| v.as_str())
928 .unwrap_or("")
929 .is_empty()
930 {
931 input["directory"] = json!(self.server.1);
932 }
933 let params = json!({
934 "spec": spec,
935 "entry": load_path.to_string_lossy(),
936 "origin": raw.to_string_lossy(),
941 "input": input,
942 "options": options,
943 });
944 let res = self.handle().request("load", params).await?;
945 let hooks: Vec<String> = res["hooks"]
946 .as_array()
947 .map(|a| {
948 a.iter()
949 .filter_map(|h| h.as_str().map(String::from))
950 .collect()
951 })
952 .unwrap_or_default();
953 self.inner.statuses.lock().insert(
954 spec.to_string(),
955 json!({"ok": true, "hooks": hooks, "id": res["id"]}),
956 );
957 self.loads.push((
958 spec.to_string(),
959 entry.to_path_buf(),
960 input,
961 options.clone(),
962 ));
963 Ok(hooks)
964 }
965
966 pub async fn trigger(&mut self, name: &str, input: Value, mut output: Value) -> Result<Value> {
968 let params = json!({"name": name, "input": input, "output": output});
969 let res = self.request("trigger", params).await?;
970 if res.is_object() {
971 output = res;
972 }
973 Ok(output)
974 }
975
976 pub async fn emit_event(&mut self, event: Value) -> Result<Value> {
979 self.request("event", json!({"event": event})).await
980 }
981
982 pub async fn trigger_v2(&mut self, domain: &str, name: &str, input: Value) -> Result<Value> {
986 self.request(
987 "trigger_v2",
988 json!({"domain": domain, "name": name, "input": input}),
989 )
990 .await
991 }
992
993 pub async fn rpc_call(&mut self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
997 self.ensure_alive().await?;
998 self.handle().rpc_call(rpc_id, method, input).await
999 }
1000
1001 pub async fn v2_inventory(&mut self) -> Result<Value> {
1004 self.ensure_alive().await?;
1005 self.handle().v2_inventory().await
1006 }
1007
1008 pub async fn transform_commands(
1022 &mut self,
1023 commands: Vec<Value>,
1024 ) -> Result<(Vec<Value>, Vec<Value>)> {
1025 self.ensure_alive().await?;
1026 self.handle().transform_commands(commands).await
1027 }
1028
1029 pub async fn config(&mut self, cfg: Value) -> Result<Value> {
1030 self.request("config", json!({"config": cfg})).await
1031 }
1032
1033 pub fn statuses(&self) -> Value {
1034 let mut out = serde_json::Map::new();
1035 for (spec, v) in self.inner.statuses.lock().iter() {
1036 out.insert(spec.clone(), v.clone());
1037 }
1038 Value::Object(out)
1039 }
1040
1041 pub async fn shutdown(&mut self) {
1042 let _ = self.request("dispose", json!({})).await;
1043 let _ = self.child.start_kill();
1044 }
1045}
1046
1047#[cfg(test)]
1048mod tests {
1049 use super::*;
1050
1051 #[test]
1052 fn strip_version_cases() {
1053 assert_eq!(strip_version("context-mode"), "context-mode");
1054 assert_eq!(strip_version("context-mode@latest"), "context-mode");
1055 assert_eq!(
1056 strip_version("@cortexkit/opencode-magic-context@latest"),
1057 "@cortexkit/opencode-magic-context"
1058 );
1059 assert_eq!(
1060 strip_version("@iam-brain/opencode-codex-auth@latest"),
1061 "@iam-brain/opencode-codex-auth"
1062 );
1063 }
1064
1065 #[test]
1066 fn entry_from_package_shapes() {
1067 let dir = tempfile::tempdir().unwrap();
1068 std::fs::write(
1070 dir.path().join("package.json"),
1071 r#"{"exports": {".": "./dist/index.js"}}"#,
1072 )
1073 .unwrap();
1074 std::fs::create_dir(dir.path().join("dist")).unwrap();
1075 std::fs::write(dir.path().join("dist/index.js"), "//").unwrap();
1076 let e = entry_from_package(&dir.path().join("package.json"), dir.path(), "x")
1077 .expect("exports dot");
1078 assert!(e.ends_with("dist/index.js"));
1079 std::fs::write(
1081 dir.path().join("package.json"),
1082 r#"{"main": "./lib/main.js"}"#,
1083 )
1084 .unwrap();
1085 std::fs::create_dir(dir.path().join("lib")).unwrap();
1086 std::fs::write(dir.path().join("lib/main.js"), "//").unwrap();
1087 let e =
1088 entry_from_package(&dir.path().join("package.json"), dir.path(), "x").expect("main");
1089 assert!(e.ends_with("lib/main.js"));
1090 }
1091
1092 #[tokio::test]
1093 async fn sidecar_load_trigger_roundtrip() -> anyhow::Result<()> {
1094 if !runtime_available() {
1095 panic!(
1096 "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1097 crate::plugin_runtime().program()
1098 );
1099 }
1100 let dir = tempfile::tempdir().unwrap();
1101 std::fs::write(
1103 dir.path().join("plug.mjs"),
1104 r#"
1105export const PluginModule = {
1106 id: "synthetic",
1107 server: async () => ({
1108 "tool.execute.after": async (input, output) => { output.seen = input.tool; },
1109 "chat.message": async (input, output) => { output.touched = true; },
1110 "event": async (payload) => {
1111 if (!payload.event || !payload.event.type) throw new Error("bad event shape");
1112 if (payload.event.type === "boom.type") throw new Error("event boom");
1113 },
1114 }),
1115};
1116export default PluginModule.server;
1117"#,
1118 )
1119 .unwrap();
1120 let host = materialize_host(&dir.path().join("host"))?;
1121 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work")
1122 .await
1123 .expect("spawn node");
1124 let ping = sc.request("ping", json!({})).await.expect("ping");
1125 assert_eq!(ping, "pong");
1126
1127 let input =
1128 json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
1129 let hooks = sc
1130 .load(
1131 "synthetic",
1132 &dir.path().join("plug.mjs"),
1133 &input,
1134 &Value::Null,
1135 )
1136 .await
1137 .expect("load");
1138 assert_eq!(
1139 hooks,
1140 vec![
1141 "tool.execute.after".to_string(),
1142 "chat.message".to_string(),
1143 "event".to_string()
1144 ],
1145 "hook names registered in declaration order"
1146 );
1147
1148 let out = sc
1150 .trigger(
1151 "tool.execute.after",
1152 json!({"tool": "write", "args": {"filePath": "/x"}}),
1153 json!({}),
1154 )
1155 .await
1156 .expect("trigger");
1157 assert_eq!(
1158 out["seen"], "write",
1159 "hook observed input and mutated output"
1160 );
1161 let out2 = sc
1163 .trigger("permission.ask", json!({}), json!({"keep": 1}))
1164 .await
1165 .expect("trigger2");
1166 assert_eq!(out2["keep"], 1);
1167
1168 let ev = sc
1173 .emit_event(json!({"id": "e1", "type": "session.created", "properties": {}}))
1174 .await
1175 .expect("emit_event");
1176 assert_eq!(ev["delivered"], 1, "event hook must receive exact shape");
1177 let ev2 = sc
1178 .emit_event(json!({"id": "e2", "type": "boom.type", "properties": {}}))
1179 .await
1180 .expect("emit_event fail-open");
1181 assert_eq!(ev2["delivered"], 0, "throwing event hook must not count");
1182
1183 let st = sc.statuses();
1184 assert_eq!(st["synthetic"]["ok"], true);
1185 assert_eq!(st["synthetic"]["hooks"][0], "tool.execute.after");
1186
1187 sc.shutdown().await;
1188 Ok(())
1189 }
1190
1191 #[tokio::test]
1192 async fn sidecar_respawns_after_death_and_reloads_plugins() -> anyhow::Result<()> {
1193 if !runtime_available() {
1194 panic!(
1195 "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1196 crate::plugin_runtime().program()
1197 );
1198 }
1199 let dir = tempfile::tempdir().unwrap();
1200 std::fs::write(
1201 dir.path().join("plug.mjs"),
1202 r#"
1203export const PluginModule = {
1204 id: "reaper",
1205 server: async () => ({
1206 "chat.message": async (_i, output) => { output.alive = true; },
1207 }),
1208};
1209export default PluginModule.server;
1210"#,
1211 )
1212 .unwrap();
1213 let host = materialize_host(&dir.path().join("host"))?;
1214 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1215 sc.load(
1216 "reaper",
1217 &dir.path().join("plug.mjs"),
1218 &json!({}),
1219 &Value::Null,
1220 )
1221 .await
1222 .expect("load");
1223 let pid = sc.child_pid();
1224 std::process::Command::new("kill")
1227 .arg("-9")
1228 .arg(pid.to_string())
1229 .status()
1230 .expect("kill -9");
1231 tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1232
1233 let out = sc
1235 .trigger("chat.message", json!({"sessionID": "s"}), json!({}))
1236 .await
1237 .expect("trigger after respawn");
1238 assert_eq!(out["alive"], true, "hook must fire after respawn");
1239 assert_ne!(sc.child_pid(), pid, "child process must be replaced");
1240 let st = sc.statuses();
1241 assert_eq!(
1242 st["reaper"]["ok"], true,
1243 "previously loaded plugins must be reloaded"
1244 );
1245 sc.shutdown().await;
1246 Ok(())
1247 }
1248
1249 #[tokio::test]
1255 async fn v2_battery_promise_and_effect_dialects() -> anyhow::Result<()> {
1256 if !runtime_available() {
1257 panic!(
1258 "plugin-runtime binary ({}) required for plugin-host tests",
1259 crate::plugin_runtime().program()
1260 );
1261 }
1262 let dir = tempfile::tempdir().unwrap();
1263 std::fs::write(
1264 dir.path().join("p_v2_promise.mjs"),
1265 r#"export default {
1266 id: "v2promise",
1267 setup: async (ctx) => {
1268 await ctx.session.hook("context", (ev) => { ev.promiseTouched = true; });
1269 await ctx.tool.hook("execute.after", (ev) => { ev.result = "mutated-by-promise"; });
1270 await ctx.rpc.register({ id: "sample" }, {
1271 hello: async (input) => ({ echoed: input, from: "promise" }),
1272 });
1273 await ctx.storage.set("k", 41);
1274 if ((await ctx.storage.get("k")) !== 41) throw new Error("storage broke");
1275 },
1276};"#,
1277 )
1278 .unwrap();
1279 let eff = dir
1280 .path()
1281 .join("p_v2_effect")
1282 .join("node_modules")
1283 .join("effect");
1284 std::fs::create_dir_all(eff.join("lib")).unwrap();
1285 std::fs::write(
1286 eff.join("package.json"),
1287 r#"{"name":"effect","version":"3.0.0","type":"module","exports":{".":"./lib/index.js"}}"#,
1288 )
1289 .unwrap();
1290 std::fs::write(
1291 eff.join("lib/index.js"),
1292 "export const Effect = { scoped: (p) => p, runPromise: async (p) => { await p; } };\nexport const Scope = {};\n",
1293 )
1294 .unwrap();
1295 std::fs::write(
1296 dir.path().join("p_v2_effect").join("plug.mjs"),
1297 r#"export default {
1298 id: "v2effect",
1299 effect: (ctx) => (async () => {
1300 await ctx.tool.hook("execute.before", (ev) => { ev.input.before = "effect"; });
1301 })(),
1302};"#,
1303 )
1304 .unwrap();
1305
1306 let host = materialize_host(&dir.path().join("host"))?;
1307 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1308 let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
1309
1310 let h1 = sc
1311 .load(
1312 "v2promise",
1313 &dir.path().join("p_v2_promise.mjs"),
1314 &input,
1315 &Value::Null,
1316 )
1317 .await?;
1318 assert!(
1319 h1.contains(&"session.context".to_string()),
1320 "promise hooks: {h1:?}"
1321 );
1322 assert!(h1.contains(&"tool.execute.after".to_string()));
1323 let h2 = sc
1324 .load(
1325 "v2effect",
1326 &dir.path().join("p_v2_effect").join("plug.mjs"),
1327 &input,
1328 &Value::Null,
1329 )
1330 .await?;
1331 assert!(
1332 h2.contains(&"tool.execute.before".to_string()),
1333 "effect hooks: {h2:?}"
1334 );
1335
1336 let out = sc.trigger_v2("session", "context", json!({})).await?;
1337 assert_eq!(out["matched"], 1);
1338 assert_eq!(out["output"]["promiseTouched"], true);
1339 let after = sc
1340 .trigger_v2(
1341 "tool",
1342 "execute.after",
1343 json!({"tool": "read", "result": "orig"}),
1344 )
1345 .await?;
1346 assert_eq!(after["output"]["result"], "mutated-by-promise");
1347 let before = sc
1348 .trigger_v2(
1349 "tool",
1350 "execute.before",
1351 json!({"tool": "read", "input": {}}),
1352 )
1353 .await?;
1354 assert_eq!(before["output"]["input"]["before"], "effect");
1355
1356 let rpc = sc.rpc_call("sample", "hello", json!({"n": 7})).await?;
1357 assert_eq!(rpc["output"]["echoed"]["n"], 7);
1358 let miss = sc.rpc_call("sample", "nope", json!({})).await?;
1359 assert_eq!(miss["error"]["type"], "rpc.method_not_found");
1360 let unreg = sc.rpc_call("ghost", "hello", json!({})).await?;
1361 assert_eq!(unreg["error"]["type"], "rpc.unavailable");
1362
1363 let inv = sc.v2_inventory().await?;
1364 assert_eq!(inv["plugins"].as_array().unwrap().len(), 2, "{inv}");
1365 assert!(
1366 inv["rpcs"]
1367 .as_array()
1368 .unwrap()
1369 .iter()
1370 .any(|r| r == "sample")
1371 );
1372
1373 sc.shutdown().await;
1374 Ok(())
1375 }
1376
1377 #[tokio::test]
1383 async fn v2_accepts_every_declared_hook_at_registration() -> anyhow::Result<()> {
1384 if !runtime_available() {
1385 panic!(
1386 "plugin-runtime binary ({}) required for plugin-host tests",
1387 crate::plugin_runtime().program()
1388 );
1389 }
1390 let dir = tempfile::tempdir().unwrap();
1391 let surface: serde_json::Value =
1393 serde_json::from_str(include_str!("../tests/fixtures/v2-hooks.json"))?;
1394 let mut body =
1395 String::from("export default {\n id: \"v2allhooks\",\n setup: async (ctx) => {\n");
1396 for (domain, hooks) in surface.as_object().unwrap() {
1397 for hook in hooks.as_array().unwrap() {
1398 let hook = hook.as_str().unwrap();
1399 body.push_str(&format!(
1400 " await ctx.{domain}.hook(\"{hook}\", () => {{}});\n"
1401 ));
1402 }
1403 }
1404 body.push_str(" await ctx.event.subscribe(() => {});\n },\n};\n");
1405 std::fs::write(dir.path().join("all_hooks.mjs"), body).unwrap();
1406 let host = materialize_host(&dir.path().join("host"))?;
1407 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1408 let h = sc
1409 .load(
1410 "v2allhooks",
1411 &dir.path().join("all_hooks.mjs"),
1412 &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1413 &Value::Null,
1414 )
1415 .await
1416 .expect("every declared hook must register without failing setup");
1417 for d in ["session", "tool", "permission", "shell"] {
1418 assert!(
1419 h.iter().any(|x| x == d || x.starts_with(&format!("{d}."))),
1420 "no {d} hook registered: {h:?}"
1421 );
1422 }
1423 sc.shutdown().await;
1424 Ok(())
1425 }
1426
1427 #[tokio::test]
1442 async fn v2_unbridged_transform_registers_instead_of_failing_setup() -> anyhow::Result<()> {
1443 if !runtime_available() {
1444 panic!(
1445 "plugin-runtime binary ({}) required for plugin-host tests",
1446 crate::plugin_runtime().program()
1447 );
1448 }
1449 let dir = tempfile::tempdir().unwrap();
1450 std::fs::write(
1451 dir.path().join("p_v2_edit.mjs"),
1452 r#"export default {
1453 id: "v2edit",
1454 setup: async (ctx) => {
1455 // A transform on a domain ocserve does not bridge (upstream's registration
1456 // form, so this is what real plugins do).
1457 await ctx.tool.transform((editor) => { editor.remove("bash"); });
1458 await ctx.integration.transform(() => {});
1459 // The common transform -> reload -> list sequence: reload must resolve.
1460 await ctx.provider.reload();
1461 // The hooks we DO bridge must survive.
1462 await ctx.session.hook("context", (ev) => { ev.survived = true; });
1463 },
1464};"#,
1465 )
1466 .unwrap();
1467
1468 let host = materialize_host(&dir.path().join("host"))?;
1469 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1470 let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
1471
1472 let hooks = sc
1473 .load(
1474 "v2edit",
1475 &dir.path().join("p_v2_edit.mjs"),
1476 &input,
1477 &Value::Null,
1478 )
1479 .await
1480 .expect("a transform on an unbridged domain must not fail setup");
1481
1482 assert!(
1484 hooks.contains(&"session.context".to_string()),
1485 "the bridged hook must survive: {hooks:?}"
1486 );
1487 let out = sc.trigger_v2("session", "context", json!({})).await?;
1488 assert_eq!(out["matched"], 1);
1489 assert_eq!(out["output"]["survived"], true);
1490
1491 let inv = sc.v2_inventory().await?;
1493 let unbridged: Vec<String> = inv["unbridged_transforms"]
1494 .as_array()
1495 .expect("inventory must list unbridged transforms")
1496 .iter()
1497 .map(|v| v.as_str().unwrap_or_default().to_string())
1498 .collect();
1499 assert!(unbridged.contains(&"tool".to_string()), "{inv}");
1500 assert!(unbridged.contains(&"integration".to_string()), "{inv}");
1501
1502 std::fs::write(
1505 dir.path().join("p_v2_use.mjs"),
1506 r#"export default {
1507 id: "v2use",
1508 setup: async (ctx) => { await ctx.vcs.apply({}); },
1509};"#,
1510 )
1511 .unwrap();
1512 let err = sc
1513 .load(
1514 "v2use",
1515 &dir.path().join("p_v2_use.mjs"),
1516 &input,
1517 &Value::Null,
1518 )
1519 .await
1520 .expect_err("using an unbridged domain must still fail loudly");
1521 let text = format!("{err:#}");
1522 assert!(text.contains("D-V2-DOMAIN"), "{text}");
1523 assert!(text.contains("vcs"), "{text}");
1524
1525 sc.shutdown().await;
1526 Ok(())
1527 }
1528
1529 #[tokio::test]
1538 async fn v2_domain_rest_methods_bind_real_routes() -> anyhow::Result<()> {
1539 if !runtime_available() {
1540 panic!(
1541 "plugin-runtime binary ({}) required for plugin-host tests",
1542 crate::plugin_runtime().program()
1543 );
1544 }
1545 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1548 let port = listener.local_addr().unwrap().port();
1549 std::thread::spawn(move || {
1550 for stream in listener.incoming() {
1551 let Ok(mut s) = stream else { continue };
1552 use std::io::{Read, Write};
1553 let mut buf = [0u8; 2048];
1554 let _ = s.read(&mut buf);
1555 let body = br#"{"id":"ses_bound","title":"bound-route"}"#;
1556 let _ = s.write_all(
1557 format!(
1558 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
1559 body.len()
1560 )
1561 .as_bytes(),
1562 );
1563 let _ = s.write_all(body);
1564 }
1565 });
1566
1567 let dir = tempfile::tempdir().unwrap();
1568 std::fs::write(
1571 dir.path().join("rest.mjs"),
1572 r#"export default {
1573 id: "restprobe",
1574 setup: async (ctx) => {
1575 const results = {};
1576 // plugin.list must return the REAL inventory, not [].
1577 results.pluginList = await ctx.plugin.list();
1578 // session.get must reach the bound route.
1579 try {
1580 const s = await ctx.session.get("ses_bound");
1581 results.sessionGet = { ok: true, id: s && s.id };
1582 } catch (e) { results.sessionGet = { ok: false, err: String(e && e.message || e) }; }
1583 // An UNBOUND verb must throw the NAMED divergence, not a TypeError.
1584 try { await ctx.session.notARealVerb("x"); results.unbound = { threw: false }; }
1585 catch (e) { results.unbound = { threw: true, msg: String(e && e.message || e) }; }
1586 await ctx.rpc.register({ id: "probe" }, { results: async () => results });
1587 },
1588};"#,
1589 )
1590 .unwrap();
1591
1592 let host = materialize_host(&dir.path().join("host"))?;
1593 let mut sc = Sidecar::spawn(&host, &format!("http://127.0.0.1:{port}"), "/work").await?;
1594 let input = json!({"directory": "/work", "serverUrl": format!("http://127.0.0.1:{port}")});
1595 sc.load(
1596 "restprobe",
1597 &dir.path().join("rest.mjs"),
1598 &input,
1599 &Value::Null,
1600 )
1601 .await?;
1602
1603 let r = sc.rpc_call("probe", "results", json!({})).await?;
1604 let out = &r["output"];
1605
1606 let listed = out["pluginList"].as_array().cloned().unwrap_or_default();
1608 assert!(
1609 listed.iter().any(|p| p["id"] == "restprobe"),
1610 "ctx.plugin.list() must report the loaded plugin: {out}"
1611 );
1612
1613 assert_eq!(
1615 out["sessionGet"]["ok"], true,
1616 "ctx.session.get must reach /api/session/{{id}}: {out}"
1617 );
1618 assert_eq!(out["sessionGet"]["id"], "ses_bound");
1619
1620 assert_eq!(
1623 out["unbound"]["threw"], true,
1624 "unbound verb must throw: {out}"
1625 );
1626 let msg = out["unbound"]["msg"].as_str().unwrap_or_default();
1627 assert!(
1628 msg.contains("D-V2-DOMAIN"),
1629 "unbound verb must name the divergence (D-V2-DOMAIN), got: {msg}"
1630 );
1631
1632 sc.shutdown().await;
1633 Ok(())
1634 }
1635
1636 #[tokio::test]
1649 async fn v2_command_transform_pulls_into_the_served_list() -> anyhow::Result<()> {
1650 if !runtime_available() {
1651 panic!(
1652 "plugin-runtime binary ({}) required for plugin-host tests",
1653 crate::plugin_runtime().program()
1654 );
1655 }
1656 let dir = tempfile::tempdir().unwrap();
1657 std::fs::write(
1658 dir.path().join("tx.mjs"),
1659 r#"export default {
1660 id: "tx",
1661 setup: async (ctx) => {
1662 // upstream shape: ctx.command.transform((editor) => editor.add({...}))
1663 await ctx.command.transform((editor) => {
1664 editor.add({ name: "plugin-cmd", description: "added by plugin" });
1665 });
1666 await ctx.skill.transform((editor) => {
1667 editor.update("demo-skill", (s) => { s.description = "rewritten by plugin"; });
1668 editor.add({ name: "plugin-skill", description: "skill from plugin", source: "skill" });
1669 });
1670 await ctx.command.reload();
1671 const listed = await ctx.command.list();
1672 await ctx.rpc.register({ id: "probe" }, {
1673 afterSetup: async () => ({ listed }),
1674 });
1675 },
1676};"#,
1677 )
1678 .unwrap();
1679
1680 let host = materialize_host(&dir.path().join("host"))?;
1681 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
1682 let input = json!({"directory": "/work"});
1683 sc.load("tx", &dir.path().join("tx.mjs"), &input, &Value::Null)
1684 .await?;
1685
1686 let pristine = vec![
1689 json!({"name": "demo-skill", "description": "original", "source": "skill"}),
1690 json!({"name": "review", "description": "config command", "source": "config"}),
1691 ];
1692 let (edited, failures) = sc.transform_commands(pristine.clone()).await?;
1693
1694 assert!(
1695 failures.is_empty(),
1696 "no transform should have failed: {failures:?}"
1697 );
1698 let added = edited
1700 .iter()
1701 .find(|c| c["name"] == "plugin-cmd")
1702 .expect("plugin command must be present");
1703 assert_eq!(added["description"], "added by plugin");
1704 let skill = edited
1706 .iter()
1707 .find(|c| c["name"] == "demo-skill")
1708 .expect("demo-skill must still be present");
1709 assert_eq!(
1710 skill["description"], "rewritten by plugin",
1711 "skill.transform must reach the vector skill_entries() reads"
1712 );
1713 assert!(
1715 edited
1716 .iter()
1717 .any(|c| c["name"] == "plugin-skill" && c["source"] == "skill"),
1718 "plugin skill must carry source=skill or skill_entries() drops it: {edited:?}"
1719 );
1720 assert!(edited.iter().any(|c| c["name"] == "review"));
1722
1723 let (again, _) = sc.transform_commands(pristine.clone()).await?;
1726 assert_eq!(
1727 serde_json::to_value(&again).unwrap(),
1728 serde_json::to_value(&edited).unwrap(),
1729 "a reload must not accumulate duplicates"
1730 );
1731
1732 let (kept, _) = sc
1735 .transform_commands(vec![json!({"name": "keepme"})])
1736 .await?;
1737 assert!(kept.iter().any(|c| c["name"] == "keepme"));
1738
1739 sc.shutdown().await;
1740 Ok(())
1741 }
1742
1743 #[tokio::test]
1748 async fn v2_command_transform_failure_keeps_the_list() -> anyhow::Result<()> {
1749 if !runtime_available() {
1750 panic!(
1751 "plugin-runtime binary ({}) required for plugin-host tests",
1752 crate::plugin_runtime().program()
1753 );
1754 }
1755 let dir = tempfile::tempdir().unwrap();
1756 std::fs::write(
1757 dir.path().join("boom.mjs"),
1758 r#"export default {
1759 id: "boom",
1760 setup: async (ctx) => {
1761 await ctx.command.transform(() => { throw new Error("transform exploded"); });
1762 await ctx.command.transform((editor) => { editor.add({ name: "survivor" }); });
1763 },
1764};"#,
1765 )
1766 .unwrap();
1767
1768 let host = materialize_host(&dir.path().join("host"))?;
1769 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
1770 let input = json!({"directory": "/work"});
1771 sc.load("boom", &dir.path().join("boom.mjs"), &input, &Value::Null)
1772 .await?;
1773
1774 let (kept, failures) = sc
1775 .transform_commands(vec![json!({"name": "existing"})])
1776 .await?;
1777 assert!(
1779 kept.iter().any(|c| c["name"] == "survivor"),
1780 "a throwing transform must not stop the others: {kept:?}"
1781 );
1782 assert!(kept.iter().any(|c| c["name"] == "existing"));
1783 assert_eq!(failures.len(), 1, "the throwing transform must be reported");
1785 assert!(
1786 failures[0]["message"]
1787 .as_str()
1788 .unwrap_or_default()
1789 .contains("transform exploded"),
1790 "{failures:?}"
1791 );
1792
1793 sc.shutdown().await;
1794 Ok(())
1795 }
1796
1797 #[tokio::test]
1801 async fn config_hook_is_dispatched() -> anyhow::Result<()> {
1802 if !runtime_available() {
1803 panic!(
1804 "plugin-runtime binary ({}) required for plugin-host tests",
1805 crate::plugin_runtime().program()
1806 );
1807 }
1808 let dir = tempfile::tempdir().unwrap();
1809 std::fs::write(
1810 dir.path().join("cfg.mjs"),
1811 r#"export const PluginModule = {
1812 id: "cfg",
1813 server: async () => ({
1814 config: async (cfg) => {
1815 if (typeof cfg !== "object" || cfg === null) throw new Error("config not object");
1816 },
1817 "chat.message": async () => {},
1818 }),
1819};
1820export default PluginModule.server;"#,
1821 )
1822 .unwrap();
1823 let host = materialize_host(&dir.path().join("host"))?;
1824 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1825 sc.load("cfg", &dir.path().join("cfg.mjs"), &json!({}), &Value::Null)
1826 .await?;
1827 let r = sc.config(json!({"model": "x"})).await?;
1828 assert_eq!(r["matched"], 1, "config hook must be dispatched: {r}");
1829 sc.shutdown().await;
1830 Ok(())
1831 }
1832
1833 fn runtime_available() -> bool {
1835 crate::which(crate::plugin_runtime().program()).is_some()
1836 }
1837
1838 #[tokio::test]
1845 async fn battery_all_authoring_forms_and_options() -> anyhow::Result<()> {
1846 if !runtime_available() {
1847 panic!(
1848 "plugin-runtime binary ({}) required for plugin-host tests",
1849 crate::plugin_runtime().program()
1850 );
1851 }
1852 let dir = tempfile::tempdir().unwrap();
1853 std::fs::write(
1855 dir.path().join("p_module.mjs"),
1856 r#"export const PluginModule = {
1857 id: "m",
1858 server: async () => ({ "chat.message": async (_i, o) => { o.module = true; } }),
1859};"#,
1860 )
1861 .unwrap();
1862 std::fs::write(
1864 dir.path().join("p_default_obj.mjs"),
1865 r#"export default { server: async () => ({ "chat.params": async (_i, o) => { o.defaultobj = true; } }) };"#,
1866 )
1867 .unwrap();
1868 std::fs::write(
1870 dir.path().join("p_default_fn.mjs"),
1871 r#"export default async () => ({ "tool.execute.after": async (_i, o) => { o.defaultfn = true; } });"#,
1872 )
1873 .unwrap();
1874 std::fs::write(
1876 dir.path().join("p_named.mjs"),
1877 r#"export async function MyPlugin() { return { "event": async () => {} }; }"#,
1878 )
1879 .unwrap();
1880 std::fs::write(
1882 dir.path().join("p_options.mjs"),
1883 r#"export const PluginModule = {
1884 id: "opts",
1885 server: async (_input, options) => ({
1886 "chat.message": async (_i, o) => { o.sawOptions = options; },
1887 }),
1888};"#,
1889 )
1890 .unwrap();
1891
1892 let host = materialize_host(&dir.path().join("host"))?;
1893 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1894 let input =
1895 json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
1896
1897 let h1 = sc
1898 .load("m", &dir.path().join("p_module.mjs"), &input, &Value::Null)
1899 .await?;
1900 assert_eq!(h1, vec!["chat.message"], "PluginModule.server form");
1901 let h2 = sc
1902 .load(
1903 "dobj",
1904 &dir.path().join("p_default_obj.mjs"),
1905 &input,
1906 &Value::Null,
1907 )
1908 .await?;
1909 assert_eq!(h2, vec!["chat.params"], "default object with .server form");
1910 let h3 = sc
1911 .load(
1912 "dfn",
1913 &dir.path().join("p_default_fn.mjs"),
1914 &input,
1915 &Value::Null,
1916 )
1917 .await?;
1918 assert_eq!(
1919 h3,
1920 vec!["tool.execute.after"],
1921 "default function (legacy) form"
1922 );
1923 let h4 = sc
1924 .load(
1925 "named",
1926 &dir.path().join("p_named.mjs"),
1927 &input,
1928 &Value::Null,
1929 )
1930 .await?;
1931 assert_eq!(h4, vec!["event"], "named function export form");
1932
1933 let opts = json!({"token": "abc", "n": 3});
1934 let h5 = sc
1935 .load("opts", &dir.path().join("p_options.mjs"), &input, &opts)
1936 .await?;
1937 assert_eq!(
1938 h5,
1939 vec!["chat.message"],
1940 "options-tuple form registers same hook"
1941 );
1942
1943 let out = sc.trigger("chat.message", json!({}), json!({})).await?;
1945 assert_eq!(out["module"], true, "form 1 hook fired");
1946 assert_eq!(out["sawOptions"], opts, "factory saw the tuple options");
1948 let out2 = sc.trigger("chat.params", json!({}), json!({})).await?;
1949 assert_eq!(out2["defaultobj"], true, "form 2 hook fired");
1950 let out3 = sc
1951 .trigger("tool.execute.after", json!({}), json!({}))
1952 .await?;
1953 assert_eq!(out3["defaultfn"], true, "form 3 hook fired");
1954
1955 let st = sc.statuses();
1957 for spec in ["m", "dobj", "dfn", "named", "opts"] {
1958 assert_eq!(st[spec]["ok"], true, "status for {spec}");
1959 }
1960 sc.shutdown().await;
1961 Ok(())
1962 }
1963}
1964
1965#[cfg(test)]
1966mod runtime_selection_tests {
1967 #[test]
1971 fn runtime_override_and_default_preference() {
1972 let has_bun = crate::which("bun").is_some();
1973 let has_node = crate::which("node").is_some();
1974 if !has_node {
1975 panic!("node required for the fallback leg (test environment gate)");
1976 }
1977
1978 unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "node") };
1980 assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
1981
1982 if has_bun {
1983 unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "bun") };
1984 assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Bun);
1985 unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
1986 assert_eq!(
1987 crate::plugin_runtime(),
1988 crate::PluginRuntime::Bun,
1989 "bun present + no override → bun preferred (upstream fidelity)"
1990 );
1991 } else {
1992 unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
1993 assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
1994 }
1995
1996 unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "deno") };
1998 let _ = crate::plugin_runtime();
1999 unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2000 }
2001}
2002
2003#[cfg(test)]
2004mod oom_wrapper_tests {
2005 #[cfg(target_os = "linux")]
2008 #[test]
2009 fn wrapper_raises_child_oom_score_adj() {
2010 let out = std::process::Command::new("sh")
2011 .arg("-c")
2012 .arg(ocserve_store::cgroup::WRAPPER)
2013 .arg("sh")
2014 .arg("cat")
2015 .arg("/proc/self/oom_score_adj")
2016 .output()
2017 .expect("wrapper spawns");
2018 assert!(
2019 out.status.success(),
2020 "wrapper failed: {}",
2021 String::from_utf8_lossy(&out.stderr)
2022 );
2023 assert_eq!(
2024 String::from_utf8_lossy(&out.stdout).trim(),
2025 "500",
2026 "child must run at adj=500"
2027 );
2028 }
2029}
2030
2031#[cfg(test)]
2032mod plugin_tool_schema_tests {
2033 use super::*;
2034
2035 #[tokio::test]
2041 async fn plugin_tool_schema_is_valid_json_schema() -> anyhow::Result<()> {
2042 let dir = tempfile::tempdir()?;
2043 let entry = dir.path().join("p_schema.mjs");
2044 std::fs::write(
2045 &entry,
2046 r#"import { z } from "zod";
2047export const hook = async () => ({
2048 tool: {
2049 ztool: {
2050 description: "zod args",
2051 args: {
2052 text: z.string(),
2053 count: z.number(),
2054 },
2055 execute: async () => "ok",
2056 },
2057 },
2058});"#,
2059 )?;
2060 std::fs::create_dir_all(dir.path().join("node_modules/zod"))?;
2062 std::fs::write(
2063 dir.path().join("node_modules/zod/package.json"),
2064 r#"{"name":"zod","version":"4.0.0","main":"./index.cjs","exports":{".":"./index.cjs","./v4":"./index.cjs"}}"#,
2065 )?;
2066 std::fs::write(
2067 dir.path().join("node_modules/zod/index.cjs"),
2068 "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'] });",
2069 )?;
2070 let host = materialize_host(&dir.path().join("host"))?;
2071 let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2072 sc.load(
2073 "schema-fixture",
2074 &entry,
2075 &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
2076 &Value::Null,
2077 )
2078 .await?;
2079 let tools = sc.handle().tools().await?;
2080 let tool = tools
2081 .iter()
2082 .find(|t| t["name"] == "ztool")
2083 .expect("ztool advertised");
2084 let params = &tool["parameters"];
2085 assert_eq!(params["type"], "object", "{params}");
2086 assert_eq!(params["properties"]["text"]["type"], "string", "{params}");
2087 assert!(
2088 params["properties"]["text"].get("~standard").is_none()
2089 && params["properties"]["text"].get("def").is_none(),
2090 "a raw Zod object must never reach the provider: {params}"
2091 );
2092 sc.shutdown().await;
2093 Ok(())
2094 }
2095}