//! Plugin-side helper: read ops from stdin, write responses to stdout. //! //! Plugins can technically implement the protocol directly — it's just //! line-delimited JSON — but every plugin needs the same small //! scaffolding around the handshake, the `init` op, and the //! one-line-per-message write loop. This module provides that so each //! plugin can focus on its per-op logic. use crate::protocol::{ Ack, Answer, Ask, AskKind, ErrorBody, Hello, HelloData, HelloOp, OkFalse, OkTrue, PROTOCOL_VERSION, Request, Terminal, }; use serde::de::DeserializeOwned; use serde_json::{Value, json}; use thiserror::Error; use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader, Stdin, Stdout}; #[derive(Error, Debug)] pub enum PluginError { #[error("Host closed stdin before completing the exchange")] HostClosed, #[error("Invalid JSON from host: {0}")] Decode(String), #[error("I/O error talking to host: {0}")] Io(#[from] std::io::Error), #[error("Unexpected message from host: {0}")] Unexpected(String), } /// Plugin server bound to stdin/stdout. Constructed once at startup; /// call [`Server::handshake`] to send the `hello` response, then loop /// on [`Server::next_request`] until the host closes stdin. pub struct Server { writer: W, reader: R, } impl Server> { /// Bind to the process's real stdin/stdout. pub fn stdio() -> Self { Self { writer: tokio::io::stdout(), reader: BufReader::new(tokio::io::stdin()), } } } impl Server where W: AsyncWrite + Unpin, R: AsyncBufReadExt + Unpin, { pub fn new(writer: W, reader: R) -> Self { Self { writer, reader } } /// Read the `hello` op from the host and reply with the plugin's /// [`HelloData`]. Must be the first call. pub async fn handshake(&mut self, identity: HelloData) -> Result<(), PluginError> { let line = self.read_line().await?; let hello: Hello = serde_json::from_str(&line).map_err(|e| PluginError::Decode(e.to_string()))?; if !matches!(hello.op, HelloOp::Hello) { return Err(PluginError::Unexpected(format!( "expected hello, got `{}`", line ))); } if hello.protocol_version != PROTOCOL_VERSION { return self .reply_err( "protocol_version", &format!( "host speaks v{}, plugin speaks v{PROTOCOL_VERSION}", hello.protocol_version ), false, ) .await; } self.reply_ok(serde_json::to_value(identity).expect("HelloData serialises")) .await } /// Read the next [`Request`] from the host. Returns `None` at EOF. pub async fn next_request(&mut self) -> Result, PluginError> { let line = match self.read_line_opt().await? { Some(l) => l, None => return Ok(None), }; let req: Request = serde_json::from_str(&line).map_err(|e| PluginError::Decode(e.to_string()))?; Ok(Some(req)) } pub async fn reply_ok(&mut self, data: Value) -> Result<(), PluginError> { let t = Terminal::Ok { ok: OkTrue, data }; self.write_line(&t).await } pub async fn reply_err( &mut self, code: &str, message: &str, retryable: bool, ) -> Result<(), PluginError> { let t = Terminal::Err { ok: OkFalse, error: ErrorBody { code: code.to_string(), message: message.to_string(), retryable, }, }; self.write_line(&t).await } /// Send an `ask` and wait for the host's [`Answer`] or [`Ack`]. pub async fn ask(&mut self, kind: AskKind) -> Result { let ask = Ask { kind: kind.clone() }; self.write_line(&ask).await?; let line = self.read_line().await?; // The reply is either an Answer (for prompt/select/confirm) or an // Ack (for open_url/info). The raw shape disambiguates: // { "answer": ... } vs { "ack": true }. let v: Value = serde_json::from_str(&line).map_err(|e| PluginError::Decode(e.to_string()))?; if let Ok(Answer { answer }) = serde_json::from_value::(v.clone()) { Ok(answer) } else if let Ok(Ack { .. }) = serde_json::from_value::(v) { Ok(Value::Null) } else { Err(PluginError::Unexpected(format!( "expected answer/ack, got `{line}`" ))) } } /// Convenience: ask a prompt and extract the single answered field. pub async fn ask_prompt( &mut self, name: &str, label: &str, secret: bool, ) -> Result { let kind = AskKind::Prompt { name: name.to_string(), label: label.to_string(), secret, }; let answer = self.ask(kind).await?; let obj = answer .as_object() .ok_or_else(|| PluginError::Unexpected("answer is not an object".into()))?; let value = obj .get(name) .and_then(|v| v.as_str()) .ok_or_else(|| PluginError::Unexpected(format!("no `{name}` in answer")))?; Ok(value.to_string()) } pub async fn ask_info(&mut self, text: &str) -> Result<(), PluginError> { let _ = self .ask(AskKind::Info { text: text.to_string(), }) .await?; Ok(()) } pub async fn ask_open_url(&mut self, url: &str) -> Result<(), PluginError> { let _ = self .ask(AskKind::OpenUrl { url: url.to_string(), }) .await?; Ok(()) } async fn write_line(&mut self, value: &T) -> Result<(), PluginError> { let mut s = serde_json::to_string(value).expect("plugin message is JSON-serialisable"); s.push('\n'); self.writer.write_all(s.as_bytes()).await?; self.writer.flush().await?; Ok(()) } async fn read_line(&mut self) -> Result { self.read_line_opt().await?.ok_or(PluginError::HostClosed) } async fn read_line_opt(&mut self) -> Result, PluginError> { let mut line = String::new(); let n = self.reader.read_line(&mut line).await?; if n == 0 { return Ok(None); } let trimmed = line.trim_end_matches(['\n', '\r']); if trimmed.is_empty() { return Err(PluginError::Decode("empty line".into())); } Ok(Some(trimmed.to_string())) } } // --------------------------------------------------------------------------- // Convenience helpers for typed params // --------------------------------------------------------------------------- /// Deserialise a [`Request`]'s params into a typed struct. Returns /// `Err(PluginError::Decode)` if the shape is wrong for the op. pub fn params_as(req: &Request) -> Result { serde_json::from_value(req.params.clone()).map_err(|e| PluginError::Decode(e.to_string())) } /// Build the JSON object returned by ops that just want `{"ok": true}` /// semantics with no data payload. pub fn empty_data() -> Value { json!({}) }