coreason-runtime 0.1.0

Kinetic Plane execution engine for the CoReason Tripartite Cybernetic Manifold
Documentation
// Copyright (c) 2026 CoReason, Inc.
// All rights reserved.

//! Discovery API routes.
//!
//! Replaces `coreason_runtime/api/discovery_router.py`.
//! Proxies service discovery and agent listing requests to the Python sidecar.

use axum::{
    extract::State,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json, Router,
};
use std::sync::Arc;

use crate::GatewayState;

// ── Proxy helpers ───────────────────────────────────────────────────────

async fn proxy_get(state: &GatewayState, path: &str) -> Response {
    let url = format!("{}{}", state.sidecar_url, path);
    match ureq::get(&url).call() {
        Ok(res) => {
            let status = StatusCode::from_u16(res.status()).unwrap_or(StatusCode::OK);
            let body: serde_json::Value = res.into_json().unwrap_or(serde_json::Value::Null);
            (status, Json(body)).into_response()
        }
        Err(ureq::Error::Status(code, res)) => {
            let status = StatusCode::from_u16(code).unwrap_or(StatusCode::BAD_REQUEST);
            let body: serde_json::Value = res.into_json().unwrap_or(serde_json::Value::Null);
            (status, Json(body)).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "status": "error",
                "message": format!("Failed to proxy GET {} to sidecar: {}", path, e),
            })),
        )
            .into_response(),
    }
}

// ── Handlers ────────────────────────────────────────────────────────────

/// GET /api/v1/discovery/capabilities
///
/// Discover available capabilities from the sidecar service registry.
async fn discovery_capabilities(State(state): State<Arc<GatewayState>>) -> Response {
    proxy_get(&state, "/api/v1/discovery/capabilities").await
}

/// GET /api/v1/discovery/agents
///
/// List registered agents from the sidecar service registry.
async fn discovery_agents(State(state): State<Arc<GatewayState>>) -> Response {
    proxy_get(&state, "/api/v1/discovery/agents").await
}

// ── Router ──────────────────────────────────────────────────────────────

/// Build the discovery router.
pub fn router() -> Router<Arc<GatewayState>> {
    Router::new()
        .route(
            "/api/v1/discovery/capabilities",
            get(discovery_capabilities),
        )
        .route("/api/v1/discovery/agents", get(discovery_agents))
}