From 263c5009de32e2017e9c552418601e6f4ca27498 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:04:54 +0100 Subject: [PATCH 1/7] feat(plugins): let plugins contribute a snapshot to /api/status A plugin that declares `plugin_status` in its manifest publishes a JSON object with `PluginContext::publish_status`. The node keeps the latest one per plugin in its runtime-data collector and shows it at `/api/status.plugin_status.`, under the host's name for the connection, inside a host-owned envelope: schema version, ready, stale or unavailable, receipt time and freshness. Status reads never reach a plugin, and every change wakes `/api/events`. The host refuses undeclared, oversized, non-object and too-frequent publications, and those from a connection that is no longer current. A publication that arrives before initialization finishes waits for it. Disconnects mark the snapshot unavailable; disabling or stopping the plugin removes it. Protocol additions: envelope fields 36/37, `PluginManifest.plugin_status` (field 15) and the `plugin_status.v1` host capability. Refs #2581 --- .../mesh-llm-host-runtime/src/api/mod.rs | 1 + .../mesh-llm-host-runtime/src/api/status.rs | 34 ++ .../src/api/tests/runtime_data.rs | 113 +++++ .../src/mesh/plugin_mesh.rs | 30 +- .../mesh-llm-host-runtime/src/plugin/mod.rs | 2 + .../src/plugin/runtime.rs | 31 +- .../plugin/runtime/default_plugin_policy.rs | 32 ++ .../plugin/runtime/exchange_request_tests.rs | 1 + .../src/plugin/runtime/lifecycle_readiness.rs | 2 + .../runtime/lifecycle_readiness_tests.rs | 1 + .../src/plugin/runtime/status_publication.rs | 244 ++++++++++ .../runtime/status_publication_tests.rs | 245 ++++++++++ .../src/plugin/status_contribution_tests.rs | 141 ++++++ .../src/plugin/transport.rs | 31 ++ .../mesh-llm-host-runtime/src/plugin/types.rs | 15 + .../src/runtime_data/api_views.rs | 2 + .../src/runtime_data/collector.rs | 79 ++++ .../src/runtime_data/mod.rs | 2 + .../src/runtime_data/plugin_status.rs | 426 ++++++++++++++++++ .../mesh-llm-plugin-manager/src/defaults.rs | 4 + .../crates/mesh-llm-plugin/proto/plugin.proto | 38 ++ mesh/crates/mesh-llm-plugin/src/context.rs | 165 +++++++ mesh/crates/mesh-llm-plugin/src/lib.rs | 30 ++ mesh/crates/mesh-llm-plugin/src/manifest.rs | 2 + .../mesh-llm-plugin/src/plugin_status.rs | 197 ++++++++ mesh/crates/mesh-llm-plugin/src/runtime.rs | 15 +- mesh/docs/plugins/README.md | 56 +++ 27 files changed, 1926 insertions(+), 13 deletions(-) create mode 100644 mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication.rs create mode 100644 mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs create mode 100644 mesh/crates/mesh-llm-host-runtime/src/plugin/status_contribution_tests.rs create mode 100644 mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs create mode 100644 mesh/crates/mesh-llm-plugin/src/plugin_status.rs diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs index dce5895765..4a83038b82 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs @@ -1033,6 +1033,7 @@ impl MeshApi { }; payload.logging = crate::logging_runtime_state().map(|state| LoggingStatusPayload::from(state.status())); + payload.plugin_status = runtime_data_collector.plugin_status_payloads(); payload } diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs index c56f901559..71315e4d35 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs @@ -20,6 +20,7 @@ pub(crate) use mesh_llm_control_api::status::metrics::{ pub(crate) use mesh_llm_control_api::status::runtime::*; use serde::Serialize; use skippy_serving::InferenceGuardrailsStatus; +use std::collections::BTreeMap; pub(crate) fn current_runtime_events_summary() -> Option { let engine = crate::runtime_events::runtime_event_engine()?; @@ -391,6 +392,35 @@ pub(crate) struct StatusPayload { /// state has been initialized so older consumers retain their prior shape. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) logging: Option, + /// Snapshots plugins published over their local connections, by the + /// host's name for each plugin; see [`PluginStatusPayload`]. Local-only, + /// and omitted while no plugin contributes, so the shape is unchanged. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub(crate) plugin_status: BTreeMap, +} + +/// One plugin's contribution to `/api/status`. The host owns everything but +/// `data`, which is the plugin's own, in version `schema_version` of its own +/// schema. The state and timestamps say when the host last heard from the +/// plugin, not how old the plugin's readings are. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub(crate) struct PluginStatusPayload { + pub(crate) schema_version: u32, + pub(crate) state: PluginStatusState, + pub(crate) received_at_unix_ms: u64, + pub(crate) fresh_until_unix_ms: u64, + pub(crate) data: serde_json::Value, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum PluginStatusState { + /// Published within the freshness the plugin asked for. + Ready, + /// Its freshness ran out before the plugin published again. + Stale, + /// The plugin connection that published it is gone. + Unavailable, } /// Local-only plugin-mesh frame telemetry. @@ -1059,6 +1089,7 @@ mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; let json = serde_json::to_string(&status).expect("serialization failed"); @@ -1134,6 +1165,7 @@ mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; let json = serde_json::to_string(&status).expect("serialization failed"); @@ -1209,6 +1241,7 @@ mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; let json = serde_json::to_value(&status).expect("serialization failed"); @@ -1279,6 +1312,7 @@ mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; let json = serde_json::to_value(&status).expect("serialization failed"); diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs index 3f027a7f8c..bf7d923880 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs @@ -262,6 +262,119 @@ async fn runtime_data_sse_bridge_delivers_initial_and_incremental_updates() { handle.abort(); } +async fn publish_test_plugin_status( + node: &mesh::Node, + plugin_id: &str, + data_json: &str, +) -> Result { + let (response_tx, response_rx) = oneshot::channel(); + node.forward_plugin_event(plugin::PluginMeshEvent::PluginStatus { + plugin_id: plugin_id.into(), + generation: 1, + schema_version: 1, + request: plugin::proto::PublishPluginStatusRequest { + data_json: data_json.into(), + fresh_for_ms: 0, + }, + response_tx, + }) + .await + .unwrap(); + response_rx.await.unwrap() +} + +#[tokio::test] +async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { + let state = build_test_mesh_api().await; + let node = state.inner.lock().await.node.clone(); + let (addr, handle) = spawn_management_test_server(state.clone()).await; + + let status_body = request_management_json(state.clone(), "/api/status").await; + assert!( + status_body.get("plugin_status").is_none(), + "no contribution, no field" + ); + + let mut events = TcpStream::connect(addr).await.unwrap(); + events + .write_all(b"GET /api/events HTTP/1.1\r\nHost: localhost\r\n\r\n") + .await + .unwrap(); + read_until_contains(&mut events, b"data: {", Duration::from_secs(2)).await; + + publish_test_plugin_status(&node, "powermetrics", r#"{"idle_watts":8.2}"#) + .await + .expect("the snapshot is accepted"); + publish_test_plugin_status(&node, "other", r#"{"ok":true}"#) + .await + .expect("the snapshot is accepted"); + let pushed = read_until_contains(&mut events, b"\"idle_watts\":8.2", Duration::from_secs(2)).await; + assert!(String::from_utf8_lossy(&pushed).contains("\"plugin_status\"")); + + let status_body = request_management_json(state.clone(), "/api/status").await; + let contribution = &status_body["plugin_status"]["powermetrics"]; + assert_eq!(contribution["schema_version"], json!(1)); + assert_eq!(contribution["state"], json!("ready")); + assert_eq!(contribution["data"], json!({"idle_watts": 8.2})); + assert!(contribution["fresh_until_unix_ms"].as_u64() > contribution["received_at_unix_ms"].as_u64()); + assert_eq!(status_body["plugin_status"]["other"]["data"], json!({"ok": true})); + + node.forward_plugin_event(plugin::PluginMeshEvent::PluginDisconnected { + plugin_id: "powermetrics".into(), + generation: 1, + }) + .await + .unwrap(); + read_until_contains(&mut events, b"\"state\":\"unavailable\"", Duration::from_secs(2)).await; + let status_body = request_management_json(state.clone(), "/api/status").await; + assert_eq!( + status_body["plugin_status"]["powermetrics"]["state"], + json!("unavailable") + ); + assert_eq!( + status_body["plugin_status"]["powermetrics"]["data"], + json!({"idle_watts": 8.2}), + "the last snapshot stays, shown as unavailable" + ); + + for plugin_id in ["powermetrics", "other"] { + node.forward_plugin_event(plugin::PluginMeshEvent::PluginStopped { + plugin_id: plugin_id.into(), + }) + .await + .unwrap(); + } + let status_body = request_management_json(state.clone(), "/api/status").await; + assert!(status_body.get("plugin_status").is_none()); + + drop(events); + handle.abort(); +} + +#[tokio::test] +async fn a_refused_plugin_status_says_why_and_changes_nothing() { + let state = build_test_mesh_api().await; + let node = state.inner.lock().await.node.clone(); + + let error = publish_test_plugin_status(&node, "powermetrics", "[1, 2]") + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::INVALID_PARAMS.0); + assert!(error.message.contains("must be a JSON object"), "{}", error.message); + + let oversized = format!( + r#"{{"pad":"{}"}}"#, + "x".repeat(mesh_llm_plugin::plugin_status::MAX_DATA_BYTES) + ); + let error = publish_test_plugin_status(&node, "powermetrics", &oversized) + .await + .unwrap_err(); + assert!(error.message.contains("the limit is 16384"), "{}", error.message); + + let status_body = request_management_json(state, "/api/status").await; + assert!(status_body.get("plugin_status").is_none()); +} + #[tokio::test] async fn api_runtime_reads_from_collector_snapshot() { let state = build_test_mesh_api().await; diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs index 6dac6af4d1..e2c6b22d76 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs @@ -246,10 +246,38 @@ impl Node { let _ = response_tx.send(self.apply_plugin_key_request(&plugin_id, request)); Ok(()) } + crate::plugin::PluginMeshEvent::PluginStatus { + plugin_id, + generation, + schema_version, + request, + response_tx, + } => { + let response = self + .runtime_data_collector() + .publish_plugin_status(&plugin_id, generation, schema_version, &request) + .map_err(|rejection| crate::plugin::proto::ErrorResponse { + code: rmcp::model::ErrorCode::INVALID_PARAMS.0, + message: rejection.message(&plugin_id), + data_json: String::new(), + }); + let _ = response_tx.send(response); + Ok(()) + } + crate::plugin::PluginMeshEvent::PluginDisconnected { + plugin_id, + generation, + } => { + self.runtime_data_collector() + .mark_plugin_status_unavailable(&plugin_id, generation); + Ok(()) + } crate::plugin::PluginMeshEvent::PluginStopped { plugin_id } => { // A disabled or removed plugin no longer runs here, so this - // node stops vouching for its key. + // node stops vouching for its key and showing its status. self.plugin_keys.remove_own(&plugin_id); + self.runtime_data_collector() + .remove_plugin_status(&plugin_id); Ok(()) } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs index 1f149d9ad8..c1b8b1219f 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs @@ -1736,5 +1736,7 @@ pub async fn run_plugin_process(name: String, args: Vec) -> Result<()> { } } +#[cfg(test)] +mod status_contribution_tests; #[cfg(test)] mod tests; diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs index beec042c05..f0e6a0d99d 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs @@ -32,8 +32,10 @@ mod identity_artifact; mod lifecycle_readiness; mod shutdown; mod socket_auth; +pub(crate) mod status_publication; use self::default_plugin_policy::restrict_default_plugin; +use self::status_publication::StatusDeclaration; /// How long a stopping plugin waits to tell the node to withdraw its key. const PLUGIN_STOPPED_SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1); @@ -65,6 +67,8 @@ pub(crate) struct PluginRuntime { pub(crate) generation: u64, pub(crate) authenticated_peer: bool, pub(crate) initialized_lifecycle: Option>, + /// What this generation's manifest says about `/api/status`. + pub(crate) status_declaration: StatusDeclaration, pub(crate) _child: Option, connection_task: tokio::task::JoinHandle<()>, pub(crate) outbound_tx: mpsc::Sender, @@ -318,6 +322,7 @@ impl ExternalPlugin { generation, authenticated_peer, initialized_lifecycle: None, + status_declaration: StatusDeclaration::Pending, _child: child, connection_task, outbound_tx, @@ -347,6 +352,7 @@ impl ExternalPlugin { mesh_llm_plugin::host_capabilities::PEER_BLOCKS.to_string(), mesh_llm_plugin::host_capabilities::OPENAI_EXCHANGE.to_string(), mesh_llm_plugin::host_capabilities::PLUGIN_KEYS.to_string(), + mesh_llm_plugin::host_capabilities::PLUGIN_STATUS.to_string(), ], }), Some(self.spec.startup.init_timeout()), @@ -434,6 +440,7 @@ impl ExternalPlugin { manifest.openai_exchange_hook.as_deref(), self.spec.openai_exchange_grant.as_deref(), )?; + status_publication::validate_declaration(&self.spec.name, manifest)?; } Ok(()) } @@ -918,11 +925,29 @@ impl ExternalPlugin { failed_runtime }; if let Some(runtime) = failed_runtime { + let generation = runtime.generation; stop_runtime(runtime, &reason).await; + self.announce_disconnected(generation).await; } self.publish_summary().await; } + /// Tell the node that connection `generation` is gone, so what it + /// published to `/api/status` shows as unavailable. Bounded like + /// [`Self::announce_stopped`]. + async fn announce_disconnected(&self, generation: u64) { + let _ = self + .mesh_tx + .send_timeout( + PluginMeshEvent::PluginDisconnected { + plugin_id: self.spec.name.clone(), + generation, + }, + PLUGIN_STOPPED_SEND_TIMEOUT, + ) + .await; + } + async fn disabled_reason(&self) -> Option { let summary = self.summary.lock().await; if summary.status == "disabled" { @@ -1209,7 +1234,7 @@ pub(crate) mod tests { plugin_for_spec_with_mesh_tx(spec, mesh_tx) } - fn plugin_for_spec_with_mesh_tx( + pub(super) fn plugin_for_spec_with_mesh_tx( spec: ExternalPluginSpec, mesh_tx: mpsc::Sender, ) -> (ExternalPlugin, RuntimeDataCollector) { @@ -1292,7 +1317,7 @@ pub(crate) mod tests { command } - async fn mark_plugin_running(plugin: &ExternalPlugin, generation: u64) { + pub(super) async fn mark_plugin_running(plugin: &ExternalPlugin, generation: u64) { let child = sleeping_test_command() .kill_on_drop(true) .spawn() @@ -1303,6 +1328,7 @@ pub(crate) mod tests { generation, authenticated_peer: true, initialized_lifecycle: None, + status_declaration: StatusDeclaration::Pending, _child: Some(child), connection_task: tokio::spawn(std::future::pending::<()>()), outbound_tx, @@ -1871,6 +1897,7 @@ pub(crate) mod tests { generation: 1, authenticated_peer: true, initialized_lifecycle: None, + status_declaration: StatusDeclaration::Pending, _child: Some(child), connection_task: tokio::spawn(std::future::pending::<()>()), outbound_tx: outbound_tx.clone(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs index da79e2f4fb..2eb1d6d149 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs @@ -72,6 +72,9 @@ pub(super) fn restrict_default_plugin( if !may(Surface::OpenAiExchangeHook) && manifest.openai_exchange_hook.take().is_some() { removed.push(Surface::OpenAiExchangeHook.name()); } + if !may(Surface::StatusContributions) && manifest.plugin_status.take().is_some() { + removed.push(Surface::StatusContributions.name()); + } } if capabilities_removed { removed.push("capabilities"); @@ -163,6 +166,35 @@ mod tests { assert_eq!(removed, ["OpenAI exchange hook"]); } + #[test] + fn a_default_keeps_its_status_contribution_only_when_its_entry_allows_it() { + let with_status = || proto::InitializeResponse { + manifest: Some(proto::PluginManifest { + plugin_status: Some(proto::PluginStatusManifest { + schema_version: 1, + required: false, + }), + ..Default::default() + }), + ..Default::default() + }; + + let mut init = with_status(); + let removed = restrict_default_plugin(&mut init, &[Surface::WebUi], &[]); + assert_eq!(removed, ["status contributions"]); + assert!(init.manifest.unwrap().plugin_status.is_none()); + + let mut init = with_status(); + let removed = restrict_default_plugin(&mut init, &[Surface::StatusContributions], &[]); + assert!(removed.is_empty()); + assert!(init.manifest.unwrap().plugin_status.is_some()); + + // Unlike the exchange hook, it shows only the plugin's own data, so an + // unlisted default keeps it. + let mut init = with_status(); + assert!(restrict_default_plugin(&mut init, UNLISTED_DEFAULT_ALLOWS, &[]).is_empty()); + } + #[test] fn a_default_within_its_allowlist_loses_nothing_and_warns_of_nothing() { let mut init = proto::InitializeResponse { diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs index ff752ce808..dcd00dcab4 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs @@ -24,6 +24,7 @@ async fn running_observer() -> (Arc, mpsc::Receiver) -> Self { + match manifest.and_then(|manifest| manifest.plugin_status.as_ref()) { + Some(status) => Self::Declared { + schema_version: status.schema_version, + }, + None => Self::Undeclared, + } + } +} + +/// Refuse a declaration whose schema version is 0: versions start at 1. +pub(crate) fn validate_declaration( + plugin_name: &str, + manifest: &proto::PluginManifest, +) -> anyhow::Result<()> { + if manifest + .plugin_status + .as_ref() + .is_some_and(|status| status.schema_version == 0) + { + anyhow::bail!( + "Plugin '{plugin_name}' declares a status contribution with schema_version 0; it starts at 1" + ); + } + Ok(()) +} + +/// Publications a lane holds before it answers new ones as busy. The host +/// accepts one a second, so a well-behaved plugin never has more than one. +const LANE_CAPACITY: usize = 4; +/// How long a publication waits for its connection to finish initializing, +/// and then for the node to answer. +const PUBLICATION_TIMEOUT: Duration = Duration::from_secs(crate::plugin::REQUEST_TIMEOUT_SECS); +const INITIALIZATION_POLL: Duration = Duration::from_millis(10); + +type Publication = (u64, proto::PublishPluginStatusRequest); + +pub(crate) struct StatusLane { + plugin_name: String, + tx: mpsc::Sender, + outbound_tx: mpsc::Sender, +} + +impl StatusLane { + /// Start the lane for connection `generation` of `plugin_name`. It ends + /// when the lane is dropped and its queue is drained. + pub(crate) fn spawn( + plugin_name: String, + generation: u64, + runtime: Arc>>, + mesh_tx: mpsc::Sender, + outbound_tx: mpsc::Sender, + ) -> Self { + let (tx, mut rx) = mpsc::channel::(LANE_CAPACITY); + let lane = Self { + plugin_name: plugin_name.clone(), + tx, + outbound_tx: outbound_tx.clone(), + }; + tokio::spawn(async move { + while let Some((request_id, request)) = rx.recv().await { + let payload = match publish(&plugin_name, generation, &runtime, &mesh_tx, request) + .await + { + Ok(response) => proto::envelope::Payload::PublishPluginStatusResponse(response), + Err(error) => proto::envelope::Payload::ErrorResponse(error), + }; + let _ = outbound_tx + .send(envelope(&plugin_name, request_id, payload)) + .await; + } + }); + lane + } + + /// Queue a publication without waiting; a full lane answers it at once. + pub(crate) fn push(&self, request_id: u64, request: proto::PublishPluginStatusRequest) { + if let Err(mpsc::error::TrySendError::Full(_)) = self.tx.try_send((request_id, request)) { + let outbound_tx = self.outbound_tx.clone(); + let reply = envelope( + &self.plugin_name, + request_id, + proto::envelope::Payload::ErrorResponse(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{}` has {LANE_CAPACITY} status publications waiting; retry later", + self.plugin_name + ), + )), + ); + tokio::spawn(async move { + let _ = outbound_tx.send(reply).await; + }); + } + } +} + +async fn publish( + plugin_name: &str, + generation: u64, + runtime: &Mutex>, + mesh_tx: &mpsc::Sender, + request: proto::PublishPluginStatusRequest, +) -> Result { + let deadline = tokio::time::Instant::now() + PUBLICATION_TIMEOUT; + let response_rx = + hand_over(plugin_name, generation, runtime, mesh_tx, request, deadline).await?; + match tokio::time::timeout_at(deadline, response_rx).await { + Ok(Ok(response)) => response, + Ok(Err(_)) => Err(error( + ErrorCode::INTERNAL_ERROR, + "status publication handler dropped the response", + )), + Err(_) => Err(error( + ErrorCode::INTERNAL_ERROR, + "status publication timed out", + )), + } +} + +type PublicationResponse = + oneshot::Receiver>; + +async fn hand_over( + plugin_name: &str, + generation: u64, + runtime: &Mutex>, + mesh_tx: &mpsc::Sender, + request: proto::PublishPluginStatusRequest, + deadline: tokio::time::Instant, +) -> Result { + loop { + { + let runtime = runtime.lock().await; + let Some(current) = runtime + .as_ref() + .filter(|runtime| runtime.generation == generation) + else { + return Err(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{plugin_name}` published its status from a connection that is no longer current" + ), + )); + }; + match current.status_declaration { + StatusDeclaration::Pending => {} + StatusDeclaration::Undeclared => { + return Err(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{plugin_name}` does not declare `plugin_status` in its manifest" + ), + )); + } + StatusDeclaration::Declared { schema_version } => { + let (response_tx, response_rx) = oneshot::channel(); + // Still under the runtime lock: see the module docs. + return match mesh_tx.try_send(PluginMeshEvent::PluginStatus { + plugin_id: plugin_name.to_string(), + generation, + schema_version, + request, + response_tx, + }) { + Ok(()) => Ok(response_rx), + Err(mpsc::error::TrySendError::Full(_)) => Err(error( + ErrorCode::INTERNAL_ERROR, + "the node is busy; retry the status publication later", + )), + Err(mpsc::error::TrySendError::Closed(_)) => Err(error( + ErrorCode::INTERNAL_ERROR, + "status publication handler is unavailable", + )), + }; + } + } + } + if tokio::time::Instant::now() >= deadline { + return Err(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{plugin_name}` published its status before it finished initializing" + ), + )); + } + tokio::time::sleep(INITIALIZATION_POLL).await; + } +} + +fn envelope( + plugin_name: &str, + request_id: u64, + payload: proto::envelope::Payload, +) -> proto::Envelope { + proto::Envelope { + protocol_version: PROTOCOL_VERSION, + plugin_id: plugin_name.to_string(), + request_id, + payload: Some(payload), + } +} + +fn error(code: ErrorCode, message: impl Into) -> proto::ErrorResponse { + proto::ErrorResponse { + code: code.0, + message: message.into(), + data_json: String::new(), + } +} + +#[cfg(test)] +#[path = "status_publication_tests.rs"] +mod tests; diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs new file mode 100644 index 0000000000..aef8c007fa --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs @@ -0,0 +1,245 @@ +use super::super::tests as runtime_tests; +use super::*; +use std::collections::HashMap; + +fn runtime_with(generation: u64, declaration: StatusDeclaration) -> PluginRuntime { + let (outbound_tx, _outbound_rx) = mpsc::channel(4); + PluginRuntime { + generation, + authenticated_peer: false, + initialized_lifecycle: None, + status_declaration: declaration, + _child: None, + connection_task: tokio::spawn(std::future::pending()), + outbound_tx, + pending: Arc::new(Mutex::new(HashMap::new())), + } +} + +struct Harness { + runtime: Arc>>, + lane: StatusLane, + mesh_rx: mpsc::Receiver, + outbound_rx: mpsc::Receiver, +} + +fn harness(lane_generation: u64, runtime: Option) -> Harness { + let runtime = Arc::new(Mutex::new(runtime)); + let (mesh_tx, mesh_rx) = mpsc::channel(8); + let (outbound_tx, outbound_rx) = mpsc::channel(8); + let lane = StatusLane::spawn( + "demo".into(), + lane_generation, + runtime.clone(), + mesh_tx, + outbound_tx, + ); + Harness { + runtime, + lane, + mesh_rx, + outbound_rx, + } +} + +fn publication(data_json: &str) -> proto::PublishPluginStatusRequest { + proto::PublishPluginStatusRequest { + data_json: data_json.into(), + fresh_for_ms: 0, + } +} + +async fn reply(outbound_rx: &mut mpsc::Receiver) -> proto::Envelope { + tokio::time::timeout(Duration::from_secs(5), outbound_rx.recv()) + .await + .expect("the lane answers") + .expect("the lane is open") +} + +fn error_message(envelope: proto::Envelope) -> String { + match envelope.payload { + Some(proto::envelope::Payload::ErrorResponse(error)) => error.message, + other => panic!("expected an error, got {other:?}"), + } +} + +#[tokio::test] +async fn a_publication_sent_before_initialization_finishes_waits_for_it() { + let mut h = harness(3, Some(runtime_with(3, StatusDeclaration::Pending))); + h.lane.push(11, publication(r#"{"watts":8.2}"#)); + + tokio::time::sleep(Duration::from_millis(50)).await; + assert!( + h.mesh_rx.try_recv().is_err(), + "nothing before initialization" + ); + h.runtime.lock().await.as_mut().unwrap().status_declaration = + StatusDeclaration::Declared { schema_version: 2 }; + + let event = tokio::time::timeout(Duration::from_secs(5), h.mesh_rx.recv()) + .await + .unwrap() + .unwrap(); + let PluginMeshEvent::PluginStatus { + plugin_id, + generation, + schema_version, + request, + response_tx, + } = event + else { + panic!("expected a status publication"); + }; + assert_eq!(plugin_id, "demo", "the host's name for the connection"); + assert_eq!((generation, schema_version), (3, 2)); + assert_eq!(request.data_json, r#"{"watts":8.2}"#); + response_tx + .send(Ok(proto::PublishPluginStatusResponse { + received_at_unix_ms: 1, + fresh_until_unix_ms: 2, + })) + .unwrap(); + + let answer = reply(&mut h.outbound_rx).await; + assert_eq!(answer.request_id, 11); + assert_eq!(answer.plugin_id, "demo"); + assert!(matches!( + answer.payload, + Some(proto::envelope::Payload::PublishPluginStatusResponse(ref response)) + if response.fresh_until_unix_ms == 2 + )); +} + +#[tokio::test] +async fn a_plugin_that_does_not_declare_it_is_refused() { + let mut h = harness(3, Some(runtime_with(3, StatusDeclaration::Undeclared))); + h.lane.push(1, publication("{}")); + let message = error_message(reply(&mut h.outbound_rx).await); + assert!( + message.contains("does not declare `plugin_status`"), + "{message}" + ); + assert!(h.mesh_rx.try_recv().is_err()); +} + +#[tokio::test] +async fn a_connection_that_is_no_longer_current_is_refused() { + let declared = StatusDeclaration::Declared { schema_version: 1 }; + // The plugin restarted: the runtime is a later connection's. + let mut h = harness(3, Some(runtime_with(4, declared))); + h.lane.push(1, publication("{}")); + let message = error_message(reply(&mut h.outbound_rx).await); + assert!(message.contains("no longer current"), "{message}"); + + // The connection is gone, and the runtime with it. + let mut h = harness(3, None); + h.lane.push(1, publication("{}")); + let message = error_message(reply(&mut h.outbound_rx).await); + assert!(message.contains("no longer current"), "{message}"); + assert!(h.mesh_rx.try_recv().is_err()); +} + +#[tokio::test] +async fn publications_reach_the_node_in_the_order_they_were_sent() { + let declared = StatusDeclaration::Declared { schema_version: 1 }; + let mut h = harness(3, Some(runtime_with(3, declared))); + for (id, data) in [(1, r#"{"n":1}"#), (2, r#"{"n":2}"#), (3, r#"{"n":3}"#)] { + h.lane.push(id, publication(data)); + } + for expected in [r#"{"n":1}"#, r#"{"n":2}"#, r#"{"n":3}"#] { + let Some(PluginMeshEvent::PluginStatus { + request, + response_tx, + .. + }) = h.mesh_rx.recv().await + else { + panic!("expected a status publication"); + }; + assert_eq!(request.data_json, expected); + response_tx + .send(Ok(proto::PublishPluginStatusResponse::default())) + .unwrap(); + } + let ids = [ + reply(&mut h.outbound_rx).await.request_id, + reply(&mut h.outbound_rx).await.request_id, + reply(&mut h.outbound_rx).await.request_id, + ]; + assert_eq!(ids, [1, 2, 3]); +} + +#[tokio::test] +async fn a_full_lane_answers_busy_at_once() { + // The first publication waits for initialization, so the next ones queue. + let mut h = harness(3, Some(runtime_with(3, StatusDeclaration::Pending))); + h.lane.push(1, publication("{}")); + tokio::time::sleep(Duration::from_millis(20)).await; + for id in 2..=(LANE_CAPACITY as u64 + 1) { + h.lane.push(id, publication("{}")); + } + h.lane.push(99, publication("{}")); + let answer = reply(&mut h.outbound_rx).await; + assert_eq!(answer.request_id, 99); + let message = error_message(answer); + assert!(message.contains("retry later"), "{message}"); +} + +#[tokio::test] +async fn a_failed_connection_tells_the_node_its_status_is_unavailable() { + let temp = tempfile::tempdir().unwrap(); + let (mesh_tx, mut mesh_rx) = mpsc::channel(8); + let (plugin, _runtime_data) = runtime_tests::plugin_for_spec_with_mesh_tx( + runtime_tests::plugin_spec( + &temp, + None, + mesh_llm_plugin_manager::store::InstalledPluginWebUiValidationStatus::Valid, + None, + ), + mesh_tx, + ); + runtime_tests::mark_plugin_running(&plugin, 4).await; + + plugin + .handle_runtime_failure(Some(4), "plugin exited".into()) + .await; + let mut disconnected = Vec::new(); + while let Ok(event) = mesh_rx.try_recv() { + if let PluginMeshEvent::PluginDisconnected { + plugin_id, + generation, + } = event + { + disconnected.push((plugin_id, generation)); + } + } + assert_eq!(disconnected, vec![("demo".to_string(), 4)]); + + // No runtime, nothing to announce. + plugin + .handle_runtime_failure(None, "plugin exited".into()) + .await; + assert!(mesh_rx.try_recv().is_err()); +} + +#[test] +fn a_declaration_must_name_a_schema_version() { + let manifest = |schema_version| proto::PluginManifest { + plugin_status: Some(proto::PluginStatusManifest { + schema_version, + required: false, + }), + ..Default::default() + }; + let error = validate_declaration("demo", &manifest(0)).unwrap_err(); + assert!(error.to_string().contains("schema_version 0"), "{error}"); + validate_declaration("demo", &manifest(1)).unwrap(); + validate_declaration("demo", &proto::PluginManifest::default()).unwrap(); + assert_eq!( + StatusDeclaration::from_manifest(Some(&manifest(3))), + StatusDeclaration::Declared { schema_version: 3 } + ); + assert_eq!( + StatusDeclaration::from_manifest(Some(&proto::PluginManifest::default())), + StatusDeclaration::Undeclared + ); +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/status_contribution_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/status_contribution_tests.rs new file mode 100644 index 0000000000..f6f027b769 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/status_contribution_tests.rs @@ -0,0 +1,141 @@ +//! Status contributions over the real plugin protocol: from an SDK plugin +//! publishing in `on_initialized` to the node's `/api/status` data. + +use super::*; +use crate::api::status::PluginStatusState; +use crate::plugin::{InProcessPluginRunner, InProcessPlugins, config}; +use mesh_llm_plugin::{PluginMetadata, PluginRuntime, SimplePlugin}; +use std::time::Duration; + +type PublishResults = mpsc::Sender<(String, std::result::Result<(), String>)>; + +/// A plugin that publishes `{"from": }` as soon as it is initialized and +/// reports how that went. +fn publisher(name: &'static str, declares: bool, results: PublishResults) -> InProcessPluginRunner { + Arc::new(move |stream| { + let mut manifest = mesh_llm_plugin::plugin_manifest(); + if declares { + manifest = manifest.item(mesh_llm_plugin::plugin_status::plugin_status(1)); + } + let results = results.clone(); + let plugin = SimplePlugin::new( + PluginMetadata::new( + name, + "1.0.0", + mesh_llm_plugin::plugin_server_info( + name, + "1.0.0", + "Publisher", + "Publishes its status", + None::, + ), + ) + .with_manifest(manifest.build()), + ) + .on_initialized(move |context| { + let results = results.clone(); + Box::pin(async move { + let published = context + .publish_status(&serde_json::json!({"from": name}), Duration::from_secs(30)) + .await + .map(|_| ()) + .map_err(|error| error.to_string()); + let _ = results.send((name.to_string(), published)).await; + Ok(()) + }) + }); + Box::pin(PluginRuntime::run_with_stream(plugin, stream)) + }) +} + +async fn start( + plugins: &[(&'static str, bool)], +) -> ( + PluginManager, + crate::mesh::Node, + mpsc::Receiver<(String, std::result::Result<(), String>)>, +) { + let node = crate::mesh::Node::new_for_tests(crate::mesh::NodeRole::Worker) + .await + .unwrap(); + let (mesh_tx, mesh_rx) = mpsc::channel(16); + node.start_plugin_channel_forwarder(mesh_rx); + let (results_tx, results_rx) = mpsc::channel(8); + let mut in_process = InProcessPlugins::default(); + let mut externals = Vec::new(); + for &(name, declares) in plugins { + in_process = in_process.with(name, publisher(name, declares, results_tx.clone())); + let mut spec = config::in_process_builtin_spec(name); + spec.startup.optional = false; + externals.push(spec); + } + let manager = PluginManager::start_with_in_process( + &config::ResolvedPlugins { + externals, + inactive: Vec::new(), + }, + config::PluginHostMode { + mesh_visibility: mesh_llm_plugin::MeshVisibility::Private, + }, + mesh_tx, + in_process, + ) + .await + .unwrap(); + (manager, node, results_rx) +} + +async fn results( + rx: &mut mpsc::Receiver<(String, std::result::Result<(), String>)>, + count: usize, +) -> BTreeMap> { + let mut out = BTreeMap::new(); + while out.len() < count { + let (name, result) = tokio::time::timeout(Duration::from_secs(10), rx.recv()) + .await + .expect("every plugin reports its publication") + .unwrap(); + out.insert(name, result); + } + out +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plugins_publishing_on_initialization_show_up_in_the_node_status() { + let (manager, node, mut results_rx) = + start(&[("alpha", true), ("beta", true), ("gamma", false)]).await; + + let results = results(&mut results_rx, 3).await; + assert_eq!(results["alpha"], Ok(())); + assert_eq!(results["beta"], Ok(())); + let refused = results["gamma"].as_ref().unwrap_err(); + assert!( + refused.contains("does not declare `plugin_status`"), + "{refused}" + ); + + let payloads = node.runtime_data_collector().plugin_status_payloads(); + assert_eq!( + payloads.keys().collect::>(), + ["alpha", "beta"], + "a plugin that does not declare it contributes nothing" + ); + for name in ["alpha", "beta"] { + assert_eq!(payloads[name].state, PluginStatusState::Ready); + assert_eq!(payloads[name].data, serde_json::json!({"from": name})); + } + + // Shutting the plugins down removes what they contributed. + manager.shutdown().await; + tokio::time::timeout(Duration::from_secs(5), async { + while !node + .runtime_data_collector() + .plugin_status_payloads() + .is_empty() + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("stopped plugins no longer contribute"); +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs index 2ff2747cd4..82f33afc70 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs @@ -32,6 +32,8 @@ const PLUGIN_ENVELOPE_BODY_READ_TIMEOUT: Duration = Duration::from_secs(30); const PLUGIN_ENVELOPE_TEST_READ_TIMEOUT: Duration = Duration::from_secs(1); const PLUGIN_MESH_STREAM_RESPONSE_TIMEOUT: Duration = Duration::from_secs(super::REQUEST_TIMEOUT_SECS); +/// Bounded: a node that is itself stopping may not read it. +const PLUGIN_DISCONNECTED_SEND_TIMEOUT: Duration = Duration::from_secs(1); fn plugin_mesh_stream_error(message: impl Into) -> super::proto::ErrorResponse { super::proto::ErrorResponse { @@ -90,6 +92,8 @@ pub(crate) const CONNECTION_LOOP: ConnectionLoopFn = let authenticated_peer = peer_state.load(Ordering::Acquire); Box::pin(async move { let result: Result<()> = async { + // Started by the first status publication, if any. + let mut status_lane = None; loop { tokio::select! { maybe_outbound = outbound_rx.recv() => { @@ -163,6 +167,21 @@ pub(crate) const CONNECTION_LOOP: ConnectionLoopFn = outbound_tx.clone(), ); } + Some(super::proto::envelope::Payload::PublishPluginStatusRequest(request)) => { + // Shown under the connection's own name, + // so one plugin cannot publish as another. + status_lane + .get_or_insert_with(|| { + super::runtime::status_publication::StatusLane::spawn( + plugin_name.clone(), + generation, + runtime.clone(), + mesh_tx.clone(), + outbound_tx.clone(), + ) + }) + .push(request_id, request); + } Some(super::proto::envelope::Payload::RpcRequest(request)) => { forward_plugin_request( plugin_name.clone(), @@ -227,6 +246,18 @@ pub(crate) const CONNECTION_LOOP: ConnectionLoopFn = let mut summary = summary.lock().await; summary.status = "stopped".into(); summary.error = Some(format!("Plugin '{}' disconnected", plugin_name)); + drop(summary); + // What this connection published to `/api/status` is now + // shown as unavailable. + let _ = mesh_tx + .send_timeout( + PluginMeshEvent::PluginDisconnected { + plugin_id: plugin_name.clone(), + generation, + }, + PLUGIN_DISCONNECTED_SEND_TIMEOUT, + ) + .await; } let mut pending = pending.lock().await; diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs index 3e86bd6663..7ef0ee60f0 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs @@ -42,6 +42,21 @@ pub enum PluginMeshEvent { request: proto::PluginKeyRequest, response_tx: oneshot::Sender>, }, + /// A snapshot for `/api/status`, from the plugin's current initialized + /// connection `generation`, whose manifest declares `schema_version`. + /// `plugin_id` is the host's name for the plugin connection. + PluginStatus { + plugin_id: String, + generation: u64, + schema_version: u32, + request: proto::PublishPluginStatusRequest, + response_tx: + oneshot::Sender>, + }, + /// The plugin connection `generation` is gone (it closed, or failed and + /// the plugin restarts): what it published to `/api/status` is shown as + /// unavailable until a later connection publishes. + PluginDisconnected { plugin_id: String, generation: u64 }, /// The plugin stopped for good (disabled, or shut down): the host /// withdraws what it announced for it. Not sent when the plugin restarts /// after a failure, so its key stays announced across a restart. diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs index dab517c2d8..f9b610f10c 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs @@ -85,6 +85,7 @@ pub(crate) fn status_payload(snapshot: StatusViewSnapshot) -> StatusPayload { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), } } @@ -253,6 +254,7 @@ mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; assert_eq!( diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs index c164407ad9..c1d064d0aa 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs @@ -10,6 +10,7 @@ use super::inventory::{ InventoryScanCoordinator, InventoryScanDisposition, InventoryScanError, InventoryScanOutcome, InventoryScanResult, replace_local_instances_snapshot, replace_local_inventory_snapshot, }; +use super::plugin_status::{PluginStatusRejection, PluginStatusStore}; use super::plugins::{ PluginDataValue, PluginsSnapshotView, clear_plugin_data, clear_plugin_endpoints, plugins_snapshot, upsert_plugin_data, upsert_plugin_endpoint, @@ -49,6 +50,8 @@ use tokio::sync::watch; #[derive(Default)] struct RuntimeDataSharedState { snapshots: RwLock, + /// Apart from `snapshots`, so that cloning them does not copy plugin data. + plugin_status: Mutex, subscriptions: RuntimeDataSubscriptions, inventory_scan: Mutex, event_cutover_health: ShadowHealth, @@ -387,6 +390,82 @@ impl RuntimeDataCollector { }) } + /// Keep `request` as `plugin_name`'s contribution to `/api/status`. The + /// caller vouches that it comes from the plugin's current initialized + /// connection `generation`, whose manifest declares `schema_version`. + pub(crate) fn publish_plugin_status( + &self, + plugin_name: &str, + generation: u64, + schema_version: u32, + request: &crate::plugin::proto::PublishPluginStatusRequest, + ) -> Result { + let mut store = self.plugin_status_store(); + let accepted = store.publish( + plugin_name, + generation, + schema_version, + request, + tokio::time::Instant::now(), + crate::mesh::current_time_unix_ms(), + )?; + if let Some(fresh_for) = accepted.fresh_for + && let Some(expiry) = self.wake_status_after(fresh_for) + { + store.set_expiry(plugin_name, expiry); + } + drop(store); + self.shared.subscriptions.publish(RuntimeDataDirty::STATUS); + Ok(accepted.response) + } + + /// The plugin connection `generation` is gone: its snapshot stays, shown + /// as unavailable. + pub(crate) fn mark_plugin_status_unavailable(&self, plugin_name: &str, generation: u64) { + let changed = self + .plugin_status_store() + .mark_unavailable(plugin_name, generation); + if changed { + self.shared.subscriptions.publish(RuntimeDataDirty::STATUS); + } + } + + /// The plugin stopped for good: its snapshot goes. + pub(crate) fn remove_plugin_status(&self, plugin_name: &str) { + let changed = self.plugin_status_store().remove(plugin_name); + if changed { + self.shared.subscriptions.publish(RuntimeDataDirty::STATUS); + } + } + + pub(crate) fn plugin_status_payloads( + &self, + ) -> BTreeMap { + self.plugin_status_store() + .payloads(tokio::time::Instant::now()) + } + + fn plugin_status_store(&self) -> std::sync::MutexGuard<'_, PluginStatusStore> { + self.shared + .plugin_status + .lock() + .expect("runtime data plugin status lock poisoned") + } + + /// Mark status dirty once `after` has passed, so `/api/events` sends the + /// snapshot turning stale. Holds the collector weakly. + fn wake_status_after(&self, after: std::time::Duration) -> Option { + let runtime = tokio::runtime::Handle::try_current().ok()?; + let shared = Arc::downgrade(&self.shared); + let task = runtime.spawn(async move { + tokio::time::sleep(after).await; + if let Some(shared) = shared.upgrade() { + shared.subscriptions.publish(RuntimeDataDirty::STATUS); + } + }); + Some(task.abort_handle()) + } + pub(crate) fn build_hardware_view(&self, input: HardwareViewInput) -> HardwareViewSnapshot { HardwareViewSnapshot { my_hostname: input.my_hostname, diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs index e940187de8..6cde31bb0f 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs @@ -9,6 +9,7 @@ mod event_cutover; mod inventory; use mesh_llm_control_api::status::metrics; mod model_labels; +mod plugin_status; #[cfg(test)] mod plugin_tests; mod plugins; @@ -496,6 +497,7 @@ pub(crate) mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; assert_eq!( diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs new file mode 100644 index 0000000000..6d471fcef5 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs @@ -0,0 +1,426 @@ +//! Plugin contributions to `GET /api/status`. +//! +//! The node's collector keeps each plugin's latest accepted snapshot, so a +//! status read never reaches a plugin. The host owns the envelope around the +//! plugin's data: receipt time, freshness and availability. Limits and the +//! wire contract are in `mesh_llm_plugin::plugin_status`. + +use crate::api::status::{PluginStatusPayload, PluginStatusState}; +use crate::plugin::proto; +use mesh_llm_plugin::plugin_status::{MAX_DATA_BYTES, MIN_PUBLISH_INTERVAL, effective_fresh_for}; +use std::collections::BTreeMap; +use std::time::Duration; +use tokio::task::AbortHandle; +use tokio::time::Instant; + +/// Why the host refused a snapshot. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum PluginStatusRejection { + TooLarge { bytes: usize }, + NotAnObject, + TooSoon { retry_after: Duration }, +} + +impl PluginStatusRejection { + pub(crate) fn message(&self, plugin_name: &str) -> String { + match self { + Self::TooLarge { bytes } => format!( + "status data from plugin `{plugin_name}` is {bytes} bytes; the limit is {MAX_DATA_BYTES}" + ), + Self::NotAnObject => { + format!("status data from plugin `{plugin_name}` must be a JSON object") + } + Self::TooSoon { retry_after } => format!( + "plugin `{plugin_name}` published its status less than {MIN_PUBLISH_INTERVAL:?} ago; retry in {retry_after:?}" + ), + } + } +} + +struct PluginStatusEntry { + /// The plugin connection that published it. + generation: u64, + schema_version: u32, + data: serde_json::Value, + received_at: Instant, + received_at_unix_ms: u64, + fresh_for: Duration, + /// False once that connection is gone. + connected: bool, + /// Wakes `/api/events` when the snapshot turns stale. + expiry: Option, +} + +impl PluginStatusEntry { + fn state(&self, now: Instant) -> PluginStatusState { + if !self.connected { + PluginStatusState::Unavailable + } else if now.saturating_duration_since(self.received_at) >= self.fresh_for { + PluginStatusState::Stale + } else { + PluginStatusState::Ready + } + } + + fn fresh_until_unix_ms(&self) -> u64 { + self.received_at_unix_ms + .saturating_add(u64::try_from(self.fresh_for.as_millis()).unwrap_or(u64::MAX)) + } + + fn cancel_expiry(&mut self) { + if let Some(expiry) = self.expiry.take() { + expiry.abort(); + } + } +} + +impl Drop for PluginStatusEntry { + fn drop(&mut self) { + self.cancel_expiry(); + } +} + +/// A snapshot the host accepted. +pub(crate) struct AcceptedPluginStatus { + pub(crate) response: proto::PublishPluginStatusResponse, + /// When it turns stale, for the expiry wake-up. `None` after a withdrawal. + pub(crate) fresh_for: Option, +} + +#[derive(Default)] +pub(crate) struct PluginStatusStore { + entries: BTreeMap, +} + +impl PluginStatusStore { + /// Accept `request` from connection `generation` of `plugin_name`, which + /// the caller has checked is the plugin's current, initialized connection + /// and declares `schema_version`. An empty `data_json` withdraws. + pub(crate) fn publish( + &mut self, + plugin_name: &str, + generation: u64, + schema_version: u32, + request: &proto::PublishPluginStatusRequest, + now: Instant, + now_unix_ms: u64, + ) -> Result { + if request.data_json.is_empty() { + self.entries.remove(plugin_name); + return Ok(AcceptedPluginStatus { + response: proto::PublishPluginStatusResponse::default(), + fresh_for: None, + }); + } + if request.data_json.len() > MAX_DATA_BYTES { + return Err(PluginStatusRejection::TooLarge { + bytes: request.data_json.len(), + }); + } + if let Some(previous) = self.entries.get(plugin_name) + && previous.generation == generation + { + let elapsed = now.saturating_duration_since(previous.received_at); + if elapsed < MIN_PUBLISH_INTERVAL { + return Err(PluginStatusRejection::TooSoon { + retry_after: MIN_PUBLISH_INTERVAL - elapsed, + }); + } + } + let data = match serde_json::from_str::(&request.data_json) { + Ok(data @ serde_json::Value::Object(_)) => data, + _ => return Err(PluginStatusRejection::NotAnObject), + }; + let entry = PluginStatusEntry { + generation, + schema_version, + data, + received_at: now, + received_at_unix_ms: now_unix_ms, + fresh_for: effective_fresh_for(request.fresh_for_ms), + connected: true, + expiry: None, + }; + let accepted = AcceptedPluginStatus { + response: proto::PublishPluginStatusResponse { + received_at_unix_ms: entry.received_at_unix_ms, + fresh_until_unix_ms: entry.fresh_until_unix_ms(), + }, + fresh_for: Some(entry.fresh_for), + }; + self.entries.insert(plugin_name.to_string(), entry); + Ok(accepted) + } + + /// Attach the wake-up that fires when `plugin_name`'s snapshot turns stale. + pub(crate) fn set_expiry(&mut self, plugin_name: &str, expiry: AbortHandle) { + match self.entries.get_mut(plugin_name) { + Some(entry) => { + entry.cancel_expiry(); + entry.expiry = Some(expiry); + } + None => expiry.abort(), + } + } + + /// The connection `generation` of `plugin_name` is gone: keep what it + /// published, shown as unavailable. A snapshot from a later connection is + /// left alone. Returns whether anything changed. + pub(crate) fn mark_unavailable(&mut self, plugin_name: &str, generation: u64) -> bool { + match self.entries.get_mut(plugin_name) { + Some(entry) if entry.generation == generation && entry.connected => { + entry.connected = false; + entry.cancel_expiry(); + true + } + _ => false, + } + } + + /// The plugin stopped for good. Returns whether it had a snapshot. + pub(crate) fn remove(&mut self, plugin_name: &str) -> bool { + self.entries.remove(plugin_name).is_some() + } + + pub(crate) fn payloads(&self, now: Instant) -> BTreeMap { + self.entries + .iter() + .map(|(name, entry)| { + ( + name.clone(), + PluginStatusPayload { + schema_version: entry.schema_version, + state: entry.state(now), + received_at_unix_ms: entry.received_at_unix_ms, + fresh_until_unix_ms: entry.fresh_until_unix_ms(), + data: entry.data.clone(), + }, + ) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use mesh_llm_plugin::plugin_status::{DEFAULT_FRESH_FOR, MAX_FRESH_FOR}; + + fn request(data_json: &str, fresh_for_ms: u64) -> proto::PublishPluginStatusRequest { + proto::PublishPluginStatusRequest { + data_json: data_json.into(), + fresh_for_ms, + } + } + + #[test] + fn a_snapshot_is_ready_then_stale_inside_a_host_owned_envelope() { + let mut store = PluginStatusStore::default(); + let start = Instant::now(); + let accepted = store + .publish( + "powermetrics", + 1, + 3, + &request(r#"{"idle_watts":8.2}"#, 5_000), + start, + 1_000, + ) + .unwrap(); + assert_eq!(accepted.response.received_at_unix_ms, 1_000); + assert_eq!(accepted.response.fresh_until_unix_ms, 6_000); + assert_eq!(accepted.fresh_for, Some(Duration::from_secs(5))); + + let ready = &store.payloads(start + Duration::from_secs(4))["powermetrics"]; + assert_eq!(ready.state, PluginStatusState::Ready); + assert_eq!(ready.schema_version, 3); + assert_eq!(ready.data, serde_json::json!({"idle_watts": 8.2})); + assert_eq!( + store.payloads(start + Duration::from_secs(5))["powermetrics"].state, + PluginStatusState::Stale + ); + } + + #[test] + fn two_plugins_keep_their_own_snapshots() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + store + .publish("a", 1, 1, &request(r#"{"from":"a"}"#, 0), now, 1) + .unwrap(); + store + .publish("b", 1, 1, &request(r#"{"from":"b"}"#, 0), now, 1) + .unwrap(); + store + .publish( + "a", + 1, + 1, + &request(r#"{"from":"a again"}"#, 0), + now + MIN_PUBLISH_INTERVAL, + 2, + ) + .unwrap(); + let payloads = store.payloads(now + MIN_PUBLISH_INTERVAL); + assert_eq!(payloads["a"].data, serde_json::json!({"from": "a again"})); + assert_eq!(payloads["b"].data, serde_json::json!({"from": "b"})); + assert_eq!( + payloads["b"].fresh_until_unix_ms, + 1 + DEFAULT_FRESH_FOR.as_millis() as u64 + ); + } + + #[test] + fn malformed_oversized_and_too_frequent_snapshots_are_refused() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + for not_an_object in ["{", "[1]", "8.2", "\"text\"", "null"] { + assert_eq!( + store + .publish("p", 1, 1, &request(not_an_object, 0), now, 1) + .err(), + Some(PluginStatusRejection::NotAnObject), + "{not_an_object}" + ); + } + let oversized = format!(r#"{{"pad":"{}"}}"#, "x".repeat(MAX_DATA_BYTES)); + assert_eq!( + store + .publish("p", 1, 1, &request(&oversized, 0), now, 1) + .err(), + Some(PluginStatusRejection::TooLarge { + bytes: oversized.len() + }) + ); + assert!(store.payloads(now).is_empty(), "nothing was stored"); + + store + .publish("p", 1, 1, &request(r#"{"n":1}"#, 0), now, 1) + .unwrap(); + let half = MIN_PUBLISH_INTERVAL / 2; + assert_eq!( + store + .publish("p", 1, 1, &request(r#"{"n":2}"#, 0), now + half, 2) + .err(), + Some(PluginStatusRejection::TooSoon { + retry_after: MIN_PUBLISH_INTERVAL - half + }) + ); + assert_eq!(store.payloads(now)["p"].data, serde_json::json!({"n": 1})); + // A new connection's first snapshot is not held to the old one's pace. + store + .publish("p", 2, 1, &request(r#"{"n":3}"#, 0), now + half, 3) + .unwrap(); + assert_eq!(store.payloads(now)["p"].data, serde_json::json!({"n": 3})); + } + + #[test] + fn freshness_is_kept_within_the_host_bounds() { + let mut store = PluginStatusStore::default(); + let accepted = store + .publish("p", 1, 1, &request("{}", u64::MAX), Instant::now(), 0) + .unwrap(); + assert_eq!(accepted.fresh_for, Some(MAX_FRESH_FOR)); + assert_eq!( + accepted.response.fresh_until_unix_ms, + MAX_FRESH_FOR.as_millis() as u64 + ); + } + + #[test] + fn a_closed_connection_leaves_its_snapshot_unavailable_but_not_a_later_one() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + store + .publish("p", 1, 1, &request(r#"{"n":1}"#, 0), now, 1) + .unwrap(); + assert!(store.mark_unavailable("p", 1)); + assert!(!store.mark_unavailable("p", 1), "already unavailable"); + let unavailable = &store.payloads(now)["p"]; + assert_eq!(unavailable.state, PluginStatusState::Unavailable); + assert_eq!(unavailable.data, serde_json::json!({"n": 1})); + + // The restarted plugin publishes again; a late notice about the old + // connection does not touch it. + store + .publish("p", 2, 1, &request(r#"{"n":2}"#, 0), now, 2) + .unwrap(); + assert!(!store.mark_unavailable("p", 1)); + assert_eq!(store.payloads(now)["p"].state, PluginStatusState::Ready); + assert!( + !store.mark_unavailable("q", 1), + "no snapshot, nothing to mark" + ); + } + + #[tokio::test(start_paused = true)] + async fn the_collector_wakes_status_readers_when_a_snapshot_turns_stale() { + use crate::runtime_data::{RuntimeDataCollector, RuntimeDataDirty}; + + let collector = RuntimeDataCollector::new(); + let mut subscription = collector.subscribe(); + collector + .publish_plugin_status("p", 1, 1, &request("{}", 2_000)) + .unwrap(); + assert!( + subscription.has_changed().unwrap(), + "a publication wakes readers" + ); + subscription.borrow_and_update(); + assert_eq!( + collector.plugin_status_payloads()["p"].state, + PluginStatusState::Ready + ); + + // A newer snapshot replaces the old one's wake-up with its own. + tokio::time::sleep(Duration::from_secs(1)).await; + collector + .publish_plugin_status("p", 1, 1, &request("{}", 5_000)) + .unwrap(); + subscription.borrow_and_update(); + tokio::time::sleep(Duration::from_millis(4_999)).await; + assert!( + !subscription.has_changed().unwrap(), + "the replaced snapshot's expiry does not fire" + ); + assert_eq!( + collector.plugin_status_payloads()["p"].state, + PluginStatusState::Ready + ); + + tokio::time::timeout(Duration::from_secs(1), subscription.changed()) + .await + .expect("readers are woken when the snapshot turns stale") + .unwrap(); + assert!( + subscription + .borrow() + .dirty + .contains(RuntimeDataDirty::STATUS) + ); + assert_eq!( + collector.plugin_status_payloads()["p"].state, + PluginStatusState::Stale + ); + } + + #[test] + fn a_withdrawal_or_a_stop_removes_the_snapshot() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + store.publish("p", 1, 1, &request("{}", 0), now, 1).unwrap(); + // Withdrawing is not held to the publication pace. + let withdrawn = store.publish("p", 1, 1, &request("", 0), now, 1).unwrap(); + assert_eq!( + withdrawn.response, + proto::PublishPluginStatusResponse::default() + ); + assert_eq!(withdrawn.fresh_for, None); + assert!(store.payloads(now).is_empty()); + + store.publish("p", 2, 1, &request("{}", 0), now, 1).unwrap(); + assert!(store.remove("p")); + assert!(!store.remove("p")); + assert!(store.payloads(now).is_empty()); + } +} diff --git a/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs b/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs index 37098ca1f9..e8e8bb6c59 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs @@ -59,6 +59,8 @@ pub enum Surface { /// The OpenAI exchange lifecycle hook: it sees every OpenAI exchange the /// node handles, prompts and answers included. OpenAiExchangeHook, + /// A snapshot of the plugin's own shown in `GET /api/status`. + StatusContributions, } impl Surface { @@ -74,6 +76,7 @@ impl Surface { Self::OtherEndpoints => "other endpoints", Self::VirtualModels => "virtual models", Self::OpenAiExchangeHook => "OpenAI exchange hook", + Self::StatusContributions => "status contributions", } } } @@ -88,6 +91,7 @@ pub const UNLISTED_DEFAULT_ALLOWS: &[Surface] = &[ Surface::HttpRoutes, Surface::McpOperations, Surface::OtherEndpoints, + Surface::StatusContributions, ]; /// This build's entry for a default plugin, by its installed name. diff --git a/mesh/crates/mesh-llm-plugin/proto/plugin.proto b/mesh/crates/mesh-llm-plugin/proto/plugin.proto index 86fda434fb..a38be9df69 100644 --- a/mesh/crates/mesh-llm-plugin/proto/plugin.proto +++ b/mesh/crates/mesh-llm-plugin/proto/plugin.proto @@ -34,6 +34,8 @@ message Envelope { PeerBlockResponse peer_block_response = 33; PluginKeyRequest plugin_key_request = 34; PluginKeyResponse plugin_key_response = 35; + PublishPluginStatusRequest publish_plugin_status_request = 36; + PublishPluginStatusResponse publish_plugin_status_response = 37; } } @@ -199,6 +201,19 @@ message PluginManifest { repeated VirtualModelManifest virtual_models = 13; // Optional, additive generation-3 lifecycle contract. Declarations are not grants. optional OpenAiExchangeHookManifest openai_exchange_hook = 14; + // This plugin publishes a snapshot shown in `GET /api/status`; see + // `PublishPluginStatusRequest`. A host takes publications only from a plugin + // that declares this. + optional PluginStatusManifest plugin_status = 15; +} + +message PluginStatusManifest { + // The version of the plugin's own snapshot schema, shown beside its data. + // At least 1. + uint32 schema_version = 1; + // Refuse to initialize on a host that does not list the `plugin_status.v1` + // capability, instead of running without a status contribution. + bool required = 2; } message VirtualModelManifest { @@ -743,6 +758,29 @@ message PluginKeyResponse { bytes binding_signature = 2; } +// A plugin publishes the snapshot shown at `/api/status.plugin_status.`, +// where `` is the host's name for the plugin connection, never a name the +// plugin claims. A later publication replaces it, and an empty `data_json` +// withdraws it. The host keeps the latest one and owns its envelope: receipt +// time and freshness. `/api/status` reads that copy and never calls the +// plugin. Handled only by a host listing the `plugin_status.v1` capability, +// for a plugin whose manifest declares `plugin_status`, from its current +// connection. +message PublishPluginStatusRequest { + // A JSON object, at most 16 KiB, in the plugin's own schema. Empty to withdraw. + string data_json = 1; + // How long the host shows the snapshot as `ready` before it turns `stale`. + // 0 means 60 s; the host keeps it between 1 s and 1 h. + uint64 fresh_for_ms = 2; +} + +message PublishPluginStatusResponse { + // When the host accepted the snapshot, Unix milliseconds; 0 after a withdrawal. + uint64 received_at_unix_ms = 1; + // When it turns `stale`, Unix milliseconds; 0 after a withdrawal. + uint64 fresh_until_unix_ms = 2; +} + message ErrorResponse { int32 code = 1; string message = 2; diff --git a/mesh/crates/mesh-llm-plugin/src/context.rs b/mesh/crates/mesh-llm-plugin/src/context.rs index 168a17b7de..95123d2384 100644 --- a/mesh/crates/mesh-llm-plugin/src/context.rs +++ b/mesh/crates/mesh-llm-plugin/src/context.rs @@ -332,6 +332,75 @@ impl<'a> PluginContext<'a> { } } + /// Publish `data`, a JSON object of at most + /// [`crate::plugin_status::MAX_DATA_BYTES`], as this plugin's snapshot in + /// `GET /api/status`; it replaces the previous one. The host shows it as + /// `ready` for `fresh_for` (0 for the default), then `stale`. See + /// [`crate::plugin_status`]. + /// + /// Fails at once, without sending anything, if the host does not list + /// [`crate::host_capabilities::PLUGIN_STATUS`]. The host refuses a snapshot + /// from a plugin whose manifest does not declare `plugin_status`, one that + /// is too large or not an object, and one sent sooner than + /// [`crate::plugin_status::MIN_PUBLISH_INTERVAL`] after the last. + pub async fn publish_status( + &mut self, + data: &T, + fresh_for: std::time::Duration, + ) -> Result { + let request = proto::PublishPluginStatusRequest { + data_json: serde_json::to_string(data)?, + fresh_for_ms: u64::try_from(fresh_for.as_millis()).unwrap_or(u64::MAX), + }; + self.publish_status_within(request, PEER_BLOCK_REQUEST_TIMEOUT) + .await + } + + /// Remove this plugin's snapshot from `GET /api/status`. + pub async fn withdraw_status(&mut self) -> Result<()> { + self.publish_status_within( + proto::PublishPluginStatusRequest::default(), + PEER_BLOCK_REQUEST_TIMEOUT, + ) + .await + .map(|_| ()) + } + + async fn publish_status_within( + &mut self, + request: proto::PublishPluginStatusRequest, + timeout: std::time::Duration, + ) -> Result { + if !self.host_supports(crate::host_capabilities::PLUGIN_STATUS) { + bail!( + "status contributions are unsupported by this host: it does not list the `{}` capability", + crate::host_capabilities::PLUGIN_STATUS + ); + } + let request_id = next_host_request_id(); + let (tx, rx) = oneshot::channel(); + insert_pending_host_response(&self.pending_host_responses, request_id, tx); + let mut pending_guard = + PendingHostResponseGuard::new(request_id, self.pending_host_responses.clone()); + + self.send_payload( + proto::envelope::Payload::PublishPluginStatusRequest(request), + request_id, + ) + .await?; + + let Ok(response) = tokio::time::timeout(timeout, rx).await else { + bail!("status publication: the host did not answer within {timeout:?}"); + }; + let response = response??; + pending_guard.disarm(); + match response.payload { + Some(proto::envelope::Payload::PublishPluginStatusResponse(response)) => Ok(response), + Some(proto::envelope::Payload::ErrorResponse(error)) => bail!(error.message), + _ => bail!("Host returned an unexpected status publication response"), + } + } + pub async fn connect_mesh_stream( &mut self, request: proto::OpenMeshStreamRequest, @@ -404,6 +473,7 @@ pub(crate) fn drain_pending_host_responses( #[cfg(test)] mod tests { use super::*; + use std::time::Duration; fn context( host_capabilities: &[&str], @@ -538,4 +608,99 @@ mod tests { assert_eq!(response.binding_signature, vec![2; 64]); host.await.unwrap(); } + + #[tokio::test] + async fn a_status_publication_to_an_older_host_fails_at_once() { + let (mut context, mut outbound_rx, pending) = context(&[]); + let error = context + .publish_status(&serde_json::json!({"watts": 8.2}), Duration::ZERO) + .await + .unwrap_err(); + assert!( + error.to_string().contains("unsupported by this host"), + "{error}" + ); + assert!(outbound_rx.try_recv().is_err(), "nothing was sent"); + assert!(pending.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_status_publication_the_host_never_answers_times_out() { + let (mut context, mut outbound_rx, pending) = + context(&[crate::host_capabilities::PLUGIN_STATUS]); + let error = context + .publish_status_within( + proto::PublishPluginStatusRequest { + data_json: "{}".into(), + fresh_for_ms: 0, + }, + Duration::from_millis(20), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("did not answer"), "{error}"); + assert!(outbound_rx.try_recv().is_ok(), "the publication was sent"); + assert!(pending.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_status_publication_sends_the_data_and_returns_the_host_answer() { + let (mut context, mut outbound_rx, pending) = + context(&[crate::host_capabilities::PLUGIN_STATUS]); + let host = tokio::spawn(async move { + let request = outbound_rx.recv().await.unwrap(); + let Some(proto::envelope::Payload::PublishPluginStatusRequest(publication)) = + request.payload + else { + panic!("expected a status publication"); + }; + assert_eq!(publication.data_json, r#"{"watts":8.2}"#); + assert_eq!(publication.fresh_for_ms, 5_000); + let sender = remove_pending_host_response(&pending, request.request_id).unwrap(); + sender + .send(Ok(proto::Envelope { + request_id: request.request_id, + payload: Some(proto::envelope::Payload::PublishPluginStatusResponse( + proto::PublishPluginStatusResponse { + received_at_unix_ms: 1_000, + fresh_until_unix_ms: 6_000, + }, + )), + ..Default::default() + })) + .unwrap(); + }); + let response = context + .publish_status(&serde_json::json!({"watts": 8.2}), Duration::from_secs(5)) + .await + .unwrap(); + assert_eq!(response.fresh_until_unix_ms, 6_000); + host.await.unwrap(); + } + + #[tokio::test] + async fn a_withdrawal_sends_empty_data() { + let (mut context, mut outbound_rx, pending) = + context(&[crate::host_capabilities::PLUGIN_STATUS]); + let host = tokio::spawn(async move { + let request = outbound_rx.recv().await.unwrap(); + assert!(matches!( + request.payload, + Some(proto::envelope::Payload::PublishPluginStatusRequest(ref publication)) + if publication.data_json.is_empty() + )); + let sender = remove_pending_host_response(&pending, request.request_id).unwrap(); + sender + .send(Ok(proto::Envelope { + request_id: request.request_id, + payload: Some(proto::envelope::Payload::PublishPluginStatusResponse( + proto::PublishPluginStatusResponse::default(), + )), + ..Default::default() + })) + .unwrap(); + }); + context.withdraw_status().await.unwrap(); + host.await.unwrap(); + } } diff --git a/mesh/crates/mesh-llm-plugin/src/lib.rs b/mesh/crates/mesh-llm-plugin/src/lib.rs index 4a6e498f2a..e845c1c004 100644 --- a/mesh/crates/mesh-llm-plugin/src/lib.rs +++ b/mesh/crates/mesh-llm-plugin/src/lib.rs @@ -11,6 +11,7 @@ mod internal_rpc; mod io; mod manifest; pub mod openai_exchange; +pub mod plugin_status; mod runtime; mod simple_plugin; mod virtual_model; @@ -106,6 +107,35 @@ pub mod host_capabilities { pub const PEER_BLOCKS: &str = "peer_blocks.v1"; /// The host accepts `PluginKeyRequest` and announces the key it binds. pub const PLUGIN_KEYS: &str = "plugin_keys.v1"; + /// The host accepts `PublishPluginStatusRequest` and shows the snapshot in + /// `GET /api/status` (see [`crate::plugin_status`]). + pub const PLUGIN_STATUS: &str = "plugin_status.v1"; + + /// Why a plugin with `manifest` cannot run on this host: a capability its + /// manifest requires that the host does not list. + pub(crate) fn unsupported_requirement( + manifest: Option<&crate::proto::PluginManifest>, + host_supports: impl Fn(&str) -> bool, + ) -> Option<&'static str> { + let manifest = manifest?; + if manifest + .openai_exchange_hook + .as_ref() + .is_some_and(|hook| hook.required) + && !host_supports(OPENAI_EXCHANGE) + { + return Some("host does not support required openai_exchange.v1 contract"); + } + if manifest + .plugin_status + .as_ref() + .is_some_and(|status| status.required) + && !host_supports(PLUGIN_STATUS) + { + return Some("host does not support required plugin_status.v1 contributions"); + } + None + } } #[macro_export] diff --git a/mesh/crates/mesh-llm-plugin/src/manifest.rs b/mesh/crates/mesh-llm-plugin/src/manifest.rs index 68858f0421..bae079e1bc 100644 --- a/mesh/crates/mesh-llm-plugin/src/manifest.rs +++ b/mesh/crates/mesh-llm-plugin/src/manifest.rs @@ -39,6 +39,7 @@ pub enum ManifestEntry { MeshEventSubscription(proto::MeshEventSubscriptionManifest), WebUi(proto::PluginWebUiManifest), OpenAiExchangeHook(proto::OpenAiExchangeHookManifest), + PluginStatus(proto::PluginStatusManifest), } #[derive(Clone, Debug, Default)] @@ -88,6 +89,7 @@ impl PluginManifestBuilder { ManifestEntry::OpenAiExchangeHook(hook) => { self.manifest.openai_exchange_hook = Some(Box::new(hook)) } + ManifestEntry::PluginStatus(status) => self.manifest.plugin_status = Some(status), } } } diff --git a/mesh/crates/mesh-llm-plugin/src/plugin_status.rs b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs new file mode 100644 index 0000000000..3910e1a309 --- /dev/null +++ b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs @@ -0,0 +1,197 @@ +//! Plugin contributions to the host's `GET /api/status`. +//! +//! A plugin declares [`plugin_status`] in its manifest and publishes snapshots +//! with [`crate::PluginContext::publish_status`]. The host keeps the latest one +//! and shows it at `/api/status.plugin_status.`, inside an +//! envelope the host owns: +//! +//! ```json +//! { +//! "schema_version": 1, +//! "state": "ready", +//! "received_at_unix_ms": 1793404800000, +//! "fresh_until_unix_ms": 1793404860000, +//! "data": { "source": "macmon", "idle_watts": 8.2 } +//! } +//! ``` +//! +//! `state` is `ready` until the snapshot's freshness runs out, then `stale`, +//! and `unavailable` once the plugin connection that published it is gone. The +//! freshness is the host's: it says when the host last heard from the plugin, +//! not how old the plugin's own readings are, which belong in `data`. + +use crate::manifest::ManifestEntry; +use crate::proto; +use std::time::Duration; + +/// The largest `data_json` a host accepts, in bytes. +pub const MAX_DATA_BYTES: usize = 16 * 1024; +/// The shortest interval between two snapshots a host accepts from one plugin +/// connection. A withdrawal is always accepted. +pub const MIN_PUBLISH_INTERVAL: Duration = Duration::from_secs(1); +/// How long a snapshot stays `ready` when it sets `fresh_for_ms` to 0. +pub const DEFAULT_FRESH_FOR: Duration = Duration::from_secs(60); +/// The shortest freshness a host keeps; a shorter one is raised to it. +pub const MIN_FRESH_FOR: Duration = Duration::from_secs(1); +/// The longest freshness a host keeps; a longer one is lowered to it. +pub const MAX_FRESH_FOR: Duration = Duration::from_secs(60 * 60); + +/// Declare that this plugin publishes snapshots in version `schema_version` +/// (at least 1) of its own schema. +pub fn plugin_status(schema_version: u32) -> PluginStatusBuilder { + PluginStatusBuilder { + inner: proto::PluginStatusManifest { + schema_version, + required: false, + }, + } +} + +#[derive(Clone, Debug)] +pub struct PluginStatusBuilder { + inner: proto::PluginStatusManifest, +} + +impl PluginStatusBuilder { + /// Refuse to initialize on a host that does not list + /// [`crate::host_capabilities::PLUGIN_STATUS`]. + pub fn required(mut self, required: bool) -> Self { + self.inner.required = required; + self + } + + pub fn build(self) -> proto::PluginStatusManifest { + self.inner + } +} + +impl From for ManifestEntry { + fn from(value: PluginStatusBuilder) -> Self { + ManifestEntry::PluginStatus(value.build()) + } +} + +/// How long the host keeps a snapshot published with `fresh_for_ms` as +/// `ready`. +pub fn effective_fresh_for(fresh_for_ms: u64) -> Duration { + if fresh_for_ms == 0 { + return DEFAULT_FRESH_FOR; + } + Duration::from_millis(fresh_for_ms).clamp(MIN_FRESH_FOR, MAX_FRESH_FOR) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + LocalStream, PROTOCOL_VERSION, PluginMetadata, PluginRuntime, SimplePlugin, + plugin_server_info, read_envelope, write_envelope, + }; + + #[test] + fn freshness_defaults_to_a_minute_and_stays_between_a_second_and_an_hour() { + assert_eq!(effective_fresh_for(0), DEFAULT_FRESH_FOR); + assert_eq!(effective_fresh_for(1), MIN_FRESH_FOR); + assert_eq!(effective_fresh_for(5_000), Duration::from_secs(5)); + assert_eq!(effective_fresh_for(u64::MAX), MAX_FRESH_FOR); + } + + #[test] + fn the_declaration_lands_in_the_manifest() { + let manifest = crate::plugin_manifest() + .item(plugin_status(2).required(true)) + .build(); + assert_eq!( + manifest.plugin_status, + Some(proto::PluginStatusManifest { + schema_version: 2, + required: true, + }) + ); + } + + async fn initialize_status_plugin( + required: bool, + host_capabilities: Vec, + ) -> Option { + let plugin = SimplePlugin::new(PluginMetadata::new( + "demo", + "1.0.0", + plugin_server_info("demo", "1.0.0", "Demo", "Demo plugin", None::), + )) + .with_manifest( + crate::plugin_manifest() + .item(crate::plugin_status::plugin_status(1).required(required)) + .build(), + ); + let (plugin_stream, host_stream) = tokio::io::duplex(64 * 1024); + let runtime = tokio::spawn(PluginRuntime::run_with_stream( + plugin, + LocalStream::Memory(plugin_stream), + )); + let mut host_stream = LocalStream::Memory(host_stream); + write_envelope( + &mut host_stream, + &proto::Envelope { + protocol_version: PROTOCOL_VERSION, + plugin_id: "demo".into(), + request_id: 1, + payload: Some(proto::envelope::Payload::InitializeRequest( + proto::InitializeRequest { + host_protocol_version: PROTOCOL_VERSION, + host_capabilities, + ..Default::default() + }, + )), + }, + ) + .await + .unwrap(); + let response = + tokio::time::timeout(Duration::from_secs(1), read_envelope(&mut host_stream)) + .await + .expect("initialize response") + .unwrap(); + runtime.abort(); + response.payload + } + + #[tokio::test] + async fn a_required_status_contribution_refuses_a_host_without_it() { + let payload = initialize_status_plugin(true, Vec::new()).await; + let Some(proto::envelope::Payload::ErrorResponse(error)) = payload else { + panic!("expected an initialize error, got {payload:?}"); + }; + assert!( + error.message.contains("plugin_status.v1"), + "{}", + error.message + ); + + let payload = + initialize_status_plugin(true, vec![crate::host_capabilities::PLUGIN_STATUS.into()]) + .await; + let Some(proto::envelope::Payload::InitializeResponse(init)) = payload else { + panic!("expected an initialize response, got {payload:?}"); + }; + assert_eq!( + init.manifest.and_then(|manifest| manifest.plugin_status), + Some(proto::PluginStatusManifest { + schema_version: 1, + required: true, + }) + ); + } + + #[tokio::test] + async fn an_optional_status_contribution_initializes_on_an_older_host() { + let payload = initialize_status_plugin(false, Vec::new()).await; + assert!( + matches!( + payload, + Some(proto::envelope::Payload::InitializeResponse(_)) + ), + "{payload:?}" + ); + } +} diff --git a/mesh/crates/mesh-llm-plugin/src/runtime.rs b/mesh/crates/mesh-llm-plugin/src/runtime.rs index f34e6ff6f2..fb3d1f7b30 100644 --- a/mesh/crates/mesh-llm-plugin/src/runtime.rs +++ b/mesh/crates/mesh-llm-plugin/src/runtime.rs @@ -1017,20 +1017,15 @@ impl PluginRuntime { Arc::from(request.host_capabilities.clone()); let mut plugin = state.plugin.clone().write_owned().await; let mut context = Self::context(&state); - if plugin - .manifest() - .and_then(|m| m.openai_exchange_hook) - .is_some_and(|h| h.required) - && !context.host_supports(crate::host_capabilities::OPENAI_EXCHANGE) - { + if let Some(message) = crate::host_capabilities::unsupported_requirement( + plugin.manifest().as_ref(), + |capability| context.host_supports(capability), + ) { Self::write_payload( &state, request_id, proto::envelope::Payload::ErrorResponse( - PluginError::invalid_request( - "host does not support required openai_exchange.v1 contract", - ) - .into_error_response(), + PluginError::invalid_request(message).into_error_response(), ), ) .await?; diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index 239fcaa681..fefe4a4d03 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -1389,6 +1389,62 @@ Every change is published once, as JSON, on the local channel `until_ms` and `reason` are omitted when absent. The host keeps no ranking, no history of changes, and no shared lists. +## Status Contributions + +A plugin can add a snapshot of its own to the node's `GET /api/status`, so +clients see it without querying a plugin endpoint. It declares +`mesh_llm_plugin::plugin_status::plugin_status(schema_version)` in its manifest +(`PluginManifest.plugin_status`), then publishes with +`PluginContext::publish_status(&data, fresh_for)`, from `on_initialized` or any +task holding an owned context. Each publication replaces the previous one; +`withdraw_status` removes it. The host shows the latest one under the name it +knows the plugin connection by, never a name the plugin claims, so one plugin +cannot overwrite another's contribution or a core field: + +```json +"plugin_status": { + "powermetrics": { + "schema_version": 1, + "state": "ready", + "received_at_unix_ms": 1793404800000, + "fresh_until_unix_ms": 1793404860000, + "data": { "source": "macmon", "idle_watts": 8.2 } + } +} +``` + +`data` is the plugin's, in version `schema_version` of its own schema. The rest +is the host's: + +- `state` is `ready` until `fresh_until_unix_ms`, then `stale`. A snapshot asks + for its freshness with `fresh_for`: 0 means 60 s, and the host keeps it + between 1 s and 1 h. When the plugin connection that published it closes or + fails, the snapshot stays, shown as `unavailable`, until a later connection + publishes. When the plugin is disabled, removed or shut down, it goes. +- The timestamps say when the host last heard from the plugin. They say nothing + about how old the plugin's own readings are: a plugin that publishes an old or + missing sensor reading says so in `data`. + +The host refuses a publication from a plugin whose manifest does not declare +`plugin_status`, from a connection that is no longer the plugin's current one, +`data_json` that is not a JSON object or is larger than 16 KiB, and a snapshot +sent less than 1 s after the previous one from the same connection. Refusals +come back as an error and change nothing; a withdrawal is always accepted. A +plugin may publish from `on_initialized`: a publication that arrives before the +host has read the plugin's manifest waits for it. + +Reads serve the host's copy: `/api/status` never starts, restarts or calls a +plugin, so a hung plugin cannot slow it. Every accepted publication, and every +change of state, wakes `/api/events`, which sends the new status. Without any +contribution, `plugin_status` is omitted and the response is unchanged. It is +local to this node, like the rest of `/api/status`: nothing is gossiped. + +The host advertises the `plugin_status.v1` host capability in its +`InitializeRequest`. Against a host without it, `publish_status` fails at once; +a plugin that cannot run without it declares `.required(true)` and then refuses +to initialize there. A default-managed plugin keeps its declaration only when +its entry in `DEFAULT_PLUGINS` allows `Surface::StatusContributions`. + ## What The Host Owns The host is responsible for: From 6290aa3ebc114877c29db56ef6074b8cfcbe8dd4 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:40:38 +0100 Subject: [PATCH 2/7] fix(plugins): never drop a plugin's disconnect notice The notice that marks a closed or failed connection's `/api/status` snapshot unavailable was sent with a one-second timeout, so a node queue that stayed full longer lost it and left the snapshot `ready`. It now waits for room on its own task and ends at once if the node is gone. The node still marks only a snapshot from that generation, so a late notice never touches a newer connection's. --- .../src/plugin/runtime.rs | 18 +------ .../src/plugin/runtime/status_publication.rs | 21 ++++++++ .../runtime/status_publication_tests.rs | 49 +++++++++++++++---- .../src/plugin/transport.rs | 18 ++----- 4 files changed, 66 insertions(+), 40 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs index f0e6a0d99d..541f8cf029 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs @@ -927,27 +927,11 @@ impl ExternalPlugin { if let Some(runtime) = failed_runtime { let generation = runtime.generation; stop_runtime(runtime, &reason).await; - self.announce_disconnected(generation).await; + status_publication::announce_disconnected(&self.mesh_tx, &self.spec.name, generation); } self.publish_summary().await; } - /// Tell the node that connection `generation` is gone, so what it - /// published to `/api/status` shows as unavailable. Bounded like - /// [`Self::announce_stopped`]. - async fn announce_disconnected(&self, generation: u64) { - let _ = self - .mesh_tx - .send_timeout( - PluginMeshEvent::PluginDisconnected { - plugin_id: self.spec.name.clone(), - generation, - }, - PLUGIN_STOPPED_SEND_TIMEOUT, - ) - .await; - } - async fn disabled_reason(&self) -> Option { let summary = self.summary.lock().await; if summary.status == "disabled" { diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication.rs index cab94abe62..5c2a5f3a38 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication.rs @@ -38,6 +38,27 @@ impl StatusDeclaration { } } +/// Tell the node that connection `generation` of `plugin_name` is gone, so what +/// it published to `/api/status` shows as unavailable. The notice waits for +/// room in the node's queue on its own task rather than giving up after a +/// deadline, since a lost notice would leave the snapshot `ready`; it ends at +/// once if the node is gone. The node marks only a snapshot from this +/// generation, so a late notice never touches a newer connection's. +pub(crate) fn announce_disconnected( + mesh_tx: &mpsc::Sender, + plugin_name: &str, + generation: u64, +) { + let mesh_tx = mesh_tx.clone(); + let event = PluginMeshEvent::PluginDisconnected { + plugin_id: plugin_name.to_string(), + generation, + }; + tokio::spawn(async move { + let _ = mesh_tx.send(event).await; + }); +} + /// Refuse a declaration whose schema version is 0: versions start at 1. pub(crate) fn validate_declaration( plugin_name: &str, diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs index aef8c007fa..7427a0e52c 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs @@ -202,25 +202,54 @@ async fn a_failed_connection_tells_the_node_its_status_is_unavailable() { plugin .handle_runtime_failure(Some(4), "plugin exited".into()) .await; - let mut disconnected = Vec::new(); - while let Ok(event) = mesh_rx.try_recv() { - if let PluginMeshEvent::PluginDisconnected { - plugin_id, - generation, - } = event - { - disconnected.push((plugin_id, generation)); + let disconnected = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(PluginMeshEvent::PluginDisconnected { + plugin_id, + generation, + }) = mesh_rx.recv().await + { + break (plugin_id, generation); + } } - } - assert_eq!(disconnected, vec![("demo".to_string(), 4)]); + }) + .await + .expect("the node is told"); + assert_eq!(disconnected, ("demo".to_string(), 4)); // No runtime, nothing to announce. plugin .handle_runtime_failure(None, "plugin exited".into()) .await; + tokio::time::sleep(Duration::from_millis(50)).await; assert!(mesh_rx.try_recv().is_err()); } +#[tokio::test(start_paused = true)] +async fn a_disconnect_notice_waits_for_a_full_node_queue_instead_of_being_lost() { + let (mesh_tx, mut mesh_rx) = mpsc::channel(1); + mesh_tx + .try_send(PluginMeshEvent::PluginStopped { + plugin_id: "other".into(), + }) + .unwrap(); + announce_disconnected(&mesh_tx, "demo", 7); + + // Far longer than any deadline a bounded send would have given it. + tokio::time::sleep(Duration::from_secs(60)).await; + assert!(matches!( + mesh_rx.recv().await, + Some(PluginMeshEvent::PluginStopped { .. }) + )); + let notice = tokio::time::timeout(Duration::from_secs(1), mesh_rx.recv()) + .await + .expect("the notice is delivered once there is room"); + assert!(matches!( + notice, + Some(PluginMeshEvent::PluginDisconnected { ref plugin_id, generation: 7 }) if plugin_id == "demo" + )); +} + #[test] fn a_declaration_must_name_a_schema_version() { let manifest = |schema_version| proto::PluginManifest { diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs index 82f33afc70..fb3fec466b 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs @@ -32,8 +32,6 @@ const PLUGIN_ENVELOPE_BODY_READ_TIMEOUT: Duration = Duration::from_secs(30); const PLUGIN_ENVELOPE_TEST_READ_TIMEOUT: Duration = Duration::from_secs(1); const PLUGIN_MESH_STREAM_RESPONSE_TIMEOUT: Duration = Duration::from_secs(super::REQUEST_TIMEOUT_SECS); -/// Bounded: a node that is itself stopping may not read it. -const PLUGIN_DISCONNECTED_SEND_TIMEOUT: Duration = Duration::from_secs(1); fn plugin_mesh_stream_error(message: impl Into) -> super::proto::ErrorResponse { super::proto::ErrorResponse { @@ -247,17 +245,11 @@ pub(crate) const CONNECTION_LOOP: ConnectionLoopFn = summary.status = "stopped".into(); summary.error = Some(format!("Plugin '{}' disconnected", plugin_name)); drop(summary); - // What this connection published to `/api/status` is now - // shown as unavailable. - let _ = mesh_tx - .send_timeout( - PluginMeshEvent::PluginDisconnected { - plugin_id: plugin_name.clone(), - generation, - }, - PLUGIN_DISCONNECTED_SEND_TIMEOUT, - ) - .await; + super::runtime::status_publication::announce_disconnected( + &mesh_tx, + &plugin_name, + generation, + ); } let mut pending = pending.lock().await; From 8ff9b518f95c02dc23b1209b84017f32dc3b94a3 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:41:05 +0100 Subject: [PATCH 3/7] docs(plugins): fix the status contributions surface doc comment --- mesh/crates/mesh-llm-plugin-manager/src/defaults.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs b/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs index e8e8bb6c59..7540b9ff10 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs @@ -59,7 +59,7 @@ pub enum Surface { /// The OpenAI exchange lifecycle hook: it sees every OpenAI exchange the /// node handles, prompts and answers included. OpenAiExchangeHook, - /// A snapshot of the plugin's own shown in `GET /api/status`. + /// The plugin's own snapshot, shown in `GET /api/status`. StatusContributions, } From 67743e45ff6ad06309051058deea5ecd18174e40 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:17:12 +0100 Subject: [PATCH 4/7] feat(plugins): show each status contribution as a top-level field A plugin's snapshot now sits in /api/status under the plugin's name, without the plugin_status wrapper. A plugin named like a core status field is refused, so it cannot shadow that field; a test keeps the list of core fields in step with StatusPayload. --- .../mesh-llm-host-runtime/src/api/status.rs | 82 ++++++++++++++++++- .../src/api/tests/runtime_data.rs | 23 ++++-- .../src/runtime_data/plugin_status.rs | 31 ++++++- .../crates/mesh-llm-plugin/proto/plugin.proto | 6 +- mesh/docs/plugins/README.md | 25 +++--- 5 files changed, 136 insertions(+), 31 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs index 71315e4d35..65c82f48e8 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs @@ -392,13 +392,67 @@ pub(crate) struct StatusPayload { /// state has been initialized so older consumers retain their prior shape. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) logging: Option, - /// Snapshots plugins published over their local connections, by the - /// host's name for each plugin; see [`PluginStatusPayload`]. Local-only, - /// and omitted while no plugin contributes, so the shape is unchanged. - #[serde(skip_serializing_if = "BTreeMap::is_empty")] + /// Snapshots plugins published over their local connections, each as a + /// top-level field named by the host's name for the plugin; see + /// [`PluginStatusPayload`]. Local-only, and absent while no plugin + /// contributes, so the shape is unchanged. A plugin named like one of + /// [`CORE_STATUS_FIELDS`] cannot contribute. + #[serde(flatten)] pub(crate) plugin_status: BTreeMap, } +/// The fields of [`StatusPayload`] besides the plugins' contributions. A +/// plugin by one of these names is refused, so it never shadows a core field. +pub(crate) const CORE_STATUS_FIELDS: &[&str] = &[ + "version", + "latest_version", + "node_id", + "owner", + "release_attestation", + "token", + "node_state", + "node_status", + "is_host", + "is_client", + "llama_ready", + "runtime", + "model_name", + "models", + "available_models", + "requested_models", + "wanted_model_refs", + "serving_models", + "hosted_models", + "draft_name", + "api_port", + "my_vram_gb", + "model_size_gb", + "peers", + "wakeable_nodes", + "local_instances", + "launch_pi", + "launch_goose", + "inflight_requests", + "mesh_id", + "mesh_name", + "mesh_discovery_mode", + "discovery_scope", + "discovery_source", + "nostr_discovery", + "publication_state", + "my_hostname", + "my_is_soc", + "my_memory", + "gpus", + "routing_affinity", + "routing_metrics", + "first_joined_mesh_ts", + "mesh_requirements", + "recent_mesh_rejections", + "plugin_frame_telemetry", + "logging", +]; + /// One plugin's contribution to `/api/status`. The host owns everything but /// `data`, which is the plugin's own, in version `schema_version` of its own /// schema. The state and timestamps say when the host last heard from the @@ -921,6 +975,26 @@ mod tests { use super::*; use crate::ReleaseAttestationSummary; + #[test] + fn core_status_fields_name_every_field_but_the_plugins() { + // Read from the struct itself, so a new field cannot be left out and + // let a plugin of that name shadow it. + let fields = include_str!("status.rs") + .lines() + .skip_while(|line| !line.starts_with("pub(crate) struct StatusPayload {")) + .skip(1) + .take_while(|line| *line != "}") + .filter_map(|line| line.trim().strip_prefix("pub(crate) ")) + .filter_map(|field| field.split_once(':').map(|(name, _)| name)) + .filter(|name| *name != "plugin_status") + .collect::>(); + assert_eq!( + fields, + CORE_STATUS_FIELDS.iter().copied().collect(), + "CORE_STATUS_FIELDS must list StatusPayload's fields" + ); + } + fn test_owner_payload() -> OwnershipPayload { OwnershipPayload { owner_id: None, diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs index bf7d923880..8d8d6bfcb1 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs @@ -291,7 +291,7 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { let status_body = request_management_json(state.clone(), "/api/status").await; assert!( - status_body.get("plugin_status").is_none(), + status_body.get("powermetrics").is_none(), "no contribution, no field" ); @@ -309,15 +309,15 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { .await .expect("the snapshot is accepted"); let pushed = read_until_contains(&mut events, b"\"idle_watts\":8.2", Duration::from_secs(2)).await; - assert!(String::from_utf8_lossy(&pushed).contains("\"plugin_status\"")); + assert!(String::from_utf8_lossy(&pushed).contains("\"powermetrics\":{")); let status_body = request_management_json(state.clone(), "/api/status").await; - let contribution = &status_body["plugin_status"]["powermetrics"]; + let contribution = &status_body["powermetrics"]; assert_eq!(contribution["schema_version"], json!(1)); assert_eq!(contribution["state"], json!("ready")); assert_eq!(contribution["data"], json!({"idle_watts": 8.2})); assert!(contribution["fresh_until_unix_ms"].as_u64() > contribution["received_at_unix_ms"].as_u64()); - assert_eq!(status_body["plugin_status"]["other"]["data"], json!({"ok": true})); + assert_eq!(status_body["other"]["data"], json!({"ok": true})); node.forward_plugin_event(plugin::PluginMeshEvent::PluginDisconnected { plugin_id: "powermetrics".into(), @@ -328,11 +328,11 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { read_until_contains(&mut events, b"\"state\":\"unavailable\"", Duration::from_secs(2)).await; let status_body = request_management_json(state.clone(), "/api/status").await; assert_eq!( - status_body["plugin_status"]["powermetrics"]["state"], + status_body["powermetrics"]["state"], json!("unavailable") ); assert_eq!( - status_body["plugin_status"]["powermetrics"]["data"], + status_body["powermetrics"]["data"], json!({"idle_watts": 8.2}), "the last snapshot stays, shown as unavailable" ); @@ -345,7 +345,8 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { .unwrap(); } let status_body = request_management_json(state.clone(), "/api/status").await; - assert!(status_body.get("plugin_status").is_none()); + assert!(status_body.get("powermetrics").is_none()); + assert!(status_body.get("other").is_none()); drop(events); handle.abort(); @@ -371,8 +372,14 @@ async fn a_refused_plugin_status_says_why_and_changes_nothing() { .unwrap_err(); assert!(error.message.contains("the limit is 16384"), "{}", error.message); + let error = publish_test_plugin_status(&node, "peers", r#"{"n":1}"#) + .await + .unwrap_err(); + assert!(error.message.contains("core /api/status field"), "{}", error.message); + let status_body = request_management_json(state, "/api/status").await; - assert!(status_body.get("plugin_status").is_none()); + assert!(status_body.get("powermetrics").is_none()); + assert!(status_body["peers"].is_array(), "the core field is untouched"); } #[tokio::test] diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs index 6d471fcef5..804db479b2 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs @@ -5,7 +5,7 @@ //! plugin's data: receipt time, freshness and availability. Limits and the //! wire contract are in `mesh_llm_plugin::plugin_status`. -use crate::api::status::{PluginStatusPayload, PluginStatusState}; +use crate::api::status::{CORE_STATUS_FIELDS, PluginStatusPayload, PluginStatusState}; use crate::plugin::proto; use mesh_llm_plugin::plugin_status::{MAX_DATA_BYTES, MIN_PUBLISH_INTERVAL, effective_fresh_for}; use std::collections::BTreeMap; @@ -16,14 +16,23 @@ use tokio::time::Instant; /// Why the host refused a snapshot. #[derive(Debug, PartialEq, Eq)] pub(crate) enum PluginStatusRejection { - TooLarge { bytes: usize }, + /// The plugin's name is a core `/api/status` field. + CoreFieldName, + TooLarge { + bytes: usize, + }, NotAnObject, - TooSoon { retry_after: Duration }, + TooSoon { + retry_after: Duration, + }, } impl PluginStatusRejection { pub(crate) fn message(&self, plugin_name: &str) -> String { match self { + Self::CoreFieldName => format!( + "plugin `{plugin_name}` is named like a core /api/status field, so it cannot publish a status; rename it in the node's config" + ), Self::TooLarge { bytes } => format!( "status data from plugin `{plugin_name}` is {bytes} bytes; the limit is {MAX_DATA_BYTES}" ), @@ -112,6 +121,9 @@ impl PluginStatusStore { fresh_for: None, }); } + if CORE_STATUS_FIELDS.contains(&plugin_name) { + return Err(PluginStatusRejection::CoreFieldName); + } if request.data_json.len() > MAX_DATA_BYTES { return Err(PluginStatusRejection::TooLarge { bytes: request.data_json.len(), @@ -314,6 +326,19 @@ mod tests { assert_eq!(store.payloads(now)["p"].data, serde_json::json!({"n": 3})); } + #[test] + fn a_plugin_named_like_a_core_field_cannot_publish() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + assert_eq!( + store + .publish("peers", 1, 1, &request(r#"{"n":1}"#, 0), now, 1) + .err(), + Some(PluginStatusRejection::CoreFieldName) + ); + assert!(store.payloads(now).is_empty(), "nothing was stored"); + } + #[test] fn freshness_is_kept_within_the_host_bounds() { let mut store = PluginStatusStore::default(); diff --git a/mesh/crates/mesh-llm-plugin/proto/plugin.proto b/mesh/crates/mesh-llm-plugin/proto/plugin.proto index a38be9df69..504983b033 100644 --- a/mesh/crates/mesh-llm-plugin/proto/plugin.proto +++ b/mesh/crates/mesh-llm-plugin/proto/plugin.proto @@ -758,9 +758,9 @@ message PluginKeyResponse { bytes binding_signature = 2; } -// A plugin publishes the snapshot shown at `/api/status.plugin_status.`, -// where `` is the host's name for the plugin connection, never a name the -// plugin claims. A later publication replaces it, and an empty `data_json` +// A plugin publishes the snapshot shown at `/api/status.`, where `` +// is the host's name for the plugin connection, never a name the plugin claims, +// and never the name of a core status field. A later publication replaces it, and an empty `data_json` // withdraws it. The host keeps the latest one and owns its envelope: receipt // time and freshness. `/api/status` reads that copy and never calls the // plugin. Handled only by a host listing the `plugin_status.v1` capability, diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index fefe4a4d03..910e77131a 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -1397,19 +1397,17 @@ clients see it without querying a plugin endpoint. It declares (`PluginManifest.plugin_status`), then publishes with `PluginContext::publish_status(&data, fresh_for)`, from `on_initialized` or any task holding an owned context. Each publication replaces the previous one; -`withdraw_status` removes it. The host shows the latest one under the name it -knows the plugin connection by, never a name the plugin claims, so one plugin -cannot overwrite another's contribution or a core field: +`withdraw_status` removes it. The host shows the latest one as a top-level +field of the status, under the name it knows the plugin connection by, never a +name the plugin claims, so one plugin cannot overwrite another's contribution: ```json -"plugin_status": { - "powermetrics": { - "schema_version": 1, - "state": "ready", - "received_at_unix_ms": 1793404800000, - "fresh_until_unix_ms": 1793404860000, - "data": { "source": "macmon", "idle_watts": 8.2 } - } +"powermetrics": { + "schema_version": 1, + "state": "ready", + "received_at_unix_ms": 1793404800000, + "fresh_until_unix_ms": 1793404860000, + "data": { "source": "macmon", "idle_watts": 8.2 } } ``` @@ -1426,7 +1424,8 @@ is the host's: missing sensor reading says so in `data`. The host refuses a publication from a plugin whose manifest does not declare -`plugin_status`, from a connection that is no longer the plugin's current one, +`plugin_status`, from a plugin named like a core status field such as `peers` +or `runtime` (rename it in the node's config), from a connection that is no longer the plugin's current one, `data_json` that is not a JSON object or is larger than 16 KiB, and a snapshot sent less than 1 s after the previous one from the same connection. Refusals come back as an error and change nothing; a withdrawal is always accepted. A @@ -1436,7 +1435,7 @@ host has read the plugin's manifest waits for it. Reads serve the host's copy: `/api/status` never starts, restarts or calls a plugin, so a hung plugin cannot slow it. Every accepted publication, and every change of state, wakes `/api/events`, which sends the new status. Without any -contribution, `plugin_status` is omitted and the response is unchanged. It is +contribution, the response is unchanged. It is local to this node, like the rest of `/api/status`: nothing is gossiped. The host advertises the `plugin_status.v1` host capability in its From dab38ffabed37794832b38ef7288ccb2e2f3d261 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:26:34 +0100 Subject: [PATCH 5/7] docs(plugins): say a status contribution is a top-level field of GET /api/status --- mesh/crates/mesh-llm-plugin/proto/plugin.proto | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mesh/crates/mesh-llm-plugin/proto/plugin.proto b/mesh/crates/mesh-llm-plugin/proto/plugin.proto index 504983b033..c7b9a61c4a 100644 --- a/mesh/crates/mesh-llm-plugin/proto/plugin.proto +++ b/mesh/crates/mesh-llm-plugin/proto/plugin.proto @@ -758,9 +758,9 @@ message PluginKeyResponse { bytes binding_signature = 2; } -// A plugin publishes the snapshot shown at `/api/status.`, where `` -// is the host's name for the plugin connection, never a name the plugin claims, -// and never the name of a core status field. A later publication replaces it, and an empty `data_json` +// A plugin publishes the snapshot that `GET /api/status` shows as its top-level +// field ``, the host's name for the plugin connection: never a name the +// plugin claims, and never the name of a core status field. A later publication replaces it, and an empty `data_json` // withdraws it. The host keeps the latest one and owns its envelope: receipt // time and freshness. `/api/status` reads that copy and never calls the // plugin. Handled only by a host listing the `plugin_status.v1` capability, From 8fdf34930eb83a31554a9b5bfac390241c6eb4ff Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:38:32 +0100 Subject: [PATCH 6/7] docs(plugins): point the SDK at the top-level status field --- mesh/crates/mesh-llm-plugin/src/plugin_status.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mesh/crates/mesh-llm-plugin/src/plugin_status.rs b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs index 3910e1a309..44aec319e5 100644 --- a/mesh/crates/mesh-llm-plugin/src/plugin_status.rs +++ b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs @@ -2,8 +2,8 @@ //! //! A plugin declares [`plugin_status`] in its manifest and publishes snapshots //! with [`crate::PluginContext::publish_status`]. The host keeps the latest one -//! and shows it at `/api/status.plugin_status.`, inside an -//! envelope the host owns: +//! and shows it as the top-level field named after the plugin in +//! `GET /api/status`, inside an envelope the host owns: //! //! ```json //! { From 90311d0b237fb5151a956a997c25f28fdede219d Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Tue, 27 Oct 2026 05:01:48 +0100 Subject: [PATCH 7/7] feat(plugins): keep status contributions in a plugins envelope Back to an envelope, now named plugins, as asked in review: a plugin's snapshot sits in /api/status under plugins., so no plugin can shadow a core field and the reserved-name check is gone. --- .../mesh-llm-host-runtime/src/api/status.rs | 83 ++----------------- .../src/api/tests/runtime_data.rs | 23 ++--- .../src/runtime_data/plugin_status.rs | 31 +------ .../crates/mesh-llm-plugin/proto/plugin.proto | 6 +- .../mesh-llm-plugin/src/plugin_status.rs | 4 +- mesh/docs/plugins/README.md | 25 +++--- 6 files changed, 34 insertions(+), 138 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs index 65c82f48e8..d853e4c7ba 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs @@ -392,67 +392,14 @@ pub(crate) struct StatusPayload { /// state has been initialized so older consumers retain their prior shape. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) logging: Option, - /// Snapshots plugins published over their local connections, each as a - /// top-level field named by the host's name for the plugin; see - /// [`PluginStatusPayload`]. Local-only, and absent while no plugin - /// contributes, so the shape is unchanged. A plugin named like one of - /// [`CORE_STATUS_FIELDS`] cannot contribute. - #[serde(flatten)] + /// `plugins`: snapshots plugins published over their local connections, + /// by the host's name for each plugin; see [`PluginStatusPayload`]. + /// Local-only, and omitted while no plugin contributes, so the shape is + /// unchanged. + #[serde(rename = "plugins", skip_serializing_if = "BTreeMap::is_empty")] pub(crate) plugin_status: BTreeMap, } -/// The fields of [`StatusPayload`] besides the plugins' contributions. A -/// plugin by one of these names is refused, so it never shadows a core field. -pub(crate) const CORE_STATUS_FIELDS: &[&str] = &[ - "version", - "latest_version", - "node_id", - "owner", - "release_attestation", - "token", - "node_state", - "node_status", - "is_host", - "is_client", - "llama_ready", - "runtime", - "model_name", - "models", - "available_models", - "requested_models", - "wanted_model_refs", - "serving_models", - "hosted_models", - "draft_name", - "api_port", - "my_vram_gb", - "model_size_gb", - "peers", - "wakeable_nodes", - "local_instances", - "launch_pi", - "launch_goose", - "inflight_requests", - "mesh_id", - "mesh_name", - "mesh_discovery_mode", - "discovery_scope", - "discovery_source", - "nostr_discovery", - "publication_state", - "my_hostname", - "my_is_soc", - "my_memory", - "gpus", - "routing_affinity", - "routing_metrics", - "first_joined_mesh_ts", - "mesh_requirements", - "recent_mesh_rejections", - "plugin_frame_telemetry", - "logging", -]; - /// One plugin's contribution to `/api/status`. The host owns everything but /// `data`, which is the plugin's own, in version `schema_version` of its own /// schema. The state and timestamps say when the host last heard from the @@ -975,26 +922,6 @@ mod tests { use super::*; use crate::ReleaseAttestationSummary; - #[test] - fn core_status_fields_name_every_field_but_the_plugins() { - // Read from the struct itself, so a new field cannot be left out and - // let a plugin of that name shadow it. - let fields = include_str!("status.rs") - .lines() - .skip_while(|line| !line.starts_with("pub(crate) struct StatusPayload {")) - .skip(1) - .take_while(|line| *line != "}") - .filter_map(|line| line.trim().strip_prefix("pub(crate) ")) - .filter_map(|field| field.split_once(':').map(|(name, _)| name)) - .filter(|name| *name != "plugin_status") - .collect::>(); - assert_eq!( - fields, - CORE_STATUS_FIELDS.iter().copied().collect(), - "CORE_STATUS_FIELDS must list StatusPayload's fields" - ); - } - fn test_owner_payload() -> OwnershipPayload { OwnershipPayload { owner_id: None, diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs index 8d8d6bfcb1..37f63ebc4a 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs @@ -291,7 +291,7 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { let status_body = request_management_json(state.clone(), "/api/status").await; assert!( - status_body.get("powermetrics").is_none(), + status_body.get("plugins").is_none(), "no contribution, no field" ); @@ -309,15 +309,15 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { .await .expect("the snapshot is accepted"); let pushed = read_until_contains(&mut events, b"\"idle_watts\":8.2", Duration::from_secs(2)).await; - assert!(String::from_utf8_lossy(&pushed).contains("\"powermetrics\":{")); + assert!(String::from_utf8_lossy(&pushed).contains("\"plugins\"")); let status_body = request_management_json(state.clone(), "/api/status").await; - let contribution = &status_body["powermetrics"]; + let contribution = &status_body["plugins"]["powermetrics"]; assert_eq!(contribution["schema_version"], json!(1)); assert_eq!(contribution["state"], json!("ready")); assert_eq!(contribution["data"], json!({"idle_watts": 8.2})); assert!(contribution["fresh_until_unix_ms"].as_u64() > contribution["received_at_unix_ms"].as_u64()); - assert_eq!(status_body["other"]["data"], json!({"ok": true})); + assert_eq!(status_body["plugins"]["other"]["data"], json!({"ok": true})); node.forward_plugin_event(plugin::PluginMeshEvent::PluginDisconnected { plugin_id: "powermetrics".into(), @@ -328,11 +328,11 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { read_until_contains(&mut events, b"\"state\":\"unavailable\"", Duration::from_secs(2)).await; let status_body = request_management_json(state.clone(), "/api/status").await; assert_eq!( - status_body["powermetrics"]["state"], + status_body["plugins"]["powermetrics"]["state"], json!("unavailable") ); assert_eq!( - status_body["powermetrics"]["data"], + status_body["plugins"]["powermetrics"]["data"], json!({"idle_watts": 8.2}), "the last snapshot stays, shown as unavailable" ); @@ -345,8 +345,7 @@ async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() { .unwrap(); } let status_body = request_management_json(state.clone(), "/api/status").await; - assert!(status_body.get("powermetrics").is_none()); - assert!(status_body.get("other").is_none()); + assert!(status_body.get("plugins").is_none()); drop(events); handle.abort(); @@ -372,14 +371,8 @@ async fn a_refused_plugin_status_says_why_and_changes_nothing() { .unwrap_err(); assert!(error.message.contains("the limit is 16384"), "{}", error.message); - let error = publish_test_plugin_status(&node, "peers", r#"{"n":1}"#) - .await - .unwrap_err(); - assert!(error.message.contains("core /api/status field"), "{}", error.message); - let status_body = request_management_json(state, "/api/status").await; - assert!(status_body.get("powermetrics").is_none()); - assert!(status_body["peers"].is_array(), "the core field is untouched"); + assert!(status_body.get("plugins").is_none()); } #[tokio::test] diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs index 804db479b2..6d471fcef5 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs @@ -5,7 +5,7 @@ //! plugin's data: receipt time, freshness and availability. Limits and the //! wire contract are in `mesh_llm_plugin::plugin_status`. -use crate::api::status::{CORE_STATUS_FIELDS, PluginStatusPayload, PluginStatusState}; +use crate::api::status::{PluginStatusPayload, PluginStatusState}; use crate::plugin::proto; use mesh_llm_plugin::plugin_status::{MAX_DATA_BYTES, MIN_PUBLISH_INTERVAL, effective_fresh_for}; use std::collections::BTreeMap; @@ -16,23 +16,14 @@ use tokio::time::Instant; /// Why the host refused a snapshot. #[derive(Debug, PartialEq, Eq)] pub(crate) enum PluginStatusRejection { - /// The plugin's name is a core `/api/status` field. - CoreFieldName, - TooLarge { - bytes: usize, - }, + TooLarge { bytes: usize }, NotAnObject, - TooSoon { - retry_after: Duration, - }, + TooSoon { retry_after: Duration }, } impl PluginStatusRejection { pub(crate) fn message(&self, plugin_name: &str) -> String { match self { - Self::CoreFieldName => format!( - "plugin `{plugin_name}` is named like a core /api/status field, so it cannot publish a status; rename it in the node's config" - ), Self::TooLarge { bytes } => format!( "status data from plugin `{plugin_name}` is {bytes} bytes; the limit is {MAX_DATA_BYTES}" ), @@ -121,9 +112,6 @@ impl PluginStatusStore { fresh_for: None, }); } - if CORE_STATUS_FIELDS.contains(&plugin_name) { - return Err(PluginStatusRejection::CoreFieldName); - } if request.data_json.len() > MAX_DATA_BYTES { return Err(PluginStatusRejection::TooLarge { bytes: request.data_json.len(), @@ -326,19 +314,6 @@ mod tests { assert_eq!(store.payloads(now)["p"].data, serde_json::json!({"n": 3})); } - #[test] - fn a_plugin_named_like_a_core_field_cannot_publish() { - let mut store = PluginStatusStore::default(); - let now = Instant::now(); - assert_eq!( - store - .publish("peers", 1, 1, &request(r#"{"n":1}"#, 0), now, 1) - .err(), - Some(PluginStatusRejection::CoreFieldName) - ); - assert!(store.payloads(now).is_empty(), "nothing was stored"); - } - #[test] fn freshness_is_kept_within_the_host_bounds() { let mut store = PluginStatusStore::default(); diff --git a/mesh/crates/mesh-llm-plugin/proto/plugin.proto b/mesh/crates/mesh-llm-plugin/proto/plugin.proto index c7b9a61c4a..c6d3360d48 100644 --- a/mesh/crates/mesh-llm-plugin/proto/plugin.proto +++ b/mesh/crates/mesh-llm-plugin/proto/plugin.proto @@ -758,9 +758,9 @@ message PluginKeyResponse { bytes binding_signature = 2; } -// A plugin publishes the snapshot that `GET /api/status` shows as its top-level -// field ``, the host's name for the plugin connection: never a name the -// plugin claims, and never the name of a core status field. A later publication replaces it, and an empty `data_json` +// A plugin publishes the snapshot that `GET /api/status` shows under +// `plugins.`, where `` is the host's name for the plugin +// connection, never a name the plugin claims. A later publication replaces it, and an empty `data_json` // withdraws it. The host keeps the latest one and owns its envelope: receipt // time and freshness. `/api/status` reads that copy and never calls the // plugin. Handled only by a host listing the `plugin_status.v1` capability, diff --git a/mesh/crates/mesh-llm-plugin/src/plugin_status.rs b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs index 44aec319e5..9f557a10d5 100644 --- a/mesh/crates/mesh-llm-plugin/src/plugin_status.rs +++ b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs @@ -2,8 +2,8 @@ //! //! A plugin declares [`plugin_status`] in its manifest and publishes snapshots //! with [`crate::PluginContext::publish_status`]. The host keeps the latest one -//! and shows it as the top-level field named after the plugin in -//! `GET /api/status`, inside an envelope the host owns: +//! and shows it in `GET /api/status` under `plugins.`, inside an +//! envelope the host owns: //! //! ```json //! { diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index 910e77131a..e35a0ffb92 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -1397,17 +1397,19 @@ clients see it without querying a plugin endpoint. It declares (`PluginManifest.plugin_status`), then publishes with `PluginContext::publish_status(&data, fresh_for)`, from `on_initialized` or any task holding an owned context. Each publication replaces the previous one; -`withdraw_status` removes it. The host shows the latest one as a top-level -field of the status, under the name it knows the plugin connection by, never a -name the plugin claims, so one plugin cannot overwrite another's contribution: +`withdraw_status` removes it. The host shows the latest one under the name it +knows the plugin connection by, never a name the plugin claims, so one plugin +cannot overwrite another's contribution or a core field: ```json -"powermetrics": { - "schema_version": 1, - "state": "ready", - "received_at_unix_ms": 1793404800000, - "fresh_until_unix_ms": 1793404860000, - "data": { "source": "macmon", "idle_watts": 8.2 } +"plugins": { + "powermetrics": { + "schema_version": 1, + "state": "ready", + "received_at_unix_ms": 1793404800000, + "fresh_until_unix_ms": 1793404860000, + "data": { "source": "macmon", "idle_watts": 8.2 } + } } ``` @@ -1424,8 +1426,7 @@ is the host's: missing sensor reading says so in `data`. The host refuses a publication from a plugin whose manifest does not declare -`plugin_status`, from a plugin named like a core status field such as `peers` -or `runtime` (rename it in the node's config), from a connection that is no longer the plugin's current one, +`plugin_status`, from a connection that is no longer the plugin's current one, `data_json` that is not a JSON object or is larger than 16 KiB, and a snapshot sent less than 1 s after the previous one from the same connection. Refusals come back as an error and change nothing; a withdrawal is always accepted. A @@ -1435,7 +1436,7 @@ host has read the plugin's manifest waits for it. Reads serve the host's copy: `/api/status` never starts, restarts or calls a plugin, so a hung plugin cannot slow it. Every accepted publication, and every change of state, wakes `/api/events`, which sends the new status. Without any -contribution, the response is unchanged. It is +contribution, `plugins` is omitted and the response is unchanged. It is local to this node, like the rest of `/api/status`: nothing is gossiped. The host advertises the `plugin_status.v1` host capability in its