Skip to main content

lean_ctx/core/hive/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Errors of the Hive connector. Messages are safe to print: they never
3//! carry tokens, keys, device codes or request bodies.
4
5use std::fmt;
6
7use lean_ctx_protocol::hive::lease::HivePlan;
8use lean_ctx_protocol::hive::{HiveErrorBody, HiveErrorCode, HiveErrorDetailV1, HiveUploadKind};
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum HiveError {
12    /// Hive could not be reached (DNS, connect, TLS, timeout, reset).
13    Offline(String),
14    /// The instance is not enrolled on this machine.
15    NotConnected,
16    /// The service refused the instance's credentials.
17    Unauthorized,
18    /// `402 plan_required`: the plan lacks a feature (C0 2.x names it), or,
19    /// from a 1.x Hive that names none, Hive itself (an engine seat).
20    PlanRequired(Box<PlanNeed>),
21    /// Every instance seat of the organization is taken.
22    InstanceLimit {
23        limit: Option<u64>,
24        used: Option<u64>,
25    },
26    /// A Release B quota is used up (`409`/`429 quota_exceeded`, Hive API
27    /// §8.1). Nothing is charged; monthly quotas are waited out (the outbox
28    /// keeps local work), counted ones need a person.
29    QuotaExceeded(Box<Quota>),
30    /// Hive' own enforcement of a policy member refused (`403
31    /// policy_denied`, API §7.2). Never retried until the policy changes.
32    PolicyDenied(PolicyDenial),
33    /// The lease is past `grace_until`; reconnect.
34    LeaseLapsed,
35    /// A workspace admin revoked this instance (`401 instance_revoked`, C0
36    /// 2.0 E12). Recorded locally; no Hive call is made until a new
37    /// connect (fail closed, never retried).
38    Revoked(Revocation),
39    /// The lease lacks the right this request needs.
40    Forbidden,
41    /// An organization veto bars this lease or handoff (`forbidden_right`,
42    /// `reason: vetoed`; C5c). Never retried until the veto is lifted.
43    Vetoed,
44    /// The organization switched this upload off; stop it and drop its
45    /// queue until a lease allows it again (never retried).
46    UploadDisabled(HiveUploadKind),
47    NotFound,
48    Conflict {
49        expected: Option<u64>,
50        actual: Option<u64>,
51    },
52    ScreeningBlocked,
53    UpgradeRequired {
54        min: Option<String>,
55    },
56    RateLimited {
57        retry_after: Option<u64>,
58    },
59    /// The device flow ended without approval.
60    DeviceFlow(String),
61    /// A response or stored artifact broke the contract (bad signature,
62    /// wrong shape, unknown key).
63    Protocol(String),
64    /// Configuration that cannot work (URL scheme, root key).
65    Config(String),
66    /// Local storage failed.
67    Local(String),
68    /// A local rule refused the request before it left (worker gate,
69    /// outgoing screening); the message carries no content.
70    Refused(String),
71    /// Hive refused a task request (C0 1.9 §1); `number` names the task.
72    Task {
73        refusal: TaskRefusal,
74        number: Option<u64>,
75        /// The roles a `not_permitted` refusal names (Hive task #17).
76        detail: Option<String>,
77    },
78    /// Any other service answer.
79    Server {
80        status: u16,
81        code: String,
82    },
83}
84
85/// A used-up quota as far as it is shown and acted on (API §8.1).
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct Quota {
88    /// HTTP status: 409 counted, 429 monthly.
89    pub status: u16,
90    /// `[a-z_]` token (`transfer_bytes`, `bus_messages`,
91    /// `registered_engines`, `private_vaults`, or a newer one).
92    pub resource: String,
93    pub limit: Option<u64>,
94    pub used: Option<u64>,
95    /// When it frees, second precision `Z` (`None`: nothing frees by itself).
96    pub reset_at: Option<String>,
97    /// `retry_after_s` (or the `Retry-After` header).
98    pub retry_after: Option<u64>,
99    /// `registered_engines` in Personal: the slot cool-down.
100    pub cooldown_days: Option<u32>,
101}
102
103/// What a `402 plan_required` says, as far as it is shown.
104#[derive(Debug, Clone, PartialEq, Eq, Default)]
105pub struct PlanNeed {
106    /// `[a-z_]` feature token (`compute`, `repos`, `internal_vaults`, …);
107    /// `None` from a 1.x Hive: Hive itself (the engine-seat text).
108    pub feature: Option<String>,
109    /// The lowest plan that includes it (`pro`, `team`, `enterprise`).
110    pub plan_needed: Option<String>,
111    /// A counted feature's limit and use (`repos`).
112    pub limit: Option<u64>,
113    pub used: Option<u64>,
114    /// The service's own words, terminal-safe.
115    pub message: Option<String>,
116    /// The workspace's plan as this engine's lease names it (set by the
117    /// session that made the call, [`HiveError::with_plan`]).
118    pub plan: Option<HivePlan>,
119    /// Why the workspace is locked (`trial_ended`, `plan_ended`, `no_plan`;
120    /// `[a-z_]`, Hive API §1a).
121    pub reason: Option<String>,
122}
123
124/// The part every locked-workspace line shares; `hive sync` prints such a
125/// refusal once per run.
126pub const LOCKED_MARK: &str = "this workspace is locked (read and export only)";
127
128/// The 1.x engine-seat text: the limits worded as everywhere (E10).
129pub const PLAN_LIMITS: &str = "Personal 3 engines, 2 connected at once; Team 5 per seat, 3 connected at once per seat; Enterprise on request";
130
131impl PlanNeed {
132    /// `trial_ended` or `plan_ended`: the workspace is locked.
133    #[must_use]
134    pub fn locked(&self) -> Option<&str> {
135        self.reason
136            .as_deref()
137            .filter(|r| matches!(*r, "trial_ended" | "plan_ended"))
138    }
139
140    /// Team wording when the refusal or the lease says team.
141    fn plan_word(&self) -> &'static str {
142        let team = self.plan_needed.as_deref() == Some("team")
143            || matches!(self.plan, Some(HivePlan::Team | HivePlan::Enterprise));
144        if team { "Team" } else { "Personal" }
145    }
146}
147
148/// The one line of a locked workspace (`reason` `trial_ended`/`plan_ended`).
149#[must_use]
150pub fn locked_line(reason: &str, plan_word: &str) -> String {
151    let what = if reason == "trial_ended" {
152        format!("Your {plan_word} trial has ended")
153    } else {
154        "Your plan has ended".to_string()
155    };
156    format!("{what}: {LOCKED_MARK}. Choose a plan in Hive to sync again.")
157}
158
159/// The plans that include a feature whose lowest plan is `needed`.
160fn plans_from(needed: &str) -> Option<&'static str> {
161    Some(match needed {
162        "personal" => "Personal, Team and Enterprise",
163        "team" => "Team and Enterprise",
164        "enterprise" => "Enterprise",
165        _ => return None,
166    })
167}
168
169fn write_plan_need(f: &mut fmt::Formatter<'_>, need: &PlanNeed) -> fmt::Result {
170    // A locked workspace is one line, whatever the feature (E9).
171    if let Some(reason) = need.locked() {
172        return f.write_str(&locked_line(reason, need.plan_word()));
173    }
174    let Some(feature) = need.feature.as_deref() else {
175        // 1.x: the plan does not include Hive (an engine seat).
176        return write!(
177            f,
178            "this workspace's plan does not include Hive here ({PLAN_LIMITS})"
179        );
180    };
181    let plans = need.plan_needed.as_deref().and_then(plans_from);
182    let on = need
183        .plan
184        .filter(|p| *p != HivePlan::Unknown)
185        .map(|p| match p {
186            HivePlan::NoPlan => "; this workspace has no plan".to_string(),
187            p => format!("; this workspace is on {}", p.display_name()),
188        })
189        .unwrap_or_default();
190    match feature {
191        "compute" => write!(
192            f,
193            "Task Compute is included in {}{on}",
194            plans.unwrap_or("Team and Enterprise")
195        ),
196        "repos" | "vaults" | "private_vaults" => {
197            f.write_str("this workspace has used all its vaults")?;
198            if let (Some(used), Some(limit)) = (need.used, need.limit) {
199                write!(f, " ({used} of {limit})")?;
200            }
201            if let Some(plans) = plans {
202                write!(f, "; more are included in {plans}")?;
203            }
204            write!(
205                f,
206                "{on}; remove or publish a vault in Hive, or upgrade the plan"
207            )
208        }
209        other => {
210            match (&need.message, plans) {
211                (Some(message), _) => f.write_str(message.trim_end_matches('.'))?,
212                (None, Some(plans)) => {
213                    write!(f, "{} is included in {plans}", other.replace('_', " "))?;
214                }
215                (None, None) => write!(
216                    f,
217                    "this workspace's plan does not include {}",
218                    other.replace('_', " ")
219                )?,
220            }
221            f.write_str(&on)
222        }
223    }
224}
225
226/// Monthly quotas reset at the start of the next calendar month (UTC).
227pub const MONTHLY_RESOURCES: &[&str] = &["transfer_bytes", "bus_messages"];
228
229impl Quota {
230    /// Whether waiting frees it (a monthly quota, or any 429).
231    #[must_use]
232    pub fn waits(&self) -> bool {
233        self.status == 429 || MONTHLY_RESOURCES.contains(&self.resource.as_str())
234    }
235
236    /// A Personal engine slot that frees after its cool-down (P7).
237    #[must_use]
238    pub fn cooling_slot(&self) -> bool {
239        self.resource == "registered_engines"
240            && self.cooldown_days.is_some_and(|d| d > 0)
241            && self.reset_at.is_some()
242    }
243}
244
245/// A server-enforced policy refusal (`policy_denied`, API §7.2).
246#[derive(Debug, Clone, PartialEq, Eq, Default)]
247pub struct PolicyDenial {
248    /// Dotted member path (`sharing.allowed_vaults`).
249    pub member: Option<String>,
250    /// `org`, `workspace`, `vault` or `engine`.
251    pub level: Option<String>,
252    /// `consent_required_for`: the action that needs a person.
253    pub action: Option<String>,
254}
255
256/// A value of the service shown on a terminal: `[a-z0-9_.-]`, 1..=max.
257fn wire_token(value: Option<&str>, max: usize) -> Option<String> {
258    value
259        .filter(|s| {
260            (1..=max).contains(&s.len())
261                && s.bytes().all(|b| {
262                    b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
263                })
264        })
265        .map(str::to_string)
266}
267
268/// An RFC 3339 time of the service in second-precision `Z` form.
269pub(crate) fn wire_time(value: Option<&str>) -> Option<String> {
270    let parsed = chrono::DateTime::parse_from_rfc3339(value?).ok()?;
271    Some(
272        parsed
273            .with_timezone(&chrono::Utc)
274            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
275    )
276}
277
278/// What a revocation statement says, as far as it is shown (E12).
279#[derive(Debug, Clone, PartialEq, Eq, Default)]
280pub struct Revocation {
281    /// The workspace that revoked it, when the engine knows its name.
282    pub workspace: Option<String>,
283    /// `web_revoke`, `admin` or `key_compromise` (`[a-z_]`, ≤ 32).
284    pub reason: Option<String>,
285    /// `revoked_at` of the statement (ms).
286    pub revoked_at: Option<u64>,
287    /// `instance_id` of the statement.
288    pub instance_id: Option<String>,
289}
290
291impl Revocation {
292    /// The statement of an `instance_revoked` error body; values that are
293    /// not of the contract's shape are left out (they reach a terminal).
294    fn of_statement(statement: &serde_json::Value) -> Self {
295        let token = |v: &serde_json::Value, max: usize| {
296            v.as_str()
297                .filter(|s| {
298                    (1..=max).contains(&s.len())
299                        && s.bytes().all(|b| {
300                            b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-'
301                        })
302                })
303                .map(str::to_string)
304        };
305        Self {
306            workspace: None,
307            reason: token(&statement["reason"], 32),
308            revoked_at: statement["revoked_at"].as_u64(),
309            instance_id: token(&statement["instance_id"], 36),
310        }
311    }
312}
313
314/// Which check refused a `not_permitted` claim (Hive task #17).
315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
316pub enum PermitCheck {
317    /// The agent has no live presence on the bus.
318    Presence,
319    /// The agent is present in another role than the task's.
320    Role,
321    /// A Hive that does not say.
322    Unknown,
323}
324
325/// Why Hive refused a task request (the `reason` of C0 1.9 §1).
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub enum TaskRefusal {
328    /// Another claim holds the task.
329    Claimed,
330    /// A claim on a task that is not `open`.
331    NotOpen,
332    /// The lease id or fencing token is not the current claim's.
333    StaleClaim,
334    /// A write to a `done`, `rejected` or `cancelled` task.
335    Closed,
336    /// A confirmation that a threshold may not count.
337    ReviewerNotIndependent,
338    /// An object of another network (org bus vs a swarm).
339    CrossNetwork,
340    /// The task's role or the owner's worker consent does not allow this agent.
341    NotPermitted(PermitCheck),
342    /// The engine's opt-in does not cover this vault or network (§4,
343    /// `optin_scope`).
344    OptinScope,
345    /// The claim named an older `optin_id`: read the opt-in again (§4,
346    /// `optin_changed`).
347    OptinChanged,
348    /// No opt-in, or the owner stopped it: every claim of the engine ended
349    /// (§4, `optin_inactive`).
350    OptinInactive,
351    /// The opt-in's daily budget is used up until 00:00 UTC (§4,
352    /// `daily_budget`); never retried before `retry_after`.
353    DailyBudget { retry_after: Option<u64> },
354}
355
356impl TaskRefusal {
357    fn from_reason(
358        code: HiveErrorCode,
359        reason: Option<&str>,
360        retry_after: Option<u64>,
361        check: Option<&str>,
362    ) -> Option<Self> {
363        Some(match (code, reason?) {
364            (HiveErrorCode::InvalidState, "task_claimed") => Self::Claimed,
365            (HiveErrorCode::InvalidState, "task_not_open") => Self::NotOpen,
366            (HiveErrorCode::InvalidState, "stale_claim") => Self::StaleClaim,
367            (HiveErrorCode::InvalidState, "task_closed") => Self::Closed,
368            (HiveErrorCode::InvalidState, "reviewer_not_independent") => {
369                Self::ReviewerNotIndependent
370            }
371            (HiveErrorCode::InvalidState, "cross_network") => Self::CrossNetwork,
372            (HiveErrorCode::ForbiddenRight, "not_permitted") => Self::NotPermitted(match check {
373                Some("presence") => PermitCheck::Presence,
374                Some("role") => PermitCheck::Role,
375                _ => PermitCheck::Unknown,
376            }),
377            (HiveErrorCode::ForbiddenRight, "optin_scope") => Self::OptinScope,
378            (HiveErrorCode::InvalidState, "optin_changed") => Self::OptinChanged,
379            (HiveErrorCode::InvalidState, "optin_inactive") => Self::OptinInactive,
380            (HiveErrorCode::RateLimited, "daily_budget") => Self::DailyBudget { retry_after },
381            _ => return None,
382        })
383    }
384
385    /// Whether the claim this request acted under is gone for good (a stop
386    /// of the opt-in ends every claim of the engine).
387    #[must_use]
388    pub fn ends_claim(self) -> bool {
389        matches!(self, Self::StaleClaim | Self::Closed | Self::OptinInactive)
390    }
391}
392
393impl fmt::Display for TaskRefusal {
394    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395        match self {
396            Self::Claimed => f.write_str("another agent holds the task"),
397            Self::NotOpen => f.write_str("the task is not open"),
398            Self::StaleClaim => f.write_str("this claim is no longer the task's claim"),
399            Self::Closed => f.write_str("the task is closed"),
400            Self::ReviewerNotIndependent => {
401                f.write_str("this confirmation is not independent of the result")
402            }
403            Self::CrossNetwork => f.write_str("the task belongs to another network"),
404            Self::NotPermitted(PermitCheck::Presence) => f.write_str(
405                "this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role",
406            ),
407            Self::NotPermitted(PermitCheck::Role) => {
408                f.write_str("this agent is on the bus in another role than the task needs")
409            }
410            Self::NotPermitted(PermitCheck::Unknown) => f.write_str(
411                "the task's role or the owner's worker consent does not allow this agent",
412            ),
413            Self::OptinScope => f.write_str("this engine's opt-in does not cover this vault"),
414            Self::OptinChanged => f.write_str("the opt-in changed; it is read again"),
415            Self::OptinInactive => f.write_str(
416                "this engine is not opted in (or the owner stopped worker mode on the web)",
417            ),
418            Self::DailyBudget { retry_after } => match retry_after {
419                Some(s) => write!(f, "today's task budget is used up (resets in {s} s)"),
420                None => f.write_str("today's task budget is used up"),
421            },
422        }
423    }
424}
425
426/// A role as the bus names it, or nothing: only `[a-z0-9-]`, 1-64 chars,
427/// so a service answer cannot put anything else on the terminal.
428fn bus_role(role: Option<&String>) -> Option<&str> {
429    role.map(String::as_str).filter(|r| {
430        (1..=64).contains(&r.len())
431            && r.bytes()
432                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
433    })
434}
435
436/// The service's own words, safe for a terminal: no control characters
437/// (escape sequences), at most 300 characters; `None` when nothing is left.
438fn safe_message(message: &str) -> Option<String> {
439    let text: String = message
440        .chars()
441        .map(|c| if c.is_control() { ' ' } else { c })
442        .take(300)
443        .collect();
444    let text = text.trim();
445    (!text.is_empty()).then(|| text.to_string())
446}
447
448/// The whole line of a `not_permitted` refusal: Hive's message (it names
449/// the agent and the roles), the check that failed and, when the agent is
450/// not on the bus, how to put it there.
451fn permit_line(refusal: TaskRefusal, detail: &HiveErrorDetailV1) -> Option<String> {
452    let TaskRefusal::NotPermitted(check) = refusal else {
453        return None;
454    };
455    let mut line =
456        safe_message(&detail.message).unwrap_or_else(|| match permit_roles(refusal, detail) {
457            Some(roles) => format!("{refusal} ({roles})"),
458            None => refusal.to_string(),
459        });
460    match check {
461        PermitCheck::Presence => line.push_str(
462            " [check: presence] Run `lean-ctx hive bus relay --for 30` (it relays, or makes the running relay announce the agent now) and claim again.",
463        ),
464        PermitCheck::Role => line.push_str(" [check: role]"),
465        PermitCheck::Unknown => {}
466    }
467    Some(line)
468}
469
470/// The roles of a `not_permitted` refusal, in words (Hive task #17).
471fn permit_roles(refusal: TaskRefusal, detail: &HiveErrorDetailV1) -> Option<String> {
472    let role = bus_role(detail.role.as_ref())?;
473    match refusal {
474        TaskRefusal::NotPermitted(PermitCheck::Presence) => {
475            Some(format!("the task needs role {role}"))
476        }
477        TaskRefusal::NotPermitted(PermitCheck::Role) => {
478            Some(match bus_role(detail.agent_role.as_ref()) {
479                Some(agent_role) => {
480                    format!("the agent works as {agent_role}, the task needs {role}")
481                }
482                None => format!("the task needs role {role}"),
483            })
484        }
485        _ => None,
486    }
487}
488
489/// The longest `retry_after_s` an answer may ask for (32 days); a larger one
490/// (up to `u64::MAX`) is shortened to this before any time arithmetic.
491pub const RETRY_AFTER_CAP_S: u64 = 32 * 86_400;
492
493impl HiveError {
494    /// Map a non-2xx answer to an error.
495    pub(crate) fn from_response(status: u16, body: &serde_json::Value) -> Self {
496        let value_reason = body["error"]["reason"].clone();
497        let revocation = body["error"]["revocation"].clone();
498        let Ok(body) = serde_json::from_value::<HiveErrorBody>(body.clone()) else {
499            return Self::Server {
500                status,
501                code: "unknown".into(),
502            };
503        };
504        let mut detail = body.error;
505        // A wait beyond the cap is a broken or hostile answer; every later
506        // `now + retry_after` stays inside chrono's range (which panics).
507        detail.retry_after_s = detail.retry_after_s.map(|s| s.min(RETRY_AFTER_CAP_S));
508        if let Some(refusal) = TaskRefusal::from_reason(
509            detail.code,
510            detail.reason.as_deref(),
511            detail.retry_after_s,
512            detail.check.as_deref(),
513        ) {
514            return Self::Task {
515                refusal,
516                number: detail.number,
517                detail: permit_line(refusal, &detail),
518            };
519        }
520        match detail.code {
521            HiveErrorCode::Unauthorized => Self::Unauthorized,
522            HiveErrorCode::LeaseExpired => Self::LeaseLapsed,
523            HiveErrorCode::InstanceRevoked => Self::Revoked(Revocation::of_statement(&revocation)),
524            HiveErrorCode::PlanRequired => Self::PlanRequired(Box::new(PlanNeed {
525                feature: wire_token(detail.feature.as_deref(), 64),
526                plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
527                limit: detail.limit,
528                used: detail.used,
529                message: safe_message(&detail.message),
530                plan: None,
531                reason: wire_token(detail.reason.as_deref(), 32),
532            })),
533            HiveErrorCode::InstanceLimit => Self::InstanceLimit {
534                limit: detail.limit,
535                used: detail.used,
536            },
537            HiveErrorCode::QuotaExceeded => Self::QuotaExceeded(Box::new(Quota {
538                status,
539                resource: wire_token(detail.resource.as_deref(), 64)
540                    .unwrap_or_else(|| "unknown".into()),
541                limit: detail.limit,
542                used: detail.used,
543                reset_at: wire_time(detail.reset_at.as_deref()),
544                retry_after: detail.retry_after_s,
545                cooldown_days: detail.cooldown_days,
546            })),
547            // Engine metrics v2 name the member `field` and the level
548            // `reason` (`metrics_hours.error.policy_denied.json`).
549            HiveErrorCode::PolicyDenied => Self::PolicyDenied(PolicyDenial {
550                member: wire_token(detail.member.as_deref().or(detail.field.as_deref()), 80),
551                level: wire_token(
552                    detail.level.as_deref().or(detail
553                        .reason
554                        .as_deref()
555                        .filter(|r| matches!(*r, "org" | "workspace" | "vault" | "engine"))),
556                    16,
557                ),
558                action: wire_token(detail.action.as_deref(), 64),
559            }),
560            HiveErrorCode::ForbiddenRight if value_reason.as_str() == Some("vetoed") => {
561                Self::Vetoed
562            }
563            HiveErrorCode::ForbiddenRight => Self::Forbidden,
564            HiveErrorCode::UploadDisabled => {
565                Self::UploadDisabled(detail.kind.unwrap_or(HiveUploadKind::Unknown))
566            }
567            HiveErrorCode::NotFound => Self::NotFound,
568            HiveErrorCode::RevisionConflict => Self::Conflict {
569                expected: detail.expected,
570                actual: detail.actual,
571            },
572            HiveErrorCode::ScreeningRequired => Self::ScreeningBlocked,
573            HiveErrorCode::UpgradeRequired => Self::UpgradeRequired {
574                min: detail.min_engine,
575            },
576            HiveErrorCode::RateLimited => Self::RateLimited {
577                retry_after: detail.retry_after_s,
578            },
579            HiveErrorCode::ExpiredToken => Self::DeviceFlow(CODE_EXPIRED.into()),
580            HiveErrorCode::AccessDenied => Self::DeviceFlow(
581                "you chose \"Not mine\" in the browser; nothing changed on this machine".into(),
582            ),
583            other => Self::Server {
584                status,
585                code: serde_json::to_value(other)
586                    .ok()
587                    .and_then(|v| v.as_str().map(str::to_string))
588                    .unwrap_or_else(|| "unknown".into()),
589            },
590        }
591    }
592
593    /// A `plan_required` of a feature names the workspace's plan as the
594    /// lease of the calling session says it; every other error is kept.
595    #[must_use]
596    pub fn with_plan(mut self, plan: HivePlan) -> Self {
597        if let Self::PlanRequired(need) = &mut self
598            && (need.feature.is_some() || need.locked().is_some())
599            && plan != HivePlan::Unknown
600        {
601            need.plan.get_or_insert(plan);
602        }
603        self
604    }
605
606    /// Whether retrying later can help.
607    pub fn is_transient(&self) -> bool {
608        match self {
609            Self::QuotaExceeded(q) => q.waits(),
610            other => matches!(
611                other,
612                Self::Offline(_) | Self::RateLimited { .. } | Self::Server { status: 500.., .. }
613            ),
614        }
615    }
616
617    /// Seconds to wait before this may be tried again, when Hive said so:
618    /// `retry_after_s`/`Retry-After` of a 429, else the time until a
619    /// waiting quota's `reset_at` (seen from `now`).
620    pub fn retry_after_at(&self, now: chrono::DateTime<chrono::Utc>) -> Option<u64> {
621        match self {
622            Self::RateLimited { retry_after } => *retry_after,
623            Self::QuotaExceeded(q) if q.waits() => q.retry_after.or_else(|| {
624                let reset = chrono::DateTime::parse_from_rfc3339(q.reset_at.as_deref()?).ok()?;
625                u64::try_from(
626                    (reset.with_timezone(&chrono::Utc) - now)
627                        .num_seconds()
628                        .max(1),
629                )
630                .ok()
631            }),
632            _ => None,
633        }
634    }
635}
636
637impl fmt::Display for HiveError {
638    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
639        match self {
640            Self::Offline(why) => write!(f, "Hive is not reachable ({why})"),
641            Self::NotConnected => f.write_str("not connected to Hive (run `lean-ctx hive connect`)"),
642            Self::Unauthorized => f.write_str(
643                "Hive does not accept this instance any more (run `lean-ctx hive connect` again)",
644            ),
645            Self::PlanRequired(need) => write_plan_need(f, need),
646            Self::InstanceLimit { limit, used } => match (limit, used) {
647                (Some(limit), Some(used)) => write!(
648                    f,
649                    "all engine instances of the workspace are in use ({used} of {limit}); remove one in Hive or upgrade the plan"
650                ),
651                _ => f.write_str(
652                    "all engine instances of the workspace are in use; remove one in Hive or upgrade the plan",
653                ),
654            },
655            Self::QuotaExceeded(q) => write_quota(f, q),
656            Self::PolicyDenied(d) => {
657                f.write_str("Hive policy refuses this")?;
658                if let Some(member) = &d.member {
659                    write!(f, " ({member}")?;
660                    if let Some(level) = &d.level {
661                        write!(f, ", set at the {level} level")?;
662                    }
663                    f.write_str(")")?;
664                }
665                match &d.action {
666                    Some(action) => write!(
667                        f,
668                        "; a person does this on the Hive web ({})",
669                        action.replace('_', " ")
670                    ),
671                    None => f.write_str(
672                        "; it is not retried until an admin changes the policy in Hive",
673                    ),
674                }
675            }
676            Self::LeaseLapsed => {
677                f.write_str("the Hive lease has lapsed (run `lean-ctx hive connect` again)")
678            }
679            Self::Revoked(r) => {
680                f.write_str("this engine was revoked by ")?;
681                match &r.workspace {
682                    Some(workspace) => f.write_str(workspace)?,
683                    None => f.write_str("its workspace")?,
684                }
685                if let Some(reason) = &r.reason {
686                    write!(f, " ({})", reason.replace('_', " "))?;
687                }
688                f.write_str("; reconnect with `lean-ctx hive connect` after an admin allows it")
689            }
690            Self::Forbidden => f.write_str("this instance's lease does not allow that"),
691            Self::Vetoed => f.write_str("a workspace veto bars it until the veto is lifted"),
692            Self::UploadDisabled(kind) => match kind {
693                HiveUploadKind::Metrics => {
694                    f.write_str("the workspace has switched metrics upload off")
695                }
696                HiveUploadKind::Receipts => {
697                    f.write_str("the workspace has switched receipts upload off")
698                }
699                HiveUploadKind::Unknown => {
700                    f.write_str("the workspace has switched this upload off")
701                }
702            },
703            Self::NotFound => f.write_str("Hive does not know that item"),
704            Self::Conflict { expected, actual } => match (expected, actual) {
705                (Some(e), Some(a)) => write!(f, "knowledge moved on (expected revision {e}, now {a})"),
706                _ => f.write_str("knowledge moved on"),
707            },
708            Self::ScreeningBlocked => f.write_str("Hive screening refused the content"),
709            Self::UpgradeRequired { min } => match min {
710                Some(min) => write!(f, "Hive needs lean-ctx {min} or newer (run `lean-ctx update`)"),
711                None => f.write_str("Hive needs a newer lean-ctx (run `lean-ctx update`)"),
712            },
713            Self::RateLimited { retry_after } => match retry_after {
714                Some(s) => write!(f, "Hive asks to retry in {s} s"),
715                None => f.write_str("Hive asks to retry later"),
716            },
717            Self::DeviceFlow(why) => write!(f, "connection not approved: {why}"),
718            Self::Protocol(why) => write!(f, "unexpected answer from Hive: {why}"),
719            Self::Config(why) => write!(f, "Hive configuration: {why}"),
720            Self::Local(why) => write!(f, "local Hive state: {why}"),
721            Self::Refused(why) => f.write_str(why),
722            Self::Task {
723                refusal,
724                number,
725                detail,
726            } => {
727                if let Some(number) = number {
728                    write!(f, "task #{number}: ")?;
729                }
730                match detail {
731                    // A not_permitted detail is the whole line (`permit_line`).
732                    Some(detail) if matches!(refusal, TaskRefusal::NotPermitted(_)) => {
733                        f.write_str(detail)
734                    }
735                    Some(detail) => write!(f, "{refusal} ({detail})"),
736                    None => write!(f, "{refusal}"),
737                }
738            }
739            Self::Server { status, code } => write!(f, "Hive answered {status} ({code})"),
740        }
741    }
742}
743
744impl std::error::Error for HiveError {}
745
746/// A device code that ran out before anyone approved it.
747pub const CODE_EXPIRED: &str =
748    "the code expired before it was approved; run `lean-ctx hive connect` again for a new one";
749
750/// Where a person frees or recovers an engine slot (P7): the recovery
751/// route (`POST /api/v1/orgs/{o}/instances/{id}/recover`, owner with a
752/// second factor) is on the web only.
753pub const RECOVER_HINT: &str = "for a lost or broken device, recover its slot now on the Hive web (Settings › Engines › Recover, with your second factor; once per 30 days)";
754
755fn write_quota(f: &mut fmt::Formatter<'_>, q: &Quota) -> fmt::Result {
756    let what = match q.resource.as_str() {
757        "transfer_bytes" => "monthly transfer",
758        "bus_messages" => "monthly bus messages",
759        "registered_engines" => "engine slots",
760        "private_vaults" => "private vaults",
761        "connected_engines" => "connected engines",
762        other => other,
763    };
764    write!(f, "this workspace has used all its {what}")?;
765    if let (Some(used), Some(limit)) = (q.used, q.limit) {
766        write!(f, " ({used} of {limit})")?;
767    }
768    f.write_str("; nothing is charged for more")?;
769    match q.resource.as_str() {
770        "registered_engines" if q.cooling_slot() => write!(
771            f,
772            "; a revoked engine's slot frees at {} ({}-day cool-down), or {RECOVER_HINT}",
773            q.reset_at.as_deref().unwrap_or("?"),
774            q.cooldown_days.unwrap_or(0)
775        ),
776        "registered_engines" => f.write_str(
777            "; revoke an engine you no longer use in Hive (Settings › Engines), or upgrade the plan",
778        ),
779        "private_vaults" => {
780            f.write_str("; remove or publish a vault in Hive, or upgrade the plan")
781        }
782        _ if q.waits() => match &q.reset_at {
783            Some(at) => write!(f, "; uploads wait in the local outbox until {at}"),
784            None => f.write_str("; uploads wait in the local outbox until it frees"),
785        },
786        _ => Ok(()),
787    }
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793    use serde_json::json;
794
795    #[test]
796    fn instance_limit_carries_the_seat_numbers() {
797        let error = HiveError::from_response(
798            409,
799            &json!({"error": {"code": "instance_limit", "message": "x", "limit": 2, "used": 2}}),
800        );
801        assert_eq!(
802            error,
803            HiveError::InstanceLimit {
804                limit: Some(2),
805                used: Some(2)
806            }
807        );
808        assert!(error.to_string().contains("2 of 2"));
809    }
810
811    #[test]
812    fn a_huge_retry_after_is_capped_on_the_way_in() {
813        for huge in [u64::MAX, i64::MAX.unsigned_abs(), RETRY_AFTER_CAP_S + 1] {
814            let error = HiveError::from_response(
815                429,
816                &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": huge}}),
817            );
818            assert_eq!(
819                error,
820                HiveError::RateLimited {
821                    retry_after: Some(RETRY_AFTER_CAP_S)
822                }
823            );
824        }
825        let small = HiveError::from_response(
826            429,
827            &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": 90}}),
828        );
829        assert_eq!(
830            small,
831            HiveError::RateLimited {
832                retry_after: Some(90)
833            }
834        );
835    }
836
837    #[test]
838    fn upload_disabled_names_the_kind_and_is_not_retried() {
839        let error = HiveError::from_response(
840            403,
841            &json!({"error": {"code": "upload_disabled", "message": "x", "kind": "metrics"}}),
842        );
843        assert_eq!(error, HiveError::UploadDisabled(HiveUploadKind::Metrics));
844        assert!(!error.is_transient());
845        assert!(error.to_string().contains("metrics upload off"));
846    }
847
848    #[test]
849    fn task_reasons_become_task_refusals_and_others_stay() {
850        let refusal = |status, code: &str, reason: &str| {
851            HiveError::from_response(
852                status,
853                &json!({"error": {"code": code, "message": "x", "reason": reason, "number": 7, "retry_after_s": 60}}),
854            )
855        };
856        assert_eq!(
857            refusal(409, "invalid_state", "stale_claim"),
858            HiveError::Task {
859                refusal: TaskRefusal::StaleClaim,
860                number: Some(7),
861                detail: None
862            }
863        );
864        assert_eq!(
865            refusal(403, "forbidden_right", "optin_scope"),
866            HiveError::Task {
867                refusal: TaskRefusal::OptinScope,
868                number: Some(7),
869                detail: None
870            }
871        );
872        // Hive task #17: a not_permitted refusal says which check failed and the roles.
873        let permit_said = |check: &str, agent_role: Option<&str>, message: &str| {
874            let mut e = json!({"error": {"code": "forbidden_right", "message": message,
875                                         "reason": "not_permitted", "number": 7, "check": check,
876                                         "role": "backend"}});
877            if let Some(r) = agent_role {
878                e["error"]["agent_role"] = r.into();
879            }
880            HiveError::from_response(403, &e).to_string()
881        };
882        let permit = |check: &str, agent_role: Option<&str>| permit_said(check, agent_role, "");
883        assert_eq!(
884            permit("presence", None),
885            "task #7: this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role (the task needs role backend) [check: presence] Run `lean-ctx hive bus relay --for 30` (it relays, or makes the running relay announce the agent now) and claim again."
886        );
887        assert_eq!(
888            permit("role", Some("web")),
889            "task #7: this agent is on the bus in another role than the task needs (the agent works as web, the task needs backend) [check: role]"
890        );
891        assert!(
892            permit("role", Some("web\u{1b}[31m"))
893                .ends_with("(the task needs role backend) [check: role]"),
894            "a role that is not a bus identifier is not printed"
895        );
896        // The service's own message is printed, with the check and the hint.
897        assert_eq!(
898            permit_said(
899                "presence",
900                None,
901                "Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again."
902            ),
903            "task #7: Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again. [check: presence] Run `lean-ctx hive bus relay --for 30` (it relays, or makes the running relay announce the agent now) and claim again."
904        );
905        assert_eq!(
906            permit_said(
907                "role",
908                Some("web"),
909                "Agent coder-1 works as role web;\u{1b}[31m this task needs role backend."
910            ),
911            "task #7: Agent coder-1 works as role web; [31m this task needs role backend. [check: role]",
912            "control characters of the service's message never reach the terminal"
913        );
914        // A Hive that names no check still has its message printed.
915        assert_eq!(
916            permit_said("", None, "Agent coder-1 may not take this task."),
917            "task #7: Agent coder-1 may not take this task."
918        );
919        let inactive = refusal(409, "invalid_state", "optin_inactive");
920        assert!(matches!(inactive, HiveError::Task { refusal, .. } if refusal.ends_claim()));
921        assert!(matches!(
922            refusal(409, "invalid_state", "optin_changed"),
923            HiveError::Task {
924                refusal: TaskRefusal::OptinChanged,
925                ..
926            }
927        ));
928        let budget = refusal(429, "rate_limited", "daily_budget");
929        assert_eq!(
930            budget,
931            HiveError::Task {
932                refusal: TaskRefusal::DailyBudget {
933                    retry_after: Some(60)
934                },
935                number: Some(7),
936                detail: None
937            }
938        );
939        assert!(!budget.is_transient(), "a used-up budget is not retried");
940        assert!(
941            budget
942                .to_string()
943                .starts_with("task #7: today's task budget")
944        );
945        // The contract's own error fixtures decode to the same refusals.
946        for (fixture, expected) in [
947            ("error.optin_scope.json", TaskRefusal::OptinScope),
948            ("error.optin_changed.json", TaskRefusal::OptinChanged),
949            ("error.optin_inactive.json", TaskRefusal::OptinInactive),
950            (
951                "error.daily_budget.json",
952                TaskRefusal::DailyBudget {
953                    retry_after: Some(43200),
954                },
955            ),
956            ("error.task_claimed.json", TaskRefusal::Claimed),
957            (
958                "error.task_not_permitted.json",
959                TaskRefusal::NotPermitted(PermitCheck::Unknown),
960            ),
961            (
962                "error.task_not_permitted_role.json",
963                TaskRefusal::NotPermitted(PermitCheck::Role),
964            ),
965        ] {
966            let path = format!(
967                "{}/crates/lean-ctx-protocol/tests/fixtures/hive/{fixture}",
968                env!("CARGO_MANIFEST_DIR")
969            );
970            let body: serde_json::Value =
971                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
972            let code: HiveErrorCode =
973                serde_json::from_value(body["error"]["code"].clone()).unwrap();
974            assert!(
975                matches!(
976                    HiveError::from_response(code.http_status(), &body),
977                    HiveError::Task { refusal, .. } if refusal == expected
978                ),
979                "{fixture}"
980            );
981        }
982        assert_eq!(refusal(403, "forbidden_right", "vetoed"), HiveError::Vetoed);
983        assert_eq!(
984            refusal(409, "invalid_state", "sealed"),
985            HiveError::Server {
986                status: 409,
987                code: "invalid_state".into()
988            },
989            "a reason of another section keeps its old meaning"
990        );
991    }
992
993    /// The `plan_required` example of a C0 2.x web fixture, by feature.
994    fn plan_required_example(file: &str, feature: &str) -> (u16, serde_json::Value) {
995        let path = format!(
996            "{}/crates/lean-ctx-protocol/tests/fixtures/hive-v2/web/{file}",
997            env!("CARGO_MANIFEST_DIR")
998        );
999        let fixture: serde_json::Value =
1000            serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
1001        let example = fixture["errors"]
1002            .as_array()
1003            .expect("errors")
1004            .iter()
1005            .find(|e| {
1006                e["body"]["error"]["code"] == "plan_required"
1007                    && e["body"]["error"]["feature"] == feature
1008            })
1009            .unwrap_or_else(|| panic!("{file}: no plan_required {feature}"));
1010        (
1011            u16::try_from(example["status"].as_u64().unwrap()).unwrap(),
1012            example["body"].clone(),
1013        )
1014    }
1015
1016    #[test]
1017    fn plan_required_keeps_the_feature_and_words_it() {
1018        // C0 2.x compute (the live e2e: a no-plan workspace's submit).
1019        let (status, body) = plan_required_example("compute-top-up.json", "compute");
1020        assert_eq!(status, 402);
1021        let error = HiveError::from_response(status, &body);
1022        assert_eq!(
1023            error,
1024            HiveError::PlanRequired(Box::new(PlanNeed {
1025                feature: Some("compute".into()),
1026                plan_needed: Some("team".into()),
1027                limit: None,
1028                used: None,
1029                message: Some("Task Compute: included in Team and Enterprise.".into()),
1030                plan: None,
1031                reason: None,
1032            }))
1033        );
1034        assert_eq!(
1035            error.to_string(),
1036            "Task Compute is included in Team and Enterprise"
1037        );
1038        let on_community = error.clone().with_plan(HivePlan::NoPlan);
1039        assert_eq!(
1040            on_community.to_string(),
1041            "Task Compute is included in Team and Enterprise; this workspace has no plan"
1042        );
1043        assert!(!on_community.to_string().contains("engine"));
1044        assert_eq!(
1045            error.clone().with_plan(HivePlan::Unknown),
1046            error,
1047            "an unknown plan is not named"
1048        );
1049        assert!(!error.is_transient());
1050
1051        // A vault limit (W11 transfer into a no-plan workspace).
1052        let (status, body) = plan_required_example("vault-transfer.json", "repos");
1053        let repos = HiveError::from_response(status, &body).with_plan(HivePlan::NoPlan);
1054        assert_eq!(
1055            repos.to_string(),
1056            "this workspace has used all its vaults (3 of 3); more are included in Personal, Team and Enterprise; this workspace has no plan; remove or publish a vault in Hive, or upgrade the plan"
1057        );
1058
1059        // Any other feature: the service's words (a company comes with Enterprise).
1060        let (status, body) = plan_required_example("organisation-create.json", "company");
1061        let org = HiveError::from_response(status, &body).with_plan(HivePlan::Team);
1062        assert_eq!(
1063            org.to_string(),
1064            "A company comes with Enterprise, on request: send a request and we set it up with you; this workspace is on Team"
1065        );
1066        let unnamed = HiveError::from_response(
1067            402,
1068            &json!({"error": {"code": "plan_required", "message": "", "feature": "team_swarms", "plan_needed": "team"}}),
1069        );
1070        assert_eq!(
1071            unnamed.to_string(),
1072            "team swarms is included in Team and Enterprise"
1073        );
1074        let hostile = HiveError::from_response(
1075            402,
1076            &json!({"error": {"code": "plan_required", "message": "x\u{1b}[2J", "feature": "Comp\u{1b}"}}),
1077        );
1078        assert_eq!(
1079            hostile,
1080            HiveError::PlanRequired(Box::new(PlanNeed {
1081                message: Some("x [2J".into()),
1082                ..PlanNeed::default()
1083            })),
1084            "a feature that is not a wire token is dropped, the message is terminal-safe"
1085        );
1086    }
1087
1088    #[test]
1089    fn plan_required_without_a_feature_keeps_the_1x_seat_text() {
1090        let path = format!(
1091            "{}/crates/lean-ctx-protocol/tests/fixtures/hive/error.plan_required.json",
1092            env!("CARGO_MANIFEST_DIR")
1093        );
1094        let body: serde_json::Value =
1095            serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
1096        let error = HiveError::from_response(402, &body).with_plan(HivePlan::NoPlan);
1097        assert_eq!(
1098            error.to_string(),
1099            "this workspace's plan does not include Hive here (Personal 3 engines, 2 connected at once; Team 5 per seat, 3 connected at once per seat; Enterprise on request)"
1100        );
1101        assert!(
1102            matches!(&error, HiveError::PlanRequired(need) if need.plan.is_none()),
1103            "a 1.x refusal is about Hive itself, not a feature of the plan"
1104        );
1105    }
1106
1107    #[test]
1108    fn a_locked_workspace_is_one_line_whatever_the_feature() {
1109        let locked = |reason: &str, feature: Option<&str>, needed: &str| {
1110            let mut body = json!({"error": {"code": "plan_required", "message": "Your trial has ended: this workspace is locked.",
1111                                            "plan_needed": needed, "reason": reason}});
1112            if let Some(f) = feature {
1113                body["error"]["feature"] = f.into();
1114            }
1115            HiveError::from_response(402, &body)
1116        };
1117        let trial = "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in Hive to sync again.";
1118        for feature in [None, Some("read_only")] {
1119            let e = locked("trial_ended", feature, "personal");
1120            assert_eq!(e.to_string(), trial);
1121            assert!(matches!(&e, HiveError::PlanRequired(n) if n.locked() == Some("trial_ended")));
1122            assert_eq!(
1123                e.with_plan(HivePlan::Personal).to_string(),
1124                trial,
1125                "the lease's plan adds nothing to the line"
1126            );
1127        }
1128        assert_eq!(
1129            locked("plan_ended", Some("read_only"), "team").to_string(),
1130            "Your plan has ended: this workspace is locked (read and export only). Choose a plan in Hive to sync again."
1131        );
1132        assert_eq!(
1133            locked("trial_ended", None, "team").to_string(),
1134            "Your Team trial has ended: this workspace is locked (read and export only). Choose a plan in Hive to sync again."
1135        );
1136        // no_plan is not a lock of an ended plan: the feature's words stay.
1137        let no_plan = locked("no_plan", None, "personal");
1138        assert!(
1139            no_plan.to_string().contains("2 connected at once"),
1140            "{no_plan}"
1141        );
1142        assert!(!no_plan.to_string().contains(LOCKED_MARK));
1143    }
1144
1145    #[test]
1146    fn non_contract_bodies_become_server_errors() {
1147        assert_eq!(
1148            HiveError::from_response(502, &json!("<html>")),
1149            HiveError::Server {
1150                status: 502,
1151                code: "unknown".into()
1152            }
1153        );
1154        assert!(
1155            HiveError::Server {
1156                status: 502,
1157                code: "unknown".into()
1158            }
1159            .is_transient()
1160        );
1161    }
1162}