Skip to main content

lean_ctx_protocol/cloud/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Error body of every non-2xx Cloud response: `{"error":{...}}`.
4
5use serde::{Deserialize, Serialize};
6
7/// Machine-readable error code. Unknown codes from a newer service decode as
8/// [`CloudErrorCode::Unknown`] and are handled by HTTP status.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum CloudErrorCode {
12    /// 400, device flow: the user has not approved yet; poll again after `interval`.
13    AuthorizationPending,
14    /// 400, device flow: polling too fast; add 5 s to the interval.
15    SlowDown,
16    /// 400, device flow: the device code expired; start again.
17    ExpiredToken,
18    /// 400, device flow: the user refused.
19    AccessDenied,
20    /// 400: body failed validation or carried unknown fields.
21    InvalidRequest,
22    /// 400 with `field` (the request path, e.g. `chat_key.bind_signature`)
23    /// and optionally `reason` (f3129: `app_key_not_announced`,
24    /// `app_key_bind_invalid`): one member of an otherwise well-formed
25    /// request was refused (`docs/contracts/app-key-bind-v1.md`).
26    InvalidField,
27    /// 401: access token missing, expired or not for this instance.
28    Unauthorized,
29    /// 402: the organization's plan does not include Cloud.
30    PlanRequired,
31    /// 403: the lease lacks the right this route needs.
32    ForbiddenRight,
33    /// 403 with `kind` (1.4): the organization switched this upload off.
34    /// Stop that kind of upload and drop its queue until a lease allows it.
35    UploadDisabled,
36    /// 404: unknown instance, vault, proposal or lease.
37    NotFound,
38    /// 404 with `feature` (Cloud API.md "feature switches"): the operator
39    /// switched this feature off on this Cloud (`instance_metrics` while
40    /// `CLOUD_ENGINE_METRICS` is off). The route exists; try again much later.
41    FeatureDisabled,
42    /// 409 with `limit`/`used`: every instance seat is taken.
43    InstanceLimit,
44    /// 409 with `expected`/`actual`: knowledge moved on.
45    RevisionConflict,
46    /// 409 with `reason` (1.5): the object is not in a state that allows
47    /// this.
48    InvalidState,
49    /// 401: the instance lease is past `grace_until`; renew or reconnect.
50    LeaseExpired,
51    /// 422: the service screening refused content the engine should have removed.
52    ScreeningRequired,
53    /// 429 with `retry_after_s`.
54    RateLimited,
55    /// 426 with `min_instance` (also in the `Cloud-Min-Instance` header).
56    UpgradeRequired,
57    /// 401 with `revocation` (C0 2.0 E12, §3.17.3): a workspace admin
58    /// revoked this instance; every engine route answers it until a new
59    /// connect. Never retried.
60    InstanceRevoked,
61    /// Release B quotas (Cloud API §8.1): `resource`, `limit`, `used`,
62    /// `reset_at`. Counted resources (`registered_instances`,
63    /// `private_vaults`) answer 409 (`registered_instances` in Personal adds
64    /// `cooldown_days`, `reset_at` = when a cooling-down slot frees);
65    /// monthly ones (`transfer_bytes`, `bus_messages`) answer 429 with
66    /// `retry_after_s` and `Retry-After` until `reset_at`. Never overage:
67    /// the engine waits, its outbox keeps local work.
68    QuotaExceeded,
69    /// 403 with `member` (dotted policy path) and `level` (the outermost
70    /// level whose document refuses; consent refusals add `action`): Cloud
71    /// itself enforces an `x-enforcement: server` policy member (§7.2).
72    PolicyDenied,
73    /// 403 with `resource: "storage_bytes"`, `limit`/`used` and
74    /// `limit_bytes`/`used_bytes`: the workspace's LeanCTX Cloud storage is
75    /// full. Nothing frees by waiting; a person frees storage or upgrades.
76    StorageQuotaExceeded,
77    /// 429 with `limit_bytes_per_hour`, `retry_after_s` and `Retry-After`:
78    /// the sliding-hour upload allowance (max(storage/4, 256 MiB)) is used
79    /// up. Transient: wait `retry_after_s`, then upload the rest.
80    UploadRateLimited,
81    /// Any code this engine does not know.
82    #[serde(other)]
83    Unknown,
84}
85
86impl CloudErrorCode {
87    /// HTTP status the service answers with for this code.
88    pub fn http_status(self) -> u16 {
89        match self {
90            Self::AuthorizationPending
91            | Self::SlowDown
92            | Self::ExpiredToken
93            | Self::AccessDenied
94            | Self::InvalidRequest
95            | Self::InvalidField => 400,
96            Self::Unauthorized | Self::LeaseExpired | Self::InstanceRevoked => 401,
97            Self::PlanRequired => 402,
98            Self::ForbiddenRight
99            | Self::UploadDisabled
100            | Self::PolicyDenied
101            | Self::StorageQuotaExceeded => 403,
102            Self::NotFound | Self::FeatureDisabled => 404,
103            Self::InstanceLimit | Self::RevisionConflict | Self::InvalidState => 409,
104            Self::ScreeningRequired => 422,
105            Self::UpgradeRequired => 426,
106            // 409 for counted resources; the monthly ones, the common case
107            // on data routes, are 429.
108            Self::RateLimited | Self::QuotaExceeded | Self::UploadRateLimited => 429,
109            Self::Unknown => 500,
110        }
111    }
112}
113
114/// The `error` object.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct CloudErrorDetailV1 {
117    pub code: CloudErrorCode,
118    /// Human-readable, safe to show; never contains secrets or tokens.
119    pub message: String,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub retry_after_s: Option<u64>,
122    /// `instance_limit`: seats in the plan; `quota_exceeded`: the quota
123    /// (bytes for `transfer_bytes`, so wider than 32 bits).
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub limit: Option<u64>,
126    /// `instance_limit`: seats in use; `quota_exceeded`: what is used.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub used: Option<u64>,
129    /// `quota_exceeded`: the quota (`registered_instances`, `private_vaults`,
130    /// `transfer_bytes`, `bus_messages`, or one a newer Cloud adds).
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub resource: Option<String>,
133    /// `quota_exceeded`: when it frees (RFC 3339; `null` when nothing frees
134    /// by itself).
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub reset_at: Option<String>,
137    /// `quota_exceeded` `registered_instances`: the Personal slot cool-down.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub cooldown_days: Option<u32>,
140    /// `policy_denied`: the dotted member path that refused.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub member: Option<String>,
143    /// `policy_denied`: the outermost level whose document refuses.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub level: Option<String>,
146    /// `policy_denied` of `consent_required_for`: the action.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub action: Option<String>,
149    /// `revision_conflict`: revision the client expected.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub expected: Option<u64>,
152    /// `revision_conflict`: current revision.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub actual: Option<u64>,
155    /// `upgrade_required`: lowest engine version accepted.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub min_instance: Option<String>,
158    /// `upload_disabled`: which upload the organization switched off.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub kind: Option<CloudUploadKind>,
161    /// 1.5: machine-readable detail of the code (`[a-z_]`, ≤ 64), e.g.
162    /// `required`.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub reason: Option<String>,
165    /// 1.5: the request field the error is about (`invalid_request`).
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub field: Option<String>,
168    /// 1.6: the proposal an error is about (`proposal_state`, `not_found`).
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub number: Option<u64>,
171    /// `not_permitted` (Cloud task #17): the check that failed, `presence`
172    /// (the agent has no live presence on the bus) or `role` (present in
173    /// another role).
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub check: Option<String>,
176    /// `not_permitted`: the task's role.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub role: Option<String>,
179    /// `not_permitted` with `check: role`: the role the agent is present in.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub agent_role: Option<String>,
182    /// 2.x `plan_required`: the feature the plan lacks (`repos`,
183    /// `internal_vaults`, …; absent from a 1.x Cloud, where it means Cloud
184    /// itself). `limit`/`used` carry a counted feature's numbers.
185    /// `feature_disabled`: the feature switched off on this Cloud
186    /// (`instance_metrics`).
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub feature: Option<String>,
189    /// 2.x `plan_required`: the lowest plan that includes `feature`
190    /// (`pro`, `team`, `enterprise`).
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub plan_needed: Option<String>,
193    /// Limit refusals (`quota_exceeded`, `storage_quota_exceeded`,
194    /// `upload_rate_limited`, `instance_limit`, `plan_required`): the
195    /// workspace's plan (`personal`, `team`, `enterprise`, `locked`).
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub plan: Option<String>,
198    /// Limit refusals: what helps (`subscribe`, `top_up`, `upgrade_team`,
199    /// `add_seats`, `contact`, `wait`, or one a newer service adds).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub next_step: Option<String>,
202    /// `storage_quota_exceeded`: the storage quota in bytes.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub limit_bytes: Option<u64>,
205    /// `storage_quota_exceeded`: the storage used in bytes.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub used_bytes: Option<u64>,
208    /// `upload_rate_limited`: the upload allowance per sliding hour.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub limit_bytes_per_hour: Option<u64>,
211    /// `instance_limit` in Team: the workspace's seats.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub seats: Option<u64>,
214    /// `instance_limit` in Team: the allowance of each seat.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub per_seat: Option<u64>,
217}
218
219/// An upload an organization can switch off (1.4).
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
221#[serde(rename_all = "snake_case")]
222pub enum CloudUploadKind {
223    Metrics,
224    Receipts,
225    #[serde(other)]
226    Unknown,
227}
228
229impl CloudErrorDetailV1 {
230    /// An error with only code and message.
231    pub fn new(code: CloudErrorCode, message: impl Into<String>) -> Self {
232        Self {
233            code,
234            message: message.into(),
235            retry_after_s: None,
236            limit: None,
237            used: None,
238            resource: None,
239            reset_at: None,
240            cooldown_days: None,
241            member: None,
242            level: None,
243            action: None,
244            expected: None,
245            actual: None,
246            min_instance: None,
247            kind: None,
248            reason: None,
249            field: None,
250            number: None,
251            check: None,
252            role: None,
253            agent_role: None,
254            feature: None,
255            plan_needed: None,
256            plan: None,
257            next_step: None,
258            limit_bytes: None,
259            used_bytes: None,
260            limit_bytes_per_hour: None,
261            seats: None,
262            per_seat: None,
263        }
264    }
265}
266
267/// Body of every non-2xx response.
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269pub struct CloudErrorBody {
270    pub error: CloudErrorDetailV1,
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn unknown_codes_decode_as_unknown() {
279        let body: CloudErrorBody =
280            serde_json::from_str(r#"{"error":{"code":"brand_new","message":"x","extra":1}}"#)
281                .unwrap();
282        assert_eq!(body.error.code, CloudErrorCode::Unknown);
283    }
284
285    /// f3129: `invalid_field` is a named code; codes still unknown stay
286    /// [`CloudErrorCode::Unknown`] (the test above).
287    #[test]
288    fn invalid_field_decodes_with_field_and_reason() {
289        let body: CloudErrorBody = serde_json::from_str(
290            r#"{"error":{"code":"invalid_field","message":"x","field":"chat_key.bind_signature","reason":"app_key_bind_invalid"}}"#,
291        )
292        .unwrap();
293        assert_eq!(body.error.code, CloudErrorCode::InvalidField);
294        assert_eq!(body.error.code.http_status(), 400);
295        assert_eq!(body.error.field.as_deref(), Some("chat_key.bind_signature"));
296        assert_eq!(body.error.reason.as_deref(), Some("app_key_bind_invalid"));
297        assert_eq!(
298            serde_json::to_value(CloudErrorCode::InvalidField).unwrap(),
299            "invalid_field"
300        );
301    }
302
303    /// Cloud answers `POST /v1/metrics/hours` with this while
304    /// `CLOUD_ENGINE_METRICS` is off (dogfood 05.11.: decoded as `unknown`).
305    #[test]
306    fn feature_disabled_decodes_with_its_feature() {
307        let body: CloudErrorBody = serde_json::from_str(
308            r#"{"error":{"code":"feature_disabled","message":"this feature is switched off on this Cloud","feature":"instance_metrics"}}"#,
309        )
310        .unwrap();
311        assert_eq!(body.error.code, CloudErrorCode::FeatureDisabled);
312        assert_eq!(body.error.code.http_status(), 404);
313        assert_eq!(body.error.feature.as_deref(), Some("instance_metrics"));
314    }
315
316    /// C0 2.0 `routes/instance_revoked.error.json` decodes to its own code
317    /// (dogfood 25.10.: it decoded as `unknown`, shown as "401 (unknown)").
318    #[test]
319    fn instance_revoked_decodes_from_the_c0_fixture() {
320        let body: CloudErrorBody = serde_json::from_str(include_str!(
321            "../../tests/fixtures/cloud-v2/routes/instance_revoked.error.json"
322        ))
323        .unwrap();
324        assert_eq!(body.error.code, CloudErrorCode::InstanceRevoked);
325        assert_eq!(body.error.code.http_status(), 401);
326    }
327
328    /// C0 2.x `routes/quota_exceeded.error.json` (Release B §8.1): a byte
329    /// quota wider than 32 bits decodes, with resource and reset.
330    #[test]
331    fn quota_exceeded_decodes_from_the_c0_fixture() {
332        let body: CloudErrorBody = serde_json::from_str(include_str!(
333            "../../tests/fixtures/cloud-v2/routes/quota_exceeded.error.json"
334        ))
335        .unwrap();
336        let e = body.error;
337        assert_eq!(e.code, CloudErrorCode::QuotaExceeded);
338        assert_eq!(e.resource.as_deref(), Some("transfer_bytes"));
339        assert_eq!(e.limit, Some(42_949_672_960));
340        assert_eq!(e.used, Some(42_949_672_960));
341        assert_eq!(e.reset_at.as_deref(), Some("2026-11-01T00:00:00Z"));
342        assert_eq!(e.retry_after_s, Some(86_400));
343    }
344
345    /// The server's own shapes (API §7.2 and §3): `policy_denied {member,
346    /// level, action?}` and the Personal slot cool-down; a 1.x engine that does
347    /// not know them still decodes the body (unknown code, extra fields).
348    #[test]
349    fn policy_denied_and_cooldown_decode_and_stay_tolerant() {
350        let denied: CloudErrorBody = serde_json::from_str(
351            r#"{"error":{"code":"policy_denied","message":"x","member":"sharing.consent_required_for","level":"org","action":"trust_boundary"}}"#,
352        )
353        .unwrap();
354        assert_eq!(denied.error.code, CloudErrorCode::PolicyDenied);
355        assert_eq!(denied.error.code.http_status(), 403);
356        assert_eq!(
357            denied.error.member.as_deref(),
358            Some("sharing.consent_required_for")
359        );
360        assert_eq!(denied.error.level.as_deref(), Some("org"));
361        assert_eq!(denied.error.action.as_deref(), Some("trust_boundary"));
362        let slot: CloudErrorBody = serde_json::from_str(
363            r#"{"error":{"code":"quota_exceeded","message":"x","resource":"registered_instances","limit":3,"used":3,"reset_at":"2026-11-02T08:00:00Z","cooldown_days":7}}"#,
364        )
365        .unwrap();
366        assert_eq!(slot.error.cooldown_days, Some(7));
367        let newer: CloudErrorBody = serde_json::from_str(
368            r#"{"error":{"code":"quota_exceeded","message":"x","resource":"gpu_minutes","reset_at":null,"extra":1}}"#,
369        )
370        .unwrap();
371        assert_eq!(newer.error.resource.as_deref(), Some("gpu_minutes"));
372        assert_eq!(newer.error.reset_at, None);
373    }
374
375    /// The cloud's limit refusals (plan limits of 17.11.) decode with
376    /// every field; none of them is `unknown` any more.
377    #[test]
378    fn cloud_limit_refusals_decode_with_their_fields() {
379        let storage: CloudErrorBody = serde_json::from_str(
380            r#"{"error":{"code":"storage_quota_exceeded","message":"x","resource":"storage_bytes","limit":1073741824,"used":1073741824,"limit_bytes":1073741824,"used_bytes":1073741824,"plan":"personal","next_step":"upgrade_team"}}"#,
381        )
382        .unwrap();
383        let e = storage.error;
384        assert_eq!(e.code, CloudErrorCode::StorageQuotaExceeded);
385        assert_eq!(e.code.http_status(), 403);
386        assert_eq!(e.resource.as_deref(), Some("storage_bytes"));
387        assert_eq!(e.limit_bytes, Some(1_073_741_824));
388        assert_eq!(e.used_bytes, Some(1_073_741_824));
389        assert_eq!(e.plan.as_deref(), Some("personal"));
390        assert_eq!(e.next_step.as_deref(), Some("upgrade_team"));
391
392        let rate: CloudErrorBody = serde_json::from_str(
393            r#"{"error":{"code":"upload_rate_limited","message":"x","limit_bytes_per_hour":268435456,"plan":"personal","next_step":"wait","retry_after_s":1200}}"#,
394        )
395        .unwrap();
396        let e = rate.error;
397        assert_eq!(e.code, CloudErrorCode::UploadRateLimited);
398        assert_eq!(e.code.http_status(), 429);
399        assert_eq!(e.limit_bytes_per_hour, Some(268_435_456));
400        assert_eq!(e.retry_after_s, Some(1200));
401        assert_eq!(e.next_step.as_deref(), Some("wait"));
402
403        let seats: CloudErrorBody = serde_json::from_str(
404            r#"{"error":{"code":"instance_limit","message":"x","resource":"connected_instances","limit":4,"used":4,"plan":"team","next_step":"add_seats","seats":2,"per_seat":2}}"#,
405        )
406        .unwrap();
407        let e = seats.error;
408        assert_eq!(e.code, CloudErrorCode::InstanceLimit);
409        assert_eq!(e.resource.as_deref(), Some("connected_instances"));
410        assert_eq!((e.seats, e.per_seat), (Some(2), Some(2)));
411        assert_eq!(e.plan.as_deref(), Some("team"));
412
413        let locked: CloudErrorBody = serde_json::from_str(
414            r#"{"error":{"code":"plan_required","message":"x","feature":"read_only","reason":"trial_ended","plan":"locked","next_step":"subscribe"}}"#,
415        )
416        .unwrap();
417        assert_eq!(locked.error.code, CloudErrorCode::PlanRequired);
418        assert_eq!(locked.error.plan.as_deref(), Some("locked"));
419        assert_eq!(locked.error.next_step.as_deref(), Some("subscribe"));
420    }
421
422    #[test]
423    fn codes_map_to_their_status() {
424        assert_eq!(CloudErrorCode::PlanRequired.http_status(), 402);
425        assert_eq!(CloudErrorCode::InstanceLimit.http_status(), 409);
426        assert_eq!(CloudErrorCode::UpgradeRequired.http_status(), 426);
427        assert_eq!(CloudErrorCode::UploadDisabled.http_status(), 403);
428    }
429
430    #[test]
431    fn upload_disabled_names_its_kind_and_tolerates_new_ones() {
432        let body: CloudErrorBody = serde_json::from_str(
433            r#"{"error":{"code":"upload_disabled","message":"x","kind":"receipts"}}"#,
434        )
435        .unwrap();
436        assert_eq!(body.error.code, CloudErrorCode::UploadDisabled);
437        assert_eq!(body.error.kind, Some(CloudUploadKind::Receipts));
438        let newer: CloudErrorBody = serde_json::from_str(
439            r#"{"error":{"code":"upload_disabled","message":"x","kind":"traces"}}"#,
440        )
441        .unwrap();
442        assert_eq!(newer.error.kind, Some(CloudUploadKind::Unknown));
443    }
444}