netget-tool 0.3.4

Network protocol stubbing toolkit: ~280 protocol servers and clients whose responses come from an LLM, a script, a static rule or a person.
Documentation
//! BLE file transfer - custom GATT control point plus data characteristic
//!
//! Profile wrapper over the `bluetooth-ble` base stack.
//!
//! The base server (`BluetoothBle::spawn_with_llm_actions`) hardcodes `BluetoothBleProtocol`
//! when it calls `call_llm`, so the events the model actually sees and the actions it may
//! answer with are always the base's. Declaring profile-specific actions or events here would
//! document a vocabulary that no code path can ever emit or execute, so this protocol forwards
//! the base's set verbatim - the same shape `doh`/`dot` use to forward `DnsProtocol`'s actions.
//! The profile identity lives in the instruction preamble and in the GATT layout suggested by
//! the startup examples below.

use crate::llm::actions::{
    protocol_trait::{ActionResult, Protocol, Server},
    ActionDefinition, ParameterDefinition,
};
use crate::protocol::EventType;
use crate::server::bluetooth_ble::actions::BluetoothBleProtocol;
use crate::state::app_state::AppState;
use anyhow::Result;
use serde_json::json;

/// BLE file transfer - custom GATT control point plus data characteristic
pub struct BluetoothBleFileTransferProtocol;

impl BluetoothBleFileTransferProtocol {
    pub fn new() -> Self {
        Self
    }

    /// The base protocol this profile delegates its whole vocabulary to.
    fn base() -> BluetoothBleProtocol {
        BluetoothBleProtocol::new()
    }
}

impl Default for BluetoothBleFileTransferProtocol {
    fn default() -> Self {
        Self::new()
    }
}

impl Protocol for BluetoothBleFileTransferProtocol {
    fn get_startup_parameters(&self) -> Vec<ParameterDefinition> {
        vec![ParameterDefinition {
            name: "device_name".to_string(),
            type_hint: "string".to_string(),
            description: "Bluetooth device name to advertise (default: NetGet-FileTransfer)"
                .to_string(),
            required: false,
            example: json!("NetGet-FileTransfer"),
            default: None,
        }]
    }

    /// Delegated: the base stack owns every action this server can execute.
    fn get_async_actions(&self, state: &AppState) -> Vec<ActionDefinition> {
        Self::base().get_async_actions(state)
    }

    /// Delegated: see `get_async_actions`. Returning `vec![]` here while the base emits
    /// events would leave the model with no way to answer a read or a write.
    fn get_sync_actions(&self) -> Vec<ActionDefinition> {
        Self::base().get_sync_actions()
    }

    /// Delegated: the base's event types are the only ones ever emitted for this server, and
    /// they carry their own `.with_actions(...)` lists, which is what `call_llm` offers the
    /// model. An event id declared here but not emitted by the base would silently match an
    /// `event_handlers` pattern that can never fire.
    fn get_event_types(&self) -> Vec<EventType> {
        Self::base().get_event_types()
    }

