Skip to main content

nexo_microapp_sdk/
plugin.rs

1//! Phase 81.15.a — Child-side helper for out-of-tree subprocess
2//! plugins. Pairs with `nexo-core`'s `SubprocessNexoPlugin`
3//! host-side adapter (Phase 81.14 + 81.14.b).
4//!
5//! Plugin authors avoid hand-rolling the JSON-RPC parser, manifest
6//! handshake, and broker-publish framing by using
7//! [`PluginAdapter`]:
8//!
9//! ```no_run
10//! # #[cfg(feature = "plugin")] {
11//! use nexo_microapp_sdk::plugin::{PluginAdapter, BrokerSender};
12//! use nexo_broker::Event;
13//!
14//! const MANIFEST: &str = include_str!("../nexo-plugin.toml");
15//!
16//! #[tokio::main]
17//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
18//!     PluginAdapter::new(MANIFEST)?
19//!         .on_broker_event(|topic, event, broker: BrokerSender| async move {
20//!             // Plugin's outbound logic — e.g. send to Slack API,
21//!             // then publish a confirmation event back.
22//!             let ack = Event::new(
23//!                 format!("plugin.inbound.slack"),
24//!                 "slack",
25//!                 serde_json::json!({"echo": event.payload}),
26//!             );
27//!             let _ = broker.publish("plugin.inbound.slack", ack).await;
28//!         })
29//!         .on_shutdown(|| async { Ok(()) })
30//!         .run_stdio()
31//!         .await
32//! }
33//! # }
34//! ```
35//!
36//! # Wire format
37//!
38//! Same JSON-RPC 2.0 newline-delimited shape as the host adapter:
39//! - `initialize` request → `{ manifest, server_version }` reply
40//! - `broker.event { topic, event }` notification → user handler
41//! - User handler may call `BrokerSender::publish` → emits
42//!   `broker.publish` notification on stdout
43//! - `shutdown` request → `{ ok: true }` reply, then loop exits
44//!
45//! # IRROMPIBLE refs
46//!
47//! - Internal: `crates/microapp-sdk/src/runtime.rs:87-264` —
48//!   existing JSON-RPC dispatch loop pattern reused structurally
49//!   (different methods, but same line/parse/dispatch shape).
50//! - Internal: `crates/core/src/agent/nexo_plugin_registry/subprocess.rs`
51//!   — host-side wire spec the SDK must match.
52//! - claude-code-leak `src/utils/computerUse/mcpServer.ts` — MCP
53//!   child-side server pattern (initialize, notifications without
54//!   `id`).
55//! - OpenClaw absence: their channel plugins ran in-process Node,
56//!   no separate child-side SDK.
57
58use std::future::Future;
59use std::pin::Pin;
60use std::sync::atomic::{AtomicU64, Ordering};
61use std::sync::Arc;
62use std::time::Duration;
63
64use dashmap::DashMap;
65use nexo_broker::Event;
66use nexo_llm::types::ChatMessage;
67use nexo_memory::MemoryEntry;
68use nexo_plugin_manifest::PluginManifest;
69use serde::{Deserialize, Serialize};
70use serde_json::{json, Value};
71use tokio::io::{
72    self, AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader,
73};
74use tokio::sync::{mpsc, oneshot, Mutex};
75
76use crate::errors::{Error as SdkError, Result as SdkResult};
77
78/// Boxed future returned by user-supplied handlers. Avoids forcing
79/// downstream authors to import `futures` crate just to type a
80/// closure.
81pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
82
83/// Handler invoked when the daemon delivers a `broker.event`
84/// notification. Receives the topic, the parsed `Event`, and a
85/// [`BrokerSender`] handle so the handler can publish back to the
86/// daemon without holding any global state.
87///
88/// Errors from the handler are intentionally swallowed — same
89/// best-effort contract the host adapter uses for `broker.publish`
90/// forwarding. A handler that wants to surface errors should log
91/// + drop on its own.
92pub trait BrokerEventHandler: Send + Sync + 'static {
93    /// Process one event delivered from the daemon.
94    fn handle(&self, topic: String, event: Event, broker: BrokerSender) -> BoxFuture<'static, ()>;
95}
96
97impl<F, Fut> BrokerEventHandler for F
98where
99    F: Fn(String, Event, BrokerSender) -> Fut + Send + Sync + 'static,
100    Fut: Future<Output = ()> + Send + 'static,
101{
102    fn handle(&self, topic: String, event: Event, broker: BrokerSender) -> BoxFuture<'static, ()> {
103        Box::pin((self)(topic, event, broker))
104    }
105}
106
107/// Handler invoked when the daemon sends `shutdown`. Called BEFORE
108/// the SDK writes the `{ok:true}` reply, so the handler can flush
109/// state. Errors propagate as `PluginInitError::Other` on the host
110/// side via the `shutdown` reply error path.
111pub trait ShutdownHandler: Send + Sync + 'static {
112    /// Hook called once at shutdown; return `Ok(())` for clean
113    /// exit, `Err(_)` to surface a structured error.
114    fn handle(&self) -> BoxFuture<'static, Result<(), String>>;
115}
116
117impl<F, Fut> ShutdownHandler for F
118where
119    F: Fn() -> Fut + Send + Sync + 'static,
120    Fut: Future<Output = Result<(), String>> + Send + 'static,
121{
122    fn handle(&self) -> BoxFuture<'static, Result<(), String>> {
123        Box::pin((self)())
124    }
125}
126
127/// Phase 81.15.c — child-side request-response correlation map.
128/// Each outbound request (memory.recall, llm.complete, ...) is
129/// keyed by an integer id; the dispatch loop's reader looks up
130/// the matching pending entry and resolves it when the host
131/// replies. Reserved ids: 1 = (host→child) initialize, 2 =
132/// (host→child) shutdown — both flow the OPPOSITE direction so
133/// they never collide with the child's outbound id space (which
134/// starts at 100).
135///
136/// 81.15.c.b — pending value type changed from a single oneshot
137/// to an enum [`PendingKind`] so streaming requests
138/// (`complete_llm_stream`) can register both a `mpsc` receiver
139/// for delta chunks AND a final oneshot for the
140/// `LlmCompleteResult` reply.
141type ChildPending = Arc<DashMap<u64, PendingKind>>;
142
143/// Phase 81.15.c.b — variant of pending entry kept alive while a
144/// child request is in flight. The dispatch loop's response
145/// path resolves `Single` / `Streaming.final_tx`; the
146/// notification path pushes chunks into `Streaming.delta_tx`.
147#[doc(hidden)]
148pub enum PendingKind {
149    /// Non-streaming request. The dispatch loop resolves this
150    /// oneshot once the response frame lands.
151    Single(oneshot::Sender<Result<Value, RpcError>>),
152    /// Streaming request. The dispatch loop pushes
153    /// `llm.complete.delta` chunks into `delta_tx` as they
154    /// arrive; the final response frame resolves `final_tx`
155    /// (which then closes the stream from the user's side).
156    Streaming {
157        /// Per-request channel for delta chunks. Unbounded so a
158        /// fast provider doesn't backpressure the dispatch loop;
159        /// the buffer is reclaimed when the consumer drops the
160        /// `LlmStream`.
161        delta_tx: mpsc::UnboundedSender<String>,
162        /// Resolved when the host's final response frame lands.
163        final_tx: oneshot::Sender<Result<LlmCompleteResult, RpcError>>,
164    },
165}
166
167/// Default timeout for child-issued RPC requests. The daemon's
168/// `memory.recall` returns in milliseconds; `llm.complete` can
169/// take seconds for large responses (especially without
170/// streaming). 30 s is comfortably above worst-case for both.
171const DEFAULT_RPC_TIMEOUT: Duration = Duration::from_secs(30);
172
173/// Child id allocator. Starts at 100 to leave headroom below
174/// the host's reserved ids (1 / 2).
175fn next_request_id(counter: &AtomicU64) -> u64 {
176    counter.fetch_add(1, Ordering::Relaxed)
177}
178
179/// Phase 81.15.c — error returned by child-issued RPC requests.
180#[derive(Debug, thiserror::Error)]
181pub enum RpcError {
182    /// Host returned a JSON-RPC error response. `code` is the
183    /// JSON-RPC error code; common values: -32601 method not
184    /// found, -32602 invalid params, -32603 internal error /
185    /// "memory not configured" / "llm not configured".
186    #[error("rpc error {code}: {message}")]
187    Server {
188        /// JSON-RPC error code from the host.
189        code: i32,
190        /// Human-readable error message from the host.
191        message: String,
192    },
193    /// No reply within `DEFAULT_RPC_TIMEOUT` (30 s). The pending
194    /// entry is removed so a late reply is silently dropped
195    /// (with a warn log on the dispatch loop side).
196    #[error("rpc request timed out after {0:?}")]
197    Timeout(Duration),
198    /// stdin writer is closed (host crashed / shutdown raced) or
199    /// the response oneshot was canceled before it was resolved.
200    #[error("rpc transport closed before reply: {0}")]
201    Transport(String),
202    /// Response payload could not be deserialized into the typed
203    /// wrapper's expected shape. Shouldn't fire in well-formed
204    /// host implementations — flagged loud so SDK + host stay
205    /// in sync.
206    #[error("rpc decode error: {0}")]
207    Decode(String),
208}
209
210/// Child-side handle for the daemon-mediated services pipeline.
211///
212/// **Notifications (publish-only):**
213/// - `publish(topic, event)` — emits a `broker.publish`
214///   notification. Host validates the topic against its allowlist.
215///
216/// **Requests (request-response, Phase 81.15.c):**
217/// - `recall_memory(agent_id, query, limit)` —
218///   long-term memory FTS recall.
219/// - `complete_llm(params)` — LLM chat completion (non-streaming
220///   today; streaming via `params.stream = true` ships in
221///   Phase 81.15.c.b SDK).
222///
223/// Cheap to clone (`Arc` internals). Plugin authors typically
224/// receive one inside their `BrokerEventHandler` and clone for
225/// background tasks.
226#[derive(Clone)]
227pub struct BrokerSender {
228    writer: Arc<Mutex<Box<dyn AsyncWrite + Send + Unpin>>>,
229    pending: ChildPending,
230    next_id: Arc<AtomicU64>,
231}
232
233/// Phase 81.15.c — typed params for `complete_llm`. Mirrors the
234/// wire shape in `nexo-plugin-contract.md` §5.2.
235#[derive(Debug, Clone, Default)]
236pub struct LlmCompleteParams {
237    /// Provider name as registered in the operator's `llm.yaml`
238    /// (e.g. `"minimax"`, `"openai"`).
239    pub provider: String,
240    /// Model identifier handed to the provider client.
241    pub model: String,
242    /// Chat messages forming the prompt. Empty rejected
243    /// host-side with `-32602`.
244    pub messages: Vec<ChatMessage>,
245    /// Optional max tokens cap. Defaults host-side to 4096.
246    pub max_tokens: Option<u32>,
247    /// Optional sampling temperature. Defaults host-side to 0.7.
248    pub temperature: Option<f32>,
249    /// Optional system prompt prepended to messages.
250    pub system_prompt: Option<String>,
251}
252
253/// Phase 81.15.c — typed result from `complete_llm`. Mirrors the
254/// host-side `handle_llm_complete` response shape. Local
255/// `TokenCount` shape (instead of `nexo_llm::TokenUsage`) keeps
256/// the SDK independent of any serde-derive quirks upstream.
257#[derive(Debug, Clone, Deserialize, Serialize)]
258pub struct LlmCompleteResult {
259    /// Full assistant text. Empty when streaming is enabled (the
260    /// child reassembled it from `llm.complete.delta`
261    /// notifications) or when the provider returned tool calls
262    /// (which the MVP rejects with -32601).
263    #[serde(default)]
264    pub content: String,
265    /// One of: `stop`, `length`, `tool_use`, `other:<reason>`.
266    pub finish_reason: String,
267    /// Token usage counts the provider reported.
268    pub usage: TokenCount,
269}
270
271/// Phase 81.15.c — token usage count returned in
272/// `LlmCompleteResult.usage`. Same shape as the host emits.
273#[derive(Debug, Clone, Default, Deserialize, Serialize)]
274pub struct TokenCount {
275    /// Tokens consumed by the prompt (input).
276    #[serde(default)]
277    pub prompt_tokens: u32,
278    /// Tokens consumed by the completion (output).
279    #[serde(default)]
280    pub completion_tokens: u32,
281}
282
283impl BrokerSender {
284    /// Phase 81.15.c — issue an RPC request to the daemon and
285    /// await the response. Allocates a fresh id, registers a
286    /// oneshot in the pending map, writes the request frame,
287    /// then awaits the response with a 30 s timeout. On timeout
288    /// the pending entry is removed; a delayed reply is dropped
289    /// silently with a debug log.
290    ///
291    /// Low-level helper. Plugin authors typically use the typed
292    /// wrappers `recall_memory()` / `complete_llm()` instead.
293    pub async fn request(
294        &self,
295        method: &str,
296        params: Value,
297        timeout: Option<Duration>,
298    ) -> Result<Value, RpcError> {
299        let id = next_request_id(&self.next_id);
300        let frame = json!({
301            "jsonrpc": "2.0",
302            "id": id,
303            "method": method,
304            "params": params,
305        });
306        let (tx, rx) = oneshot::channel::<Result<Value, RpcError>>();
307        self.pending.insert(id, PendingKind::Single(tx));
308
309        // Serialize + write atomically under the writer lock so a
310        // concurrent publish() can't interleave bytes mid-frame.
311        let line = serde_json::to_string(&frame).map_err(|e| {
312            self.pending.remove(&id);
313            RpcError::Decode(format!("serialize request: {e}"))
314        })?;
315        {
316            let mut w = self.writer.lock().await;
317            if w.write_all(line.as_bytes()).await.is_err()
318                || w.write_all(b"\n").await.is_err()
319                || w.flush().await.is_err()
320            {
321                self.pending.remove(&id);
322                return Err(RpcError::Transport(
323                    "stdin write failed (host closed?)".to_string(),
324                ));
325            }
326        }
327
328        let timeout = timeout.unwrap_or(DEFAULT_RPC_TIMEOUT);
329        match tokio::time::timeout(timeout, rx).await {
330            Ok(Ok(payload)) => payload,
331            Ok(Err(_canceled)) => {
332                // Pending oneshot canceled before reply — host
333                // dispatch loop most likely exited mid-request.
334                self.pending.remove(&id);
335                Err(RpcError::Transport(
336                    "response oneshot canceled before reply".to_string(),
337                ))
338            }
339            Err(_elapsed) => {
340                // Timeout. Remove the pending so a late reply is
341                // dropped instead of leaking memory.
342                self.pending.remove(&id);
343                Err(RpcError::Timeout(timeout))
344            }
345        }
346    }
347
348    /// Phase 81.15.c — typed wrapper for `memory.recall`. Asks
349    /// the daemon's long-term memory for entries matching `query`
350    /// for `agent_id`, capped at `limit` results. Returns the
351    /// deserialized `Vec<MemoryEntry>` from the response payload.
352    ///
353    /// Errors:
354    /// - [`RpcError::Server`] with `-32603` when the operator
355    ///   hasn't configured long-term memory.
356    /// - [`RpcError::Server`] with `-32602` for bad params.
357    /// - [`RpcError::Timeout`] after 30 s default.
358    pub async fn recall_memory(
359        &self,
360        agent_id: &str,
361        query: &str,
362        limit: u64,
363    ) -> Result<Vec<MemoryEntry>, RpcError> {
364        let params = json!({
365            "agent_id": agent_id,
366            "query": query,
367            "limit": limit,
368        });
369        let result = self.request("memory.recall", params, None).await?;
370        let entries_val = result.get("entries").cloned().unwrap_or(Value::Null);
371        serde_json::from_value::<Vec<MemoryEntry>>(entries_val)
372            .map_err(|e| RpcError::Decode(format!("memory.recall entries: {e}")))
373    }
374
375    /// Phase 81.15.c.b — streaming variant of `complete_llm`.
376    /// Issues the request with `stream: true` and returns an
377    /// [`LlmStream`] handle the caller drives via
378    /// [`LlmStream::next_chunk`] (delta chunks as they arrive)
379    /// and [`LlmStream::await_final`] (final usage + finish
380    /// reason after the stream closes). Dropping the
381    /// `LlmStream` before the host sends its final response is
382    /// safe — the pending entry is cleaned up via `Drop` so a
383    /// late delta or final reply is silently discarded with a
384    /// debug log.
385    ///
386    /// Errors:
387    /// - [`RpcError::Transport`] when the stdin write fails
388    ///   before the request leaves (host already closed).
389    /// - The returned `LlmStream`'s `await_final()` resolves
390    ///   with [`RpcError::Server`] when the host returns a
391    ///   JSON-RPC error response (e.g. `-32603 "llm not
392    ///   configured"`).
393    pub async fn complete_llm_stream(
394        &self,
395        p: LlmCompleteParams,
396    ) -> Result<LlmStream, RpcError> {
397        let mut params = json!({
398            "provider": p.provider,
399            "model": p.model,
400            "messages": p.messages,
401            "stream": true,
402        });
403        if let Some(max) = p.max_tokens {
404            params["max_tokens"] = json!(max);
405        }
406        if let Some(temp) = p.temperature {
407            params["temperature"] = json!(temp);
408        }
409        if let Some(sys) = p.system_prompt {
410            params["system_prompt"] = json!(sys);
411        }
412        let id = next_request_id(&self.next_id);
413        let frame = json!({
414            "jsonrpc": "2.0",
415            "id": id,
416            "method": "llm.complete",
417            "params": params,
418        });
419        let (delta_tx, delta_rx) = mpsc::unbounded_channel::<String>();
420        let (final_tx, final_rx) =
421            oneshot::channel::<Result<LlmCompleteResult, RpcError>>();
422        self.pending.insert(
423            id,
424            PendingKind::Streaming {
425                delta_tx,
426                final_tx,
427            },
428        );
429
430        let line = serde_json::to_string(&frame).map_err(|e| {
431            self.pending.remove(&id);
432            RpcError::Decode(format!("serialize stream request: {e}"))
433        })?;
434        {
435            let mut w = self.writer.lock().await;
436            if w.write_all(line.as_bytes()).await.is_err()
437                || w.write_all(b"\n").await.is_err()
438                || w.flush().await.is_err()
439            {
440                self.pending.remove(&id);
441                return Err(RpcError::Transport(
442                    "stdin write failed (host closed?)".to_string(),
443                ));
444            }
445        }
446        Ok(LlmStream {
447            request_id: id,
448            chunks: delta_rx,
449            finished: Some(final_rx),
450            pending: self.pending.clone(),
451        })
452    }
453
454    /// Phase 81.15.c — typed wrapper for `llm.complete`
455    /// (non-streaming). Builds the JSON-RPC params from
456    /// [`LlmCompleteParams`], issues the request, deserializes
457    /// the response into [`LlmCompleteResult`].
458    ///
459    /// For streaming consumption use
460    /// [`Self::complete_llm_stream`] instead — that variant
461    /// returns an [`LlmStream`] handle yielding delta chunks +
462    /// a final `LlmCompleteResult`.
463    ///
464    /// Errors mirror the host wire spec at
465    /// `nexo-plugin-contract.md` §5.2.
466    pub async fn complete_llm(
467        &self,
468        p: LlmCompleteParams,
469    ) -> Result<LlmCompleteResult, RpcError> {
470        let mut params = json!({
471            "provider": p.provider,
472            "model": p.model,
473            "messages": p.messages,
474        });
475        if let Some(max) = p.max_tokens {
476            params["max_tokens"] = json!(max);
477        }
478        if let Some(temp) = p.temperature {
479            params["temperature"] = json!(temp);
480        }
481        if let Some(sys) = p.system_prompt {
482            params["system_prompt"] = json!(sys);
483        }
484        let result = self.request("llm.complete", params, None).await?;
485        serde_json::from_value::<LlmCompleteResult>(result)
486            .map_err(|e| RpcError::Decode(format!("llm.complete result: {e}")))
487    }
488
489    /// Emit `broker.publish { topic, event }` on stdout. The host
490    /// validates the topic against its allowlist before forwarding
491    /// to the broker — bad publishes get dropped (with a warn-level
492    /// log on the host side).
493    pub async fn publish(&self, topic: &str, event: Event) -> SdkResult<()> {
494        let frame = json!({
495            "jsonrpc": "2.0",
496            "method": "broker.publish",
497            "params": { "topic": topic, "event": event },
498        });
499        let line = serde_json::to_string(&frame).map_err(|e| {
500            SdkError::Io(io::Error::new(io::ErrorKind::Other, e.to_string()))
501        })?;
502        let mut writer = self.writer.lock().await;
503        writer.write_all(line.as_bytes()).await?;
504        writer.write_all(b"\n").await?;
505        writer.flush().await?;
506        Ok(())
507    }
508}
509
510// ────────────────────────────────────────────────────────────────
511// Phase 81.17.c / 81.29.b — child-side tool dispatch
512//
513// Wire shape (contract v1.10.0 §5.t):
514//   host  → child   `tool.invoke { plugin_id, tool_name, args, agent_id }`
515//   child → host    `{ result }` or `{ error: { code, message } }`
516//                   error band: -33401 NotFound .. -33405 Denied.
517//
518// Authors register tool defs declaratively via
519// [`PluginAdapter::declare_tools`] (advertised in the initialize
520// reply so the host's `RemoteToolHandler` registration succeeds —
521// see `crates/core/src/agent/nexo_plugin_registry/subprocess.rs`)
522// and a single dispatch closure via [`PluginAdapter::on_tool`].
523// ────────────────────────────────────────────────────────────────
524
525/// Declarative tool descriptor advertised in the `initialize` reply.
526///
527/// Wire-compatible with the host's
528/// `nexo_core::agent::tool_remote::RemoteToolDef` — same field
529/// names + `serde(rename_all)` so the JSON shape round-trips
530/// without per-side translators.
531///
532/// `name` MUST appear in the manifest's `[plugin.extends] tools = [...]`
533/// allowlist; advertising a name not in the manifest causes the
534/// host to kill the subprocess at handshake (defense against
535/// out-of-tree binaries advertising tools the operator did not
536/// authorise).
537#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
538pub struct ToolDef {
539    /// LLM-facing tool name. Per 81.3 namespace policy must match
540    /// `<plugin_id>_*` or `ext_<plugin_id>_*`.
541    pub name: String,
542    /// One-sentence description shown to the LLM in the tool
543    /// catalogue. Keep concise; LLMs prune noisy descriptions.
544    pub description: String,
545    /// JSON Schema (object) for tool arguments. Must validate the
546    /// payload the LLM produces; the host runs schema validation
547    /// before round-tripping `tool.invoke` to the child.
548    pub input_schema: serde_json::Value,
549}
550
551/// Decoded `tool.invoke` request as the host hands it to the
552/// child-side handler. Field names mirror contract v1.10.0 §5.t.
553#[derive(Debug, Clone, serde::Deserialize)]
554pub struct ToolInvocation {
555    /// Stable plugin id from the manifest (echoed by the host so
556    /// multi-plugin handlers can dispatch).
557    pub plugin_id: String,
558    /// Canonical tool name — handlers route on this.
559    pub tool_name: String,
560    /// Tool-specific arguments. Defaults to `Value::Null` when the
561    /// host omits the field.
562    #[serde(default)]
563    pub args: serde_json::Value,
564    /// Agent id producing the call. `None` when the host
565    /// dispatcher is operator-driven (admin RPC, debug CLI).
566    #[serde(default)]
567    pub agent_id: Option<String>,
568}
569
570/// Failure modes the child can surface from a `tool.invoke`
571/// handler. Each variant maps onto the `-33401..-33405` JSON-RPC
572/// error band the host's `RemoteToolHandler` decodes (see
573/// `nexo_core::agent::tool_remote::parse_tool_error_string`).
574#[non_exhaustive]
575#[derive(Debug, thiserror::Error)]
576pub enum ToolInvocationError {
577    /// `-33401` — tool name not advertised by this plugin.
578    /// Surfaces when the host dispatched a tool the manifest
579    /// allows but the runtime handler doesn't recognise.
580    #[error("tool not found: {0}")]
581    NotFound(String),
582    /// `-33402` — args failed handler-side validation. The host
583    /// already ran JSON-Schema validation; this branch covers
584    /// semantic checks the schema can't express.
585    #[error("invalid argument: {0}")]
586    ArgumentInvalid(String),
587    /// `-33403` — handler ran but failed (network blip, browser
588    /// crash, downstream API 5xx). LLM sees a soft failure and
589    /// can route around.
590    #[error("execution failed: {0}")]
591    ExecutionFailed(String),
592    /// `-33404` — tool exists but cannot run right now (e.g.,
593    /// missing binary on disk, dependency offline).
594    #[error("unavailable: {0}")]
595    Unavailable(String),
596    /// `-33405` — tool exists but the caller is not authorised.
597    /// Reserved for future capability-aware ACLs (81.28.b).
598    #[error("denied: {0}")]
599    Denied(String),
600}
601
602impl ToolInvocationError {
603    /// JSON-RPC error code corresponding to the variant. Matches
604    /// the host's decoder; see contract v1.10.0 §5.t.
605    pub fn code(&self) -> i32 {
606        match self {
607            Self::NotFound(_) => -33401,
608            Self::ArgumentInvalid(_) => -33402,
609            Self::ExecutionFailed(_) => -33403,
610            Self::Unavailable(_) => -33404,
611            Self::Denied(_) => -33405,
612        }
613    }
614}
615
616/// Async handler invoked by the dispatch loop on every
617/// `tool.invoke` request the host sends. Plugin authors register
618/// one via [`PluginAdapter::on_tool`]; the closure typically
619/// matches on `inv.tool_name` and routes to per-tool logic.
620///
621/// Blanket-implemented for any `Fn(ToolInvocation) -> Fut` where
622/// `Fut: Future<Output = Result<Value, ToolInvocationError>> + Send`,
623/// so call sites pass closures naturally:
624///
625/// ```ignore
626/// PluginAdapter::new(MANIFEST)?
627///     .on_tool(|inv: ToolInvocation| async move {
628///         match inv.tool_name.as_str() {
629///             "echo" => Ok(inv.args),
630///             other => Err(ToolInvocationError::NotFound(other.into())),
631///         }
632///     })
633///     .run_stdio().await
634/// ```
635pub trait ToolHandler: Send + Sync + 'static {
636    /// Invoke the handler. Returning `Ok(Value)` becomes the
637    /// `result` field of the JSON-RPC reply; `Err(...)` maps to
638    /// `{ error: { code, message } }` in the
639    /// `-33401..-33405` band.
640    fn call(
641        &self,
642        invocation: ToolInvocation,
643    ) -> std::pin::Pin<
644        Box<
645            dyn std::future::Future<Output = Result<serde_json::Value, ToolInvocationError>>
646                + Send,
647        >,
648    >;
649}
650
651impl<F, Fut> ToolHandler for F
652where
653    F: Fn(ToolInvocation) -> Fut + Send + Sync + 'static,
654    Fut: std::future::Future<Output = Result<serde_json::Value, ToolInvocationError>> + Send + 'static,
655{
656    fn call(
657        &self,
658        invocation: ToolInvocation,
659    ) -> std::pin::Pin<
660        Box<
661            dyn std::future::Future<Output = Result<serde_json::Value, ToolInvocationError>>
662                + Send,
663        >,
664    > {
665        Box::pin((self)(invocation))
666    }
667}
668
669/// Builder for the child-side plugin runtime. Authors call
670/// [`PluginAdapter::new`] with their manifest TOML, register
671/// `on_broker_event` + `on_shutdown` handlers, then drive the
672/// dispatch loop with `run_stdio`.
673pub struct PluginAdapter {
674    cached_manifest: PluginManifest,
675    server_version: String,
676    on_broker_event: Option<Arc<dyn BrokerEventHandler>>,
677    on_shutdown: Option<Arc<dyn ShutdownHandler>>,
678    /// Phase 81.17.c — tool defs advertised in the `initialize`
679    /// reply's `tools: [...]` field. The host's decoder
680    /// (`nexo_core::agent::tool_remote::RemoteToolDef`) consumes
681    /// this list to register `RemoteToolHandler`s in the agent's
682    /// scoped registry. Empty when the plugin doesn't expose
683    /// tools — initialize-reply omits the field.
684    declared_tools: Vec<ToolDef>,
685    /// Phase 81.17.c — single dispatch closure invoked on every
686    /// `tool.invoke` request. `None` when the plugin doesn't
687    /// expose tools — `tool.invoke` requests reply `-32601 method
688    /// not found` so the host's RemoteToolHandler surfaces a
689    /// clear error.
690    tool_handler: Option<Arc<dyn ToolHandler>>,
691}
692
693/// Phase 81.15.c.b — handle returned by
694/// [`BrokerSender::complete_llm_stream`]. Yields text chunks as
695/// the host streams them, then a final [`LlmCompleteResult`] with
696/// usage + finish reason after the stream closes.
697///
698/// Typical usage:
699///
700/// ```ignore
701/// let mut stream = broker.complete_llm_stream(params).await?;
702/// while let Some(chunk) = stream.next_chunk().await {
703///     print!("{}", chunk);
704/// }
705/// let result = stream.await_final().await?;
706/// println!("\n[finish_reason={}]", result.finish_reason);
707/// ```
708///
709/// Dropping the `LlmStream` early is safe — the pending entry
710/// is cleaned up via `Drop` so a late delta or final reply
711/// from the host is silently discarded with a debug log on the
712/// dispatch loop side.
713pub struct LlmStream {
714    request_id: u64,
715    chunks: mpsc::UnboundedReceiver<String>,
716    /// `Option` so [`Self::await_final`] can `take()` ownership
717    /// of the receiver despite `LlmStream` having a `Drop` impl
718    /// (which forbids moving fields out of `&mut self`).
719    finished: Option<oneshot::Receiver<Result<LlmCompleteResult, RpcError>>>,
720    pending: ChildPending,
721}
722
723impl LlmStream {
724    /// Pull the next text chunk. Returns `None` when the stream
725    /// closes (after which [`Self::await_final`] should be
726    /// awaited for the final result).
727    pub async fn next_chunk(&mut self) -> Option<String> {
728        self.chunks.recv().await
729    }
730
731    /// Await the host's final response. Resolves once all
732    /// deltas have been delivered and the host's response frame
733    /// lands. Returns [`RpcError::Server`] when the host
734    /// returned a JSON-RPC error (e.g. mid-stream provider
735    /// failure mapped to `-32603`); [`RpcError::Transport`] when
736    /// the dispatch loop dropped the oneshot before resolving
737    /// (host crashed mid-stream). Calling twice returns
738    /// `RpcError::Transport` on the second call (the receiver
739    /// was already taken).
740    pub async fn await_final(mut self) -> Result<LlmCompleteResult, RpcError> {
741        let rx = self.finished.take().ok_or_else(|| {
742            RpcError::Transport("await_final already consumed".into())
743        })?;
744        match rx.await {
745            Ok(payload) => payload,
746            Err(_canceled) => Err(RpcError::Transport(
747                "final response oneshot canceled (host closed mid-stream)".into(),
748            )),
749        }
750    }
751}
752
753impl Drop for LlmStream {
754    fn drop(&mut self) {
755        // Clean up the pending entry if it's still there. The
756        // dispatch loop's get/remove on response path is the
757        // normal cleanup; this Drop covers the case where the
758        // user dropped the stream before consuming the final
759        // reply (or before any deltas arrived). Late deltas /
760        // final reply land on a missing pending entry → dropped
761        // with debug log.
762        self.pending.remove(&self.request_id);
763    }
764}
765
766impl PluginAdapter {
767    /// Parse the bundled manifest. Plugin authors typically pass
768    /// the result of `include_str!("../nexo-plugin.toml")`. The
769    /// manifest's `plugin.id` becomes the identity the daemon
770    /// validates after `initialize`.
771    pub fn new(manifest_toml: &str) -> SdkResult<Self> {
772        let cached_manifest: PluginManifest = toml::from_str(manifest_toml).map_err(|e| {
773            SdkError::Io(io::Error::new(
774                io::ErrorKind::InvalidData,
775                format!("PluginAdapter: parse manifest TOML failed: {e}"),
776            ))
777        })?;
778        let server_version = format!(
779            "{}-{}",
780            cached_manifest.plugin.id, cached_manifest.plugin.version
781        );
782        Ok(Self {
783            cached_manifest,
784            server_version,
785            on_broker_event: None,
786            on_shutdown: None,
787            declared_tools: Vec::new(),
788            tool_handler: None,
789        })
790    }
791
792    /// Override the default `server_version` (which defaults to
793    /// `<plugin.id>-<plugin.version>` from the manifest). Useful
794    /// when the binary's runtime version differs from the manifest
795    /// version (e.g. a hot-patched build).
796    pub fn with_server_version(mut self, version: impl Into<String>) -> Self {
797        self.server_version = version.into();
798        self
799    }
800
801    /// Register the handler invoked for each `broker.event`
802    /// notification the daemon delivers. Without one, events are
803    /// silently dropped.
804    pub fn on_broker_event<H: BrokerEventHandler>(mut self, handler: H) -> Self {
805        self.on_broker_event = Some(Arc::new(handler));
806        self
807    }
808
809    /// Phase 81.17.c — declare the tools this plugin will expose
810    /// in its `initialize` reply. Each [`ToolDef::name`] MUST
811    /// appear in the manifest's `[plugin.extends] tools = [...]`
812    /// allowlist or the host kills the subprocess at handshake.
813    ///
814    /// Pair with [`Self::on_tool`] to handle invocations.
815    pub fn declare_tools(mut self, defs: impl IntoIterator<Item = ToolDef>) -> Self {
816        self.declared_tools = defs.into_iter().collect();
817        self
818    }
819
820    /// Phase 81.17.c — register the dispatch handler for
821    /// incoming `tool.invoke` requests. The handler matches on
822    /// [`ToolInvocation::tool_name`] and routes to per-tool
823    /// logic; returning `Ok(value)` becomes the JSON-RPC
824    /// `result`, `Err(...)` maps to a `-33401..-33405` error.
825    ///
826    /// Without a handler, the dispatch loop replies `-32601
827    /// method not found` to `tool.invoke` requests so the host's
828    /// `RemoteToolHandler` surfaces a clear error.
829    pub fn on_tool<H: ToolHandler>(mut self, handler: H) -> Self {
830        self.tool_handler = Some(Arc::new(handler));
831        self
832    }
833
834    /// Register the handler invoked when the daemon sends
835    /// `shutdown`. Called BEFORE the reply, so the handler can
836    /// flush state; an `Err` propagates as JSON-RPC error so the
837    /// host surfaces `PluginShutdownError::Other`.
838    pub fn on_shutdown<H: ShutdownHandler>(mut self, handler: H) -> Self {
839        self.on_shutdown = Some(Arc::new(handler));
840        self
841    }
842
843    /// Drive the dispatch loop on stdin/stdout until the daemon
844    /// sends `shutdown` or stdin reaches EOF.
845    pub async fn run_stdio(self) -> SdkResult<()> {
846        let stdin = io::stdin();
847        let stdout = io::stdout();
848        self.run(BufReader::new(stdin), stdout).await
849    }
850
851    /// Drive the dispatch loop on caller-supplied IO. Used by unit
852    /// tests via `tokio::io::duplex` and by integration tests that
853    /// want to inject mocks.
854    pub async fn run<R, W>(self, reader: R, writer: W) -> SdkResult<()>
855    where
856        R: AsyncBufRead + Unpin + Send + 'static,
857        W: AsyncWrite + Unpin + Send + 'static,
858    {
859        let writer: Arc<Mutex<Box<dyn AsyncWrite + Send + Unpin>>> =
860            Arc::new(Mutex::new(Box::new(writer)));
861        dispatch_loop(reader, writer, self).await
862    }
863}
864
865/// Inner dispatch loop. Reads JSON-RPC lines, demuxes by method,
866/// invokes user handlers, writes replies. Returns on EOF or
867/// `shutdown`.
868async fn dispatch_loop<R>(
869    reader: R,
870    writer: Arc<Mutex<Box<dyn AsyncWrite + Send + Unpin>>>,
871    adapter: PluginAdapter,
872) -> SdkResult<()>
873where
874    R: AsyncBufRead + Unpin + Send + 'static,
875{
876    let mut lines = reader.lines();
877    let manifest_value = serde_json::to_value(&adapter.cached_manifest).map_err(|e| {
878        SdkError::Io(io::Error::new(io::ErrorKind::Other, e.to_string()))
879    })?;
880    // Phase 81.15.c — child-side request-response correlation.
881    // Each outbound request (memory.recall / llm.complete / ...)
882    // registers a oneshot here under its allocated id; the reader
883    // demuxes response frames (id + result/error, no method) back
884    // to the matching pending entry.
885    let pending: ChildPending = Arc::new(DashMap::new());
886    let next_id: Arc<AtomicU64> = Arc::new(AtomicU64::new(100));
887    while let Some(line) = lines.next_line().await? {
888        let trimmed = line.trim();
889        if trimmed.is_empty() {
890            continue;
891        }
892        let frame: Value = match serde_json::from_str(trimmed) {
893            Ok(v) => v,
894            Err(e) => {
895                write_error(&writer, None, -32700, &format!("parse error: {e}")).await?;
896                continue;
897            }
898        };
899        let id = frame.get("id").cloned();
900        let method = frame.get("method").and_then(Value::as_str).unwrap_or("");
901        let params = frame.get("params").cloned().unwrap_or(Value::Null);
902
903        // Phase 81.15.c — RESPONSE to one of OUR outbound
904        // requests: frame has `id` AND no `method` AND has
905        // `result` or `error`. Look up in pending map; resolve
906        // the oneshot. Out-of-order responses (id we don't
907        // recognize) are dropped with a debug log — most likely
908        // a delayed reply after timeout.
909        if let Some(id_val) = id.as_ref() {
910            if method.is_empty() {
911                if let Some(req_id) = id_val.as_u64() {
912                    if let Some((_, kind)) = pending.remove(&req_id) {
913                        let err_obj = frame.get("error").cloned();
914                        let result_val = frame.get("result").cloned().unwrap_or(Value::Null);
915                        match kind {
916                            PendingKind::Single(sender) => {
917                                let payload = if let Some(err) = err_obj {
918                                    let code = err
919                                        .get("code")
920                                        .and_then(|v| v.as_i64())
921                                        .unwrap_or(-32603)
922                                        as i32;
923                                    let message = err
924                                        .get("message")
925                                        .and_then(|v| v.as_str())
926                                        .unwrap_or("(no message)")
927                                        .to_string();
928                                    Err(RpcError::Server { code, message })
929                                } else {
930                                    Ok(result_val)
931                                };
932                                let _ = sender.send(payload);
933                            }
934                            PendingKind::Streaming { final_tx, .. } => {
935                                // Phase 81.15.c.b — final response
936                                // for a streaming request. delta_tx
937                                // drops with the enum, closing the
938                                // chunks channel cleanly so the
939                                // user's `next_chunk()` loop returns
940                                // `None`. Then `await_final()`
941                                // resolves with this payload.
942                                let payload = if let Some(err) = err_obj {
943                                    let code = err
944                                        .get("code")
945                                        .and_then(|v| v.as_i64())
946                                        .unwrap_or(-32603)
947                                        as i32;
948                                    let message = err
949                                        .get("message")
950                                        .and_then(|v| v.as_str())
951                                        .unwrap_or("(no message)")
952                                        .to_string();
953                                    Err(RpcError::Server { code, message })
954                                } else {
955                                    serde_json::from_value::<LlmCompleteResult>(result_val)
956                                        .map_err(|e| RpcError::Decode(format!(
957                                            "llm.complete stream final result: {e}"
958                                        )))
959                                };
960                                let _ = final_tx.send(payload);
961                            }
962                        }
963                        continue;
964                    }
965                    tracing::debug!(
966                        id = req_id,
967                        "rpc response with unknown id — drop (likely after timeout)"
968                    );
969                    continue;
970                }
971            }
972        }
973
974        // Notifications carry no `id`. Today the only one we
975        // accept is `broker.event`; everything else is dropped
976        // with a debug log.
977        if id.is_none() {
978            if method == "broker.event" {
979                let topic = params
980                    .get("topic")
981                    .and_then(Value::as_str)
982                    .unwrap_or("")
983                    .to_string();
984                let event_val = params.get("event").cloned().unwrap_or(Value::Null);
985                let event: Event = match serde_json::from_value(event_val) {
986                    Ok(e) => e,
987                    Err(e) => {
988                        tracing::warn!(error = %e, topic, "broker.event: deserialize Event failed — drop");
989                        continue;
990                    }
991                };
992                if let Some(handler) = &adapter.on_broker_event {
993                    let sender = BrokerSender {
994                        writer: writer.clone(),
995                        pending: pending.clone(),
996                        next_id: next_id.clone(),
997                    };
998                    // Phase 81.15.c — spawn the handler so the
999                    // dispatch loop keeps reading the next line
1000                    // while the handler awaits any RPC responses.
1001                    // Without spawn, a handler that calls
1002                    // `broker.request(...)` deadlocks: the
1003                    // request's oneshot can only be resolved by
1004                    // the dispatch loop reading the response
1005                    // frame, but the loop is blocked awaiting
1006                    // the handler future itself.
1007                    let handler_clone = handler.clone();
1008                    tokio::spawn(async move {
1009                        handler_clone.handle(topic, event, sender).await;
1010                    });
1011                }
1012            } else if method == "llm.complete.delta" {
1013                // Phase 81.15.c.b — streaming chunk for an
1014                // outstanding `complete_llm_stream` request. Look
1015                // up the pending entry by request_id; if it's
1016                // Streaming, push the chunk into delta_tx. If the
1017                // pending entry is missing (already finalized or
1018                // user dropped the LlmStream), the chunk is
1019                // dropped with debug log.
1020                let req_id = params
1021                    .get("request_id")
1022                    .and_then(|v| v.as_u64());
1023                let chunk = params
1024                    .get("chunk")
1025                    .and_then(|v| v.as_str())
1026                    .unwrap_or("");
1027                if let Some(req_id) = req_id {
1028                    if let Some(entry) = pending.get(&req_id) {
1029                        if let PendingKind::Streaming { delta_tx, .. } = entry.value() {
1030                            let _ = delta_tx.send(chunk.to_string());
1031                        } else {
1032                            tracing::debug!(
1033                                request_id = req_id,
1034                                "llm.complete.delta arrived for non-streaming pending — drop"
1035                            );
1036                        }
1037                    } else {
1038                        tracing::debug!(
1039                            request_id = req_id,
1040                            "llm.complete.delta with unknown request_id — drop"
1041                        );
1042                    }
1043                }
1044            } else {
1045                tracing::debug!(method, "unhandled notification — drop");
1046            }
1047            continue;
1048        }
1049
1050        match method {
1051            "initialize" => {
1052                // Phase 81.17.c — when the plugin declared tools,
1053                // emit them as `tools: [...]` so the host's
1054                // `Inner.declared_tools` (subprocess.rs:1052)
1055                // populates and `register_remote_tool_handlers_after_init`
1056                // can register `RemoteToolHandler`s.
1057                let mut result_obj = json!({
1058                    "manifest": manifest_value,
1059                    "server_version": adapter.server_version,
1060                });
1061                if !adapter.declared_tools.is_empty() {
1062                    let tools_value =
1063                        serde_json::to_value(&adapter.declared_tools).map_err(|e| {
1064                            SdkError::Io(io::Error::new(
1065                                io::ErrorKind::InvalidData,
1066                                format!("declared_tools serialise failed: {e}"),
1067                            ))
1068                        })?;
1069                    if let Some(map) = result_obj.as_object_mut() {
1070                        map.insert("tools".to_string(), tools_value);
1071                    }
1072                }
1073                write_result(&writer, id, result_obj).await?;
1074            }
1075            "shutdown" => {
1076                if let Some(handler) = &adapter.on_shutdown {
1077                    match handler.handle().await {
1078                        Ok(()) => {
1079                            write_result(&writer, id, json!({"ok": true})).await?;
1080                        }
1081                        Err(e) => {
1082                            write_error(&writer, id, -32000, &e).await?;
1083                        }
1084                    }
1085                } else {
1086                    write_result(&writer, id, json!({"ok": true})).await?;
1087                }
1088                break;
1089            }
1090            "tool.invoke" => {
1091                // Phase 81.17.c — host-initiated tool dispatch. No
1092                // registered handler ⇒ reply with -32601 so the
1093                // host's `RemoteToolHandler` surfaces a typed
1094                // ToolError to the agent.
1095                let Some(handler) = adapter.tool_handler.clone() else {
1096                    write_error(
1097                        &writer,
1098                        id,
1099                        -32601,
1100                        "method not found: tool.invoke (no handler registered — call PluginAdapter::on_tool)",
1101                    )
1102                    .await?;
1103                    continue;
1104                };
1105                let params = frame.get("params").cloned().unwrap_or(Value::Null);
1106                let invocation: ToolInvocation = match serde_json::from_value(params) {
1107                    Ok(inv) => inv,
1108                    Err(e) => {
1109                        write_error(
1110                            &writer,
1111                            id,
1112                            -32602,
1113                            &format!("tool.invoke: invalid params: {e}"),
1114                        )
1115                        .await?;
1116                        continue;
1117                    }
1118                };
1119                match handler.call(invocation).await {
1120                    Ok(value) => {
1121                        write_result(&writer, id, value).await?;
1122                    }
1123                    Err(err) => {
1124                        let code = err.code();
1125                        write_error(&writer, id, code, &err.to_string()).await?;
1126                    }
1127                }
1128            }
1129            other => {
1130                write_error(
1131                    &writer,
1132                    id,
1133                    -32601,
1134                    &format!("method not found: {other}"),
1135                )
1136                .await?;
1137            }
1138        }
1139    }
1140    Ok(())
1141}
1142
1143async fn write_result(
1144    writer: &Arc<Mutex<Box<dyn AsyncWrite + Send + Unpin>>>,
1145    id: Option<Value>,
1146    result: Value,
1147) -> SdkResult<()> {
1148    let frame = json!({
1149        "jsonrpc": "2.0",
1150        "id": id.unwrap_or(Value::Null),
1151        "result": result,
1152    });
1153    write_line(writer, &frame).await
1154}
1155
1156async fn write_error(
1157    writer: &Arc<Mutex<Box<dyn AsyncWrite + Send + Unpin>>>,
1158    id: Option<Value>,
1159    code: i32,
1160    message: &str,
1161) -> SdkResult<()> {
1162    let frame = json!({
1163        "jsonrpc": "2.0",
1164        "id": id.unwrap_or(Value::Null),
1165        "error": { "code": code, "message": message },
1166    });
1167    write_line(writer, &frame).await
1168}
1169
1170async fn write_line(
1171    writer: &Arc<Mutex<Box<dyn AsyncWrite + Send + Unpin>>>,
1172    frame: &Value,
1173) -> SdkResult<()> {
1174    let line = serde_json::to_string(frame)
1175        .map_err(|e| SdkError::Io(io::Error::new(io::ErrorKind::Other, e.to_string())))?;
1176    let mut w = writer.lock().await;
1177    w.write_all(line.as_bytes()).await?;
1178    w.write_all(b"\n").await?;
1179    w.flush().await?;
1180    Ok(())
1181}
1182
1183#[cfg(test)]
1184mod tests {
1185    use super::*;
1186    use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
1187    use tokio::io::{duplex, BufReader as TokioBufReader};
1188
1189    const TEST_MANIFEST: &str = r#"
1190[plugin]
1191id = "test_plugin"
1192version = "0.1.0"
1193name = "test"
1194description = "fixture"
1195min_nexo_version = ">=0.1.0"
1196"#;
1197
1198    // ── Phase 81.17.c — tool dispatch types ────────────────────
1199
1200    #[test]
1201    fn tool_def_serde_round_trip() {
1202        let def = ToolDef {
1203            name: "test_plugin_echo".into(),
1204            description: "Echo the args back.".into(),
1205            input_schema: serde_json::json!({
1206                "type": "object",
1207                "properties": { "msg": { "type": "string" } },
1208                "required": ["msg"],
1209            }),
1210        };
1211        let s = serde_json::to_string(&def).unwrap();
1212        // Wire-shape sentinel: must match the host-side decoder
1213        // (`nexo_core::agent::tool_remote::RemoteToolDef`).
1214        assert!(s.contains("\"name\":\"test_plugin_echo\""));
1215        assert!(s.contains("\"description\":\"Echo the args back.\""));
1216        assert!(s.contains("\"input_schema\""));
1217        let back: ToolDef = serde_json::from_str(&s).unwrap();
1218        assert_eq!(back.name, def.name);
1219        assert_eq!(back.description, def.description);
1220        assert_eq!(back.input_schema, def.input_schema);
1221    }
1222
1223    #[test]
1224    fn tool_invocation_args_default_to_null() {
1225        let raw = r#"{ "plugin_id": "p", "tool_name": "t" }"#;
1226        let inv: ToolInvocation = serde_json::from_str(raw).unwrap();
1227        assert_eq!(inv.plugin_id, "p");
1228        assert_eq!(inv.tool_name, "t");
1229        assert_eq!(inv.args, serde_json::Value::Null);
1230        assert!(inv.agent_id.is_none());
1231    }
1232
1233    #[test]
1234    fn tool_invocation_full_shape_round_trip() {
1235        let raw = r#"{
1236            "plugin_id": "browser",
1237            "tool_name": "browser_navigate",
1238            "args": { "url": "about:blank" },
1239            "agent_id": "ana"
1240        }"#;
1241        let inv: ToolInvocation = serde_json::from_str(raw).unwrap();
1242        assert_eq!(inv.tool_name, "browser_navigate");
1243        assert_eq!(inv.args["url"], "about:blank");
1244        assert_eq!(inv.agent_id.as_deref(), Some("ana"));
1245    }
1246
1247    #[test]
1248    fn tool_invocation_error_codes_match_contract_v1_10_band() {
1249        assert_eq!(ToolInvocationError::NotFound("x".into()).code(), -33401);
1250        assert_eq!(ToolInvocationError::ArgumentInvalid("x".into()).code(), -33402);
1251        assert_eq!(ToolInvocationError::ExecutionFailed("x".into()).code(), -33403);
1252        assert_eq!(ToolInvocationError::Unavailable("x".into()).code(), -33404);
1253        assert_eq!(ToolInvocationError::Denied("x".into()).code(), -33405);
1254    }
1255
1256    #[test]
1257    fn tool_invocation_error_messages_format_with_payload() {
1258        let e = ToolInvocationError::NotFound("browser_thirteenth".into());
1259        assert_eq!(e.to_string(), "tool not found: browser_thirteenth");
1260        let e = ToolInvocationError::ExecutionFailed("CDP 500".into());
1261        assert_eq!(e.to_string(), "execution failed: CDP 500");
1262    }
1263
1264    #[tokio::test]
1265    async fn tool_handler_blanket_impl_accepts_closure() {
1266        // The closure form is the canonical entry point — verify
1267        // that an `impl Fn(ToolInvocation) -> Fut` satisfies the
1268        // `ToolHandler` trait via the blanket impl, and that the
1269        // dispatch routes args through unchanged.
1270        let handler = |inv: ToolInvocation| async move {
1271            match inv.tool_name.as_str() {
1272                "echo" => Ok(inv.args),
1273                other => Err(ToolInvocationError::NotFound(other.into())),
1274            }
1275        };
1276        let inv = ToolInvocation {
1277            plugin_id: "p".into(),
1278            tool_name: "echo".into(),
1279            args: serde_json::json!({"hello": "world"}),
1280            agent_id: None,
1281        };
1282        let out = ToolHandler::call(&handler, inv).await.unwrap();
1283        assert_eq!(out, serde_json::json!({"hello": "world"}));
1284    }
1285
1286    #[tokio::test]
1287    async fn tool_handler_blanket_impl_propagates_error_variant() {
1288        let handler = |_inv: ToolInvocation| async move {
1289            Err::<serde_json::Value, _>(ToolInvocationError::Denied("nope".into()))
1290        };
1291        let inv = ToolInvocation {
1292            plugin_id: "p".into(),
1293            tool_name: "x".into(),
1294            args: serde_json::Value::Null,
1295            agent_id: None,
1296        };
1297        let err = ToolHandler::call(&handler, inv).await.unwrap_err();
1298        assert_eq!(err.code(), -33405);
1299    }
1300
1301    /// Spawn the adapter on a duplex pipe + return helpers to
1302    /// drive it from the test's side: write requests, read
1303    /// replies. The adapter task is moved off so the test can
1304    /// proceed with assertions.
1305    async fn run_adapter_on_duplex(
1306        adapter: PluginAdapter,
1307    ) -> (
1308        tokio::io::WriteHalf<tokio::io::DuplexStream>,
1309        TokioBufReader<tokio::io::ReadHalf<tokio::io::DuplexStream>>,
1310        tokio::task::JoinHandle<SdkResult<()>>,
1311    ) {
1312        // Two duplex pipes: host_to_plugin (test writes, adapter
1313        // reads) + plugin_to_host (adapter writes, test reads).
1314        let (host_writer_end, plugin_reader_end) = duplex(8192);
1315        let (plugin_writer_end, host_reader_end) = duplex(8192);
1316        let plugin_reader = TokioBufReader::new(plugin_reader_end);
1317        let plugin_writer = plugin_writer_end;
1318        let join = tokio::spawn(adapter.run(plugin_reader, plugin_writer));
1319        let (_unused_read, host_write) = tokio::io::split(host_writer_end);
1320        let (host_read, _unused_write) = tokio::io::split(host_reader_end);
1321        (host_write, TokioBufReader::new(host_read), join)
1322    }
1323
1324    async fn read_reply_line(
1325        reader: &mut TokioBufReader<tokio::io::ReadHalf<tokio::io::DuplexStream>>,
1326    ) -> Value {
1327        let mut buf = String::new();
1328        reader.read_line(&mut buf).await.expect("read reply line");
1329        serde_json::from_str(buf.trim()).expect("reply parses as JSON")
1330    }
1331
1332    #[tokio::test]
1333    async fn initialize_replies_with_cached_manifest() {
1334        let adapter = PluginAdapter::new(TEST_MANIFEST).expect("manifest parses");
1335        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1336        host_write
1337            .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}\n")
1338            .await
1339            .unwrap();
1340        let reply = read_reply_line(&mut host_read).await;
1341        assert_eq!(reply["jsonrpc"], "2.0");
1342        assert_eq!(reply["id"], 1);
1343        assert_eq!(reply["result"]["manifest"]["plugin"]["id"], "test_plugin");
1344        assert_eq!(reply["result"]["server_version"], "test_plugin-0.1.0");
1345    }
1346
1347    // ── Phase 81.17.c — initialize-reply tools + tool.invoke routing ──
1348
1349    #[tokio::test]
1350    async fn initialize_reply_omits_tools_when_none_declared() {
1351        // Default builder: no `.declare_tools(...)` call; the
1352        // initialize reply must NOT carry a `tools` field so the
1353        // host's `result.pointer("/tools")` returns None and
1354        // `Inner.declared_tools` stays empty.
1355        let adapter = PluginAdapter::new(TEST_MANIFEST).expect("manifest parses");
1356        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1357        host_write
1358            .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}\n")
1359            .await
1360            .unwrap();
1361        let reply = read_reply_line(&mut host_read).await;
1362        assert!(reply["result"].get("tools").is_none(),
1363            "expected no `tools` field; got: {}", reply["result"]);
1364    }
1365
1366    #[tokio::test]
1367    async fn initialize_reply_includes_declared_tools_array() {
1368        let defs = vec![
1369            ToolDef {
1370                name: "test_plugin_echo".into(),
1371                description: "Echo args.".into(),
1372                input_schema: serde_json::json!({"type":"object"}),
1373            },
1374            ToolDef {
1375                name: "test_plugin_ping".into(),
1376                description: "Ping/pong.".into(),
1377                input_schema: serde_json::json!({"type":"object"}),
1378            },
1379        ];
1380        let adapter = PluginAdapter::new(TEST_MANIFEST)
1381            .expect("manifest parses")
1382            .declare_tools(defs);
1383        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1384        host_write
1385            .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}\n")
1386            .await
1387            .unwrap();
1388        let reply = read_reply_line(&mut host_read).await;
1389        let tools = reply["result"]["tools"].as_array().expect("tools array");
1390        assert_eq!(tools.len(), 2);
1391        assert_eq!(tools[0]["name"], "test_plugin_echo");
1392        assert_eq!(tools[1]["name"], "test_plugin_ping");
1393    }
1394
1395    #[tokio::test]
1396    async fn tool_invoke_routes_to_registered_handler() {
1397        let adapter = PluginAdapter::new(TEST_MANIFEST)
1398            .expect("manifest parses")
1399            .on_tool(|inv: ToolInvocation| async move {
1400                Ok(serde_json::json!({"echoed": inv.args}))
1401            });
1402        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1403        host_write
1404            .write_all(
1405                br#"{"jsonrpc":"2.0","id":7,"method":"tool.invoke","params":{"plugin_id":"test_plugin","tool_name":"echo","args":{"x":1}}}
1406"#,
1407            )
1408            .await
1409            .unwrap();
1410        let reply = read_reply_line(&mut host_read).await;
1411        assert_eq!(reply["id"], 7);
1412        assert_eq!(reply["result"]["echoed"]["x"], 1);
1413    }
1414
1415    #[tokio::test]
1416    async fn tool_invoke_handler_error_maps_to_minus_33401() {
1417        let adapter = PluginAdapter::new(TEST_MANIFEST)
1418            .expect("manifest parses")
1419            .on_tool(|inv: ToolInvocation| async move {
1420                Err::<serde_json::Value, _>(ToolInvocationError::NotFound(inv.tool_name))
1421            });
1422        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1423        host_write
1424            .write_all(
1425                br#"{"jsonrpc":"2.0","id":8,"method":"tool.invoke","params":{"plugin_id":"test_plugin","tool_name":"unknown"}}
1426"#,
1427            )
1428            .await
1429            .unwrap();
1430        let reply = read_reply_line(&mut host_read).await;
1431        assert_eq!(reply["id"], 8);
1432        assert_eq!(reply["error"]["code"], -33401);
1433        assert!(reply["error"]["message"].as_str().unwrap().contains("unknown"));
1434    }
1435
1436    #[tokio::test]
1437    async fn tool_invoke_without_handler_returns_method_not_found() {
1438        // No `.on_tool(...)` call; dispatch loop must reply
1439        // -32601 (method not found) so the host's
1440        // RemoteToolHandler surfaces a typed error rather than
1441        // hanging on a never-resolved oneshot.
1442        let adapter = PluginAdapter::new(TEST_MANIFEST).expect("manifest parses");
1443        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1444        host_write
1445            .write_all(
1446                br#"{"jsonrpc":"2.0","id":9,"method":"tool.invoke","params":{"plugin_id":"test_plugin","tool_name":"x"}}
1447"#,
1448            )
1449            .await
1450            .unwrap();
1451        let reply = read_reply_line(&mut host_read).await;
1452        assert_eq!(reply["id"], 9);
1453        assert_eq!(reply["error"]["code"], -32601);
1454    }
1455
1456    #[tokio::test]
1457    async fn broker_event_dispatches_to_user_handler() {
1458        let called = Arc::new(AtomicBool::new(false));
1459        let called_clone = called.clone();
1460        let adapter = PluginAdapter::new(TEST_MANIFEST)
1461            .expect("manifest parses")
1462            .on_broker_event(
1463                move |topic: String, event: Event, _broker: BrokerSender| {
1464                    let called = called_clone.clone();
1465                    async move {
1466                        assert_eq!(topic, "plugin.outbound.test");
1467                        assert_eq!(event.source, "host");
1468                        called.store(true, Ordering::SeqCst);
1469                    }
1470                },
1471            );
1472        let (mut host_write, _host_read, _join) = run_adapter_on_duplex(adapter).await;
1473        // Fabricate a broker.event notification.
1474        let frame = serde_json::json!({
1475            "jsonrpc": "2.0",
1476            "method": "broker.event",
1477            "params": {
1478                "topic": "plugin.outbound.test",
1479                "event": {
1480                    "id": "00000000-0000-0000-0000-000000000010",
1481                    "timestamp": "2026-05-01T00:00:00Z",
1482                    "topic": "plugin.outbound.test",
1483                    "source": "host",
1484                    "session_id": null,
1485                    "payload": {"hello": "world"},
1486                }
1487            }
1488        });
1489        let line = format!("{}\n", serde_json::to_string(&frame).unwrap());
1490        host_write.write_all(line.as_bytes()).await.unwrap();
1491        // Give the adapter a tick to process; tighter than 100ms
1492        // makes flaky.
1493        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1494        assert!(called.load(Ordering::SeqCst), "handler must be invoked");
1495    }
1496
1497    #[tokio::test]
1498    async fn broker_sender_writes_publish_notification() {
1499        let adapter = PluginAdapter::new(TEST_MANIFEST)
1500            .expect("manifest parses")
1501            .on_broker_event(
1502                |_topic: String, event: Event, broker: BrokerSender| async move {
1503                    let echo = Event::new(
1504                        "plugin.inbound.test",
1505                        "plugin",
1506                        serde_json::json!({"echo": event.payload}),
1507                    );
1508                    broker
1509                        .publish("plugin.inbound.test", echo)
1510                        .await
1511                        .expect("publish ok");
1512                },
1513            );
1514        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1515        let frame = serde_json::json!({
1516            "jsonrpc": "2.0",
1517            "method": "broker.event",
1518            "params": {
1519                "topic": "plugin.outbound.test",
1520                "event": {
1521                    "id": "00000000-0000-0000-0000-000000000010",
1522                    "timestamp": "2026-05-01T00:00:00Z",
1523                    "topic": "plugin.outbound.test",
1524                    "source": "host",
1525                    "session_id": null,
1526                    "payload": {"foo": "bar"},
1527                }
1528            }
1529        });
1530        let line = format!("{}\n", serde_json::to_string(&frame).unwrap());
1531        host_write.write_all(line.as_bytes()).await.unwrap();
1532        // Read the next outbound line — must be a broker.publish
1533        // notification carrying the echo payload.
1534        let reply = read_reply_line(&mut host_read).await;
1535        assert!(reply.get("id").is_none(), "publish must have NO id");
1536        assert_eq!(reply["method"], "broker.publish");
1537        assert_eq!(reply["params"]["topic"], "plugin.inbound.test");
1538        assert_eq!(reply["params"]["event"]["payload"]["echo"]["foo"], "bar");
1539    }
1540
1541    #[tokio::test]
1542    async fn shutdown_invokes_handler_and_breaks_loop() {
1543        let calls = Arc::new(AtomicU32::new(0));
1544        let calls_clone = calls.clone();
1545        let adapter = PluginAdapter::new(TEST_MANIFEST)
1546            .expect("manifest parses")
1547            .on_shutdown(move || {
1548                let calls = calls_clone.clone();
1549                async move {
1550                    calls.fetch_add(1, Ordering::SeqCst);
1551                    Ok(())
1552                }
1553            });
1554        let (mut host_write, mut host_read, join) = run_adapter_on_duplex(adapter).await;
1555        host_write
1556            .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"shutdown\",\"params\":{}}\n")
1557            .await
1558            .unwrap();
1559        let reply = read_reply_line(&mut host_read).await;
1560        assert_eq!(reply["id"], 7);
1561        assert_eq!(reply["result"]["ok"], true);
1562        // Loop must exit after shutdown.
1563        let res = tokio::time::timeout(std::time::Duration::from_millis(500), join).await;
1564        assert!(
1565            res.is_ok(),
1566            "dispatch loop must exit promptly after shutdown"
1567        );
1568        assert_eq!(calls.load(Ordering::SeqCst), 1);
1569    }
1570
1571    #[tokio::test]
1572    async fn unknown_method_returns_neg_32601() {
1573        let adapter = PluginAdapter::new(TEST_MANIFEST).expect("manifest parses");
1574        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1575        host_write
1576            .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"bogus\",\"params\":{}}\n")
1577            .await
1578            .unwrap();
1579        let reply = read_reply_line(&mut host_read).await;
1580        assert_eq!(reply["id"], 5);
1581        assert_eq!(reply["error"]["code"], -32601);
1582        assert!(reply["error"]["message"]
1583            .as_str()
1584            .unwrap()
1585            .contains("bogus"));
1586    }
1587
1588    #[tokio::test]
1589    async fn parse_error_returns_neg_32700() {
1590        let adapter = PluginAdapter::new(TEST_MANIFEST).expect("manifest parses");
1591        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1592        host_write.write_all(b"not-json\n").await.unwrap();
1593        let reply = read_reply_line(&mut host_read).await;
1594        assert_eq!(reply["error"]["code"], -32700);
1595    }
1596
1597    /// Phase 81.15.c — `BrokerSender::request` issues a JSON-RPC
1598    /// request with an allocated id, then awaits the response on
1599    /// the dispatch loop's pending map. We drive the adapter from
1600    /// inside a `broker.event` handler that calls `request()`,
1601    /// then the test side reads the outgoing request frame from
1602    /// the adapter's stdout, sends a synthetic response back via
1603    /// the adapter's stdin, and asserts the handler observed the
1604    /// expected result. Round-trip end-to-end.
1605    #[tokio::test]
1606    async fn request_helper_round_trips_via_dispatch_loop() {
1607        use std::sync::atomic::{AtomicBool, Ordering};
1608
1609        let observed = Arc::new(AtomicBool::new(false));
1610        let observed_clone = observed.clone();
1611        let adapter = PluginAdapter::new(TEST_MANIFEST)
1612            .expect("manifest parses")
1613            .on_broker_event(
1614                move |_topic, _event, broker: BrokerSender| {
1615                    let observed = observed_clone.clone();
1616                    async move {
1617                        let result = broker
1618                            .request(
1619                                "test.echo",
1620                                serde_json::json!({"x": 1}),
1621                                Some(Duration::from_secs(1)),
1622                            )
1623                            .await;
1624                        match result {
1625                            Ok(v) => {
1626                                assert_eq!(v["echoed"], 1);
1627                                observed.store(true, Ordering::SeqCst);
1628                            }
1629                            Err(e) => {
1630                                panic!("request must succeed, got {e}")
1631                            }
1632                        }
1633                    }
1634                },
1635            );
1636        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1637
1638        // Trigger the handler: send a broker.event notification.
1639        let trigger = serde_json::json!({
1640            "jsonrpc": "2.0",
1641            "method": "broker.event",
1642            "params": {
1643                "topic": "plugin.outbound.test",
1644                "event": {
1645                    "id": "00000000-0000-0000-0000-000000000010",
1646                    "timestamp": "2026-05-01T00:00:00Z",
1647                    "topic": "plugin.outbound.test",
1648                    "source": "host",
1649                    "session_id": null,
1650                    "payload": {}
1651                }
1652            }
1653        });
1654        host_write
1655            .write_all(format!("{}\n", trigger).as_bytes())
1656            .await
1657            .unwrap();
1658
1659        // Read the outgoing request frame the handler issued.
1660        let request_frame = read_reply_line(&mut host_read).await;
1661        assert_eq!(request_frame["method"], "test.echo");
1662        let req_id = request_frame["id"].as_u64().expect("id is u64");
1663        assert!(req_id >= 100, "child ids start at 100, got {req_id}");
1664        assert_eq!(request_frame["params"]["x"], 1);
1665
1666        // Send the response back. Match the id; carry an `echoed`
1667        // value the handler will assert against.
1668        let response = serde_json::json!({
1669            "jsonrpc": "2.0",
1670            "id": req_id,
1671            "result": {"echoed": request_frame["params"]["x"]},
1672        });
1673        host_write
1674            .write_all(format!("{}\n", response).as_bytes())
1675            .await
1676            .unwrap();
1677
1678        // Wait briefly for the handler to observe + assert.
1679        tokio::time::sleep(Duration::from_millis(150)).await;
1680        assert!(
1681            observed.load(Ordering::SeqCst),
1682            "handler must observe the response"
1683        );
1684    }
1685
1686    /// Phase 81.15.c — when the host returns a JSON-RPC error
1687    /// response, `request()` propagates as `RpcError::Server`
1688    /// with the code + message preserved.
1689    #[tokio::test]
1690    async fn request_helper_propagates_server_error() {
1691        use std::sync::atomic::{AtomicBool, Ordering};
1692
1693        let observed = Arc::new(AtomicBool::new(false));
1694        let observed_clone = observed.clone();
1695        let adapter = PluginAdapter::new(TEST_MANIFEST)
1696            .expect("manifest parses")
1697            .on_broker_event(move |_t, _e, broker: BrokerSender| {
1698                let observed = observed_clone.clone();
1699                async move {
1700                    let result = broker
1701                        .request(
1702                            "memory.recall",
1703                            serde_json::json!({"agent_id": "x", "query": "x"}),
1704                            Some(Duration::from_secs(1)),
1705                        )
1706                        .await;
1707                    match result {
1708                        Err(RpcError::Server { code, message }) => {
1709                            assert_eq!(code, -32603);
1710                            assert!(message.contains("not configured"));
1711                            observed.store(true, Ordering::SeqCst);
1712                        }
1713                        other => panic!("expected RpcError::Server, got {other:?}"),
1714                    }
1715                }
1716            });
1717        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1718
1719        // Trigger.
1720        let trigger = serde_json::json!({
1721            "jsonrpc": "2.0",
1722            "method": "broker.event",
1723            "params": {
1724                "topic": "plugin.outbound.test",
1725                "event": {
1726                    "id": "00000000-0000-0000-0000-000000000010",
1727                    "timestamp": "2026-05-01T00:00:00Z",
1728                    "topic": "plugin.outbound.test",
1729                    "source": "host",
1730                    "session_id": null,
1731                    "payload": {}
1732                }
1733            }
1734        });
1735        host_write
1736            .write_all(format!("{}\n", trigger).as_bytes())
1737            .await
1738            .unwrap();
1739
1740        let req = read_reply_line(&mut host_read).await;
1741        let err_resp = serde_json::json!({
1742            "jsonrpc": "2.0",
1743            "id": req["id"],
1744            "error": { "code": -32603, "message": "memory not configured" }
1745        });
1746        host_write
1747            .write_all(format!("{}\n", err_resp).as_bytes())
1748            .await
1749            .unwrap();
1750
1751        tokio::time::sleep(Duration::from_millis(150)).await;
1752        assert!(
1753            observed.load(Ordering::SeqCst),
1754            "handler must observe RpcError::Server"
1755        );
1756    }
1757
1758    /// Phase 81.15.c — when no response arrives within the
1759    /// timeout, `request()` returns `RpcError::Timeout` and
1760    /// the pending entry is removed (so a delayed reply is
1761    /// dropped silently rather than leaking memory).
1762    #[tokio::test]
1763    async fn request_helper_times_out_when_host_silent() {
1764        use std::sync::atomic::{AtomicBool, Ordering};
1765
1766        let observed = Arc::new(AtomicBool::new(false));
1767        let observed_clone = observed.clone();
1768        let adapter = PluginAdapter::new(TEST_MANIFEST)
1769            .expect("manifest parses")
1770            .on_broker_event(move |_t, _e, broker: BrokerSender| {
1771                let observed = observed_clone.clone();
1772                async move {
1773                    let result = broker
1774                        .request(
1775                            "test.silent",
1776                            serde_json::json!({}),
1777                            Some(Duration::from_millis(150)),
1778                        )
1779                        .await;
1780                    match result {
1781                        Err(RpcError::Timeout(_)) => {
1782                            observed.store(true, Ordering::SeqCst);
1783                        }
1784                        other => panic!("expected Timeout, got {other:?}"),
1785                    }
1786                }
1787            });
1788        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1789
1790        let trigger = serde_json::json!({
1791            "jsonrpc": "2.0",
1792            "method": "broker.event",
1793            "params": {
1794                "topic": "plugin.outbound.test",
1795                "event": {
1796                    "id": "00000000-0000-0000-0000-000000000010",
1797                    "timestamp": "2026-05-01T00:00:00Z",
1798                    "topic": "plugin.outbound.test",
1799                    "source": "host",
1800                    "session_id": null,
1801                    "payload": {}
1802                }
1803            }
1804        });
1805        host_write
1806            .write_all(format!("{}\n", trigger).as_bytes())
1807            .await
1808            .unwrap();
1809
1810        // Drain the outgoing request frame so it doesn't pile up;
1811        // never send a response.
1812        let _req = read_reply_line(&mut host_read).await;
1813
1814        tokio::time::sleep(Duration::from_millis(400)).await;
1815        assert!(
1816            observed.load(Ordering::SeqCst),
1817            "handler must observe Timeout"
1818        );
1819    }
1820
1821    /// Phase 81.15.c — `recall_memory()` typed wrapper deserializes
1822    /// the `entries` array from the response into `Vec<MemoryEntry>`.
1823    /// Bad shape surfaces as `RpcError::Decode`.
1824    #[tokio::test]
1825    async fn recall_memory_typed_wrapper_round_trips() {
1826        use std::sync::atomic::{AtomicBool, Ordering};
1827
1828        let observed = Arc::new(AtomicBool::new(false));
1829        let observed_clone = observed.clone();
1830        let adapter = PluginAdapter::new(TEST_MANIFEST)
1831            .expect("manifest parses")
1832            .on_broker_event(move |_t, _e, broker: BrokerSender| {
1833                let observed = observed_clone.clone();
1834                async move {
1835                    let result = broker.recall_memory("agent_x", "preference", 5).await;
1836                    match result {
1837                        Ok(entries) => {
1838                            assert_eq!(entries.len(), 1);
1839                            assert_eq!(entries[0].agent_id, "agent_x");
1840                            observed.store(true, Ordering::SeqCst);
1841                        }
1842                        Err(e) => panic!("recall_memory must succeed, got {e}"),
1843                    }
1844                }
1845            });
1846        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1847
1848        let trigger = serde_json::json!({
1849            "jsonrpc": "2.0",
1850            "method": "broker.event",
1851            "params": {
1852                "topic": "plugin.outbound.test",
1853                "event": {
1854                    "id": "00000000-0000-0000-0000-000000000010",
1855                    "timestamp": "2026-05-01T00:00:00Z",
1856                    "topic": "plugin.outbound.test",
1857                    "source": "host",
1858                    "session_id": null,
1859                    "payload": {}
1860                }
1861            }
1862        });
1863        host_write
1864            .write_all(format!("{}\n", trigger).as_bytes())
1865            .await
1866            .unwrap();
1867
1868        // Adapter issues the memory.recall request; respond with
1869        // a fabricated entries array shaped like nexo_memory::MemoryEntry.
1870        let req = read_reply_line(&mut host_read).await;
1871        assert_eq!(req["method"], "memory.recall");
1872        assert_eq!(req["params"]["agent_id"], "agent_x");
1873        assert_eq!(req["params"]["query"], "preference");
1874        assert_eq!(req["params"]["limit"], 5);
1875        let response = serde_json::json!({
1876            "jsonrpc": "2.0",
1877            "id": req["id"],
1878            "result": {
1879                "entries": [{
1880                    "id": "00000000-0000-0000-0000-000000000001",
1881                    "agent_id": "agent_x",
1882                    "content": "user prefers concise",
1883                    "tags": ["preference"],
1884                    "concept_tags": [],
1885                    "created_at": "2026-05-01T00:00:00Z",
1886                    "memory_type": null
1887                }]
1888            }
1889        });
1890        host_write
1891            .write_all(format!("{}\n", response).as_bytes())
1892            .await
1893            .unwrap();
1894
1895        tokio::time::sleep(Duration::from_millis(150)).await;
1896        assert!(
1897            observed.load(Ordering::SeqCst),
1898            "recall_memory wrapper must deserialize entries"
1899        );
1900    }
1901
1902    /// Phase 81.15.c.b — `complete_llm_stream` returns an
1903    /// `LlmStream` yielding text chunks via `next_chunk()` and
1904    /// resolving `await_final()` once the host sends the final
1905    /// response frame. Test fabricates 3 deltas + a final
1906    /// response, asserts the handler reassembled the text and
1907    /// got the right finish_reason + usage.
1908    #[tokio::test]
1909    async fn complete_llm_stream_yields_chunks_and_final_result() {
1910        use std::sync::atomic::{AtomicBool, Ordering};
1911
1912        let observed = Arc::new(AtomicBool::new(false));
1913        let observed_clone = observed.clone();
1914        let adapter = PluginAdapter::new(TEST_MANIFEST)
1915            .expect("manifest parses")
1916            .on_broker_event(move |_t, _e, broker: BrokerSender| {
1917                let observed = observed_clone.clone();
1918                async move {
1919                    let params = LlmCompleteParams {
1920                        provider: "stub".into(),
1921                        model: "x".into(),
1922                        messages: vec![],
1923                        ..Default::default()
1924                    };
1925                    let mut stream = match broker.complete_llm_stream(params).await {
1926                        Ok(s) => s,
1927                        Err(e) => panic!("complete_llm_stream open failed: {e}"),
1928                    };
1929                    let mut assembled = String::new();
1930                    while let Some(chunk) = stream.next_chunk().await {
1931                        assembled.push_str(&chunk);
1932                    }
1933                    let result = match stream.await_final().await {
1934                        Ok(r) => r,
1935                        Err(e) => panic!("await_final failed: {e}"),
1936                    };
1937                    assert_eq!(assembled, "hello world");
1938                    assert_eq!(result.finish_reason, "stop");
1939                    assert_eq!(result.usage.completion_tokens, 5);
1940                    observed.store(true, Ordering::SeqCst);
1941                }
1942            });
1943        let (mut host_write, mut host_read, _join) = run_adapter_on_duplex(adapter).await;
1944
1945        // Trigger the handler via broker.event.
1946        let trigger = serde_json::json!({
1947            "jsonrpc": "2.0",
1948            "method": "broker.event",
1949            "params": {
1950                "topic": "plugin.outbound.test",
1951                "event": {
1952                    "id": "00000000-0000-0000-0000-000000000010",
1953                    "timestamp": "2026-05-01T00:00:00Z",
1954                    "topic": "plugin.outbound.test",
1955                    "source": "host",
1956                    "session_id": null,
1957                    "payload": {}
1958                }
1959            }
1960        });
1961        host_write
1962            .write_all(format!("{}\n", trigger).as_bytes())
1963            .await
1964            .unwrap();
1965
1966        // Adapter issues llm.complete with stream:true; capture
1967        // the request id then send 3 delta notifications + final
1968        // response.
1969        let req = read_reply_line(&mut host_read).await;
1970        assert_eq!(req["method"], "llm.complete");
1971        assert_eq!(req["params"]["stream"], true);
1972        let req_id = req["id"].clone();
1973        for chunk in ["hello", " ", "world"] {
1974            let delta = serde_json::json!({
1975                "jsonrpc": "2.0",
1976                "method": "llm.complete.delta",
1977                "params": { "request_id": req_id, "chunk": chunk }
1978            });
1979            host_write
1980                .write_all(format!("{}\n", delta).as_bytes())
1981                .await
1982                .unwrap();
1983        }
1984        // After deltas land, send final response. The dispatch
1985        // loop dropping the Streaming pending entry closes
1986        // delta_tx → next_chunk() returns None → handler proceeds
1987        // to await_final.
1988        let final_resp = serde_json::json!({
1989            "jsonrpc": "2.0",
1990            "id": req_id,
1991            "result": {
1992                "content": "",
1993                "finish_reason": "stop",
1994                "usage": { "prompt_tokens": 3, "completion_tokens": 5 }
1995            }
1996        });
1997        host_write
1998            .write_all(format!("{}\n", final_resp).as_bytes())
1999            .await
2000            .unwrap();
2001
2002        tokio::time::sleep(Duration::from_millis(200)).await;
2003        assert!(
2004            observed.load(Ordering::SeqCst),
2005            "handler must reassemble chunks + observe final result"
2006        );
2007    }
2008}