lean-ctx 3.12.11

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! The computer's meter heartbeat: `POST <origin>/api/v1/computer-meter/
//! computers/{id}/tick` with the computer's own `lcm_` token (cloud API
//! §21). Each tick books the minutes due since the last one; ticks are
//! idempotent by minute, so a repeated or late tick books nothing twice.
//!
//! The token travels only in the `Authorization` header: never in the URL,
//! a log line or an error. HTTPS only, no redirects, a bounded answer.

use std::time::Duration;

use serde::Deserialize;
use zeroize::Zeroizing;

/// The largest tick answer read.
const MAX_ANSWER: u64 = 64 * 1024;

/// What the cloud wants the computer to do after a tick.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Action {
    Run,
    /// The computer is not running in the cloud's books, or the credit ran
    /// out (`suspended_balance`).
    Stop,
}

/// The parts of a tick answer the computer acts on.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Tick {
    pub action: Action,
    /// The computer's state in the cloud (`running`, `stopped`,
    /// `suspended_balance`, …), shown as is.
    pub state: String,
    /// Minutes booked by this tick (`to_minute - from_minute`), 0 when none.
    pub booked_minutes: i64,
}

/// Why a tick did not book.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum TickError {
    /// `401`/`403`: the meter token was refused.
    Refused(u16),
    /// `503 not_configured`: metering is off on this cloud.
    NotConfigured,
    /// Any other status.
    Status(u16),
    /// No answer (DNS, connect, TLS, timeout).
    Offline(String),
    /// An answer that is not a tick.
    Protocol(String),
}

impl std::fmt::Display for TickError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TickError::Refused(code) => write!(f, "the cloud refused the meter token ({code})"),
            TickError::NotConfigured => {
                f.write_str("metering is not configured on this cloud (503)")
            }
            TickError::Status(code) => write!(f, "the cloud answered {code}"),
            TickError::Offline(why) => write!(f, "the cloud is unreachable: {why}"),
            TickError::Protocol(why) => write!(f, "unexpected tick answer: {why}"),
        }
    }
}

#[derive(Deserialize)]
struct Answer {
    computer: AnswerComputer,
    action: String,
    booked: Option<Booked>,
}

#[derive(Deserialize)]
struct AnswerComputer {
    state: String,
}

#[derive(Deserialize)]
struct Booked {
    from_minute: i64,
    to_minute: i64,
}

/// Parse a `200` tick answer.
pub(crate) fn parse_tick(body: &[u8]) -> Result<Tick, TickError> {
    let answer: Answer =
        serde_json::from_slice(body).map_err(|e| TickError::Protocol(e.to_string()))?;
    let action = match answer.action.as_str() {
        "run" => Action::Run,
        "stop" => Action::Stop,
        _ => return Err(TickError::Protocol("action is neither run nor stop".into())),
    };
    let state: String = answer
        .computer
        .state
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
        .take(40)
        .collect();
    let booked_minutes = answer
        .booked
        .map_or(0, |b| b.to_minute.saturating_sub(b.from_minute).max(0));
    Ok(Tick {
        action,
        state,
        booked_minutes,
    })
}

/// Map a non-`200` status to its error.
pub(crate) fn status_error(status: u16) -> TickError {
    match status {
        401 | 403 => TickError::Refused(status),
        503 => TickError::NotConfigured,
        _ => TickError::Status(status),
    }
}

/// The meter URL of `computer_id` at `origin` (both validated by the
/// config); the routes are `<base>/tick` and `<base>/host-keys`.
pub(crate) fn computer_url(origin: &str, computer_id: &str) -> String {
    format!("{origin}/api/v1/computer-meter/computers/{computer_id}")
}

/// The meter client of one computer.
pub(crate) struct Meter {
    agent: ureq::Agent,
    url: String,
    bearer: Zeroizing<String>,
}

impl Meter {
    pub(crate) fn new(origin: &str, computer_id: &str, token: &str) -> Result<Self, String> {
        if !origin.starts_with("https://") {
            return Err("the meter talks to an https:// origin only".into());
        }
        let agent: ureq::Agent = ureq::config::Config::builder()
            .tls_config(lean_ctx::core::http_client::platform_tls_config())
            .http_status_as_error(false)
            .max_redirects(0)
            .https_only(true)
            .timeout_resolve(Some(Duration::from_secs(5)))
            .timeout_connect(Some(Duration::from_secs(10)))
            .timeout_global(Some(Duration::from_secs(30)))
            .build()
            .into();
        Ok(Self {
            agent,
            url: computer_url(origin, computer_id),
            bearer: Zeroizing::new(format!("Bearer {token}")),
        })
    }