    fn protocol_name(&self) -> &'static str {
        "BLUETOOTH_BLE_FILE_TRANSFER"
    }

    fn stack_name(&self) -> &'static str {
        "BLUETOOTH_BLE_FILE_TRANSFER"
    }

    fn keywords(&self) -> Vec<&'static str> {
        // Deliberately no bare single words: bare "file" and "transfer" swallowed FTP's "file transfer" and NFS's "file server". A keyword is matched with
        // word boundaries against the whole prompt, so a generic one silently wins
        // requests meant for another protocol. "bluetooth"/"ble" are dropped too --
        // they are shared by 18 BLE profiles and identify none of them.
        vec!["ble file transfer", "ble ota", "ota update"]
    }

    fn metadata(&self) -> crate::protocol::metadata::ProtocolMetadataV2 {
        use crate::protocol::metadata::{DevelopmentState, ProtocolMetadataV2};

        ProtocolMetadataV2::builder()
            .state(DevelopmentState::Experimental)
            .implementation(
                "bluetooth-ble base stack (ble-peripheral-rust) plus an instruction preamble for the custom file transfer service",
            )
            .llm_control(
                "Base BLE GATT control (add_service, start_advertising, stop_advertising, respond_to_read, respond_to_write, send_notification); the LLM builds the custom file transfer service itself.",
            )
            .e2e_testing(
                "Two automated suites, neither of which is evidence for a rating above Experimental. tests/server/bluetooth_ble_file_transfer/e2e_test.rs covers the wiring only: open_server reaches this protocol's spawn, the base brings the radio up, and a bluetooth_ble_started event is raised and answered - it builds no service and puts no byte on the wire, and it claims the machine's Bluetooth adapter. gatt_examples_test.rs needs no adapter and checks the startup examples for internal coherence (this profile's UUIDs are custom, so there is no SIG layout to check the bytes against). Proving the profile works still needs a real central (nRF Connect, btleplug) exercising a service this profile built; nothing in the tree does that.",
            )
            .notes(
                "Thin profile wrapper over the bluetooth-ble base stack. It prepends an instruction describing the custom file transfer service and otherwise reuses the base entirely: the base hardcodes BluetoothBleProtocol when it calls the LLM, so the action vocabulary, the event types and the executor are the base's. This protocol deliberately declares no actions or events of its own - one that did would be documented to the model but never reachable at runtime.",
            )
            .build()
    }

    fn description(&self) -> &'static str {
        "BLE file transfer - custom GATT control point plus data characteristic"
    }

    fn example_prompt(&self) -> &'static str {
        "Act as a BLE file server offering a 4 KB file named readme.txt in 180-byte chunks"
    }

    fn group_name(&self) -> &'static str {
        "Network"
    }

    fn get_startup_examples(&self) -> crate::llm::actions::StartupExamples {
        use crate::llm::actions::StartupExamples;

        // Every event id and action name below is one the base stack really emits and really
        // executes. UUIDs are written in full 128-bit form because the base parses them with
        // `Uuid::parse_str`, which rejects the 16-bit shorthand.
        StartupExamples::new(
            // LLM mode: the model builds the GATT layout and answers reads itself.
            json!({
                "type": "open_server",
                "port": 0,
                "base_stack": "bluetooth-ble-file-transfer",
                "instruction": "Act as a BLE file server offering a 4 KB file named readme.txt in 180-byte chunks",
                "startup_params": {
                    "device_name": "NetGet-FileTransfer"
                }
            }),
            // Script mode: a write is acknowledged in-process, with no model call. Neither
            // characteristic is readable, so there is no read to answer here.
            json!({
                "type": "open_server",
                "port": 0,
                "base_stack": "bluetooth-ble-file-transfer",
                "startup_params": {
                    "device_name": "NetGet-FileTransfer"
                },
                "event_handlers": [
                    {
                        "event_pattern": "bluetooth_write_request",
                        "handler": {
                            "type": "script",
                            "language": "python",
                            "code": "import json,sys\njson.load(sys.stdin)\nprint(json.dumps({'actions':[{'type':'respond_to_write','status':'success'}]}))"
                        }
                    }
                ]
            }),
            // Static mode: a fixed GATT layout and a fixed write acknowledgement, with no model
            // call. Nothing here is readable, so there is no read to answer.
            json!({
                "type": "open_server",
                "port": 0,
                "base_stack": "bluetooth-ble-file-transfer",
                "startup_params": {
                    "device_name": "NetGet-FileTransfer"
                },
                "event_handlers": [
                    {
                        "event_pattern": "bluetooth_ble_started",
                        "handler": {
                            "type": "static",
                            "actions": [
                                {
                                    "type": "add_service",
                                    "uuid": "0000fe59-0000-1000-8000-00805f9b34fb",
                                    "primary": true,
                                    "characteristics": [
                                        {
                                            "uuid": "00008ec9-0000-1000-8000-00805f9b34fb",
                                            "properties": [
                                                "write",
                                                "notify"
                                            ],
                                            "permissions": [
                                                "writeable"
                                            ]
                                        },
                                        {
                                            "uuid": "00008ec8-0000-1000-8000-00805f9b34fb",
                                            "properties": [
                                                "write_without_response",
                                                "notify"
                                            ],
                                            "permissions": [
                                                "writeable"
                                            ]
                                        }
                                    ]
                                },
                                {
                                    "type": "start_advertising",
                                    "device_name": "NetGet-FileTransfer",
                                    "service_uuids": [
                                        "0000fe59-0000-1000-8000-00805f9b34fb"
                                    ]
                                }
                            ]
                        }
                    },
                    // A write handler, not a read one. Neither characteristic above is
                    // readable — both are write/notify, which is what a file-transfer
                    // control point and data pipe are — so the `bluetooth_read_request`
                    // handler this example used to carry could never match anything. It
                    // validated at startup and then sat there, an answer to a question the
                    // service cannot be asked, in the example a model copies verbatim.
                    //
                    // `respond_to_write` acknowledges the write; the transfer's own
                    // progress goes back over the notify characteristic with
                    // `send_notification`, which needs the model (or a script) to decide
                    // what to say, so it is not part of a static example.
                    {
                        "event_pattern": "bluetooth_write_request",
                        "handler": {
                            "type": "static",
                            "actions": [
                                {
                                    "type": "respond_to_write",
                                    "status": "success"
                                }
                            ]
                        }
                    }
                ]
            }),
        )
    }
}

impl Server for BluetoothBleFileTransferProtocol {
    fn spawn(
        &self,
        ctx: crate::protocol::SpawnContext,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<std::net::SocketAddr>> + Send>>
    {
        Box::pin(async move {
            let device_name = ctx
                .startup_params
                .as_ref()
                .map(|p| p.get_optional_string("device_name"))
                .transpose()?
                .flatten()
                .unwrap_or_else(|| "NetGet-FileTransfer".to_string());

            // The user's own instruction must reach the base stack; the profile preamble is
            // added there, not substituted for it.
            let instruction = ctx
                .state
                .get_server(ctx.server_id)
                .await
                .map(|s| s.instruction)
                .unwrap_or_default();

            crate::server::bluetooth_ble_file_transfer::BluetoothBleFileTransfer::spawn_with_llm_actions(
                device_name,
                ctx.llm_client,
                ctx.state,
                ctx.status_tx,
                ctx.server_id,
                instruction,
            )
            .await
        })
    }

    /// Delegated: the base's executor is what actually runs, so validation must accept exactly
    /// the base's action names and reject everything else rather than waving any action through.
    fn execute_action(&self, action: serde_json::Value) -> Result<ActionResult> {
        Self::base().execute_action(action)
    }
}