Skip to main content

lean_ctx/core/config/
cloud.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `[cloud]` configuration.
3//!
4//! ```toml
5//! [cloud]
6//! # enabled = true          # unset: on while this machine is connected
7//! url = "https://cloud.leanctx.com"
8//! # root_key = "<base64>"   # self-hosted Cloud: its root public key
9//! auto_capture = true       # 3.11.5 name `auto_draft` is read as an alias
10//! pull_interval_minutes = 5  # 1..=60
11//! metrics_upload = true
12//! receipts_upload = true
13//! bus = "auto"              # auto | off
14//! vault_labels = true
15//! presence_names = true     # false: no "working on" line for your team
16//!
17//! [cloud.worker]             # stricter local caps on the opt-in budget
18//! # max_tasks_per_day = 3
19//! # max_tokens_per_day = 200000
20//! # max_usd_micros_per_day = 2000000
21//! ```
22//!
23//! The Cloud connector reads this section and re-exports these types as
24//! its own config. It also registers what a `config set`
25//! of a `cloud.` key applies at once ([`register_off_switches`]).
26
27use std::sync::OnceLock;
28
29use serde::{Deserialize, Serialize};
30
31use lean_ctx_protocol::cloud::CLOUD_DEFAULT_URL;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum CloudBusMode {
36    #[default]
37    Auto,
38    Off,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(default)]
43pub struct CloudConfig {
44    /// `None`: on while this machine is connected. `false` pauses all Cloud
45    /// traffic without disconnecting.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub enabled: Option<bool>,
48    /// Cloud origin; any `https` URL for a self-hosted Cloud.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub url: Option<String>,
51    /// Root public key (base64 Ed25519) of a self-hosted Cloud.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub root_key: Option<String>,
54    /// Run the capture gate on session learnings (3.11.5: `auto_draft`,
55    /// still read as an alias, `core::config::renamed`).
56    pub auto_capture: bool,
57    /// Minutes between scheduler passes; [`CloudConfig::pull_interval`]
58    /// clamps it to [`PULL_INTERVAL_BOUNDS`].
59    pub pull_interval_minutes: u32,
60    pub metrics_upload: bool,
61    pub receipts_upload: bool,
62    pub bus: CloudBusMode,
63    pub vault_labels: bool,
64    /// Team presence names: your team sees what your agents are working on
65    /// (the status line each agent sets itself, with paths and secrets
66    /// removed) and this machine's short name as `machine_name`. Sent only
67    /// to a Cloud that shows them to members of the same team; `false`
68    /// keeps presence to role, state and the Instance's short name, which
69    /// every presence carries (never a domain).
70    pub presence_names: bool,
71    /// The user agreed to install the proprietary Intelligence runtime that
72    /// the lease licenses (`cloud connect` asks, `cloud runtime install`
73    /// records it). Nothing installs it without this consent.
74    pub runtime_consent: bool,
75    /// Worker mode: local caps that only tighten the server opt-in budget.
76    pub worker: CloudWorkerConfig,
77    /// mz6: origin of the Cloud models gateway that serves the subscription
78    /// models (`leanctx` provider). `None`: `https://models.<cloud host>`.
79    /// Honoured only when its host is the Cloud host or a direct subdomain
80    /// of it (loopback for tests); any other value is refused and the
81    /// instance token is never sent (`core::cloud_models::models_origin`).
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub models_url: Option<String>,
84    /// mz6 owner question Q3 (open): whether Anthropic-shaped agents may
85    /// reach the subscription models through `shape-xlat` routing aliases.
86    /// Default `false`: OpenAI-shaped agents only, the rel2 launch scope;
87    /// `true` has no effect until Q3 is decided (routing refuses aliases to
88    /// `leanctx`).
89    pub models_anthropic_agents: bool,
90    /// How the bus treats a sender presenting as the Queen that is no
91    /// registered Queen session: `warn` (unset: pass, log, mark) or
92    /// `enforce` (refuse); any other value counts as `enforce`. Kept as
93    /// text so a wrong value never breaks the whole config.
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub queen_identity: Option<String>,
96    /// What remains of the pre-3.12 `[cloud]` table (hosted account sync):
97    /// the legacy opt-in the loader turns into `telemetry.enabled`. Read,
98    /// never written; the config migration retires the key.
99    #[serde(skip_serializing)]
100    pub contribute_enabled: bool,
101}
102
103impl Default for CloudConfig {
104    fn default() -> Self {
105        Self {
106            enabled: None,
107            url: None,
108            root_key: None,
109            auto_capture: true,
110            pull_interval_minutes: DEFAULT_PULL_INTERVAL_MINUTES,
111            metrics_upload: true,
112            receipts_upload: true,
113            bus: CloudBusMode::Auto,
114            vault_labels: true,
115            presence_names: true,
116            runtime_consent: false,
117            worker: CloudWorkerConfig::default(),
118            models_url: None,
119            models_anthropic_agents: false,
120            queen_identity: None,
121            contribute_enabled: false,
122        }
123    }
124}
125
126/// Default minutes between scheduler passes (SPEC-ENGINE §3.16).
127pub const DEFAULT_PULL_INTERVAL_MINUTES: u32 = 5;
128/// Allowed `pull_interval_minutes` (SPEC-ENGINE §3.16).
129pub const PULL_INTERVAL_BOUNDS: std::ops::RangeInclusive<u32> = 1..=60;
130
131impl CloudConfig {
132    /// `pull_interval_minutes` within [`PULL_INTERVAL_BOUNDS`].
133    pub fn pull_interval(&self) -> u32 {
134        self.pull_interval_minutes
135            .clamp(*PULL_INTERVAL_BOUNDS.start(), *PULL_INTERVAL_BOUNDS.end())
136    }
137}
138
139/// Applies the `[cloud]` off switches to the connector's local state.
140pub type OffSwitches = fn(&CloudConfig);
141
142static OFF_SWITCHES: OnceLock<OffSwitches> = OnceLock::new();
143
144/// Register what a `config set` of a `cloud.` key applies at once (the
145/// connector stops its local recording when a switch is off). The first
146/// registration wins.
147pub fn register_off_switches(apply: OffSwitches) {
148    let _ = OFF_SWITCHES.set(apply);
149}
150
151/// Apply the off switches in `config`. Without a registration there is no
152/// connector state to stop, so nothing happens.
153pub(crate) fn apply_off_switches(config: &CloudConfig) {
154    if let Some(apply) = OFF_SWITCHES.get() {
155        apply(config);
156    }
157}
158
159/// `[cloud.worker]`: stricter local caps on top of the server's budget.
160#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(default)]
162pub struct CloudWorkerConfig {
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub max_tasks_per_day: Option<u32>,
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub max_tokens_per_day: Option<u64>,
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub max_usd_micros_per_day: Option<u64>,
169}
170
171/// `[cloud]` in `lean-ctx config schema` / `config validate`.
172pub fn schema_section() -> crate::core::config::schema::SectionSchema {
173    use crate::core::config::schema::{KeySchema, SectionSchema};
174    let defaults = CloudConfig::default();
175    let key = |ty: &str, default: serde_json::Value, description: &str, values: Option<&[&str]>| {
176        KeySchema {
177            ty: ty.into(),
178            default,
179            description: description.into(),
180            values: values.map(|v| v.iter().map(|s| (*s).to_string()).collect()),
181            env_override: None,
182        }
183    };
184    let keys = [
185        (
186            "enabled",
187            key(
188                "bool",
189                serde_json::Value::Null,
190                "Pause all LeanCTX traffic with false; unset means on while this computer is connected.",
191                None,
192            ),
193        ),
194        (
195            "url",
196            key(
197                "string",
198                serde_json::json!(CLOUD_DEFAULT_URL),
199                "LeanCTX origin (https; a self-hosted LeanCTX server may use any https URL).",
200                None,
201            ),
202        ),
203        (
204            "root_key",
205            key(
206                "string",
207                serde_json::Value::Null,
208                "Root public key (base64 Ed25519) of a self-hosted LeanCTX server.",
209                None,
210            ),
211        ),
212        (
213            "auto_capture",
214            key(
215                "bool",
216                serde_json::json!(defaults.auto_capture),
217                "Run the capture gate on session learnings and share what passes (renamed from auto_draft).",
218                None,
219            ),
220        ),
221        (
222            "pull_interval_minutes",
223            key(
224                "integer",
225                serde_json::json!(defaults.pull_interval_minutes),
226                "Minutes between LeanCTX sync passes (1-60; values outside are clamped).",
227                None,
228            ),
229        ),
230        (
231            "metrics_upload",
232            key(
233                "bool",
234                serde_json::json!(defaults.metrics_upload),
235                "Send hourly instance metrics to LeanCTX (counts only, including full re-fetches and unregulated program names; never content).",
236                None,
237            ),
238        ),
239        (
240            "receipts_upload",
241            key(
242                "bool",
243                serde_json::json!(defaults.receipts_upload),
244                "Upload context receipts to LeanCTX.",
245                None,
246            ),
247        ),
248        (
249            "bus",
250            key(
251                "string",
252                serde_json::json!("auto"),
253                "Relay the agent bus through LeanCTX (auto) or keep it local (off).",
254                Some(&["auto", "off"]),
255            ),
256        ),
257        (
258            "queen_identity",
259            KeySchema {
260                env_override: Some("LEAN_CTX_CLOUD_QUEEN_IDENTITY".into()),
261                ..key(
262                    "string",
263                    serde_json::json!("warn"),
264                    "A bus sender presenting as the app's coordinator session that is no registered coordinator session: warn (pass, log in bus/queen-warnings.json, mark for the receiver) or enforce (refuse); any other value counts as enforce. Enforce only once queen-sessions.json lists every coordinator session.",
265                    Some(&["warn", "enforce"]),
266                )
267            },
268        ),
269        (
270            "vault_labels",
271            key(
272                "bool",
273                serde_json::json!(defaults.vault_labels),
274                "Send checkout folder names as vault labels.",
275                None,
276            ),
277        ),
278        (
279            "presence_names",
280            key(
281                "bool",
282                serde_json::json!(defaults.presence_names),
283                "Show your team what your agents are working on: the status line each agent sets itself, with paths and secrets removed (only through a server that shows it to your team alone); false keeps presence to role, state and this machine's short name.",
284                None,
285            ),
286        ),
287        (
288            "runtime_consent",
289            key(
290                "bool",
291                serde_json::json!(defaults.runtime_consent),
292                "You agreed to install the proprietary Intelligence runtime your plan licenses (set by `cloud connect` or `cloud runtime install`).",
293                None,
294            ),
295        ),
296        (
297            "models_url",
298            key(
299                "string",
300                serde_json::Value::Null,
301                "Origin of the LeanCTX models gateway for the leanctx provider; unset means https://models.<cloud host>. Only the LeanCTX host or a direct subdomain of it is honoured.",
302                None,
303            ),
304        ),
305        (
306            "models_anthropic_agents",
307            key(
308                "bool",
309                serde_json::json!(defaults.models_anthropic_agents),
310                "Let Anthropic-shaped agents reach the subscription models through shape-xlat routing aliases; false means OpenAI-shaped agents only. Owner question Q3 is open: true takes effect only once it is decided.",
311                None,
312            ),
313        ),
314        (
315            "worker.max_tasks_per_day",
316            key(
317                "integer",
318                serde_json::Value::Null,
319                "Worker mode: at most this many claimed tasks per day on this machine; only tightens the opt-in budget set on the web.",
320                None,
321            ),
322        ),
323        (
324            "worker.max_tokens_per_day",
325            key(
326                "integer",
327                serde_json::Value::Null,
328                "Worker mode: stop claiming once the day's results reported this many tokens; only tightens the opt-in budget.",
329                None,
330            ),
331        ),
332        (
333            "worker.max_usd_micros_per_day",
334            key(
335                "integer",
336                serde_json::Value::Null,
337                "Worker mode: stop claiming once the day's results reported this cost (USD millionths); only tightens the opt-in budget.",
338                None,
339            ),
340        ),
341    ];
342    SectionSchema {
343        description: "LeanCTX: workspace knowledge, policies and the shared agent bus.".into(),
344        keys: keys
345            .into_iter()
346            .map(|(name, key)| (name.to_string(), key))
347            .collect(),
348    }
349}