    /// One tick with a fresh request id. `active` reports activity on the
    /// computer since the last tick (an SSH session or a running job); it
    /// holds off the cloud's idle stop.
    pub(crate) fn tick(&self, active: bool) -> Result<Tick, TickError> {
        let body = serde_json::json!({
            "request_id": uuid::Uuid::new_v4().to_string(),
            "active": active,
        });
        parse_tick(&self.post("tick", &body)?)
    }

    /// Report the computer's SSH host key fingerprints (`SHA256:…`, 1-8),
    /// which the cloud shows next to the computer.
    pub(crate) fn host_keys(&self, fingerprints: &[String]) -> Result<(), TickError> {
        let body = serde_json::json!({ "fingerprints": fingerprints });
        self.post("host-keys", &body).map(drop)
    }

    fn post(&self, route: &str, body: &serde_json::Value) -> Result<Vec<u8>, TickError> {
        let response = self
            .agent
            .post(&format!("{}/{route}", self.url))
            .header("Authorization", self.bearer.as_str())
            .header("User-Agent", lean_ctx_cloud::transport::user_agent())
            .header("Content-Type", "application/json")
            .send(body.to_string().as_bytes())
            .map_err(|e| TickError::Offline(e.to_string()))?;
        let status = response.status().as_u16();
        if status != 200 {
            return Err(status_error(status));
        }
        response
            .into_body()
            .into_with_config()
            .limit(MAX_ANSWER)
            .read_to_vec()
            .map_err(|e| TickError::Protocol(format!("body: {e}")))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_metered_tick_parses() {
        let body = br#"{"computer":{"id":"0b7a3f4e-9c1d-4e2a-8f00-1234567890ab","org_id":"x","role":"weave_host",
            "state":"running","stop_reason":null,"vcpu":2,"ram_gib":4,"usd_micros_per_hour":90000,
            "run_id":"r","started_at":"2026-11-20T10:00:00Z","created_at":"2026-11-20T09:59:00Z"},
            "action":"run","booked":{"from_minute":3,"to_minute":5,"allowance_minutes":2,"paid_minutes":0,
            "cost_usd_micros":0,"topup_usd_micros":0}}"#;
        let tick = parse_tick(body).unwrap();
        assert_eq!(tick.action, Action::Run);
        assert_eq!(tick.state, "running");
        assert_eq!(tick.booked_minutes, 2);
    }

    #[test]
    fn a_stop_and_an_unbooked_tick_parse() {
        let body = br#"{"computer":{"state":"suspended_balance"},"action":"stop","booked":null}"#;
        let tick = parse_tick(body).unwrap();
        assert_eq!(tick.action, Action::Stop);
        assert_eq!(tick.state, "suspended_balance");
        assert_eq!(tick.booked_minutes, 0);
    }

    #[test]
    fn anything_else_is_a_protocol_error() {
        for body in [
            &br#"{"computer":{"state":"running"},"action":"reboot","booked":null}"#[..],
            br#"{"action":"run","booked":null}"#,
            b"<html>",
            b"",
        ] {
            assert!(matches!(parse_tick(body), Err(TickError::Protocol(_))));
        }
        // A state the cloud sends is shown, but never anything but a word.
        let odd = br#"{"computer":{"state":"run\u001b[31mning"},"action":"run","booked":null}"#;
        assert_eq!(parse_tick(odd).unwrap().state, "run31mning");
    }

    #[test]
    fn statuses_map_to_their_meaning_and_the_url_holds_no_token() {
        assert_eq!(status_error(401), TickError::Refused(401));
        assert_eq!(status_error(403), TickError::Refused(403));
        assert_eq!(status_error(503), TickError::NotConfigured);
        assert_eq!(status_error(500), TickError::Status(500));
        assert_eq!(
            computer_url(
                "https://cloud.leanctx.com",
                "0b7a3f4e-9c1d-4e2a-8f00-1234567890ab"
            ),
            "https://cloud.leanctx.com/api/v1/computer-meter/computers/0b7a3f4e-9c1d-4e2a-8f00-1234567890ab"
        );
        assert!(Meter::new("http://cloud.leanctx.com", "x", "lcm_x").is_err());
    }
}