Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

8.8 KB
Raw Blame
use openhuman_embed::__host::core::runtime::DispatchCtx;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde_json::{Map, Value};
use tinyhumans_sdk::api::webhooks::UpdateWebhookTunnelRequest;

use openhuman_embed::__host::core::all::{ControllerFuture, RegisteredController};
use openhuman_embed::__host::core::Outcome;
use openhuman_embed::__host::core::{ControllerSchema, FieldSchema, TypeSchema};

#[derive(Debug, Deserialize)]
struct WebhookCreateTunnelParams {
    name: String,
    description: Option<String>,
}

#[derive(Debug, Deserialize)]
struct WebhookTunnelIdParams {
    id: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WebhookUpdateTunnelParams {
    id: String,
    name: Option<String>,
    description: Option<String>,
    is_active: Option<bool>,
}

const FUNCTIONS: &[&str] = &[
    "list_tunnels",
    "create_tunnel",
    "get_tunnel",
    "update_tunnel",
    "delete_tunnel",
    "get_bandwidth",
];

pub fn all_webhooks_controller_schemas() -> Vec<ControllerSchema> {
    FUNCTIONS.iter().map(|f| webhooks_schemas(f)).collect()
}

pub fn all_webhooks_registered_controllers() -> Vec<RegisteredController> {
    vec![
        RegisteredController {
            schema: webhooks_schemas("list_tunnels"),
            handler: handle_list_tunnels,
        },
        RegisteredController {
            schema: webhooks_schemas("create_tunnel"),
            handler: handle_create_tunnel,
        },
        RegisteredController {
            schema: webhooks_schemas("get_tunnel"),
            handler: handle_get_tunnel,
        },
        RegisteredController {
            schema: webhooks_schemas("update_tunnel"),
            handler: handle_update_tunnel,
        },
        RegisteredController {
            schema: webhooks_schemas("delete_tunnel"),
            handler: handle_delete_tunnel,
        },
        RegisteredController {
            schema: webhooks_schemas("get_bandwidth"),
            handler: handle_get_bandwidth,
        },
    ]
}

/// Schema for one hosted `webhooks.*` function (unchanged wire contract).
pub fn webhooks_schemas(function: &str) -> ControllerSchema {
    match function {
        "list_tunnels" => ControllerSchema {
            namespace: "webhooks",
            function: "list_tunnels",
            description: "List backend-managed webhook tunnels for the current user.",
            inputs: vec![],
            outputs: vec![json_output("result", "Webhook tunnel list.")],
        },
        "create_tunnel" => ControllerSchema {
            namespace: "webhooks",
            function: "create_tunnel",
            description: "Create a backend-managed webhook tunnel.",
            inputs: vec![
                FieldSchema {
                    name: "name",
                    ty: TypeSchema::String,
                    comment: "Tunnel name.",
                    required: true,
                },
                FieldSchema {
                    name: "description",
                    ty: TypeSchema::Option(Box::new(TypeSchema::String)),
                    comment: "Optional tunnel description.",
                    required: false,
                },
            ],
            outputs: vec![json_output("result", "Created webhook tunnel.")],
        },
        "get_tunnel" => ControllerSchema {
            namespace: "webhooks",
            function: "get_tunnel",
            description: "Fetch a backend-managed webhook tunnel by id.",
            inputs: vec![FieldSchema {
                name: "id",
                ty: TypeSchema::String,
                comment: "Backend tunnel id.",
                required: true,
            }],
            outputs: vec![json_output("result", "Webhook tunnel payload.")],
        },
        "update_tunnel" => ControllerSchema {
            namespace: "webhooks",
            function: "update_tunnel",
            description: "Update a backend-managed webhook tunnel.",
            inputs: vec![
                FieldSchema {
                    name: "id",
                    ty: TypeSchema::String,
                    comment: "Backend tunnel id.",
                    required: true,
                },
                FieldSchema {
                    name: "name",
                    ty: TypeSchema::Option(Box::new(TypeSchema::String)),
                    comment: "Optional tunnel name.",
                    required: false,
                },
                FieldSchema {
                    name: "description",
                    ty: TypeSchema::Option(Box::new(TypeSchema::String)),
                    comment: "Optional tunnel description.",
                    required: false,
                },
                FieldSchema {
                    name: "isActive",
                    ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
                    comment: "Optional active flag.",
                    required: false,
                },
            ],
            outputs: vec![json_output("result", "Updated webhook tunnel payload.")],
        },
        "delete_tunnel" => ControllerSchema {
            namespace: "webhooks",
            function: "delete_tunnel",
            description: "Delete a backend-managed webhook tunnel.",
            inputs: vec![FieldSchema {
                name: "id",
                ty: TypeSchema::String,
                comment: "Backend tunnel id.",
                required: true,
            }],
            outputs: vec![json_output("result", "Delete webhook tunnel result.")],
        },
        "get_bandwidth" => ControllerSchema {
            namespace: "webhooks",
            function: "get_bandwidth",
            description: "Fetch the remaining webhook bandwidth budget.",
            inputs: vec![],
            outputs: vec![json_output("result", "Webhook bandwidth payload.")],
        },
        _ => ControllerSchema {
            namespace: "webhooks",
            function: "unknown",
            description: "Unknown webhooks controller function.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "error",
                ty: TypeSchema::String,
                comment: "Lookup error details.",
                required: true,
            }],
        },
    }
}

fn handle_list_tunnels(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        to_json(crate::hosted::webhooks::list_tunnels(&config).await?)
    })
}

fn handle_create_tunnel(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        let payload = deserialize_params::<WebhookCreateTunnelParams>(params)?;
        to_json(
            crate::hosted::webhooks::create_tunnel(
                &config,
                payload.name.trim(),
                payload.description,
            )
            .await?,
        )
    })
}

fn handle_delete_tunnel(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        let payload = deserialize_params::<WebhookTunnelIdParams>(params)?;
        to_json(crate::hosted::webhooks::delete_tunnel(&config, &payload.id).await?)
    })
}

fn handle_get_tunnel(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        let payload = deserialize_params::<WebhookTunnelIdParams>(params)?;
        to_json(crate::hosted::webhooks::get_tunnel(&config, &payload.id).await?)
    })
}

fn handle_update_tunnel(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        let payload = deserialize_params::<WebhookUpdateTunnelParams>(params)?;
        let request = UpdateWebhookTunnelRequest {
            name: payload.name,
            description: payload.description,
            is_active: payload.is_active,
        };
        to_json(crate::hosted::webhooks::update_tunnel(&config, &payload.id, request).await?)
    })
}

fn handle_get_bandwidth(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        to_json(crate::hosted::webhooks::get_bandwidth(&config).await?)
    })
}

fn deserialize_params<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {
    serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))
}

fn to_json<T: serde::Serialize>(outcome: Outcome<T>) -> Result<Value, String> {
    outcome.into_cli_compatible_json()
}

fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
    FieldSchema {
        name,
        ty: TypeSchema::Json,
        comment,
        required: true,
    }
}

#[cfg(test)]
#[path = "schemas_tests.rs"]
mod tests;