netget-tool 0.3.5

Network protocol stubbing toolkit: ~280 protocol servers and clients whose responses come from an LLM, a script, a static rule or a person.
use crate::llm::actions::{
    client_trait::{Client, ClientActionResult},
    protocol_trait::Protocol,
    ActionDefinition, ParameterDefinition,
};
use crate::protocol::{ConnectContext, EventType};
use crate::server::dav_common::actions::{action, parameter};
use crate::server::dav_common::{client as engine, server::Kind};
use anyhow::Result;
use serde_json::{json, Value};
use std::sync::LazyLock;

#[derive(Default)]
pub struct CalDavClientProtocol;
impl CalDavClientProtocol {
    pub const fn new() -> Self {
        Self
    }
}

pub static PROTOCOL: CalDavClientProtocol = CalDavClientProtocol;

fn coll() -> crate::llm::actions::Parameter {
    parameter(
        "collection",
        "string",
        "Calendar name under the home (as listed on connect) or its absolute path",
        true,
    )
}
fn name() -> crate::llm::actions::Parameter {
    parameter("name", "string", "Object file name, e.g. standup.ics", true)
}
fn actions() -> Vec<ActionDefinition> {
    vec![
        action("caldav_list", "List a calendar's objects with their ETags (PROPFIND Depth 1)", vec![coll()], json!({"type":"caldav_list","collection":"work"})),
        action("caldav_get", "Fetch one object (GET)", vec![coll(), name()], json!({"type":"caldav_get","collection":"work","name":"standup.ics"})),
        action(
            "caldav_put",
            "Create or replace an object (PUT); Rust checks the iCalendar text before sending",
            vec![coll(), name(), parameter("data", "string", "iCalendar text, e.g. BEGIN:VCALENDAR … BEGIN:VEVENT … UID … DTSTART … END:VEVENT … END:VCALENDAR", true), parameter("if_match", "string", "ETag the object must still have (update without overwriting someone else's change)", false), parameter("create_only", "boolean", "Send If-None-Match: * so an existing object is not overwritten", false)],
            json!({"type":"caldav_put","collection":"work","name":"standup.ics","data":"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//NetGet//EN\r\nBEGIN:VEVENT\r\nUID:standup\r\nDTSTAMP:20261005T090000Z\r\nDTSTART:20261005T100000Z\r\nDTEND:20261005T101500Z\r\nSUMMARY:Standup\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n","create_only":true}),
        ),
        action("caldav_delete", "Delete an object, or the whole calendar when name is omitted", vec![coll(), parameter("name", "string", "Object file name; omit to delete the calendar", false), parameter("if_match", "string", "ETag the object must still have", false)], json!({"type":"caldav_delete","collection":"work","name":"standup.ics"})),
        action("caldav_query", "Find objects overlapping a time range (calendar-query REPORT); data comes back with them", vec![coll(), parameter("start", "string", "UTC start like 20261005T000000Z", false), parameter("end", "string", "UTC end like 20261012T000000Z", false), parameter("component", "string", "VEVENT (default) or VTODO", false)], json!({"type":"caldav_query","collection":"work","start":"20261005T000000Z","end":"20261012T000000Z"})),
        action("caldav_make_collection", "Create a calendar under the home (MKCALENDAR)", vec![coll(), parameter("displayname", "string", "Display name for the new calendar", false)], json!({"type":"caldav_make_collection","collection":"work2","displayname":"Second"})),
        action("disconnect", "Stop this CalDAV client", vec![], json!({"type":"disconnect"})),
    ]
}

pub static CONNECTED_EVENT: LazyLock<EventType> = LazyLock::new(|| {
    EventType::new(
        "caldav_connected",
        "Discovery finished: the principal, the home and its calendars",
        json!({"type":"caldav_list","collection":"work"}),
    )
    .with_parameters(vec![
        parameter(
            "principal",
            "string",
            "Path of the current user's principal",
            true,
        ),
        parameter("home", "string", "Path of the calendar home", true),
        parameter(
            "collections",
            "array",
            "[{href, name, displayname, ctag}] for every calendar in the home",
            true,
        ),
    ])
    .with_actions(actions())
});
pub static RESPONSE_EVENT: LazyLock<EventType> = LazyLock::new(|| {
    EventType::new(
        "caldav_response",
        "The server's answer to the last operation",
        json!({"type":"disconnect"}),
    )
    .with_parameters(vec![
        parameter(
            "operation",
            "string",
            "list, get, put, delete, query or make_collection",
            true,
        ),
        parameter(
            "status",
            "number",
            "HTTP status of the answer (207 for list and query)",
            true,
        ),
        parameter(
            "objects",
            "array",
            "For list and query: [{href, name, etag, data (query only)}]",
            false,
        ),
        parameter("data", "string", "For get: the object text", false),
        parameter(
            "etag",
            "string",
            "For get and put: the object's entity tag",
            false,
        ),
        parameter(
            "error",
            "string",
            "For a refused put: the server's error body",
            false,
        ),
    ])
    .with_actions(actions())
});

