Skip to main content

netget/client/nut/
actions.rs

1use crate::llm::actions::{
2    client_trait::{Client, ClientActionResult},
3    protocol_trait::Protocol,
4    ActionDefinition,
5};
6use crate::protocol::{ConnectContext, EventType};
7use crate::server::nut::{
8    actions::{action, parameter},
9    wire::Request,
10};
11use crate::state::app_state::AppState;
12use anyhow::{bail, Result};
13use serde_json::{json, Value};
14use std::sync::LazyLock;
15#[derive(Default)]
16pub struct NutClientProtocol;
17impl NutClientProtocol {
18    pub fn new() -> Self {
19        Self
20    }
21}
22fn request_action() -> ActionDefinition {
23    action("nut_request", "Send a structured NUT operation. Requests are serialized and replies are correlated before raising nut_response.", vec![
24        parameter("operation","string","list_ups/list_var/list_rw/list_cmd/list_enum/get_var/get_desc/get_cmddesc/get_upsdesc/get_type/set_var/instcmd/username/password/logout",true),
25        parameter("ups","string","UPS identifier except list_ups and credentials/logout",false),parameter("name","string","Variable or command name",false),parameter("value","string","Value for set_var, username or password",false),
26    ],json!({"type":"nut_request","operation":"list_ups"}))
27}
28fn disconnect_action() -> ActionDefinition {
29    action(
30        "disconnect",
31        "Close the NUT connection",
32        vec![],
33        json!({"type":"disconnect"}),
34    )
35}
36fn actions() -> Vec<ActionDefinition> {
37    vec![request_action(), disconnect_action()]
38}
39pub static CONNECTED_EVENT: LazyLock<EventType> = LazyLock::new(|| {
40    EventType::new(
41        "nut_connected",
42        "Connected to NUT; send a request",
43        request_action().example.clone(),
44    )
45    .with_parameters(vec![parameter(
46        "remote_addr",
47        "string",
48        "NUT server address",
49        true,
50    )])
51    .with_actions(actions())
52});
53pub static RESPONSE_EVENT: LazyLock<EventType> = LazyLock::new(|| {
54    EventType::new("nut_response","Complete, validated NUT response, or a NUT server error. Credentials are redacted from request.",disconnect_action().example.clone()).with_parameters(vec![parameter("request","object","Structured request",true),parameter("response","object","entries, value, types, ok or error",true)]).with_actions(actions())
55});
56impl Protocol for NutClientProtocol {
57    fn protocol_name(&self) -> &'static str {
58        "NUT"
59    }
60    fn stack_name(&self) -> &'static str {
61        "ETH>IP>TCP>NUT"
62    }
63    fn keywords(&self) -> Vec<&'static str> {
64        vec!["nut", "ups", "upsc", "rfc9271"]
65    }
66    fn description(&self) -> &'static str {
67        "NUT UPS management client with structured queries and authenticated commands"
68    }
69    fn get_async_actions(&self, _: &AppState) -> Vec<ActionDefinition> {
70        actions()
71    }
72    fn get_sync_actions(&self) -> Vec<ActionDefinition> {
73        vec![]
74    }
75    fn get_event_types(&self) -> Vec<EventType> {
76        vec![CONNECTED_EVENT.clone(), RESPONSE_EVENT.clone()]
77    }
78    fn metadata(&self) -> crate::protocol::metadata::ProtocolMetadataV2 {
79        use crate::protocol::metadata::*;
80        ProtocolMetadataV2::builder().state(DevelopmentState::Experimental).privilege_requirement(PrivilegeRequirement::None).well_known_port(3493)
81        .implementation("Tokio TCP with bounded ASCII parser, serialized request/reply correlation, structured lists")
82        .llm_control("UPS/variable queries, authentication, SET and instant commands; response events and injected actions")
83        .e2e_testing("tests/client/nut: independent wire fixture, malformed/mismatched replies, command injection and event handlers; see CLAUDE.md for real upsd evidence")
84        .notes("Plain TCP only; no TLS negotiation, attachment/primary/FSD or command tracking. Connect/response/write deadlines 30s, 8192-byte lines, 1 MiB/4096-entry replies. All tasks are registered and event/request queues are bounded at 16.")
85        .max_inbound_bytes(crate::server::nut::wire::MAX_RESPONSE_BYTES).build()
86    }
87    fn example_prompt(&self) -> &'static str {
88        "Connect to NUT at localhost:3493 and read ups.status"
89    }
90    fn get_startup_examples(&self) -> crate::llm::actions::StartupExamples {
91        let llm = json!({"type":"open_client","protocol":"nut","remote_addr":"127.0.0.1:3493","instruction":"List UPS devices"});
92        let mut static_example = llm.clone();
93        static_example["event_handlers"] = json!([{"event_pattern":"nut_connected","handler":{"type":"static","actions":[{"type":"nut_request","operation":"list_ups"}]}},{"event_pattern":"nut_response","handler":{"type":"static","actions":[]}}]);
94        let mut scripted = static_example.clone();
95        scripted["event_handlers"][0]["handler"] = json!({"type":"script","language":"python","code":"respond([{'type':'nut_request','operation':'list_ups'}])"});
96        crate::llm::actions::StartupExamples::new(llm, scripted, static_example)
97    }
98    fn group_name(&self) -> &'static str {
99        "Monitoring"
100    }
101}
102impl Client for NutClientProtocol {
103    fn connect(
104        &self,
105        ctx: ConnectContext,
106    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<std::net::SocketAddr>> + Send>>
107    {
108        Box::pin(super::connect(ctx))
109    }
110    fn execute_action(&self, v: Value) -> Result<ClientActionResult> {
111        match v["type"].as_str() {
112            Some("nut_request") => Ok(ClientActionResult::Custom {
113                name: "nut_request".into(),
114                data: json!(Request::from_action(&v)?),
115            }),
116            Some("disconnect") => Ok(ClientActionResult::Disconnect),
117            _ => bail!("Unknown NUT client action"),
118        }
119    }
120}