Skip to main content

lean_ctx_protocol/cloud/
optin.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Engine opt-in (C0 1.9, section 4; owner decision O1).
4//!
5//! An engine's agents work on tasks only by *pulling* them, and only within
6//! the opt-in its owner set on the web: which vaults and networks, how
7//! much per day, and whether at all. Cloud never starts an agent;
8//! nothing here spawns anything.
9//!
10//! `GET /v1/me/optin` (instance token) → [`EngineOptinV1`]. The owner
11//! changes it on the web; every change gets a new `optin_id`, and
12//! `active: false` (the stop) ends every claim of that engine at once.
13//! The engine may stop itself: `PUT /v1/me/optin` [`EngineOptinStopV1`] →
14//! [`EngineOptinV1`]. It turns task pickup on only with the person at the
15//! computer (rc4-16): `PUT /v1/me/optin` [`EngineOptinOnV1`], signed with
16//! the app's bound opt-in key (no per-turn-on prompt) over [`OPTIN_SIGNING_DOMAIN`] ‖
17//! canonical JSON of the body without `presence_signature`, plus
18//! `instance_id`. Only the bound opt-in key signs it; there is no
19//! presence-key fallback. The instance token alone never turns it on
20//! (`403 forbidden_right` reason `person_unproven`); without a bound opt-in
21//! key the engine refuses it before sending (`no_optin_key`: pair LeanCTX
22//! Code with the computer first). Turning it off needs no key.
23//!
24//! Cloud is the source of truth and enforces it on every claim:
25//! - a claim carries the `optin_id` the engine last read (section 1
26//!   `TaskClaimRequestV1.optin_id`, required since this section; without it
27//!   `400 invalid_request` field `optin_id`);
28//! - an older `optin_id` → `409 invalid_state` reason `optin_changed`: the
29//!   engine reads the opt-in again before it pulls;
30//! - `active: false`, or no opt-in → `409 invalid_state` reason
31//!   `optin_inactive`;
32//! - a vault or network outside the opt-in → `403 forbidden_right` reason
33//!   `optin_scope`;
34//! - the day's budget used up → `429 rate_limited` reason `daily_budget`,
35//!   with `limit`, `used` (claims) and `retry_after_s` until 00:00 UTC.
36//!
37//! Usage counts per UTC day: a claim counts one task when it is granted; the
38//! `usage` of task results (section 1) adds tokens and `usd_micros`. A claim
39//! is refused once any set limit is reached; a running claim is never cut
40//! short by the budget. A granted claim counts atomically: parallel claims
41//! of one engine never exceed `daily_budget.tasks` together.
42//!
43//! An engine may apply stricter local caps (fewer tasks, a lower budget, a
44//! narrower scope). It never widens what Cloud allows.
45
46use serde::{Deserialize, Serialize};
47
48use super::{require_schema, validate_id};
49use crate::{UtcTimestamp, ValidationError};
50
51/// A network an engine may pull questions from: an org channel
52/// (`org:<org_id>/vault:<vault_id>/<name>`). Any other kind does not decode.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
55pub enum NetworkV1 {
56    Org { channel: String },
57}
58
59impl NetworkV1 {
60    pub fn validate(&self) -> Result<(), ValidationError> {
61        match self {
62            Self::Org { channel } => validate_channel(channel),
63        }
64    }
65}
66
67/// Validate `org:<org>/vault:<vault_id>/<name>`.
68fn validate_channel(channel: &str) -> Result<(), ValidationError> {
69    let mut parts = channel.splitn(3, '/');
70    let org = parts.next().and_then(|part| part.strip_prefix("org:"));
71    let vault = parts.next().and_then(|part| part.strip_prefix("vault:"));
72    let name = parts.next();
73    match (org, vault, name) {
74        (Some(org), Some(vault), Some(name)) => {
75            validate_id(org, "channel org")?;
76            super::validate_vault_id(vault)?;
77            validate_id(name, "channel name")
78        }
79        _ => Err(ValidationError::new(
80            "channel must be org:<org>/vault:<vault>/<name>",
81        )),
82    }
83}
84
85pub const ENGINE_OPTIN_SCHEMA: &str = "leanctx.cloud.instance-optin/v1";
86pub const ENGINE_OPTIN_STOP_SCHEMA: &str = "leanctx.cloud.instance-optin-stop/v1";
87/// `PUT /v1/me/optin` with `active: true` (rc4-16).
88pub const ENGINE_OPTIN_ON_SCHEMA: &str = "leanctx.cloud.instance-optin-on/v1";
89/// The domain the person's presence signature of a turn-on is made under.
90pub const OPTIN_SIGNING_DOMAIN: &str = "leanctx.cloud.optin.v1\n";
91pub const DEFAULT_DAILY_TASKS: u32 = 5;
92pub const MAX_DAILY_TASKS: u32 = 100;
93pub const MAX_OPTIN_VAULTS: usize = 200;
94pub const MAX_OPTIN_NETWORKS: usize = 200;
95
96/// Limits per UTC day. A limit that is absent is no limit; since Cloud
97/// task #19 (owner decision 23.10.) that holds for the task count too.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
99pub struct DailyBudgetV1 {
100    /// Claims per day, 1-100 (default 5); `None`: no limit.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub tasks: Option<u32>,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub tokens: Option<u64>,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub usd_micros: Option<u64>,
107}
108
109impl DailyBudgetV1 {
110    /// The budget task pickup starts with when it is turned on for the
111    /// person's own vaults without a budget of theirs (owner decision rc3-72
112    /// part 4): 3 tasks and 1M tokens a day, no cost limit.
113    pub const AUTO: Self = Self {
114        tasks: Some(3),
115        tokens: Some(1_000_000),
116        usd_micros: None,
117    };
118
119    /// 1-100 tasks or none, and a non-zero token limit or none.
120    pub fn validate(&self) -> Result<(), ValidationError> {
121        if self
122            .tasks
123            .is_some_and(|t| !(1..=MAX_DAILY_TASKS).contains(&t))
124            || self.tokens == Some(0)
125        {
126            return Err(ValidationError::new(
127                "daily_budget is 1-100 tasks or none, and a non-zero token limit",
128            ));
129        }
130        Ok(())
131    }
132}
133
134impl Default for DailyBudgetV1 {
135    fn default() -> Self {
136        Self {
137            tasks: Some(DEFAULT_DAILY_TASKS),
138            tokens: None,
139            usd_micros: None,
140        }
141    }
142}
143
144/// What the engine used today (UTC).
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct DailyUsageV1 {
147    /// `YYYY-MM-DD`, UTC.
148    pub day: String,
149    pub tasks: u32,
150    pub tokens: u64,
151    pub usd_micros: u64,
152}
153
154/// `GET /v1/me/optin`.
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156pub struct EngineOptinV1 {
157    pub schema: String,
158    /// Absent when the owner never opted this engine in (then `active` is
159    /// false and every list is empty).
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub optin_id: Option<String>,
162    pub active: bool,
163    /// Vaults (`vault_id`) whose tasks the agents may pull.
164    #[serde(default)]
165    pub vaults: Vec<String>,
166    /// Networks whose questions they may pull ([`NetworkV1`]).
167    #[serde(default)]
168    pub networks: Vec<NetworkV1>,
169    pub daily_budget: DailyBudgetV1,
170    pub used_today: DailyUsageV1,
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub stopped_at: Option<UtcTimestamp>,
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub updated_at: Option<UtcTimestamp>,
175}
176
177fn day_ok(day: &str) -> bool {
178    let b = day.as_bytes();
179    b.len() == 10
180        && b[4] == b'-'
181        && b[7] == b'-'
182        && [0..4, 5..7, 8..10]
183            .iter()
184            .all(|r| b[r.clone()].iter().all(u8::is_ascii_digit))
185}
186
187impl EngineOptinV1 {
188    pub fn validate(&self) -> Result<(), ValidationError> {
189        require_schema(&self.schema, ENGINE_OPTIN_SCHEMA)?;
190        match &self.optin_id {
191            Some(id) => validate_id(id, "optin_id")?,
192            None if self.active || !self.vaults.is_empty() || !self.networks.is_empty() => {
193                return Err(ValidationError::new(
194                    "an engine without opt-in is inactive with empty scope",
195                ));
196            }
197            None => {}
198        }
199        if self.vaults.len() > MAX_OPTIN_VAULTS || self.networks.len() > MAX_OPTIN_NETWORKS {
200            return Err(ValidationError::new(format!(
201                "at most {MAX_OPTIN_VAULTS} vaults and {MAX_OPTIN_NETWORKS} networks"
202            )));
203        }
204        for (i, vault) in self.vaults.iter().enumerate() {
205            super::validate_vault_id(vault)?;
206            if i > 0 && self.vaults[i - 1] >= *vault {
207                return Err(ValidationError::new(
208                    "vaults must be sorted without repeats",
209                ));
210            }
211        }
212        self.daily_budget.validate()?;
213        if !day_ok(&self.used_today.day) {
214            return Err(ValidationError::new("used_today.day is YYYY-MM-DD"));
215        }
216        if self.active == self.stopped_at.is_some() && self.optin_id.is_some() {
217            return Err(ValidationError::new(
218                "stopped_at is set exactly while the opt-in is inactive",
219            ));
220        }
221        Ok(())
222    }
223}
224
225/// `PUT /v1/me/optin`: the engine's own stop.
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(deny_unknown_fields)]
228pub struct EngineOptinStopV1 {
229    pub schema: String,
230    /// Always `false`; turning on is [`EngineOptinOnV1`].
231    pub active: bool,
232}
233
234impl EngineOptinStopV1 {
235    pub fn validate(&self) -> Result<(), ValidationError> {
236        require_schema(&self.schema, ENGINE_OPTIN_STOP_SCHEMA)?;
237        if self.active {
238            return Err(ValidationError::new("an engine can only stop its opt-in"));
239        }
240        Ok(())
241    }
242}
243
244/// `PUT /v1/me/optin`: task pickup turned on from the computer, with the
245/// person at it (rc4-16). `presence_signature` is the signature of the
246/// app's bound opt-in key only (never the presence key; the field keeps its
247/// name on the wire) (base64url, no padding) over [`OPTIN_SIGNING_DOMAIN`] ‖
248/// canonical JSON of the body without it, plus `"instance_id"` (the
249/// instance UUID, lowercase with hyphens). Cloud refuses a `prev_optin_id`
250/// that is not the opt-in's current one (`409 invalid_state` reason
251/// `optin_changed`), so a signature works at most once.
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(deny_unknown_fields)]
254pub struct EngineOptinOnV1 {
255    pub schema: String,
256    /// Always `true`.
257    pub active: bool,
258    /// The `optin_id` `GET /v1/me/optin` showed when the person signed;
259    /// `null` only while there is none. Always sent.
260    pub prev_optin_id: Option<String>,
261    /// Vaults (project ids); left out means none (it replaces the list).
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub vaults: Option<Vec<String>>,
264    pub daily_budget: DailyBudgetV1,
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub presence_signature: Option<String>,
267}
268
269impl EngineOptinOnV1 {
270    pub fn validate(&self) -> Result<(), ValidationError> {
271        require_schema(&self.schema, ENGINE_OPTIN_ON_SCHEMA)?;
272        if !self.active {
273            return Err(ValidationError::new(
274                "a turn-on is active; a stop is the stop schema",
275            ));
276        }
277        if let Some(id) = &self.prev_optin_id {
278            validate_id(id, "prev_optin_id")?;
279        }
280        let vaults = self.vaults.as_deref().unwrap_or_default();
281        if vaults.len() > MAX_OPTIN_VAULTS {
282            return Err(ValidationError::new(format!(
283                "at most {MAX_OPTIN_VAULTS} vaults"
284            )));
285        }
286        for vault in vaults {
287            super::validate_vault_id(vault)?;
288        }
289        self.daily_budget.validate()
290    }
291}
292
293#[cfg(test)]
294mod on_tests {
295    use super::*;
296
297    fn on() -> EngineOptinOnV1 {
298        EngineOptinOnV1 {
299            schema: ENGINE_OPTIN_ON_SCHEMA.into(),
300            active: true,
301            prev_optin_id: None,
302            vaults: Some(vec!["0f3c2b6a8d4e4a7b9c105e2f6a7b8c01".into()]),
303            daily_budget: DailyBudgetV1::AUTO,
304            presence_signature: None,
305        }
306    }
307
308    #[test]
309    fn pickup_turn_on_body_keeps_a_null_prev_optin_id_and_the_auto_budget() {
310        let body = serde_json::to_value(on()).unwrap();
311        assert!(body["prev_optin_id"].is_null());
312        assert!(body.as_object().unwrap().contains_key("prev_optin_id"));
313        assert!(!body.as_object().unwrap().contains_key("presence_signature"));
314        assert_eq!(
315            body["daily_budget"],
316            serde_json::json!({"tasks": 3, "tokens": 1_000_000})
317        );
318        on().validate().unwrap();
319    }
320
321    #[test]
322    fn pickup_turn_on_refuses_a_stop_a_bad_vault_and_a_bad_budget() {
323        let mut stop = on();
324        stop.active = false;
325        assert!(stop.validate().is_err());
326        let mut vault = on();
327        vault.vaults = Some(vec!["notes".into()]);
328        assert!(vault.validate().is_err());
329        let mut budget = on();
330        budget.daily_budget.tasks = Some(0);
331        assert!(budget.validate().is_err());
332        let extra = serde_json::json!({
333            "schema": ENGINE_OPTIN_ON_SCHEMA, "active": true, "prev_optin_id": null,
334            "daily_budget": {"tasks": 3}, "networks": []
335        });
336        assert!(serde_json::from_value::<EngineOptinOnV1>(extra).is_err());
337    }
338}