impl Protocol for CalDavClientProtocol {
    fn protocol_name(&self) -> &'static str {
        "CalDAV"
    }
    fn stack_name(&self) -> &'static str {
        "ETH>IP>TCP>HTTP>WebDAV>CalDAV"
    }
    fn keywords(&self) -> Vec<&'static str> {
        vec!["caldav", "calendar client", "ical"]
    }
    fn description(&self) -> &'static str {
        "CalDAV client: discovers the user's calendars, lists, queries, reads, writes and deletes objects"
    }
    fn get_async_actions(&self, _: &crate::state::app_state::AppState) -> Vec<ActionDefinition> {
        actions()
    }
    fn get_sync_actions(&self) -> Vec<ActionDefinition> {
        vec![]
    }
    fn get_event_types(&self) -> Vec<EventType> {
        vec![CONNECTED_EVENT.clone(), RESPONSE_EVENT.clone()]
    }
    fn get_startup_parameters(&self) -> Vec<ParameterDefinition> {
        let p =
            |name: &str, kind: &str, description: &str, example: Value, default: Option<Value>| {
                ParameterDefinition {
                    name: name.into(),
                    type_hint: kind.into(),
                    description: description.into(),
                    required: false,
                    example,
                    default,
                }
            };
        vec![
            p(
                "scheme",
                "string",
                "URL scheme to reach the server with: https (default) or http",
                json!("http"),
                Some(json!(engine::DEFAULT_SCHEME)),
            ),
            p(
                "username",
                "string",
                "User name for HTTP Basic authentication",
                json!("alice"),
                None,
            ),
            p(
                "password",
                "string",
                "Password for HTTP Basic authentication",
                json!("secret"),
                None,
            ),
        ]
    }
    fn metadata(&self) -> crate::protocol::metadata::ProtocolMetadataV2 {
        use crate::protocol::metadata::*;
        ProtocolMetadataV2::builder()
            .state(DevelopmentState::Experimental)
            .privilege_requirement(PrivilegeRequirement::None)
            .implementation("Shared http_fetch client (reqwest natively, redirects followed by hand for discovery only); RFC 6764 well-known discovery, PROPFIND, calendar-query REPORT, multistatus parsing, If-Match / If-None-Match, MKCALENDAR; objects validated with the server's parser before PUT")
            .llm_control("Which calendars and objects to read, query, write or delete")
            .e2e_testing("tests/client/caldav: Radicale 3.8.1 (independent) answers discovery, collection creation, PUT, list, query, GET, conditional PUT and DELETE")
            .notes("No sync-collection or scheduling; one request at a time.")
            .max_inbound_bytes(crate::server::dav_common::xml::MAX_BODY * 4)
            .build()
    }
    fn example_prompt(&self) -> &'static str {
        "List this week's events on the CalDAV server at 127.0.0.1:5232"
    }
    fn get_startup_examples(&self) -> crate::llm::actions::StartupExamples {
        let llm = json!({"type":"open_client","protocol":"caldav","remote_addr":"127.0.0.1:5232","instruction":"List this week's meetings","startup_params":{"scheme":"http","username":"alice","password":"secret"}});
        let mut static_example = llm.clone();
        static_example["event_handlers"] = json!([
            {"event_pattern":"caldav_connected","handler":{"type":"static","actions":[{"type":"caldav_list","collection":"work"}]}},
            {"event_pattern":"caldav_response","handler":{"type":"static","actions":[]}}
        ]);
        let mut scripted = static_example.clone();
        scripted["event_handlers"][1]["handler"] = json!({"type":"script","language":"python","code":"import json\nprint(json.dumps({'actions':[]}))"});
        crate::llm::actions::StartupExamples::new(llm, scripted, static_example)
    }
    fn group_name(&self) -> &'static str {
        "Web & File"
    }
}

impl Client for CalDavClientProtocol {
    fn connect(
        &self,
        ctx: ConnectContext,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<std::net::SocketAddr>> + Send>>
    {
        Box::pin(engine::connect(ctx, &super::FLAVOR))
    }
    fn execute_action(&self, v: Value) -> Result<ClientActionResult> {
        engine::check_action("caldav", Kind::Calendar, &v)
    }
}