Skip to main content

lean_ctx_cloud/workers/
card.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The capability card a worker presents (C0 2.0 `worker.schema.json`
3//! `$defs/card`; SPEC-ENGINE ยง3.6). `history` is server-computed and
4//! never sent.
5
6use serde::{Deserialize, Serialize};
7
8/// Most tools a card lists, and the longest tool or model name.
9const TOOLS_MAX: usize = 64;
10const NAME_MAX: usize = 64;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum Availability {
15    Online,
16    Idle,
17    Offline,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum ModelSource {
23    SelfReported,
24    Unknown,
25}
26
27/// The worker's daily budget; USD amounts are integer cents (C0 carries no
28/// floats).
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
30pub struct Budget {
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub tasks_per_day: Option<u32>,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub usd_cents_per_day: Option<u32>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct WorkerCard {
39    pub host_app: String,
40    pub model: String,
41    pub model_source: ModelSource,
42    pub tools: Vec<String>,
43    pub budget: Budget,
44    pub availability: Availability,
45}
46
47impl WorkerCard {
48    /// A card within the contract bounds: the model is the host's
49    /// self-report when there is one, else `unknown`; tools are the lean-ctx
50    /// tool names the host was offered, deduplicated, sorted and capped.
51    pub fn new(
52        host_app: &str,
53        model: Option<&str>,
54        tools: impl IntoIterator<Item = String>,
55        budget: Budget,
56        availability: Availability,
57    ) -> Self {
58        let model = model
59            .map(str::trim)
60            .filter(|m| !m.is_empty())
61            .map(|m| m.chars().take(NAME_MAX).collect::<String>());
62        let mut tools: Vec<String> = tools
63            .into_iter()
64            .filter(|t| !t.is_empty() && t.chars().count() <= NAME_MAX)
65            .collect();
66        tools.sort();
67        tools.dedup();
68        tools.truncate(TOOLS_MAX);
69        let budget = Budget {
70            tasks_per_day: budget.tasks_per_day.map(|n| n.clamp(1, 200)),
71            usd_cents_per_day: budget.usd_cents_per_day.map(|n| n.min(50_000)),
72        };
73        Self {
74            host_app: host_app.to_string(),
75            model_source: if model.is_some() {
76                ModelSource::SelfReported
77            } else {
78                ModelSource::Unknown
79            },
80            model: model.unwrap_or_else(|| "unknown".to_string()),
81            tools,
82            budget,
83            availability,
84        }
85    }
86}
87
88/// The model the host reports about itself, from its environment.
89pub fn self_reported_model<I, K, V>(env: I) -> Option<String>
90where
91    I: IntoIterator<Item = (K, V)>,
92    K: AsRef<str>,
93    V: AsRef<str>,
94{
95    const KEYS: [&str; 4] = [
96        "ANTHROPIC_MODEL",
97        "CLAUDE_CODE_MODEL",
98        "CODEX_MODEL",
99        "GEMINI_MODEL",
100    ];
101    let mut found: Vec<(usize, String)> = env
102        .into_iter()
103        .filter_map(|(k, v)| {
104            let rank = KEYS.iter().position(|key| *key == k.as_ref())?;
105            let v = v.as_ref().trim();
106            (!v.is_empty()).then(|| (rank, v.to_string()))
107        })
108        .collect();
109    found.sort();
110    found.into_iter().next().map(|(_, v)| v)
111}