Skip to main content

rpi_cli/host/
types.rs

1use super::{HostError, HostResult, TimeoutOverrides};
2use serde::{Deserialize, Serialize};
3use std::{fmt, path::PathBuf};
4use uuid::Uuid;
5
6macro_rules! identity {
7    ($name:ident) => {
8        #[derive(
9            Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
10        )]
11        #[serde(try_from = "String", into = "String")]
12        pub struct $name(Uuid);
13
14        impl $name {
15            pub fn new() -> Self {
16                Self(Uuid::new_v4())
17            }
18        }
19        impl Default for $name {
20            fn default() -> Self {
21                Self::new()
22            }
23        }
24        impl TryFrom<String> for $name {
25            type Error = HostError;
26            fn try_from(value: String) -> HostResult<Self> {
27                let id = Uuid::parse_str(&value)
28                    .map_err(|_| HostError::InvalidInput("invalid identity"))?;
29                if id.is_nil() {
30                    return Err(HostError::InvalidInput("nil identity"));
31                }
32                Ok(Self(id))
33            }
34        }
35        impl From<$name> for String {
36            fn from(value: $name) -> Self {
37                value.0.to_string()
38            }
39        }
40        impl fmt::Display for $name {
41            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42                self.0.fmt(f)
43            }
44        }
45    };
46}
47identity!(AgentId);
48identity!(HostEpoch);
49identity!(RunId);
50identity!(RequestId);
51// Stable namespace for trusted administrative requests, distinct from epochs.
52identity!(ControlScopeId);
53// Opaque nonce for one frozen trusted profile, never a digest of private inputs.
54identity!(ProfileVersion);
55
56/// Public identity of immutable trusted inputs. Possessing/constructing this
57/// value grants nothing: the Host must resolve the exact pair in its allowlist.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct ProfileRef {
61    pub agent_id: AgentId,
62    pub version: ProfileVersion,
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum AgentMode {
68    Persistent,
69    Mini,
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum ExecutionMode {
75    InProcess,
76    ChildProcess,
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
80#[serde(rename_all = "snake_case")]
81pub enum AgentState {
82    Registered,
83    Starting,
84    Idle,
85    Running,
86    WaitingApproval,
87    Closing,
88    Unloaded,
89    Closed,
90    Interrupted,
91    Lost,
92}
93
94impl AgentState {
95    /// Starting reserves a slot; closing retains it until cleanup finishes.
96    pub fn is_resident(self) -> bool {
97        matches!(
98            self,
99            Self::Starting | Self::Idle | Self::Running | Self::WaitingApproval | Self::Closing
100        )
101    }
102
103    pub fn is_executing(self) -> bool {
104        matches!(self, Self::Running | Self::WaitingApproval)
105    }
106
107    /// Waiting for a model/tool/retry/approval must not look idle to a reaper.
108    pub fn is_busy(self) -> bool {
109        self.is_resident() && self != Self::Idle
110    }
111
112    pub fn validate_for(self, mode: AgentMode) -> HostResult<()> {
113        if (mode == AgentMode::Persistent && self == Self::Lost)
114            || (mode == AgentMode::Mini
115                && matches!(self, Self::Closed | Self::Unloaded | Self::Interrupted))
116        {
117            return Err(HostError::InvalidInput(
118                "state does not match persistence mode",
119            ));
120        }
121        Ok(())
122    }
123
124    /// Backend adapters must apply these only after the actual boundary: e.g.
125    /// Running -> Idle requires settlement, Closing -> Closed requires cleanup.
126    /// This helper does not perform execution, cancellation or persistence.
127    pub fn transition(self, next: Self, mode: AgentMode) -> HostResult<Self> {
128        self.validate_for(mode)?;
129        if mode == AgentMode::Mini && self == Self::Lost {
130            return Err(HostError::MiniStateLost);
131        }
132        next.validate_for(mode)?;
133        let allowed = match self {
134            Self::Registered => matches!(next, Self::Starting | Self::Closed | Self::Lost),
135            // A restored provider-deferred conversation is already waiting for
136            // external model work; publishing it as Idle would mislead reapers.
137            Self::Starting => {
138                matches!(
139                    next,
140                    Self::Idle | Self::Running | Self::Unloaded | Self::Closed | Self::Lost
141                )
142            }
143            Self::Idle => matches!(next, Self::Running | Self::Closing),
144            Self::Running => matches!(next, Self::Idle | Self::WaitingApproval | Self::Closing),
145            Self::WaitingApproval => matches!(next, Self::Running | Self::Idle | Self::Closing),
146            Self::Closing => matches!(next, Self::Unloaded | Self::Closed | Self::Lost),
147            Self::Unloaded | Self::Interrupted => matches!(next, Self::Starting | Self::Closed),
148            Self::Closed => next == Self::Starting,
149            Self::Lost => false,
150        };
151        if !allowed {
152            return Err(HostError::InvalidTransition {
153                from: self,
154                to: next,
155            });
156        }
157        Ok(next)
158    }
159
160    /// Classify stale observations after host restart. This neither restores a
161    /// Session nor authorizes replay of a tool whose external effects are unknown.
162    pub fn after_restart(self, mode: AgentMode) -> HostResult<Self> {
163        self.validate_for(mode)?;
164        if mode == AgentMode::Mini {
165            return Ok(Self::Lost);
166        }
167        Ok(match self {
168            Self::Idle => Self::Unloaded,
169            Self::Starting | Self::Running | Self::WaitingApproval | Self::Closing => {
170                Self::Interrupted
171            }
172            other => other,
173        })
174    }
175}
176
177#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(deny_unknown_fields)]
179pub struct SessionRef {
180    pub id: String,
181    pub path: PathBuf,
182}
183
184#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
185#[serde(deny_unknown_fields)]
186pub struct ModelRef {
187    pub provider: String,
188    pub model: String,
189}
190
191/// Allowlisted startup metadata, not a raw argv/env bag. No prompts, credentials
192/// or tool arguments belong here. Full restore bindings are a backend concern.
193#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(deny_unknown_fields)]
195pub struct LaunchSpec {
196    pub cwd: PathBuf,
197    pub model: Option<ModelRef>,
198    pub tools: Vec<String>,
199    pub resource_profile: Option<String>,
200}
201
202#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(deny_unknown_fields)]
204pub struct AgentSpec {
205    pub id: AgentId,
206    pub name: String,
207    /// Relationship metadata, never an authorization grant.
208    pub parent_id: Option<AgentId>,
209    pub execution: ExecutionMode,
210    pub mode: AgentMode,
211    pub session: Option<SessionRef>,
212    pub launch: LaunchSpec,
213    #[serde(default)]
214    pub timeouts: TimeoutOverrides,
215}
216
217impl AgentSpec {
218    /// Structural validation only; no filesystem access or Session recovery.
219    pub fn validate(&self) -> HostResult<()> {
220        fn text(value: &str, limit: usize) -> HostResult<()> {
221            if value.trim().is_empty() || value.len() > limit || value.contains('\0') {
222                return Err(HostError::InvalidInput(
223                    "empty, oversized or NUL-containing metadata",
224                ));
225            }
226            Ok(())
227        }
228        fn path(value: &std::path::Path) -> HostResult<()> {
229            let Some(value) = value.to_str().filter(|_| value.is_absolute()) else {
230                return Err(HostError::InvalidInput(
231                    "paths must be absolute UTF-8 paths",
232                ));
233            };
234            text(value, 4096)
235        }
236        text(&self.name, 256)?;
237        path(&self.launch.cwd)?;
238        if self.parent_id == Some(self.id) {
239            return Err(HostError::InvalidInput("Agent cannot be its own parent"));
240        }
241        match (self.mode, &self.session) {
242            (AgentMode::Persistent, Some(session)) => {
243                text(&session.id, 256)?;
244                path(&session.path)?;
245            }
246            (AgentMode::Mini, None) => {}
247            _ => {
248                return Err(HostError::InvalidInput(
249                    "Session reference does not match persistence mode",
250                ))
251            }
252        }
253        if let Some(model) = &self.launch.model {
254            text(&model.provider, 256)?;
255            text(&model.model, 256)?;
256        }
257        if self.launch.tools.len() > 256 {
258            return Err(HostError::InvalidInput("too many tool names"));
259        }
260        for tool in &self.launch.tools {
261            text(tool, 128)?;
262        }
263        if let Some(profile) = &self.launch.resource_profile {
264            text(profile, 256)?;
265        }
266        self.timeouts.validate()?;
267        Ok(())
268    }
269}