Skip to main content

lean_ctx/core/hive/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/// Pledge summary; USD amounts are integer cents (C0 carries no floats).
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Budget {
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub tasks_per_day: Option<u32>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub usd_cents_per_day: Option<u32>,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct WorkerCard {
38    pub host_app: String,
39    pub model: String,
40    pub model_source: ModelSource,
41    pub tools: Vec<String>,
42    pub budget: Budget,
43    pub availability: Availability,
44}
45
46impl WorkerCard {
47    /// A card within the contract bounds: the model is the host's
48    /// self-report when there is one, else `unknown`; tools are the lean-ctx
49    /// tool names the host was offered, deduplicated, sorted and capped.
50    pub fn new(
51        host_app: &str,
52        model: Option<&str>,
53        tools: impl IntoIterator<Item = String>,
54        budget: Budget,
55        availability: Availability,
56    ) -> Self {
57        let model = model
58            .map(str::trim)
59            .filter(|m| !m.is_empty())
60            .map(|m| m.chars().take(NAME_MAX).collect::<String>());
61        let mut tools: Vec<String> = tools
62            .into_iter()
63            .filter(|t| !t.is_empty() && t.chars().count() <= NAME_MAX)
64            .collect();
65        tools.sort();
66        tools.dedup();
67        tools.truncate(TOOLS_MAX);
68        let budget = Budget {
69            tasks_per_day: budget.tasks_per_day.map(|n| n.clamp(1, 200)),
70            usd_cents_per_day: budget.usd_cents_per_day.map(|n| n.min(50_000)),
71        };
72        Self {
73            host_app: host_app.to_string(),
74            model_source: if model.is_some() {
75                ModelSource::SelfReported
76            } else {
77                ModelSource::Unknown
78            },
79            model: model.unwrap_or_else(|| "unknown".to_string()),
80            tools,
81            budget,
82            availability,
83        }
84    }
85}
86
87/// The model the host reports about itself, from its environment.
88pub fn self_reported_model<I, K, V>(env: I) -> Option<String>
89where
90    I: IntoIterator<Item = (K, V)>,
91    K: AsRef<str>,
92    V: AsRef<str>,
93{
94    const KEYS: [&str; 4] = [
95        "ANTHROPIC_MODEL",
96        "CLAUDE_CODE_MODEL",
97        "CODEX_MODEL",
98        "GEMINI_MODEL",
99    ];
100    let mut found: Vec<(usize, String)> = env
101        .into_iter()
102        .filter_map(|(k, v)| {
103            let rank = KEYS.iter().position(|key| *key == k.as_ref())?;
104            let v = v.as_ref().trim();
105            (!v.is_empty()).then(|| (rank, v.to_string()))
106        })
107        .collect();
108    found.sort();
109    found.into_iter().next().map(|(_, v)| v)
110}