Skip to main content

ocserve_plugin/
lib.rs

1//! ocserve-plugin: opencode plugin compatibility via a Node sidecar (M4b).
2//!
3//! Gate rationale (PLAN §10, evidence not assumption): the frozen plugins
4//! import `bun:sqlite`, `child_process`, `node:fs/crypto/url` and TTY UI
5//! modules (import audit of the actual artifacts). A quickjs embed would need
6//! a dozen shims with a *synchronous* SQLite bridge — rejected as high-risk;
7//! one Node sidecar (v25 present, `node:sqlite` built in) is the low-
8//! maintenance host. Isolation: sidecar crash/restart cannot take down the
9//! server; protocol = NDJSON on stdio; plugin chatter is forced to stderr by
10//! the host so framing cannot corrupt.
11#![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
25/// Host files (written next to the data dir once; content-addressed by embed).
26pub const HOST_FILES: &[(&str, &str)] = &[
27    ("host.mjs", include_str!("host/host.mjs")),
28    ("native-assets.mjs", include_str!("host/native-assets.mjs")),
29    ("v2.mjs", include_str!("host/v2.mjs")),
30    (
31        "bun-sqlite-loader.mjs",
32        include_str!("host/bun-sqlite-loader.mjs"),
33    ),
34    (
35        "shim-bun-sqlite.mjs",
36        include_str!("host/shim-bun-sqlite.mjs"),
37    ),
38    (
39        "shim-bun-sqlite.cjs",
40        include_str!("host/shim-bun-sqlite.cjs"),
41    ),
42];
43
44/// Per-RPC timeout (hooks are local JS; anything longer is a runaway plugin).
45pub const RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
46
47/// Write host files into `dir` (idempotent overwrite — embed is authoritative).
48pub fn materialize_host(dir: &Path) -> Result<PathBuf> {
49    std::fs::create_dir_all(dir).with_context(|| format!("create host dir {}", dir.display()))?;
50    for (name, body) in HOST_FILES {
51        let path = dir.join(name);
52        std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
53    }
54    Ok(dir.join("host.mjs"))
55}
56
57/// Resolve a plugin spec to an entry file (loader.ts semantics, npm-install
58/// stage assumed already done by opencode's cache — we re-use it read-only):
59/// - `file://` URL (what upstream configs and launchers inject) → path
60/// - absolute/relative path → direct entry (a directory resolves through its
61///   package.json or conventional `index`/`server` files, v2 config semantics)
62/// - npm spec (`name`, `@scope/name`, `name@version`) →
63///   `~/.cache/opencode/packages/{spec}[@latest]/node_modules/{pkg}/…` entry
64///   via package.json exports["."] | main | module
65pub fn resolve_entry(spec: &str, home: &Path) -> Result<PathBuf> {
66    if let Some(p) = file_url_path(spec) {
67        return entry_from_path(&p);
68    }
69    // Upstream config paths are allowed to start with `~/`; a literal tilde
70    // otherwise falls through to the npm cache and reports "not found".
71    if let Some(rest) = spec.strip_prefix("~/") {
72        return entry_from_path(&home.join(rest));
73    }
74    if is_path_spec(spec) {
75        return entry_from_path(Path::new(spec));
76    }
77    let cache = home.join(".cache/opencode/packages");
78    let pkg_name = strip_version(spec);
79    let candidates = [
80        cache.join(format!("{spec}@latest")),
81        cache.join(spec),
82        cache.join(format!("{pkg_name}@latest")),
83    ];
84    for dir in &candidates {
85        if !dir.exists() {
86            continue;
87        }
88        // wrapper package.json → node_modules/<pkg>/package.json
89        let direct = dir.join("package.json");
90        if let Some(entry) = entry_from_package(&direct, dir, &pkg_name) {
91            return Ok(entry);
92        }
93        let nested = dir
94            .join("node_modules")
95            .join(&pkg_name)
96            .join("package.json");
97        if let Some(entry) = entry_from_package(&nested, nested.parent().unwrap_or(dir), &pkg_name)
98        {
99            return Ok(entry);
100        }
101    }
102    anyhow::bail!("plugin target not found in opencode cache: {spec}")
103}
104
105/// Upstream `isPathPluginSpec`: `file://`, dot-relative, absolute, or a
106/// Windows drive path (`C:\…` / `C:/…`).
107fn is_path_spec(spec: &str) -> bool {
108    let b = spec.as_bytes();
109    let drive = b.len() >= 3
110        && b[0].is_ascii_alphabetic()
111        && b[1] == b':'
112        && (b[2] == b'\\' || b[2] == b'/');
113    spec.starts_with('/')
114        || spec.starts_with("./")
115        || spec.starts_with("../")
116        || Path::new(spec).is_absolute()
117        || drive
118}
119
120/// Resolve a concrete path: a file IS the entry; a directory resolves to its
121/// package entry (v2 `plugins` entries point at package directories).
122fn entry_from_path(p: &Path) -> Result<PathBuf> {
123    // Absolutize before the containment check: a relative base containing
124    // `..` otherwise makes `entry_from_package`'s normalized entry look like
125    // an escape (`../pkg` + `dist/x.js` → `pkg/dist/x.js`).
126    let abs;
127    let p = if p.is_absolute() {
128        p
129    } else {
130        match std::env::current_dir() {
131            Ok(cwd) => {
132                abs = cwd.join(p);
133                &abs
134            }
135            Err(_) => p,
136        }
137    };
138    if p.is_file() {
139        return Ok(p.to_path_buf());
140    }
141    if p.is_dir() {
142        return dir_entry(p)
143            .ok_or_else(|| anyhow!("plugin directory has no entrypoint: {}", p.display()));
144    }
145    anyhow::bail!("plugin file not found: {}", p.display())
146}
147
148/// Entry file of a plugin DIRECTORY. Upstream `resolvePathPluginTarget`
149/// (`plugin/shared.ts`): package.json first (`exports["./server"]`, then
150/// `main`/`module`), else `index.{ts,tsx,js,mjs,cjs}`.
151fn dir_entry(dir: &Path) -> Option<PathBuf> {
152    if let Some(entry) = entry_from_package(&dir.join("package.json"), dir, "") {
153        return Some(entry);
154    }
155    for name in [
156        "index.ts",
157        "index.tsx",
158        "index.js",
159        "index.mjs",
160        "index.cjs",
161    ] {
162        let p = dir.join(name);
163        if p.is_file() {
164            return Some(p);
165        }
166    }
167    None
168}
169
170/// `file://` URL → local path (Paseo and other launchers configure plugins as
171/// `pathToFileURL(...)`). Percent-decoding is required: a temp path with a
172/// space is otherwise "not found". Returns None for non-file specs; a
173/// non-localhost authority is not supported (there is no local path).
174fn file_url_path(spec: &str) -> Option<PathBuf> {
175    let rest = spec.strip_prefix("file://")?;
176    // `file:///tmp/x` (empty authority) or `file://localhost/tmp/x`.
177    let rest = match rest.strip_prefix("localhost") {
178        Some(r) if r.starts_with('/') => r,
179        _ => rest,
180    };
181    if !rest.starts_with('/') {
182        return None;
183    }
184    let decoded = percent_decode(rest);
185    if decoded.is_empty() {
186        return None;
187    }
188    #[cfg(windows)]
189    let decoded = decoded.trim_start_matches('/').to_string();
190    Some(PathBuf::from(decoded))
191}
192
193fn percent_decode(s: &str) -> String {
194    let bytes = s.as_bytes();
195    let mut out = Vec::with_capacity(bytes.len());
196    let mut i = 0;
197    while i < bytes.len() {
198        if bytes[i] == b'%'
199            && i + 2 < bytes.len()
200            && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
201        {
202            out.push(hi * 16 + lo);
203            i += 3;
204            continue;
205        }
206        out.push(bytes[i]);
207        i += 1;
208    }
209    String::from_utf8_lossy(&out).into_owned()
210}
211
212fn hex_nibble(b: u8) -> Option<u8> {
213    match b {
214        b'0'..=b'9' => Some(b - b'0'),
215        b'a'..=b'f' => Some(b - b'a' + 10),
216        b'A'..=b'F' => Some(b - b'A' + 10),
217        _ => None,
218    }
219}
220
221/// Auto-discovered plugin targets under `<config_dir>/{plugin,plugins}`.
222///
223/// Upstream v2 `PluginSourceDirectory.discover`: a FILE ending `.ts`/`.js`, or
224/// ANY directory (a package with its own entrypoint). Sorted, deduped and
225/// CAPPED — a hostile/huge config dir must not make every `/api/plugin` poll
226/// pay an unbounded scan (AGENTS §2.3). `.mjs` files are deliberately not
227/// discovered (upstream does not); an explicitly configured spec may still
228/// name one.
229pub fn discover_plugin_specs(config_dir: &Path) -> Vec<String> {
230    const MAX_DISCOVERED: usize = 64;
231    let mut out = Vec::new();
232    for sub in ["plugin", "plugins"] {
233        let dir = config_dir.join(sub);
234        let Ok(entries) = std::fs::read_dir(&dir) else {
235            continue;
236        };
237        let mut entries: Vec<_> = entries.flatten().collect();
238        entries.sort_by_key(|e| e.file_name());
239        for entry in entries {
240            if out.len() >= MAX_DISCOVERED {
241                break;
242            }
243            let path = entry.path();
244            // `metadata` follows symlinks: a linked plugin file/dir loads like
245            // the target, matching upstream's isFile/isDir checks.
246            let Ok(meta) = std::fs::metadata(&path) else {
247                continue;
248            };
249            let is_source = meta.is_file()
250                && matches!(
251                    path.extension().and_then(|e| e.to_str()),
252                    Some("ts") | Some("js")
253                );
254            if (is_source || meta.is_dir())
255                && let Some(s) = path.to_str()
256            {
257                out.push(s.to_string());
258            }
259        }
260    }
261    out.sort();
262    out.dedup();
263    out.truncate(MAX_DISCOVERED);
264    out
265}
266
267fn strip_version(spec: &str) -> String {
268    // "@scope/name@latest" → "@scope/name"; "name@1.2.3" → "name"
269    let bytes = spec.as_bytes();
270    // find the LAST '@' that is NOT at index 0 (scope marker)
271    let mut cut = None;
272    for (i, b) in bytes.iter().enumerate() {
273        if *b == b'@' && i > 0 {
274            cut = Some(i);
275        }
276    }
277    match cut {
278        Some(i) => spec[..i].to_string(),
279        None => spec.to_string(),
280    }
281}
282
283fn entry_from_package(pkg_json: &Path, base: &Path, _pkg_name: &str) -> Option<PathBuf> {
284    let text = std::fs::read_to_string(pkg_json).ok()?;
285    let v: Value = serde_json::from_str(&text).ok()?;
286    let mut rel: Option<&str> = None;
287    if let Some(exp) = v.get("exports") {
288        // `exports["."]` is the npm entry; v2 plugin packages name their
289        // server part `exports["./server"]` (upstream `resolvePathPluginTarget`
290        // tries that first for a directory target).
291        for key in [".", "./server"] {
292            let Some(dot) = exp.get(key) else { continue };
293            rel = match dot {
294                Value::String(s) => Some(s.as_str()),
295                Value::Object(_) => dot
296                    .get("import")
297                    .and_then(|x| x.as_str())
298                    .or_else(|| dot.get("default").and_then(|x| x.as_str())),
299                _ => None,
300            };
301            if rel.is_some() {
302                break;
303            }
304        }
305    }
306    rel = rel.or_else(|| v.get("main").and_then(|x| x.as_str()));
307    rel = rel.or_else(|| v.get("module").and_then(|x| x.as_str()));
308    let rel = rel?;
309    let entry = base.join(rel);
310    // G6: the package's own `exports`/`main`/`module` may point outside the
311    // package (e.g. `../../other`). Lexically normalize and require the entry
312    // to stay inside `base`; a plugin entry is loaded only from its package.
313    let lex = lexically_normalize(&entry);
314    if !lex.starts_with(base)
315        && !std::fs::canonicalize(base)
316            .ok()
317            .is_some_and(|cb| lex.starts_with(&cb))
318    {
319        tracing::warn!("plugin entry {rel} escapes its package dir — refused");
320        return None;
321    }
322    lex.exists().then_some(lex)
323}
324
325fn lexically_normalize(p: &Path) -> PathBuf {
326    use std::path::Component;
327    let mut out = PathBuf::new();
328    for c in p.components() {
329        match c {
330            Component::ParentDir => {
331                out.pop();
332            }
333            Component::CurDir => {}
334            other => out.push(other.as_os_str()),
335        }
336    }
337    out
338}
339
340struct Pending {
341    tx: oneshot::Sender<Result<Value, String>>,
342}
343
344/// Removes its id from `pending` on every exit path, including a cancelled
345/// future. Without this, abort/delete cancel the awaiting task, the entry
346/// leaks, and `in_flight()` never returns 0 — the L1 recycle gate wedges.
347struct PendingGuard {
348    pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
349    id: i64,
350}
351
352impl PendingGuard {
353    fn new(pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>, id: i64) -> Self {
354        Self { pending, id }
355    }
356}
357
358impl Drop for PendingGuard {
359    fn drop(&mut self) {
360        self.pending.lock().remove(&self.id);
361    }
362}
363
364/// Everything a request needs, shareable WITHOUT the owning `Sidecar` lock.
365///
366/// Why this exists (2026-10-22): `hook_mutate` held `Arc<Mutex<Sidecar>>` for
367/// the whole hook await, so two sessions' hooks fully serialized — the
368/// reference interleaves them at `await` points. Writes are serialized by the
369/// stdin mutex and responses correlate by id, so nothing needs exclusive
370/// access to the process while a hook runs.
371///
372/// Liveness (2026-10-23 review): a handle is tied to ONE child generation.
373/// The reader marks `alive=false` when it stops, and `poisoned=true` when the
374/// protocol is no longer trustworthy; both make requests fail fast, and the
375/// owner's `ensure_alive` replaces the generation. A stale handle can never
376/// deliver a response to the wrong waiter.
377pub struct Inner {
378    stdin: tokio::sync::Mutex<ChildStdin>,
379    /// SHARED with the reader task (it resolves responses by id).
380    pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
381    next_id: std::sync::atomic::AtomicI64,
382    /// load results (spec → {hooks,…}) for introspection AND round-trip skips.
383    statuses: parking_lot::Mutex<HashMap<String, Value>>,
384    /// reader still running; false = requests must not be attempted.
385    alive: Arc<std::sync::atomic::AtomicBool>,
386    /// the child must be replaced before the next request (framing lost).
387    poisoned: Arc<std::sync::atomic::AtomicBool>,
388    /// last successfully fetched plugin-tool list. A busy host must not make
389    /// plugin tools vanish from the provider schema for a round (M6).
390    last_tools: parking_lot::Mutex<Option<Vec<Value>>>,
391}
392
393/// Cheap clone handle: hook dispatch drops the owner lock and awaits this.
394#[derive(Clone)]
395pub struct Handle(Arc<Inner>);
396
397impl Handle {
398    /// Is this generation still able to answer? Used by callers to decide
399    /// between a fast failure and a recovery attempt.
400    pub fn is_alive(&self) -> bool {
401        self.0.alive.load(std::sync::atomic::Ordering::Acquire)
402    }
403
404    /// Does any loaded plugin register `hook`? Lets the hot path skip the
405    /// sidecar round-trip entirely when nobody listens (most installs).
406    pub fn registers(&self, hook: &str) -> bool {
407        self.0.statuses.lock().values().any(|v| {
408            v.get("hooks")
409                .and_then(|h| h.as_array())
410                .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(hook)))
411        })
412    }
413
414    /// Any v1 or v2 plugin loaded successfully. The tool fetch is gated on
415    /// this (not on a specific hook/tool count) because v2 tools can be added
416    /// after load.
417    pub fn any_loaded(&self) -> bool {
418        self.0
419            .statuses
420            .lock()
421            .values()
422            .any(|v| v.get("ok").and_then(|b| b.as_bool()).unwrap_or(false))
423    }
424
425    /// Did any loaded plugin contribute tools outside the v1 `tool` hook
426    /// (v2 `tool.transform`)? Observability only; a v2 plugin may add more
427    /// tools later, so this must not gate `tools()`.
428    pub fn has_tools(&self) -> bool {
429        self.0.statuses.lock().values().any(|v| {
430            v.get("has_tools")
431                .and_then(|b| b.as_bool())
432                .unwrap_or(false)
433        })
434    }
435
436    pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
437        self.request_with_timeout(method, params, Some(RPC_TIMEOUT))
438            .await
439    }
440
441    pub async fn request_with_timeout(
442        &self,
443        method: &str,
444        params: Value,
445        timeout: Option<std::time::Duration>,
446    ) -> Result<Value> {
447        if !self.is_alive() {
448            anyhow::bail!("plugin host is down ({method}); a respawn is required");
449        }
450        let id = self
451            .0
452            .next_id
453            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
454        let (tx, rx) = oneshot::channel();
455        self.0.pending.lock().insert(id, Pending { tx });
456        let _guard = PendingGuard::new(Arc::clone(&self.0.pending), id);
457        let msg = json!({"id": id, "method": method, "params": params});
458        let mut line = msg.to_string();
459        line.push('\n');
460        // The BUDGET COVERS THE WRITE (review C2). Previously only the response
461        // wait was timed, so a host that stopped draining blocked every caller
462        // on the stdin mutex with no timer. A timeout now also poisons the
463        // generation: a partially written frame makes the protocol untrustworthy.
464        let exchange = async {
465            {
466                let mut stdin = self.0.stdin.lock().await;
467                stdin.write_all(line.as_bytes()).await?;
468                stdin.flush().await?;
469            }
470            match rx.await {
471                Ok(res) => res.map_err(|e| anyhow!("plugin host {method}: {e}")),
472                Err(_) => Err(anyhow!("plugin host dropped response for {method}")),
473            }
474        };
475        match timeout {
476            None => exchange
477                .await
478                .map_err(|e| e.context("plugin host stdin write")),
479            Some(d) => match tokio::time::timeout(d, exchange).await {
480                Ok(res) => res,
481                Err(_) => {
482                    self.0
483                        .poisoned
484                        .store(true, std::sync::atomic::Ordering::Release);
485                    self.0
486                        .alive
487                        .store(false, std::sync::atomic::Ordering::Release);
488                    ocserve_metrics::labeled_counter(
489                        "ocserve_plugin_hook_timeout_total",
490                        &format!("hook=\"{method}\""),
491                        1,
492                    );
493                    Err(anyhow!(
494                        "plugin host {method} timed out after {}ms (runaway hook?)",
495                        d.as_millis()
496                    ))
497                }
498            },
499        }
500    }
501}
502
503impl Handle {
504    pub async fn trigger_bounded(
505        &self,
506        name: &str,
507        input: Value,
508        mut output: Value,
509        budget: Option<std::time::Duration>,
510    ) -> Result<Value> {
511        let res = self
512            .request_with_timeout(
513                "trigger",
514                json!({"name": name, "input": input, "output": output}),
515                budget,
516            )
517            .await?;
518        if res.is_object() {
519            output = res;
520        }
521        Ok(output)
522    }
523
524    pub async fn trigger_v2_bounded(
525        &self,
526        domain: &str,
527        name: &str,
528        input: Value,
529        budget: Option<std::time::Duration>,
530    ) -> Result<Value> {
531        self.request_with_timeout(
532            "trigger_v2",
533            json!({"domain": domain, "name": name, "input": input}),
534            budget,
535        )
536        .await
537    }
538
539    pub async fn emit_event_bounded(
540        &self,
541        event: Value,
542        budget: Option<std::time::Duration>,
543    ) -> Result<Value> {
544        self.request_with_timeout("event", json!({"event": event}), budget)
545            .await
546    }
547}
548
549/// Per-hook budget. Upstream has NO hook timeout (`Effect.promise(...)` awaits
550/// forever); any bound is our safety divergence, recorded as D-HOOK-TIMEOUT.
551/// Defaults come from measured maxima on a real install (27 prompts):
552/// `v2.session.context` 15.3 s, `tool.execute.after` 30.0 s,
553/// `system.transform` 5.4 s. `OCSERVE_HOOK_TIMEOUT_MS=0` restores parity
554/// (unbounded) for an operator who needs it.
555pub fn hook_budget(hook: &str) -> Option<std::time::Duration> {
556    match std::env::var("OCSERVE_HOOK_TIMEOUT_MS")
557        .ok()
558        .and_then(|v| v.parse::<u64>().ok())
559    {
560        Some(0) => None,
561        Some(ms) => Some(std::time::Duration::from_millis(ms)),
562        None => Some(std::time::Duration::from_secs(
563            if hook.contains("tool.execute") {
564                180
565            } else if hook.contains("transform")
566                || hook.contains("context")
567                // `experimental.session.compacting` does NOT contain
568                // "compaction" (review M1: a substring miss gave it 30 s).
569                || hook.contains("compact")
570            {
571                60
572            } else {
573                30
574            },
575        )),
576    }
577}
578
579impl Handle {
580    /// v2 RPC dispatch (see `Sidecar::rpc_call`, which delegates here).
581    pub async fn rpc_call(&self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
582        self.request(
583            "rpc_call",
584            json!({"rpcID": rpc_id, "method": method, "input": input}),
585        )
586        .await
587    }
588
589    /// v2 plugin inventory (real — id/dialect per loaded v2 plugin + the
590    /// registered RPC ids). Powers `/api/plugin` without fabricating a list.
591    pub async fn v2_inventory(&self) -> Result<Value> {
592        self.request("v2_inventory", json!({})).await
593    }
594
595    /// Pulled v2 command/skill transform (see `Sidecar::transform_commands`).
596    pub async fn transform_commands(
597        &self,
598        commands: Vec<Value>,
599    ) -> Result<(Vec<Value>, Vec<Value>)> {
600        let r = self
601            .request("v2_transform_commands", json!({ "commands": commands }))
602            .await?;
603        let out = r["commands"]
604            .as_array()
605            .cloned()
606            .unwrap_or_default()
607            .into_iter()
608            .collect();
609        let failures = r["failures"].as_array().cloned().unwrap_or_default();
610        Ok((out, failures))
611    }
612}
613
614impl Handle {
615    /// Plugin-declared tools (v1 `hooks.tool`), with JSON Schema generated in
616    /// the plugin's own runtime. Empty when no plugin registers one, so the
617    /// provider `tools` array is byte-identical for everyone else.
618    ///
619    /// A failed fetch returns the LAST KNOWN list rather than an empty one
620    /// (review M6): dropping tools mid-session made a later call to one fall
621    /// through to "unknown tool", a worse failure than a stale schema.
622    pub async fn tools(&self) -> Result<Vec<Value>> {
623        // Any loaded plugin may advertise tools — v1 via the `tool` hook, v2
624        // via `tool.transform`, which a launcher can call LATER (Paseo installs
625        // its `paseo_*` tools on `rpc.bind`, after load). A load-time tool
626        // count would therefore short-circuit exactly the tools that matter.
627        // The RPC only happens when a plugin host exists at all (most installs
628        // have none; `tools()` then returns before this).
629        if !self.any_loaded() {
630            return Ok(Vec::new());
631        }
632        match self.request("tools", json!({})).await {
633            Ok(res) => {
634                let list = res.as_array().cloned().unwrap_or_default();
635                *self.0.last_tools.lock() = Some(list.clone());
636                Ok(list)
637            }
638            Err(e) => {
639                if let Some(cached) = self.0.last_tools.lock().clone() {
640                    tracing::warn!("plugin tools: {e:#} — serving the last known list");
641                    return Ok(cached);
642                }
643                Err(e)
644            }
645        }
646    }
647
648    /// Execute one plugin tool. `ctx` carries {sessionID, messageID, agent,
649    /// directory}. The permission gate ran already for the call as a whole.
650    pub async fn execute_tool(&self, name: &str, input: Value, ctx: Value) -> Result<Value> {
651        self.request_with_timeout(
652            "tool_execute",
653            json!({"name": name, "input": input, "ctx": ctx}),
654            Some(std::time::Duration::from_secs(300)),
655        )
656        .await
657    }
658}
659
660/// Sidecar owner: one Node process, NDJSON request/response, reader task.
661pub struct Sidecar {
662    inner: Arc<Inner>,
663    child: Child,
664    /// server/directory context for loads (kept for future reloads)
665    server: (String, String),
666    /// spawn identity for respawn-after-death
667    args: SpawnArgs,
668    /// successful loads (spec, entry, input, options) — replayed on respawn
669    /// (entries stored RAW; load_raw re-normalizes on replay — D1-PLAN).
670    /// `options` is the v1 `[spec, options]` tuple's second element (Null when
671    /// the plain-string form was used) — passed to the server factory.
672    loads: Vec<(String, PathBuf, Value, Value)>,
673    /// normalization output root (`data/normalized`); None = skip (tests,
674    /// any sidecar without it — existing behavior untouched, D1-PLAN)
675    normalize_root: Option<PathBuf>,
676    /// spawn time for the L1 recycle min-uptime guard (SRE §5) — fresh on
677    /// every (re)spawn, so a recycled sidecar can't be recycled again until
678    /// the guard window passes.
679    started_at: std::time::Instant,
680    /// L1 recycle marker: set when WE killed the child on purpose; the next
681    /// ensure_alive must log that as INFO (planned), not ERROR (crash) —
682    /// an intentional action must never read as a failure in the logs.
683    recycled: bool,
684}
685
686/// Plugin-host runtime: Bun preferred (upstream runs plugins under Bun; real
687/// `bun:sqlite`, TS plugins load, lower RSS floor), Node fallback.
688/// `OCSERVE_PLUGIN_RUNTIME=node|bun` forces one (lab A/B control).
689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
690pub enum PluginRuntime {
691    Bun,
692    Node,
693}
694
695impl PluginRuntime {
696    pub fn program(self) -> &'static str {
697        match self {
698            PluginRuntime::Bun => "bun",
699            PluginRuntime::Node => "node",
700        }
701    }
702}
703
704/// Resolve an executable on PATH plus `~/.bun/bin` (the common user-local
705/// bun install location — systemd units do not see shell PATH extras).
706pub(crate) fn which(prog: &str) -> Option<PathBuf> {
707    // Windows resolves executables by suffix; `Path::join("bun")` never finds
708    // `bun.exe` (PLATFORM.md §1.2). The suffix lives in one place — ocserve-core
709    // — so the plugin host, the MCP client and the tools cannot drift.
710    let name = ocserve_store::platform::exe(prog);
711    if let Ok(path) = std::env::var("PATH") {
712        for dir in std::env::split_paths(&path) {
713            let cand = dir.join(&name);
714            if ocserve_store::platform::is_executable_file(&cand) {
715                return Some(cand);
716            }
717        }
718    }
719    for key in ["OCSERVE_HOME", "HOME", "USERPROFILE"] {
720        let Some(home) = std::env::var_os(key).filter(|v| !v.is_empty()) else {
721            continue;
722        };
723        let cand = Path::new(&home).join(".bun/bin").join(&name);
724        if ocserve_store::platform::is_executable_file(&cand) {
725            return Some(cand);
726        }
727    }
728    None
729}
730
731pub fn plugin_runtime() -> PluginRuntime {
732    match std::env::var("OCSERVE_PLUGIN_RUNTIME").as_deref() {
733        Ok("node") => return PluginRuntime::Node,
734        Ok("bun") => return PluginRuntime::Bun,
735        _ => {}
736    }
737    if which("bun").is_some() {
738        PluginRuntime::Bun
739    } else {
740        PluginRuntime::Node
741    }
742}
743
744#[derive(Clone)]
745struct SpawnArgs {
746    host_path: PathBuf,
747    server_url: String,
748    directory: String,
749}
750
751impl Sidecar {
752    pub async fn spawn(host_path: &Path, server_url: &str, directory: &str) -> Result<Self> {
753        // A3 (OOM-resilience): same wrapper as ocserve-mcp — the plugin host
754        // dies first on memcg pressure (ensure_alive respawns it) instead
755        // of the main service.
756        let runtime = crate::plugin_runtime();
757        // absolute path (systemd PATH may lack ~/.bun/bin); fall back to the
758        // bare name so a PATH-only environment still resolves
759        let program = which(runtime.program())
760            .map(|p| p.to_string_lossy().into_owned())
761            .unwrap_or_else(|| runtime.program().to_string());
762        // Containment (SRE §5.2): the child moves itself into kids/plugin and
763        // raises its oom_score_adj before exec, so a memcg kill takes the
764        // sidecar (ensure_alive respawns it) instead of the server.
765        let shape = ocserve_store::cgroup::contained(&program, "plugin");
766        let mut cmd = Command::new(&shape.program);
767        cmd.args(&shape.prefix);
768        // `ctx.app.version` must match the running server, not a literal in the
769        // shim (it said 0.3.1 through 0.6.x). Env keeps the host script
770        // version-agnostic.
771        cmd.env("OCSERVE_VERSION", env!("CARGO_PKG_VERSION"));
772        match &shape.cgroup {
773            Some(p) => {
774                cmd.env(ocserve_store::cgroup::ENV, p);
775            }
776            None => {
777                cmd.env_remove(ocserve_store::cgroup::ENV);
778            }
779        }
780        match runtime {
781            // Bun (upstream's own plugin runtime): real bun:sqlite + TS
782            // plugins load; `--smol` trades GC frequency for a lower RSS
783            // floor. No V8 --max-old-space knobs exist here.
784            PluginRuntime::Bun => {
785                cmd.arg("--smol");
786            }
787            // Node (fallback when bun is absent): V8 heap cap (env-tunable).
788            // Default raised64→128 after the LIVE battery (2026-10-03): with
789            // the real plugin set the sidecar OOM-killed at64 (observed boot
790            // death → hooks broken-piped until restart). Measured
791            // 64/128/192/256: RSS flat ~145-148MB either way (native
792            // dominates; heap cap only binds when heap actually grows).
793            PluginRuntime::Node => {
794                cmd.arg(format!(
795                    "--max-old-space-size={}",
796                    std::env::var("OCSERVE_PLUGIN_HEAP_MB")
797                        .ok()
798                        .and_then(|v| v.parse().ok())
799                        .unwrap_or(128)
800                ));
801                cmd.arg("--max-semi-space-size=2");
802            }
803        }
804        cmd.arg(host_path)
805            .stdin(std::process::Stdio::piped())
806            .stdout(std::process::Stdio::piped())
807            .stderr(std::process::Stdio::inherit())
808            .kill_on_drop(true);
809        let mut child = cmd
810            .spawn()
811            .with_context(|| format!("spawn {} plugin host", runtime.program()))?;
812        let stdin = child.stdin.take().context("host stdin")?;
813        let stdout = child.stdout.take().context("host stdout")?;
814        let pending = Arc::new(parking_lot::Mutex::new(HashMap::<i64, Pending>::new()));
815        let pending_task = Arc::clone(&pending);
816        let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
817        let alive_task = Arc::clone(&alive);
818        let poisoned = Arc::new(std::sync::atomic::AtomicBool::new(false));
819        let poisoned_task = Arc::clone(&poisoned);
820        tokio::spawn(async move {
821            // Bounded line reads: a plugin that prints a giant line (no newline)
822            // would otherwise grow `line` unbounded (host.mjs stdout is reserved
823            // for RPC, but a runaway plugin can still emit garbage). Cap at the
824            // RPC line budget; a longer line is discarded.
825            const MAX_HOST_LINE: usize = 8 * 1024 * 1024;
826            let mut reader = BufReader::new(stdout);
827            let mut line = String::new();
828            loop {
829                line.clear();
830                use tokio::io::AsyncBufReadExt as _;
831                let n = {
832                    let mut limited =
833                        tokio::io::AsyncReadExt::take(&mut reader, MAX_HOST_LINE as u64 + 1);
834                    limited.read_line(&mut line).await
835                };
836                match n {
837                    Ok(0) | Err(_) => break,
838                    // oversized: the rest of the line is unreadable framing —
839                    // stop; in-flight RPCs fail on timeout (never hang the pump).
840                    Ok(_) if line.len() > MAX_HOST_LINE => {
841                        // Framing is lost. Mark the generation dead AND poisoned
842                        // so the owner replaces the child instead of leaving a
843                        // live-but-deaf host that times out every request
844                        // (review C1/M-6).
845                        tracing::warn!("plugin host: oversized line — child marked for respawn");
846                        poisoned_task.store(true, std::sync::atomic::Ordering::Release);
847                        break;
848                    }
849                    Ok(_) => {}
850                }
851                let trimmed = line.trim();
852                if trimmed.is_empty() {
853                    continue;
854                }
855                match serde_json::from_str::<Value>(trimmed) {
856                    Ok(v) => {
857                        if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
858                            let result = match v.get("error") {
859                                Some(e) if !e.is_null() => {
860                                    Err(e["message"].as_str().unwrap_or("host error").to_string())
861                                }
862                                _ => Ok(v.get("result").cloned().unwrap_or(Value::Null)),
863                            };
864                            if let Some(p) = pending_task.lock().remove(&id) {
865                                let _ = p.tx.send(result);
866                            }
867                        } else if v.get("event").and_then(|e| e.as_str()) == Some("plugin_error") {
868                            // Per-plugin internal failure (the class that hid a
869                            // configured plugin for weeks: the plugin caught its
870                            // own TypeError and returned the input unchanged, so
871                            // Rust saw Ok). Counted by name so silence is visible.
872                            ocserve_metrics::labeled_counter(
873                                "ocserve_plugin_internal_error_total",
874                                &format!(
875                                    "plugin=\"{}\",hook=\"{}\"",
876                                    v["plugin"].as_str().unwrap_or("?"),
877                                    v["hook"].as_str().unwrap_or("?")
878                                ),
879                                1,
880                            );
881                            tracing::warn!(
882                                "plugin internal error: {} {}: {}",
883                                v["plugin"].as_str().unwrap_or("?"),
884                                v["hook"].as_str().unwrap_or("?"),
885                                v["error"].as_str().unwrap_or("?")
886                            );
887                        }
888                        // no id → informational; host routes plugin chatter to stderr
889                    }
890                    Err(_) => {
891                        let head: String = trimmed.chars().take(120).collect();
892                        tracing::warn!("plugin host: unparsable line: {head}");
893                    }
894                }
895            }
896            // host death (or reader death): fail everything in flight (fail
897            // fast, AGENTS §2.4) and tell every handle this generation is gone.
898            alive_task.store(false, std::sync::atomic::Ordering::Release);
899            for (_, p) in pending_task.lock().drain() {
900                let _ = p.tx.send(Err("plugin host exited".into()));
901            }
902            ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 0);
903        });
904        ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 1);
905        Ok(Self {
906            inner: Arc::new(Inner {
907                stdin: tokio::sync::Mutex::new(stdin),
908                pending,
909                next_id: std::sync::atomic::AtomicI64::new(1),
910                statuses: parking_lot::Mutex::new(HashMap::new()),
911                alive,
912                poisoned,
913                last_tools: parking_lot::Mutex::new(None),
914            }),
915            child,
916            server: (server_url.to_string(), directory.to_string()),
917            args: SpawnArgs {
918                host_path: host_path.to_path_buf(),
919                server_url: server_url.to_string(),
920                directory: directory.to_string(),
921            },
922            loads: Vec::new(),
923            normalize_root: None,
924            started_at: std::time::Instant::now(),
925            recycled: false,
926        })
927    }
928
929    /// RPCs currently in flight (the L1 recycle idle gate — a hook must
930    /// never be interrupted mid-call).
931    pub fn in_flight(&self) -> usize {
932        self.inner.pending.lock().len()
933    }
934
935    /// Seconds since this sidecar instance was spawned (respawns reset it).
936    pub fn uptime(&self) -> std::time::Duration {
937        self.started_at.elapsed()
938    }
939
940    /// L1 graceful recycle (SRE §5): kill the sidecar child while idle.
941    /// State is disk-backed (context.db / pins) and `loads` is kept, so the
942    /// next `ensure_alive` respawns + replays hooks (warm-hash normalize is
943    /// a no-op). SIGKILL is deliberate: the host has no shutdown protocol
944    /// and nothing in it needs flushing. Returns false if already dead.
945    pub fn recycle_child(&mut self) -> bool {
946        if self.child.try_wait().ok().flatten().is_some() {
947            return false;
948        }
949        let _ = self.child.start_kill();
950        // Do NOT clear `statuses`: the loads are still known and will be
951        // replayed on respawn. Clearing them made `registers()` false, so every
952        // hook short-circuited to "no plugin" forever — the 2026-10-23 review
953        // found a recycle silently disabled every plugin (the Magic Context
954        // class again). The generation flag says "needs respawn"; the hook
955        // path now acts on it.
956        self.inner
957            .alive
958            .store(false, std::sync::atomic::Ordering::Release);
959        self.recycled = true;
960        true
961    }
962
963    /// Enable normalization for this sidecar (set once at boot; carried to
964    /// respawns by `ensure_alive`). None/never-set = raw loads (today's
965    /// behavior — all existing tests stay on this path).
966    pub fn set_normalize_root(&mut self, root: PathBuf) {
967        self.normalize_root = Some(root);
968    }
969
970    /// Respawn after unexpected death (V8 OOM / crash) and replay every
971    /// previously loaded plugin. Without this a dead sidecar leaves ALL
972    /// hooks broken-piped until service restart (live battery finding
973    /// 2026-10-03: boot-time heap OOM, fail-open hid it in the prompt path).
974    pub async fn ensure_alive(&mut self) -> Result<()> {
975        // The reader can die while the child is alive (oversized line, lost
976        // framing). A live-but-deaf host times out every request, so treat
977        // poison as death and replace the whole generation.
978        if self
979            .inner
980            .poisoned
981            .load(std::sync::atomic::Ordering::Acquire)
982        {
983            let _ = self.child.start_kill();
984            self.inner
985                .alive
986                .store(false, std::sync::atomic::Ordering::Release);
987        } else if self.inner.alive.load(std::sync::atomic::Ordering::Acquire)
988            && let Ok(None) = self.child.try_wait()
989        {
990            return Ok(());
991        }
992        ocserve_metrics::labeled_counter(
993            "ocserve_plugin_sidecar_respawn_total",
994            if self.recycled {
995                "reason=\"recycle\""
996            } else {
997                "reason=\"exit\""
998            },
999            1,
1000        );
1001        let status = self.child.try_wait().ok().flatten();
1002        if std::mem::take(&mut self.recycled) {
1003            tracing::info!(
1004                "plugin sidecar recycled (L1, was {status:?}) — respawning + replaying hooks"
1005            );
1006        } else if let Some(status) = status {
1007            tracing::error!("plugin sidecar exited ({status}) — respawning");
1008        } else {
1009            tracing::warn!("plugin sidecar unresponsive — replacing the host");
1010        }
1011        let args = self.args.clone();
1012        let loads = std::mem::take(&mut self.loads);
1013        // Spawn failure must NOT lose `loads`: `self` is only replaced on
1014        // success, so restore the taken entries and surface the error. Without
1015        // this the plugin set is silently empty after a failed respawn — hooks
1016        // never replay and `in_flight()` stays zero (statuses stale).
1017        let mut fresh =
1018            match Sidecar::spawn(&args.host_path, &args.server_url, &args.directory).await {
1019                Ok(f) => f,
1020                Err(e) => {
1021                    self.loads = loads;
1022                    tracing::error!("plugin sidecar respawn failed: {e:#} — plugin set preserved");
1023                    return Err(e);
1024                }
1025            };
1026        // D1-PLAN: replay must normalize too (warm no-op; rebuilds if outputs
1027        // were wiped mid-run — A1 stores raw, rebuilds here AND at next boot).
1028        fresh.normalize_root = self.normalize_root.clone();
1029        for (spec, entry, input, options) in &loads {
1030            if let Err(e) = fresh.load_raw(spec, entry, input, options).await {
1031                tracing::warn!("plugin {spec} reload after respawn failed: {e:#}");
1032            }
1033        }
1034        *self = fresh;
1035        Ok(())
1036    }
1037
1038    /// Child pid (test/diag: force-kill to prove respawn).
1039    pub fn child_pid(&self) -> u32 {
1040        self.child.id().unwrap_or(0)
1041    }
1042
1043    pub fn handle(&self) -> Handle {
1044        Handle(Arc::clone(&self.inner))
1045    }
1046
1047    pub async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
1048        self.ensure_alive().await?;
1049        self.handle().request(method, params).await
1050    }
1051
1052    /// Request with an explicit budget; `None` keeps the historical RPC bound.
1053    pub async fn request_bounded(
1054        &mut self,
1055        method: &str,
1056        params: Value,
1057        timeout: Option<std::time::Duration>,
1058    ) -> Result<Value> {
1059        self.ensure_alive().await?;
1060        self.handle()
1061            .request_with_timeout(method, params, timeout)
1062            .await
1063    }
1064
1065    /// Load one plugin (v1 server-factory extraction happens host-side).
1066    /// `options` is the v1 `[spec, options]` tuple's second element (pass
1067    /// `Value::Null` for the plain-string form) — delivered to the factory.
1068    pub async fn load(
1069        &mut self,
1070        spec: &str,
1071        entry: &Path,
1072        input: &Value,
1073        options: &Value,
1074    ) -> Result<Vec<String>> {
1075        self.ensure_alive().await?;
1076        self.load_raw(spec, entry, input, options).await
1077    }
1078
1079    /// Unguarded load (respawn replay only — fresh child is alive).
1080    async fn load_raw(
1081        &mut self,
1082        spec: &str,
1083        entry: &Path,
1084        input: &Value,
1085        options: &Value,
1086    ) -> Result<Vec<String>> {
1087        // D1: normalize for the RPC (CPU on spawn_blocking — A2 class); the
1088        // RAW entry is what gets recorded for respawn replay (A1).
1089        let root = self.normalize_root.clone();
1090        let raw = entry.to_path_buf();
1091        let raw_for_spawn = raw.clone();
1092        let (load_path, outcome) = tokio::task::spawn_blocking(move || {
1093            crate::normalize::normalize_or_raw_sync(root.as_deref(), &raw_for_spawn)
1094        })
1095        .await
1096        .map_err(|e| anyhow!("normalize task: {e}"))?;
1097        ocserve_metrics::labeled_counter(
1098            "ocserve_plugin_normalize_total",
1099            &format!("result=\"{}\"", outcome.label()),
1100            1,
1101        );
1102        match &outcome {
1103            crate::normalize::Outcome::Built {
1104                path,
1105                ms,
1106                beside,
1107                rss_before_kb,
1108                rss_after_kb,
1109            } => tracing::info!(
1110                "plugin normalize {spec}: built {} ({}) in {ms}ms rss {rss_before_kb}→{rss_after_kb}kB",
1111                path.display(),
1112                if *beside { "beside-entry" } else { "data-dir" }
1113            ),
1114            crate::normalize::Outcome::Fallback { err, .. } => {
1115                tracing::warn!("plugin normalize {spec} failed, loading raw entry: {err}")
1116            }
1117            _ => {}
1118        }
1119        // server/directory context defaults from spawn (input may omit them)
1120        let mut input = input.clone();
1121        if input
1122            .get("serverUrl")
1123            .and_then(|v| v.as_str())
1124            .unwrap_or("")
1125            .is_empty()
1126        {
1127            input["serverUrl"] = json!(self.server.0);
1128        }
1129        if input
1130            .get("directory")
1131            .and_then(|v| v.as_str())
1132            .unwrap_or("")
1133            .is_empty()
1134        {
1135            input["directory"] = json!(self.server.1);
1136        }
1137        let params = json!({
1138            "spec": spec,
1139            "entry": load_path.to_string_lossy(),
1140            // Where the plugin ACTUALLY lives. Normalized bundles are emitted
1141            // outside the plugin's tree, so `createRequire(entry)` cannot
1142            // resolve its `zod` from there — and a tool schema that cannot be
1143            // converted is an invalid JSON Schema the provider 400s.
1144            "origin": raw.to_string_lossy(),
1145            "input": input,
1146            "options": options,
1147        });
1148        let res = self.handle().request("load", params).await?;
1149        let hooks: Vec<String> = res["hooks"]
1150            .as_array()
1151            .map(|a| {
1152                a.iter()
1153                    .filter_map(|h| h.as_str().map(String::from))
1154                    .collect()
1155            })
1156            .unwrap_or_default();
1157        self.inner.statuses.lock().insert(
1158            spec.to_string(),
1159            json!({
1160                "ok": true,
1161                "hooks": hooks,
1162                "id": res["id"],
1163                // v2 tools are registered through `tool.transform`, not a hook
1164                // name; this flag is what lets `tools()` skip the RPC when
1165                // nobody advertises one (v1 keeps the `tool` hook).
1166                "has_tools": res["has_tools"].as_bool().unwrap_or(false),
1167            }),
1168        );
1169        self.loads.push((
1170            spec.to_string(),
1171            entry.to_path_buf(),
1172            input,
1173            options.clone(),
1174        ));
1175        Ok(hooks)
1176    }
1177
1178    /// Was this spec already attempted (loaded OR failed)? Failures stay
1179    /// recorded so a launcher polling `/api/plugin` every 50 ms cannot re-run a
1180    /// crashing plugin thousands of times.
1181    pub fn attempted(&self, spec: &str) -> bool {
1182        self.inner.statuses.lock().contains_key(spec)
1183    }
1184
1185    /// Load one auto-discovered plugin on demand (hot pickup for a launcher
1186    /// that provisions `<config_dir>/plugins/…` after the server booted, as
1187    /// Paseo does). Idempotent; a resolve/load failure is recorded as a failed
1188    /// status instead of being retried on every poll.
1189    pub async fn load_discovered(&mut self, spec: &str, home: &Path) -> Result<Vec<String>> {
1190        if self.attempted(spec) {
1191            return Ok(Vec::new());
1192        }
1193        let entry = match resolve_entry(spec, home) {
1194            Ok(entry) => entry,
1195            Err(e) => {
1196                self.note_failure(spec, &e);
1197                return Err(e);
1198            }
1199        };
1200        self.ensure_alive().await?;
1201        let input = json!({
1202            "directory": self.server.1,
1203            "projectID": "global",
1204            "worktree": "/",
1205            "serverUrl": self.server.0,
1206        });
1207        match self.load(spec, &entry, &input, &json!({})).await {
1208            Ok(hooks) => Ok(hooks),
1209            Err(e) => {
1210                self.note_failure(spec, &e);
1211                Err(e)
1212            }
1213        }
1214    }
1215
1216    /// Record a failed attempt so `/api/plugin` reports `failed` instead of
1217    /// pretending the plugin is absent, and the discovery poll does not retry
1218    /// forever.
1219    pub fn note_failure(&self, spec: &str, e: &anyhow::Error) {
1220        self.inner.statuses.lock().insert(
1221            spec.to_string(),
1222            json!({"ok": false, "hooks": [], "error": format!("{e:#}")}),
1223        );
1224    }
1225
1226    /// v1 trigger semantics: sequential hooks mutate `output` in place.
1227    pub async fn trigger(&mut self, name: &str, input: Value, mut output: Value) -> Result<Value> {
1228        let params = json!({"name": name, "input": input, "output": output});
1229        let res = self.request("trigger", params).await?;
1230        if res.is_object() {
1231            output = res;
1232        }
1233        Ok(output)
1234    }
1235
1236    /// v1 event delivery (plugin/index.ts:255-259): per-plugin
1237    /// `hooks["event"]({event})`. Returns host delivery count.
1238    pub async fn emit_event(&mut self, event: Value) -> Result<Value> {
1239        self.request("event", json!({"event": event})).await
1240    }
1241
1242    /// v2 domain-hook dispatch (Phase 3): v2 hooks mutate the event object in
1243    /// place (like v1's output), so this returns `{output, matched}`. `matched`
1244    /// = 0 means no v2 plugin installed this hook (caller skips mutation).
1245    pub async fn trigger_v2(&mut self, domain: &str, name: &str, input: Value) -> Result<Value> {
1246        self.request(
1247            "trigger_v2",
1248            json!({"domain": domain, "name": name, "input": input}),
1249        )
1250        .await
1251    }
1252
1253    /// v2 RPC dispatch (Phase 3): `{rpcID, method, input}` →
1254    /// `{output}` (success) or `{error:{type,message}}` (unavailable /
1255    /// method_not_found / handler_error).
1256    pub async fn rpc_call(&mut self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
1257        self.ensure_alive().await?;
1258        self.handle().rpc_call(rpc_id, method, input).await
1259    }
1260
1261    /// v2 plugin inventory (real — id/dialect per loaded v2 plugin + the
1262    /// registered RPC ids). Powers `/api/plugin` without fabricating a list.
1263    pub async fn v2_inventory(&mut self) -> Result<Value> {
1264        self.ensure_alive().await?;
1265        self.handle().v2_inventory().await
1266    }
1267
1268    /// Run every registered v2 `command.transform` / `skill.transform` over
1269    /// `commands` and return the edited list.
1270    ///
1271    /// PULLED by the caller on config reload (never pushed by the plugin), so
1272    /// a payload can only ever serve a list this call actually returned — the
1273    /// property that kills the push-race where a stale list is served after a
1274    /// reconcile that never asked. Upstream semantics mirrored from
1275    /// `State.create` (core/state.ts:172-194): transforms start from the
1276    /// pristine list each call and a throwing transform is reported, not fatal.
1277    ///
1278    /// Returns `(commands, failures)`; a sidecar error propagates so the
1279    /// caller can fall back to the untransformed list rather than serve an
1280    /// empty command surface.
1281    pub async fn transform_commands(
1282        &mut self,
1283        commands: Vec<Value>,
1284    ) -> Result<(Vec<Value>, Vec<Value>)> {
1285        self.ensure_alive().await?;
1286        self.handle().transform_commands(commands).await
1287    }
1288
1289    pub async fn config(&mut self, cfg: Value) -> Result<Value> {
1290        self.request("config", json!({"config": cfg})).await
1291    }
1292
1293    pub fn statuses(&self) -> Value {
1294        let mut out = serde_json::Map::new();
1295        for (spec, v) in self.inner.statuses.lock().iter() {
1296            out.insert(spec.clone(), v.clone());
1297        }
1298        Value::Object(out)
1299    }
1300
1301    pub async fn shutdown(&mut self) {
1302        let _ = self.request("dispose", json!({})).await;
1303        let _ = self.child.start_kill();
1304    }
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309    use super::*;
1310
1311    #[test]
1312    fn strip_version_cases() {
1313        assert_eq!(strip_version("context-mode"), "context-mode");
1314        assert_eq!(strip_version("context-mode@latest"), "context-mode");
1315        assert_eq!(
1316            strip_version("@cortexkit/opencode-magic-context@latest"),
1317            "@cortexkit/opencode-magic-context"
1318        );
1319        assert_eq!(
1320            strip_version("@iam-brain/opencode-codex-auth@latest"),
1321            "@iam-brain/opencode-codex-auth"
1322        );
1323    }
1324
1325    #[test]
1326    fn entry_from_package_shapes() {
1327        let dir = tempfile::tempdir().unwrap();
1328        // exports["."] string
1329        std::fs::write(
1330            dir.path().join("package.json"),
1331            r#"{"exports": {".": "./dist/index.js"}}"#,
1332        )
1333        .unwrap();
1334        std::fs::create_dir(dir.path().join("dist")).unwrap();
1335        std::fs::write(dir.path().join("dist/index.js"), "//").unwrap();
1336        let e = entry_from_package(&dir.path().join("package.json"), dir.path(), "x")
1337            .expect("exports dot");
1338        assert!(e.ends_with("dist/index.js"));
1339        // main fallback
1340        std::fs::write(
1341            dir.path().join("package.json"),
1342            r#"{"main": "./lib/main.js"}"#,
1343        )
1344        .unwrap();
1345        std::fs::create_dir(dir.path().join("lib")).unwrap();
1346        std::fs::write(dir.path().join("lib/main.js"), "//").unwrap();
1347        let e =
1348            entry_from_package(&dir.path().join("package.json"), dir.path(), "x").expect("main");
1349        assert!(e.ends_with("lib/main.js"));
1350    }
1351
1352    #[test]
1353    fn resolve_entry_accepts_file_urls_and_directories() {
1354        let dir = tempfile::tempdir().unwrap();
1355        // file:// URL (what launchers inject via OPENCODE_CONFIG_CONTENT)
1356        let file = dir.path().join("bridge.mjs");
1357        std::fs::write(&file, "//").unwrap();
1358        let url = format!("file://{}", file.display());
1359        assert_eq!(resolve_entry(&url, dir.path()).unwrap(), file);
1360        // percent-encoded URL (a temp path with a space must still resolve)
1361        let spaced = dir.path().join("bridge copy.mjs");
1362        std::fs::write(&spaced, "//").unwrap();
1363        let encoded = format!("file://{}", spaced.display()).replace(' ', "%20");
1364        assert_eq!(resolve_entry(&encoded, dir.path()).unwrap(), spaced);
1365        // directory with a v2-style package manifest: the `./server` export is
1366        // the entry, even when no conventional index file exists (upstream
1367        // resolvePathPluginTarget reads exports["./server"], then main).
1368        let pkg = dir.path().join("managed-bridge");
1369        std::fs::create_dir_all(pkg.join("dist")).unwrap();
1370        std::fs::write(
1371            pkg.join("package.json"),
1372            r#"{"name":"paseo-managed-bridge","type":"module","exports":{"./server":"./dist/main.mjs"}}"#,
1373        )
1374        .unwrap();
1375        std::fs::write(pkg.join("dist/main.mjs"), "//").unwrap();
1376        assert_eq!(
1377            resolve_entry(pkg.to_str().unwrap(), dir.path()).unwrap(),
1378            pkg.join("dist/main.mjs")
1379        );
1380        // no package.json exports → conventional index.ts (upstream order)
1381        let plain = dir.path().join("plain");
1382        std::fs::create_dir_all(&plain).unwrap();
1383        std::fs::write(plain.join("index.ts"), "//").unwrap();
1384        assert_eq!(
1385            resolve_entry(plain.to_str().unwrap(), dir.path()).unwrap(),
1386            plain.join("index.ts")
1387        );
1388        // directory without any entrypoint is a named error, never a dir import
1389        let empty = dir.path().join("empty");
1390        std::fs::create_dir_all(&empty).unwrap();
1391        let err = resolve_entry(empty.to_str().unwrap(), dir.path()).unwrap_err();
1392        assert!(err.to_string().contains("no entrypoint"), "{err}");
1393    }
1394
1395    #[test]
1396    fn resolve_entry_negative_control_still_rejects_unknown_packages() {
1397        let dir = tempfile::tempdir().unwrap();
1398        let err = resolve_entry("no-such-plugin-package", dir.path()).unwrap_err();
1399        assert!(err.to_string().contains("plugin target not found"), "{err}");
1400    }
1401
1402    #[test]
1403    fn discover_plugin_specs_matches_upstream_layout() {
1404        let dir = tempfile::tempdir().unwrap();
1405        std::fs::create_dir_all(dir.path().join("plugin")).unwrap();
1406        std::fs::create_dir_all(dir.path().join("plugins/managed-bridge")).unwrap();
1407        std::fs::write(dir.path().join("plugin/a.js"), "//").unwrap();
1408        std::fs::write(dir.path().join("plugin/b.mjs"), "//").unwrap(); // upstream: not discovered
1409        std::fs::write(dir.path().join("plugins/readme.txt"), "x").unwrap();
1410        let got = discover_plugin_specs(dir.path());
1411        assert!(
1412            got.iter().any(|s| s.ends_with("/plugin/a.js")),
1413            "a .js source file is discovered: {got:?}"
1414        );
1415        assert!(
1416            got.iter().any(|s| s.ends_with("/plugins/managed-bridge")),
1417            "a package DIRECTORY is discovered: {got:?}"
1418        );
1419        assert!(
1420            !got.iter().any(|s| s.ends_with("b.mjs")),
1421            "upstream does not discover .mjs by glob: {got:?}"
1422        );
1423        assert!(!got.iter().any(|s| s.ends_with("readme.txt")));
1424        // Another volume of entries must not panic or duplicate; the cap is
1425        // enforced by construction (bounded scan).
1426        assert_eq!(got.len(), 2, "{got:?}");
1427    }
1428
1429    /// v2 tools: `ctx.tool.transform(editor => editor.add(...))` must actually
1430    /// install the tool (Paseo's bridge depends on it), advertise its JSON
1431    /// Schema, and dispatch `execute(input, {sessionID})`.
1432    #[tokio::test]
1433    async fn v2_tool_transform_registers_and_executes() -> anyhow::Result<()> {
1434        if !runtime_available() {
1435            panic!(
1436                "plugin-runtime binary ({}) required for plugin-host tests",
1437                crate::plugin_runtime().program()
1438            );
1439        }
1440        let dir = tempfile::tempdir().unwrap();
1441        std::fs::write(
1442            dir.path().join("tools.mjs"),
1443            r#"export default {
1444  id: "toolshop",
1445  setup: async (ctx) => {
1446    await ctx.tool.transform((editor) => {
1447      editor.add({
1448        name: "echo",
1449        description: "echo the input",
1450        input: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
1451        async execute(input, call) {
1452          return {
1453            content: [{ type: "text", text: `hi ${input.text} ${call.sessionID}` }],
1454            metadata: { tag: "v2" },
1455          };
1456        },
1457      });
1458    });
1459  },
1460};"#,
1461        )
1462        .unwrap();
1463        let host = materialize_host(&dir.path().join("host"))?;
1464        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1465        sc.load(
1466            "toolshop",
1467            &dir.path().join("tools.mjs"),
1468            &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1469            &json!({}),
1470        )
1471        .await?;
1472        assert!(sc.handle().has_tools(), "load must report has_tools");
1473        let tools = sc.handle().tools().await?;
1474        let tool = tools
1475            .iter()
1476            .find(|t| t["name"] == "echo")
1477            .expect("v2 tool advertised");
1478        assert_eq!(tool["parameters"]["properties"]["text"]["type"], "string");
1479        let res = sc
1480            .handle()
1481            .execute_tool("echo", json!({"text": "x"}), json!({"sessionID": "s1"}))
1482            .await?;
1483        assert_eq!(res["ok"], true, "{res}");
1484        assert_eq!(res["output"], "hi x s1", "{res}");
1485        assert_eq!(res["metadata"]["tag"], "v2", "{res}");
1486        // Negative control: an unregistered name still fails honestly.
1487        let missing = sc
1488            .handle()
1489            .execute_tool("nope", json!({}), json!({}))
1490            .await?;
1491        assert_eq!(missing["ok"], false, "{missing}");
1492        sc.shutdown().await;
1493        Ok(())
1494    }
1495
1496    /// The Paseo sequencing: tools are added AFTER load, from an RPC handler
1497    /// (`rpc.bind` → `tool.transform`). A load-time tool count must not gate
1498    /// `tools()` — this test goes red under that gate.
1499    #[tokio::test]
1500    async fn v2_tool_added_after_load_is_advertised() -> anyhow::Result<()> {
1501        if !runtime_available() {
1502            panic!(
1503                "plugin-runtime binary ({}) required for plugin-host tests",
1504                crate::plugin_runtime().program()
1505            );
1506        }
1507        let dir = tempfile::tempdir().unwrap();
1508        std::fs::write(
1509            dir.path().join("late.mjs"),
1510            r#"export default {
1511  id: "late",
1512  setup: async (ctx) => {
1513    await ctx.rpc.register(
1514      { id: "late.rpc", methods: { add: { input: {}, output: {} } }, events: {} },
1515      {
1516        add: async () => {
1517          await ctx.tool.transform((editor) => {
1518            editor.add({
1519              name: "late_tool",
1520              description: "added by rpc",
1521              input: { type: "object", properties: {} },
1522              async execute() { return { content: [{ type: "text", text: "late-ok" }] }; },
1523            });
1524          });
1525          return {};
1526        },
1527      },
1528    );
1529  },
1530};"#,
1531        )
1532        .unwrap();
1533        let host = materialize_host(&dir.path().join("host"))?;
1534        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1535        let hooks = sc
1536            .load(
1537                "late",
1538                &dir.path().join("late.mjs"),
1539                &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1540                &json!({}),
1541            )
1542            .await?;
1543        assert!(hooks.is_empty(), "no hooks at load: {hooks:?}");
1544        assert!(
1545            sc.handle().tools().await?.is_empty(),
1546            "no tools before bind"
1547        );
1548        let out = sc.rpc_call("late.rpc", "add", json!({})).await?;
1549        assert!(out.get("output").is_some(), "{out}");
1550        let tools = sc.handle().tools().await?;
1551        assert!(
1552            tools.iter().any(|t| t["name"] == "late_tool"),
1553            "tool added after load must be advertised: {tools:?}"
1554        );
1555        sc.shutdown().await;
1556        Ok(())
1557    }
1558
1559    #[tokio::test]
1560    async fn sidecar_load_trigger_roundtrip() -> anyhow::Result<()> {
1561        if !runtime_available() {
1562            panic!(
1563                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1564                crate::plugin_runtime().program()
1565            );
1566        }
1567        let dir = tempfile::tempdir().unwrap();
1568        // synthetic v1 plugin: PluginModule.server factory + mutating hook
1569        std::fs::write(
1570            dir.path().join("plug.mjs"),
1571            r#"
1572export const PluginModule = {
1573  id: "synthetic",
1574  server: async () => ({
1575    "tool.execute.after": async (input, output) => { output.seen = input.tool; },
1576    "chat.message": async (input, output) => { output.touched = true; },
1577    "event": async (payload) => {
1578      if (!payload.event || !payload.event.type) throw new Error("bad event shape");
1579      if (payload.event.type === "boom.type") throw new Error("event boom");
1580    },
1581  }),
1582};
1583export default PluginModule.server;
1584"#,
1585        )
1586        .unwrap();
1587        let host = materialize_host(&dir.path().join("host"))?;
1588        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work")
1589            .await
1590            .expect("spawn node");
1591        let ping = sc.request("ping", json!({})).await.expect("ping");
1592        assert_eq!(ping, "pong");
1593
1594        let input =
1595            json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
1596        let hooks = sc
1597            .load(
1598                "synthetic",
1599                &dir.path().join("plug.mjs"),
1600                &input,
1601                &Value::Null,
1602            )
1603            .await
1604            .expect("load");
1605        assert_eq!(
1606            hooks,
1607            vec![
1608                "tool.execute.after".to_string(),
1609                "chat.message".to_string(),
1610                "event".to_string()
1611            ],
1612            "hook names registered in declaration order"
1613        );
1614
1615        // trigger mutates output in place (v1 semantics)
1616        let out = sc
1617            .trigger(
1618                "tool.execute.after",
1619                json!({"tool": "write", "args": {"filePath": "/x"}}),
1620                json!({}),
1621            )
1622            .await
1623            .expect("trigger");
1624        assert_eq!(
1625            out["seen"], "write",
1626            "hook observed input and mutated output"
1627        );
1628        // unregistered hook name → output unchanged
1629        let out2 = sc
1630            .trigger("permission.ask", json!({}), json!({"keep": 1}))
1631            .await
1632            .expect("trigger2");
1633        assert_eq!(out2["keep"], 1);
1634
1635        // v1 event delivery (plugin/index.ts:255-259): hooks["event"]
1636        // receives {event:{id,type,properties}}; shape-asserting fixture
1637        // only succeeds if the wrapper is exact (delivered counts non-
1638        // throwing hooks), and a throwing event hook fails open.
1639        let ev = sc
1640            .emit_event(json!({"id": "e1", "type": "session.created", "properties": {}}))
1641            .await
1642            .expect("emit_event");
1643        assert_eq!(ev["delivered"], 1, "event hook must receive exact shape");
1644        let ev2 = sc
1645            .emit_event(json!({"id": "e2", "type": "boom.type", "properties": {}}))
1646            .await
1647            .expect("emit_event fail-open");
1648        assert_eq!(ev2["delivered"], 0, "throwing event hook must not count");
1649
1650        let st = sc.statuses();
1651        assert_eq!(st["synthetic"]["ok"], true);
1652        assert_eq!(st["synthetic"]["hooks"][0], "tool.execute.after");
1653
1654        sc.shutdown().await;
1655        Ok(())
1656    }
1657
1658    #[tokio::test]
1659    async fn sidecar_resolves_bun_pty_library_from_original_package_tree() -> anyhow::Result<()> {
1660        if !runtime_available() {
1661            panic!(
1662                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1663                crate::plugin_runtime().program()
1664            );
1665        }
1666
1667        #[cfg(target_os = "macos")]
1668        let library_name = if cfg!(target_arch = "aarch64") {
1669            "librust_pty_arm64.dylib"
1670        } else {
1671            "librust_pty.dylib"
1672        };
1673        #[cfg(target_os = "linux")]
1674        let library_name = if cfg!(target_arch = "aarch64") {
1675            "librust_pty_arm64.so"
1676        } else {
1677            "librust_pty.so"
1678        };
1679        #[cfg(target_os = "windows")]
1680        let library_name = "rust_pty.dll";
1681        #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
1682        let library_name = "librust_pty.so";
1683
1684        let dir = tempfile::tempdir()?;
1685        let package = dir.path().join("opencode-pty");
1686        let entry = package.join("index.mjs");
1687        let library = package
1688            .join("node_modules/bun-pty/rust-pty/target/release")
1689            .join(library_name);
1690        std::fs::create_dir_all(library.parent().expect("library has parent"))?;
1691        std::fs::write(&library, b"synthetic native library path fixture")?;
1692        let expected = serde_json::to_string(&library.to_string_lossy())?;
1693        std::fs::write(
1694            &entry,
1695            format!(
1696                r#"
1697const expected = {expected};
1698if (process.env.BUN_PTY_LIB !== expected) throw new Error("native library path was not resolved from plugin origin");
1699export const PluginModule = {{
1700  id: "native-asset-probe",
1701  server: async () => ({{ "chat.message": async (_input, output) => {{ output.resolved = true; }} }}),
1702}};
1703export default PluginModule.server;
1704"#
1705            ),
1706        )?;
1707
1708        let host = materialize_host(&dir.path().join("host"))?;
1709        // The sidecar inherits this process's environment; an operator-set
1710        // BUN_PTY_LIB would (correctly) win and mask the origin lookup.
1711        assert!(
1712            std::env::var_os("BUN_PTY_LIB").is_none(),
1713            "unset BUN_PTY_LIB to run this test"
1714        );
1715        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1716        let hooks = sc
1717            .load("opencode-pty", &entry, &json!({}), &Value::Null)
1718            .await?;
1719        assert_eq!(hooks, vec!["chat.message"]);
1720        let output = sc.trigger("chat.message", json!({}), json!({})).await?;
1721        assert_eq!(output["resolved"], true);
1722        sc.shutdown().await;
1723        Ok(())
1724    }
1725
1726    #[tokio::test]
1727    async fn sidecar_respawns_after_death_and_reloads_plugins() -> anyhow::Result<()> {
1728        if !runtime_available() {
1729            panic!(
1730                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1731                crate::plugin_runtime().program()
1732            );
1733        }
1734        let dir = tempfile::tempdir().unwrap();
1735        std::fs::write(
1736            dir.path().join("plug.mjs"),
1737            r#"
1738export const PluginModule = {
1739  id: "reaper",
1740  server: async () => ({
1741    "chat.message": async (_i, output) => { output.alive = true; },
1742  }),
1743};
1744export default PluginModule.server;
1745"#,
1746        )
1747        .unwrap();
1748        let host = materialize_host(&dir.path().join("host"))?;
1749        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1750        sc.load(
1751            "reaper",
1752            &dir.path().join("plug.mjs"),
1753            &json!({}),
1754            &Value::Null,
1755        )
1756        .await
1757        .expect("load");
1758        let pid = sc.child_pid();
1759        // force-kill the child (the live OOM class: sidecar dies, hooks
1760        // silently broken-piped until a respawn guard exists)
1761        std::process::Command::new("kill")
1762            .arg("-9")
1763            .arg(pid.to_string())
1764            .status()
1765            .expect("kill -9");
1766        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1767
1768        // next RPC must respawn + replay loads + deliver the mutation
1769        let out = sc
1770            .trigger("chat.message", json!({"sessionID": "s"}), json!({}))
1771            .await
1772            .expect("trigger after respawn");
1773        assert_eq!(out["alive"], true, "hook must fire after respawn");
1774        assert_ne!(sc.child_pid(), pid, "child process must be replaced");
1775        let st = sc.statuses();
1776        assert_eq!(
1777            st["reaper"]["ok"], true,
1778            "previously loaded plugins must be reloaded"
1779        );
1780        sc.shutdown().await;
1781        Ok(())
1782    }
1783
1784    /// v2 plugin battery (Phase 3): both dialects through the real sidecar.
1785    /// A promise-flavor plugin registers a session hook + an RPC; an
1786    /// effect-flavor plugin (with its own `effect` runtime vendored beside it)
1787    /// registers a tool hook. Asserts detection, dispatch, RPC round-trip, the
1788    /// real inventory, and that unregistered/missing RPCs keep exact errors.
1789    #[tokio::test]
1790    async fn v2_battery_promise_and_effect_dialects() -> anyhow::Result<()> {
1791        if !runtime_available() {
1792            panic!(
1793                "plugin-runtime binary ({}) required for plugin-host tests",
1794                crate::plugin_runtime().program()
1795            );
1796        }
1797        let dir = tempfile::tempdir().unwrap();
1798        std::fs::write(
1799            dir.path().join("p_v2_promise.mjs"),
1800            r#"export default {
1801  id: "v2promise",
1802  setup: async (ctx) => {
1803    await ctx.session.hook("context", (ev) => { ev.promiseTouched = true; });
1804    await ctx.tool.hook("execute.after", (ev) => { ev.result = "mutated-by-promise"; });
1805    await ctx.rpc.register({ id: "sample" }, {
1806      hello: async (input) => ({ echoed: input, from: "promise" }),
1807    });
1808    await ctx.storage.set("k", 41);
1809    if ((await ctx.storage.get("k")) !== 41) throw new Error("storage broke");
1810  },
1811};"#,
1812        )
1813        .unwrap();
1814        let eff = dir
1815            .path()
1816            .join("p_v2_effect")
1817            .join("node_modules")
1818            .join("effect");
1819        std::fs::create_dir_all(eff.join("lib")).unwrap();
1820        std::fs::write(
1821            eff.join("package.json"),
1822            r#"{"name":"effect","version":"3.0.0","type":"module","exports":{".":"./lib/index.js"}}"#,
1823        )
1824        .unwrap();
1825        std::fs::write(
1826            eff.join("lib/index.js"),
1827            "export const Effect = { scoped: (p) => p, runPromise: async (p) => { await p; } };\nexport const Scope = {};\n",
1828        )
1829        .unwrap();
1830        std::fs::write(
1831            dir.path().join("p_v2_effect").join("plug.mjs"),
1832            r#"export default {
1833  id: "v2effect",
1834  effect: (ctx) => (async () => {
1835    await ctx.tool.hook("execute.before", (ev) => { ev.input.before = "effect"; });
1836  })(),
1837};"#,
1838        )
1839        .unwrap();
1840
1841        let host = materialize_host(&dir.path().join("host"))?;
1842        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1843        let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
1844
1845        let h1 = sc
1846            .load(
1847                "v2promise",
1848                &dir.path().join("p_v2_promise.mjs"),
1849                &input,
1850                &Value::Null,
1851            )
1852            .await?;
1853        assert!(
1854            h1.contains(&"session.context".to_string()),
1855            "promise hooks: {h1:?}"
1856        );
1857        assert!(h1.contains(&"tool.execute.after".to_string()));
1858        let h2 = sc
1859            .load(
1860                "v2effect",
1861                &dir.path().join("p_v2_effect").join("plug.mjs"),
1862                &input,
1863                &Value::Null,
1864            )
1865            .await?;
1866        assert!(
1867            h2.contains(&"tool.execute.before".to_string()),
1868            "effect hooks: {h2:?}"
1869        );
1870
1871        let out = sc.trigger_v2("session", "context", json!({})).await?;
1872        assert_eq!(out["matched"], 1);
1873        assert_eq!(out["output"]["promiseTouched"], true);
1874        let after = sc
1875            .trigger_v2(
1876                "tool",
1877                "execute.after",
1878                json!({"tool": "read", "result": "orig"}),
1879            )
1880            .await?;
1881        assert_eq!(after["output"]["result"], "mutated-by-promise");
1882        let before = sc
1883            .trigger_v2(
1884                "tool",
1885                "execute.before",
1886                json!({"tool": "read", "input": {}}),
1887            )
1888            .await?;
1889        assert_eq!(before["output"]["input"]["before"], "effect");
1890
1891        let rpc = sc.rpc_call("sample", "hello", json!({"n": 7})).await?;
1892        assert_eq!(rpc["output"]["echoed"]["n"], 7);
1893        let miss = sc.rpc_call("sample", "nope", json!({})).await?;
1894        assert_eq!(miss["error"]["type"], "rpc.method_not_found");
1895        let unreg = sc.rpc_call("ghost", "hello", json!({})).await?;
1896        assert_eq!(unreg["error"]["type"], "rpc.unavailable");
1897
1898        let inv = sc.v2_inventory().await?;
1899        assert_eq!(inv["plugins"].as_array().unwrap().len(), 2, "{inv}");
1900        assert!(
1901            inv["rpcs"]
1902                .as_array()
1903                .unwrap()
1904                .iter()
1905                .any(|r| r == "sample")
1906        );
1907
1908        sc.shutdown().await;
1909        Ok(())
1910    }
1911
1912    /// Every hook upstream declares must be REGISTRABLE. Registering
1913    /// `experimental.ws.handshake` used to throw `unknown session hook`, which
1914    /// failed the plugin's whole setup and discarded the hooks ocserve does
1915    /// dispatch (found 2026-10-23 by diffing bench/v2/hooks.json against the
1916    /// shim table).
1917    #[tokio::test]
1918    async fn v2_accepts_every_declared_hook_at_registration() -> anyhow::Result<()> {
1919        if !runtime_available() {
1920            panic!(
1921                "plugin-runtime binary ({}) required for plugin-host tests",
1922                crate::plugin_runtime().program()
1923            );
1924        }
1925        let dir = tempfile::tempdir().unwrap();
1926        // One plugin registers every hook the extracted surface declares.
1927        let surface: serde_json::Value =
1928            serde_json::from_str(include_str!("../tests/fixtures/v2-hooks.json"))?;
1929        let mut body =
1930            String::from("export default {\n  id: \"v2allhooks\",\n  setup: async (ctx) => {\n");
1931        for (domain, hooks) in surface.as_object().unwrap() {
1932            for hook in hooks.as_array().unwrap() {
1933                let hook = hook.as_str().unwrap();
1934                body.push_str(&format!(
1935                    "    await ctx.{domain}.hook(\"{hook}\", () => {{}});\n"
1936                ));
1937            }
1938        }
1939        body.push_str("    await ctx.event.subscribe(() => {});\n  },\n};\n");
1940        std::fs::write(dir.path().join("all_hooks.mjs"), body).unwrap();
1941        let host = materialize_host(&dir.path().join("host"))?;
1942        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1943        let h = sc
1944            .load(
1945                "v2allhooks",
1946                &dir.path().join("all_hooks.mjs"),
1947                &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1948                &Value::Null,
1949            )
1950            .await
1951            .expect("every declared hook must register without failing setup");
1952        for d in ["session", "tool", "permission", "shell"] {
1953            assert!(
1954                h.iter().any(|x| x == d || x.starts_with(&format!("{d}."))),
1955                "no {d} hook registered: {h:?}"
1956            );
1957        }
1958        sc.shutdown().await;
1959        Ok(())
1960    }
1961
1962    /// A v2 plugin that registers a transform on an UNBRIDGED domain must still
1963    /// load, and the divergence must be reported.
1964    ///
1965    /// The corpus run on 2026-10-21 found four real plugins failing to load with
1966    /// `D-V2-DOMAIN: ctx.<domain>.transform is not bridged`. They were not
1967    /// broken plugins: they register transforms during `setup`, which is
1968    /// upstream's only way to contribute to those domains, and our shim threw on
1969    /// the registration call. That failed the WHOLE plugin, discarding the hooks
1970    /// we do bridge — `session.context`, `tool.execute.before`, events. A
1971    /// divergence must degrade one capability, never the plugin.
1972    ///
1973    /// The transform is accepted and recorded, never invoked (calling it would
1974    /// mean applying an edit ocserve cannot apply), and the domain is reported in
1975    /// the inventory so the operator can see it.
1976    #[tokio::test]
1977    async fn v2_unbridged_transform_registers_instead_of_failing_setup() -> anyhow::Result<()> {
1978        if !runtime_available() {
1979            panic!(
1980                "plugin-runtime binary ({}) required for plugin-host tests",
1981                crate::plugin_runtime().program()
1982            );
1983        }
1984        let dir = tempfile::tempdir().unwrap();
1985        std::fs::write(
1986            dir.path().join("p_v2_edit.mjs"),
1987            r#"export default {
1988  id: "v2edit",
1989  setup: async (ctx) => {
1990    // A transform on a domain ocserve does not bridge (upstream's registration
1991    // form, so this is what real plugins do).
1992    await ctx.tool.transform((editor) => { editor.remove("bash"); });
1993    await ctx.integration.transform(() => {});
1994    // The common transform -> reload -> list sequence: reload must resolve.
1995    await ctx.provider.reload();
1996    // The hooks we DO bridge must survive.
1997    await ctx.session.hook("context", (ev) => { ev.survived = true; });
1998  },
1999};"#,
2000        )
2001        .unwrap();
2002
2003        let host = materialize_host(&dir.path().join("host"))?;
2004        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2005        let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
2006
2007        let hooks = sc
2008            .load(
2009                "v2edit",
2010                &dir.path().join("p_v2_edit.mjs"),
2011                &input,
2012                &Value::Null,
2013            )
2014            .await
2015            .expect("a transform on an unbridged domain must not fail setup");
2016
2017        // The bridged hook registered by the same plugin still works.
2018        assert!(
2019            hooks.contains(&"session.context".to_string()),
2020            "the bridged hook must survive: {hooks:?}"
2021        );
2022        let out = sc.trigger_v2("session", "context", json!({})).await?;
2023        assert_eq!(out["matched"], 1);
2024        assert_eq!(out["output"]["survived"], true);
2025
2026        // And the still-unbridged domains are reported, not silently swallowed.
2027        // `tool` is NOT here any more: its transform runs against a live editor
2028        // (see v2_tool_transform_registers_and_executes).
2029        let inv = sc.v2_inventory().await?;
2030        let unbridged: Vec<String> = inv["unbridged_transforms"]
2031            .as_array()
2032            .expect("inventory must list unbridged transforms")
2033            .iter()
2034            .map(|v| v.as_str().unwrap_or_default().to_string())
2035            .collect();
2036        assert!(!unbridged.contains(&"tool".to_string()), "{inv}");
2037        assert!(unbridged.contains(&"integration".to_string()), "{inv}");
2038
2039        // Genuine USE of an unbridged domain still throws its named divergence
2040        // (the capability really is absent; only registration is tolerated).
2041        std::fs::write(
2042            dir.path().join("p_v2_use.mjs"),
2043            r#"export default {
2044  id: "v2use",
2045  setup: async (ctx) => { await ctx.vcs.apply({}); },
2046};"#,
2047        )
2048        .unwrap();
2049        let err = sc
2050            .load(
2051                "v2use",
2052                &dir.path().join("p_v2_use.mjs"),
2053                &input,
2054                &Value::Null,
2055            )
2056            .await
2057            .expect_err("using an unbridged domain must still fail loudly");
2058        let text = format!("{err:#}");
2059        assert!(text.contains("D-V2-DOMAIN"), "{text}");
2060        assert!(text.contains("vcs"), "{text}");
2061
2062        sc.shutdown().await;
2063        Ok(())
2064    }
2065
2066    /// The v2 REST half of a domain is bound to the route that actually exists —
2067    /// and an UNBOUND verb keeps the named divergence instead of a bare TypeError.
2068    ///
2069    /// The 2026-10-18 finding: `session: { ...registrar("session") }` gave
2070    /// `ctx.session` only `hook`, so `ctx.session.get(id)` was
2071    /// `TypeError: ... is not a function` — a crash, not the honest throw the rest
2072    /// of the shim uses. `ctx.plugin.list()` likewise returned `[]` while
2073    /// `/api/plugin` serves the real inventory (D-PLUGIN-INVENTORY was closed).
2074    #[tokio::test]
2075    async fn v2_domain_rest_methods_bind_real_routes() -> anyhow::Result<()> {
2076        if !runtime_available() {
2077            panic!(
2078                "plugin-runtime binary ({}) required for plugin-host tests",
2079                crate::plugin_runtime().program()
2080            );
2081        }
2082        // A real HTTP responder so ctx.session.get() exercises an actual route
2083        // (stdlib thread; the shim fetches it like any other client would).
2084        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2085        let port = listener.local_addr().unwrap().port();
2086        std::thread::spawn(move || {
2087            for stream in listener.incoming() {
2088                let Ok(mut s) = stream else { continue };
2089                use std::io::{Read, Write};
2090                let mut buf = [0u8; 2048];
2091                let _ = s.read(&mut buf);
2092                let body = br#"{"id":"ses_bound","title":"bound-route"}"#;
2093                let _ = s.write_all(
2094                format!(
2095                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
2096                    body.len()
2097                )
2098                .as_bytes(),
2099            );
2100                let _ = s.write_all(body);
2101            }
2102        });
2103
2104        let dir = tempfile::tempdir().unwrap();
2105        // The fixture reports each probe's outcome back over RPC so the test can
2106        // read real results (not shim internals).
2107        std::fs::write(
2108            dir.path().join("rest.mjs"),
2109            r#"export default {
2110  id: "restprobe",
2111  setup: async (ctx) => {
2112    const results = {};
2113    // plugin.list must return the REAL inventory, not [].
2114    results.pluginList = await ctx.plugin.list();
2115    // session.get must reach the bound route.
2116    try {
2117      const s = await ctx.session.get("ses_bound");
2118      results.sessionGet = { ok: true, id: s && s.id };
2119    } catch (e) { results.sessionGet = { ok: false, err: String(e && e.message || e) }; }
2120    // An UNBOUND verb must throw the NAMED divergence, not a TypeError.
2121    try { await ctx.session.notARealVerb("x"); results.unbound = { threw: false }; }
2122    catch (e) { results.unbound = { threw: true, msg: String(e && e.message || e) }; }
2123    await ctx.rpc.register({ id: "probe" }, { results: async () => results });
2124  },
2125};"#,
2126        )
2127        .unwrap();
2128
2129        let host = materialize_host(&dir.path().join("host"))?;
2130        let mut sc = Sidecar::spawn(&host, &format!("http://127.0.0.1:{port}"), "/work").await?;
2131        let input = json!({"directory": "/work", "serverUrl": format!("http://127.0.0.1:{port}")});
2132        sc.load(
2133            "restprobe",
2134            &dir.path().join("rest.mjs"),
2135            &input,
2136            &Value::Null,
2137        )
2138        .await?;
2139
2140        let r = sc.rpc_call("probe", "results", json!({})).await?;
2141        let out = &r["output"];
2142
2143        // 1. plugin.list is real (contains our own id), not empty.
2144        let listed = out["pluginList"].as_array().cloned().unwrap_or_default();
2145        assert!(
2146            listed.iter().any(|p| p["id"] == "restprobe"),
2147            "ctx.plugin.list() must report the loaded plugin: {out}"
2148        );
2149
2150        // 2. session.get hit the bound route (the stub answered ses_bound).
2151        assert_eq!(
2152            out["sessionGet"]["ok"], true,
2153            "ctx.session.get must reach /api/session/{{id}}: {out}"
2154        );
2155        assert_eq!(out["sessionGet"]["id"], "ses_bound");
2156
2157        // 3. an unbound verb throws the NAMED divergence (D-V2-DOMAIN), not a
2158        //    TypeError and not silently succeeding.
2159        assert_eq!(
2160            out["unbound"]["threw"], true,
2161            "unbound verb must throw: {out}"
2162        );
2163        let msg = out["unbound"]["msg"].as_str().unwrap_or_default();
2164        assert!(
2165            msg.contains("D-V2-DOMAIN"),
2166            "unbound verb must name the divergence (D-V2-DOMAIN), got: {msg}"
2167        );
2168
2169        sc.shutdown().await;
2170        Ok(())
2171    }
2172
2173    /// A v2 plugin's `command.transform` / `skill.transform` edits are PULLED by
2174    /// Rust and come back as the list both consumers serve.
2175    ///
2176    /// The all-consumers rule (TESTING §1): `skill_entries()` filters
2177    /// `Payloads.command` on `source=="skill"`, so a skill transform must change
2178    /// the SYSTEM PROMPT the model reads, not just the `/command` route. A test
2179    /// that only asserted the RPC round-trip would pass while the prompt kept the
2180    /// old text — shape without mutation.
2181    ///
2182    /// Also covers: add REPLACES a same-named entry (upstream `editor.set`,
2183    /// core/command.ts:61, so a reload is idempotent), and a THROWING transform is
2184    /// reported without taking the list down.
2185    #[tokio::test]
2186    async fn v2_command_transform_pulls_into_the_served_list() -> anyhow::Result<()> {
2187        if !runtime_available() {
2188            panic!(
2189                "plugin-runtime binary ({}) required for plugin-host tests",
2190                crate::plugin_runtime().program()
2191            );
2192        }
2193        let dir = tempfile::tempdir().unwrap();
2194        std::fs::write(
2195            dir.path().join("tx.mjs"),
2196            r#"export default {
2197  id: "tx",
2198  setup: async (ctx) => {
2199    // upstream shape: ctx.command.transform((editor) => editor.add({...}))
2200    await ctx.command.transform((editor) => {
2201      editor.add({ name: "plugin-cmd", description: "added by plugin" });
2202    });
2203    await ctx.skill.transform((editor) => {
2204      editor.update("demo-skill", (s) => { s.description = "rewritten by plugin"; });
2205      editor.add({ name: "plugin-skill", description: "skill from plugin", source: "skill" });
2206    });
2207    await ctx.command.reload();
2208    const listed = await ctx.command.list();
2209    await ctx.rpc.register({ id: "probe" }, {
2210      afterSetup: async () => ({ listed }),
2211    });
2212  },
2213};"#,
2214        )
2215        .unwrap();
2216
2217        let host = materialize_host(&dir.path().join("host"))?;
2218        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
2219        let input = json!({"directory": "/work"});
2220        sc.load("tx", &dir.path().join("tx.mjs"), &input, &Value::Null)
2221            .await?;
2222
2223        // The pristine list: one skill (what ocserve's own config produced) and
2224        // one config command. Skills and commands share ONE vector.
2225        let pristine = vec![
2226            json!({"name": "demo-skill", "description": "original", "source": "skill"}),
2227            json!({"name": "review", "description": "config command", "source": "config"}),
2228        ];
2229        let (edited, failures) = sc.transform_commands(pristine.clone()).await?;
2230
2231        assert!(
2232            failures.is_empty(),
2233            "no transform should have failed: {failures:?}"
2234        );
2235        // 1. the command transform's add landed
2236        let added = edited
2237            .iter()
2238            .find(|c| c["name"] == "plugin-cmd")
2239            .expect("plugin command must be present");
2240        assert_eq!(added["description"], "added by plugin");
2241        // 2. the skill transform's update landed — THIS is the prompt-visible half
2242        let skill = edited
2243            .iter()
2244            .find(|c| c["name"] == "demo-skill")
2245            .expect("demo-skill must still be present");
2246        assert_eq!(
2247            skill["description"], "rewritten by plugin",
2248            "skill.transform must reach the vector skill_entries() reads"
2249        );
2250        // 3. the skill add landed with the skill source (so skill_entries picks it up)
2251        assert!(
2252            edited
2253                .iter()
2254                .any(|c| c["name"] == "plugin-skill" && c["source"] == "skill"),
2255            "plugin skill must carry source=skill or skill_entries() drops it: {edited:?}"
2256        );
2257        // 4. untouched entries survive (the all-consumers rule cuts both ways)
2258        assert!(edited.iter().any(|c| c["name"] == "review"));
2259
2260        // 5. IDEMPOTENT: a second pull from pristine yields the same list (add
2261        //    replaces, never accumulates).
2262        let (again, _) = sc.transform_commands(pristine.clone()).await?;
2263        assert_eq!(
2264            serde_json::to_value(&again).unwrap(),
2265            serde_json::to_value(&edited).unwrap(),
2266            "a reload must not accumulate duplicates"
2267        );
2268
2269        // 6. a pull over a one-entry list keeps that entry (the plugin's own adds are
2270        //    additive; the caller must never receive a shorter list than it sent)
2271        let (kept, _) = sc
2272            .transform_commands(vec![json!({"name": "keepme"})])
2273            .await?;
2274        assert!(kept.iter().any(|c| c["name"] == "keepme"));
2275
2276        sc.shutdown().await;
2277        Ok(())
2278    }
2279
2280    /// A throwing v2 transform is reported, never fatal — upstream's state machine
2281    /// disables a failing transform (core/state.ts:178-184) rather than
2282    /// propagating, because a broken third-party plugin must not take the server's
2283    /// command surface down with it.
2284    #[tokio::test]
2285    async fn v2_command_transform_failure_keeps_the_list() -> anyhow::Result<()> {
2286        if !runtime_available() {
2287            panic!(
2288                "plugin-runtime binary ({}) required for plugin-host tests",
2289                crate::plugin_runtime().program()
2290            );
2291        }
2292        let dir = tempfile::tempdir().unwrap();
2293        std::fs::write(
2294            dir.path().join("boom.mjs"),
2295            r#"export default {
2296  id: "boom",
2297  setup: async (ctx) => {
2298    await ctx.command.transform(() => { throw new Error("transform exploded"); });
2299    await ctx.command.transform((editor) => { editor.add({ name: "survivor" }); });
2300  },
2301};"#,
2302        )
2303        .unwrap();
2304
2305        let host = materialize_host(&dir.path().join("host"))?;
2306        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
2307        let input = json!({"directory": "/work"});
2308        sc.load("boom", &dir.path().join("boom.mjs"), &input, &Value::Null)
2309            .await?;
2310
2311        let (kept, failures) = sc
2312            .transform_commands(vec![json!({"name": "existing"})])
2313            .await?;
2314        // the good transform still ran (a broken one does not abort the rest)
2315        assert!(
2316            kept.iter().any(|c| c["name"] == "survivor"),
2317            "a throwing transform must not stop the others: {kept:?}"
2318        );
2319        assert!(kept.iter().any(|c| c["name"] == "existing"));
2320        // and the failure is reported so the server can log + count it
2321        assert_eq!(failures.len(), 1, "the throwing transform must be reported");
2322        assert!(
2323            failures[0]["message"]
2324                .as_str()
2325                .unwrap_or_default()
2326                .contains("transform exploded"),
2327            "{failures:?}"
2328        );
2329
2330        sc.shutdown().await;
2331        Ok(())
2332    }
2333
2334    /// The `config` hook is dispatched (v1 parity, plugin/index.ts:244-251).
2335    /// Closes the registered-but-never-called class: a plugin whose `config`
2336    /// is a real hook must see it run (host `config` used to hard-code "ok").
2337    #[tokio::test]
2338    async fn config_hook_is_dispatched() -> anyhow::Result<()> {
2339        if !runtime_available() {
2340            panic!(
2341                "plugin-runtime binary ({}) required for plugin-host tests",
2342                crate::plugin_runtime().program()
2343            );
2344        }
2345        let dir = tempfile::tempdir().unwrap();
2346        std::fs::write(
2347            dir.path().join("cfg.mjs"),
2348            r#"export const PluginModule = {
2349  id: "cfg",
2350  server: async () => ({
2351    config: async (cfg) => {
2352      if (typeof cfg !== "object" || cfg === null) throw new Error("config not object");
2353    },
2354    "chat.message": async () => {},
2355  }),
2356};
2357export default PluginModule.server;"#,
2358        )
2359        .unwrap();
2360        let host = materialize_host(&dir.path().join("host"))?;
2361        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2362        sc.load("cfg", &dir.path().join("cfg.mjs"), &json!({}), &Value::Null)
2363            .await?;
2364        let r = sc.config(json!({"model": "x"})).await?;
2365        assert_eq!(r["matched"], 1, "config hook must be dispatched: {r}");
2366        sc.shutdown().await;
2367        Ok(())
2368    }
2369
2370    /// Test environment gate: the ACTUAL runtime (bun preferred) must exist.
2371    fn runtime_available() -> bool {
2372        crate::which(crate::plugin_runtime().program()).is_some()
2373    }
2374
2375    /// Real-plugin battery (V2-EXECUTION-PLAN Phase 2): every v1 authoring
2376    /// form the frozen client supports (plugin/index.ts readV1Plugin +
2377    /// getLegacyPlugins) plus the `[spec, options]` tuple. Loads all forms
2378    /// through ONE sidecar (as production does) and asserts each registered
2379    /// the expected hook AND that options actually reach the factory (the
2380    /// silently-dropped-tuple bug this battery exists to pin).
2381    #[tokio::test]
2382    async fn battery_all_authoring_forms_and_options() -> anyhow::Result<()> {
2383        if !runtime_available() {
2384            panic!(
2385                "plugin-runtime binary ({}) required for plugin-host tests",
2386                crate::plugin_runtime().program()
2387            );
2388        }
2389        let dir = tempfile::tempdir().unwrap();
2390        // 1. PluginModule.server (v1 canonical)
2391        std::fs::write(
2392            dir.path().join("p_module.mjs"),
2393            r#"export const PluginModule = {
2394  id: "m",
2395  server: async () => ({ "chat.message": async (_i, o) => { o.module = true; } }),
2396};"#,
2397        )
2398        .unwrap();
2399        // 2. default object with .server
2400        std::fs::write(
2401            dir.path().join("p_default_obj.mjs"),
2402            r#"export default { server: async () => ({ "chat.params": async (_i, o) => { o.defaultobj = true; } }) };"#,
2403        )
2404        .unwrap();
2405        // 3. default function (legacy)
2406        std::fs::write(
2407            dir.path().join("p_default_fn.mjs"),
2408            r#"export default async () => ({ "tool.execute.after": async (_i, o) => { o.defaultfn = true; } });"#,
2409        )
2410        .unwrap();
2411        // 4. named plain-function export (each IS a server factory)
2412        std::fs::write(
2413            dir.path().join("p_named.mjs"),
2414            r#"export async function MyPlugin() { return { "event": async () => {} }; }"#,
2415        )
2416        .unwrap();
2417        // 5. options tuple: the factory must SEE the second tuple element.
2418        std::fs::write(
2419            dir.path().join("p_options.mjs"),
2420            r#"export const PluginModule = {
2421  id: "opts",
2422  server: async (_input, options) => ({
2423    "chat.message": async (_i, o) => { o.sawOptions = options; },
2424  }),
2425};"#,
2426        )
2427        .unwrap();
2428
2429        let host = materialize_host(&dir.path().join("host"))?;
2430        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2431        let input =
2432            json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
2433
2434        let h1 = sc
2435            .load("m", &dir.path().join("p_module.mjs"), &input, &Value::Null)
2436            .await?;
2437        assert_eq!(h1, vec!["chat.message"], "PluginModule.server form");
2438        let h2 = sc
2439            .load(
2440                "dobj",
2441                &dir.path().join("p_default_obj.mjs"),
2442                &input,
2443                &Value::Null,
2444            )
2445            .await?;
2446        assert_eq!(h2, vec!["chat.params"], "default object with .server form");
2447        let h3 = sc
2448            .load(
2449                "dfn",
2450                &dir.path().join("p_default_fn.mjs"),
2451                &input,
2452                &Value::Null,
2453            )
2454            .await?;
2455        assert_eq!(
2456            h3,
2457            vec!["tool.execute.after"],
2458            "default function (legacy) form"
2459        );
2460        let h4 = sc
2461            .load(
2462                "named",
2463                &dir.path().join("p_named.mjs"),
2464                &input,
2465                &Value::Null,
2466            )
2467            .await?;
2468        assert_eq!(h4, vec!["event"], "named function export form");
2469
2470        let opts = json!({"token": "abc", "n": 3});
2471        let h5 = sc
2472            .load("opts", &dir.path().join("p_options.mjs"), &input, &opts)
2473            .await?;
2474        assert_eq!(
2475            h5,
2476            vec!["chat.message"],
2477            "options-tuple form registers same hook"
2478        );
2479
2480        // Dispatch across ALL loaded plugins: each form's hook fires.
2481        let out = sc.trigger("chat.message", json!({}), json!({})).await?;
2482        assert_eq!(out["module"], true, "form 1 hook fired");
2483        // options reached the factory (the tuple was NOT dropped)
2484        assert_eq!(out["sawOptions"], opts, "factory saw the tuple options");
2485        let out2 = sc.trigger("chat.params", json!({}), json!({})).await?;
2486        assert_eq!(out2["defaultobj"], true, "form 2 hook fired");
2487        let out3 = sc
2488            .trigger("tool.execute.after", json!({}), json!({}))
2489            .await?;
2490        assert_eq!(out3["defaultfn"], true, "form 3 hook fired");
2491
2492        // statuses carry all five loads (real inventory, not empty).
2493        let st = sc.statuses();
2494        for spec in ["m", "dobj", "dfn", "named", "opts"] {
2495            assert_eq!(st[spec]["ok"], true, "status for {spec}");
2496        }
2497        sc.shutdown().await;
2498        Ok(())
2499    }
2500}
2501
2502#[cfg(test)]
2503mod runtime_selection_tests {
2504    /// `OCSERVE_PLUGIN_RUNTIME` forces the runtime (lab A/B control);
2505    /// unset/unknown → bun-if-present else node. Env is process-local and
2506    /// restored (this file is the only env mutator in its own process).
2507    #[test]
2508    fn runtime_override_and_default_preference() {
2509        let has_bun = crate::which("bun").is_some();
2510        let has_node = crate::which("node").is_some();
2511        if !has_node {
2512            panic!("node required for the fallback leg (test environment gate)");
2513        }
2514
2515        // SAFETY: single-threaded env mutation, restored below.
2516        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "node") };
2517        assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
2518
2519        if has_bun {
2520            unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "bun") };
2521            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Bun);
2522            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2523            assert_eq!(
2524                crate::plugin_runtime(),
2525                crate::PluginRuntime::Bun,
2526                "bun present + no override → bun preferred (upstream fidelity)"
2527            );
2528        } else {
2529            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2530            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
2531        }
2532
2533        // unknown value falls through to preference, never panics
2534        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "deno") };
2535        let _ = crate::plugin_runtime();
2536        unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2537    }
2538}
2539
2540#[cfg(test)]
2541mod oom_wrapper_tests {
2542    /// A3 proof: the spawn wrapper makes the CHILD report adj=500 so a
2543    /// memcg OOM kill takes the child (respawnable) — not the main service.
2544    #[cfg(target_os = "linux")]
2545    #[test]
2546    fn wrapper_raises_child_oom_score_adj() {
2547        let out = std::process::Command::new("sh")
2548            .arg("-c")
2549            .arg(ocserve_store::cgroup::WRAPPER)
2550            .arg("sh")
2551            .arg("cat")
2552            .arg("/proc/self/oom_score_adj")
2553            .output()
2554            .expect("wrapper spawns");
2555        assert!(
2556            out.status.success(),
2557            "wrapper failed: {}",
2558            String::from_utf8_lossy(&out.stderr)
2559        );
2560        assert_eq!(
2561            String::from_utf8_lossy(&out.stdout).trim(),
2562            "500",
2563            "child must run at adj=500"
2564        );
2565    }
2566}
2567
2568#[cfg(test)]
2569mod plugin_tool_schema_tests {
2570    use super::*;
2571
2572    /// A plugin tool's Zod args must become a VALID JSON Schema before it
2573    /// reaches the provider. The first implementation passed the raw Zod
2574    /// objects straight through (`{~standard, def, type}`) and the provider
2575    /// rejected every request in the session with 400 (found live on
2576    /// `ctx_reduce`, 2026-10-23).
2577    #[tokio::test]
2578    async fn plugin_tool_schema_is_valid_json_schema() -> anyhow::Result<()> {
2579        let dir = tempfile::tempdir()?;
2580        let entry = dir.path().join("p_schema.mjs");
2581        std::fs::write(
2582            &entry,
2583            r#"import { z } from "zod";
2584export const hook = async () => ({
2585  tool: {
2586    ztool: {
2587      description: "zod args",
2588      args: {
2589        text: z.string(),
2590        count: z.number(),
2591      },
2592      execute: async () => "ok",
2593    },
2594  },
2595});"#,
2596        )?;
2597        // `z` is resolved from the plugin's own tree, exactly like a real one.
2598        std::fs::create_dir_all(dir.path().join("node_modules/zod"))?;
2599        std::fs::write(
2600            dir.path().join("node_modules/zod/package.json"),
2601            r#"{"name":"zod","version":"4.0.0","main":"./index.cjs","exports":{".":"./index.cjs","./v4":"./index.cjs"}}"#,
2602        )?;
2603        std::fs::write(
2604            dir.path().join("node_modules/zod/index.cjs"),
2605            "exports.object = (shape) => ({ shape }); exports.z = { object: (shape) => ({ shape }), string: () => ({ _zod: 1, type: 'string' }), number: () => ({ _zod: 1, type: 'number' }) }; exports.toJSONSchema = () => ({ type: 'object', properties: { text: { type: 'string' }, count: { type: 'integer' } }, required: ['text'] });",
2606        )?;
2607        let host = materialize_host(&dir.path().join("host"))?;
2608        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2609        sc.load(
2610            "schema-fixture",
2611            &entry,
2612            &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
2613            &Value::Null,
2614        )
2615        .await?;
2616        let tools = sc.handle().tools().await?;
2617        let tool = tools
2618            .iter()
2619            .find(|t| t["name"] == "ztool")
2620            .expect("ztool advertised");
2621        let params = &tool["parameters"];
2622        assert_eq!(params["type"], "object", "{params}");
2623        assert_eq!(params["properties"]["text"]["type"], "string", "{params}");
2624        assert!(
2625            params["properties"]["text"].get("~standard").is_none()
2626                && params["properties"]["text"].get("def").is_none(),
2627            "a raw Zod object must never reach the provider: {params}"
2628        );
2629        sc.shutdown().await;
2630        Ok(())
2631    }
2632}