Skip to main content

qualia_app_contract/
delegation.rs

1use crate::effects::CommandEffect;
2use crate::id::{AppId, DecimalU64};
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum DelegationMode {
8    Observe,
9    Propose,
10    ApproveEachAction,
11    BoundedDelegation,
12}
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum DelegationLifecycle {
17    Submitted,
18    Validating,
19    AwaitingApproval,
20    Approved,
21    Running,
22    Paused,
23    Cancelling,
24    Completed,
25    Failed,
26    Cancelled,
27    Revoked,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
31pub struct ResourceBudgets {
32    pub max_steps: u32,
33    pub max_cpu_time_ms: u64,
34    pub max_memory_bytes: u64,
35    pub external_cost_minor_units: Option<u64>,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39pub struct TaskDelegation {
40    pub delegation_id: String,
41    pub principal_id: String,
42    pub actor_id: String,
43    pub app_id: AppId,
44    pub goal: String,
45    pub allowed_effects: Vec<CommandEffect>,
46    pub allowed_command_ids: Vec<String>,
47    pub mode: DelegationMode,
48    pub state: DelegationLifecycle,
49    pub budgets: ResourceBudgets,
50    pub expiry_timestamp_ms: DecimalU64,
51}
52
53impl TaskDelegation {
54    /// `true` when active.
55    pub fn is_active(&self) -> bool {
56        matches!(self.state, DelegationLifecycle::Approved | DelegationLifecycle::Running)
57    }
58
59    /// `true` when effect-allowed.
60    pub fn is_effect_allowed(&self, effect: &CommandEffect) -> bool {
61        self.allowed_effects.contains(effect)
62    }
63
64    /// `true` when command-allowed.
65    pub fn is_command_allowed(&self, command_id: &str) -> bool {
66        self.allowed_command_ids.is_empty() || self.allowed_command_ids.iter().any(|id| id == command_id)
67    }
68
69    /// Revokes.
70    pub fn revoke(&mut self) {
71        self.state = DelegationLifecycle::Revoked;
72    }
73
74    /// Pauses.
75    pub fn pause(&mut self) {
76        if self.state == DelegationLifecycle::Running {
77            self.state = DelegationLifecycle::Paused;
78        }
79    }
80}