| 1 | //! Safe, ordered Engine owner projection shared by desktop and web hosts. |
| 2 | //! |
| 3 | //! The Engine owns operation and turn facts: it emits |
| 4 | //! `operation_activity_started` / `operation_activity_completed` with an |
| 5 | //! [`OwnerActivityKind`] and [`OwnerOperationOutcome`], a bounded canonical action identity, never an |
| 6 | //! argument, command or result. Apps may bind this session-scoped projection |
| 7 | //! to an authenticated account and serve it to another client; the account |
| 8 | //! identity is intentionally not supplied by the Engine. |
| 9 | //! |
| 10 | //! Known limits: |
| 11 | //! - Operation events only carry `Reading`, `Editing`, `Searching`, |
| 12 | //! `Testing`, `Executing`, `Browsing`, `Computer`, `Memory` or `Tool`. |
| 13 | //! `Thinking`, `Responding` and `Delegating` are derived by the reducer |
| 14 | //! from message, reasoning and agent lifecycle events. |
| 15 | //! - [`EngineOwnerProjection`] itself is computed today by the pet reducer |
| 16 | //! (`pet/src/core/pet-engine.ts`, bundled into the TUI pet worker), and |
| 17 | //! validated here on the way back. No Rust producer exists yet; a host |
| 18 | //! that needs it outside the pet must decide whether the runtime produces |
| 19 | //! it in Rust rather than adding a second reducer. |
| 20 | |
| 21 | use serde::{Deserialize, Serialize}; |
| 22 | |
| 23 | use crate::event_msg::TurnOutcomeStatus; |
| 24 | |
| 25 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 26 | #[serde(rename_all = "snake_case")] |
| 27 | pub enum OwnerActivityKind { |
| 28 | Reading, |
| 29 | Editing, |
| 30 | Searching, |
| 31 | Testing, |
| 32 | Executing, |
| 33 | Browsing, |
| 34 | Computer, |
| 35 | Memory, |
| 36 | Tool, |
| 37 | Thinking, |
| 38 | Responding, |
| 39 | Delegating, |
| 40 | } |
| 41 | |
| 42 | impl OwnerActivityKind { |
| 43 | #[must_use] |
| 44 | pub const fn as_str(self) -> &'static str { |
| 45 | match self { |
| 46 | Self::Reading => "reading", |
| 47 | Self::Editing => "editing", |
| 48 | Self::Searching => "searching", |
| 49 | Self::Testing => "testing", |
| 50 | Self::Executing => "executing", |
| 51 | Self::Browsing => "browsing", |
| 52 | Self::Computer => "computer", |
| 53 | Self::Memory => "memory", |
| 54 | Self::Tool => "tool", |
| 55 | Self::Thinking => "thinking", |
| 56 | Self::Responding => "responding", |
| 57 | Self::Delegating => "delegating", |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 63 | #[serde(rename_all = "snake_case")] |
| 64 | pub enum OwnerOperationOutcome { |
| 65 | Succeeded, |
| 66 | Failed, |
| 67 | Cancelled, |
| 68 | Denied, |
| 69 | } |
| 70 | |
| 71 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 72 | #[serde(rename_all = "snake_case")] |
| 73 | pub enum OwnerPresence { |
| 74 | Unknown, |
| 75 | Working, |
| 76 | NeedsYou, |
| 77 | Done, |
| 78 | Idle, |
| 79 | } |
| 80 | |
| 81 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 82 | #[serde(rename_all = "snake_case")] |
| 83 | pub enum OwnerFreshness { |
| 84 | Missing, |
| 85 | Fresh, |
| 86 | Stale, |
| 87 | } |
| 88 | |
| 89 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 90 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 91 | pub struct OwnerActiveSpan { |
| 92 | pub activity_kind: OwnerActivityKind, |
| 93 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 94 | pub action_id: Option<String>, |
| 95 | pub started_at_ms: f64, |
| 96 | } |
| 97 | |
| 98 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 99 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 100 | pub struct OwnerFailedToolAge { |
| 101 | pub activity_kind: OwnerActivityKind, |
| 102 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 103 | pub action_id: Option<String>, |
| 104 | pub age_ms: f64, |
| 105 | } |
| 106 | |
| 107 | /// Ordered, account-neutral read model. `cursor` is monotonic within the |
| 108 | /// existing session owner. The Apps control plane supplies account isolation |
| 109 | /// by authenticating the caller and resolving the requested session there. |
| 110 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 111 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 112 | pub struct EngineOwnerProjection { |
| 113 | pub schema_version: u8, |
| 114 | pub session_id: Option<String>, |
| 115 | pub cursor: u64, |
| 116 | pub observed: bool, |
| 117 | pub freshness: OwnerFreshness, |
| 118 | pub authoritative_presence: OwnerPresence, |
| 119 | pub activity_kind: Option<OwnerActivityKind>, |
| 120 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 121 | pub action_id: Option<String>, |
| 122 | pub observed_at_ms: Option<f64>, |
| 123 | pub parallel_agent_count: u32, |
| 124 | pub active_spans: Vec<OwnerActiveSpan>, |
| 125 | pub turn_id: Option<String>, |
| 126 | pub turn_outcome: Option<TurnOutcomeStatus>, |
| 127 | pub done_effect_id: Option<String>, |
| 128 | pub failed_tool_age: Option<OwnerFailedToolAge>, |
| 129 | } |
| 130 | |
| 131 | impl EngineOwnerProjection { |
| 132 | #[must_use] |
| 133 | pub fn is_valid(&self) -> bool { |
| 134 | let valid_action = |
| 135 | |id: &String| !id.is_empty() && id.len() <= 256 && !id.chars().any(char::is_control); |
| 136 | self.schema_version == 1 |
| 137 | && self.action_id.as_ref().is_none_or(valid_action) |
| 138 | && (self.action_id.is_none() || self.activity_kind.is_some()) |
| 139 | && self.session_id.as_ref().is_none_or(|id| { |
| 140 | !id.is_empty() && id.len() <= 256 && id.bytes().all(|byte| !byte.is_ascii_control()) |
| 141 | }) |
| 142 | && self.turn_id.as_ref().is_none_or(|id| { |
| 143 | !id.is_empty() && id.len() <= 256 && id.bytes().all(|byte| !byte.is_ascii_control()) |
| 144 | }) |
| 145 | && self.active_spans.len() <= 4 |
| 146 | && self.parallel_agent_count <= 100_000 |
| 147 | && self |
| 148 | .observed_at_ms |
| 149 | .is_none_or(|time| time.is_finite() && time >= 0.0) |
| 150 | && self.active_spans.iter().all(|span| { |
| 151 | span.action_id.as_ref().is_none_or(valid_action) |
| 152 | && span.started_at_ms.is_finite() |
| 153 | && span.started_at_ms >= 0.0 |
| 154 | && self |
| 155 | .observed_at_ms |
| 156 | .is_none_or(|observed_at| span.started_at_ms <= observed_at) |
| 157 | }) |
| 158 | && self.failed_tool_age.as_ref().is_none_or(|failure| { |
| 159 | failure.action_id.as_ref().is_none_or(valid_action) |
| 160 | && failure.age_ms.is_finite() |
| 161 | && failure.age_ms >= 0.0 |
| 162 | }) |
| 163 | && (self.turn_outcome.is_none() || self.turn_id.is_some()) |
| 164 | && match self.freshness { |
| 165 | OwnerFreshness::Missing => { |
| 166 | !self.observed |
| 167 | && self.observed_at_ms.is_none() |
| 168 | && self.activity_kind.is_none() |
| 169 | && self.active_spans.is_empty() |
| 170 | && self.parallel_agent_count == 0 |
| 171 | && self.authoritative_presence == OwnerPresence::Unknown |
| 172 | && self.turn_id.is_none() |
| 173 | && self.turn_outcome.is_none() |
| 174 | && self.failed_tool_age.is_none() |
| 175 | && self.done_effect_id.is_none() |
| 176 | } |
| 177 | OwnerFreshness::Stale => { |
| 178 | self.observed |
| 179 | && self.session_id.is_some() |
| 180 | && self.observed_at_ms.is_some() |
| 181 | && self.activity_kind.is_none() |
| 182 | && self.active_spans.is_empty() |
| 183 | && self.parallel_agent_count == 0 |
| 184 | && self.authoritative_presence == OwnerPresence::Unknown |
| 185 | && self.failed_tool_age.is_none() |
| 186 | && self.done_effect_id.is_none() |
| 187 | } |
| 188 | OwnerFreshness::Fresh => { |
| 189 | self.observed |
| 190 | && self.session_id.is_some() |
| 191 | && self.observed_at_ms.is_some() |
| 192 | && (self.authoritative_presence != OwnerPresence::Done |
| 193 | || (self.turn_outcome == Some(TurnOutcomeStatus::Completed) |
| 194 | && self.turn_id.is_some() |
| 195 | && self.done_effect_id == self.turn_id)) |
| 196 | && (self.done_effect_id.is_none() |
| 197 | || self.authoritative_presence == OwnerPresence::Done) |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | #[cfg(test)] |
| 204 | mod tests { |
| 205 | use super::*; |
| 206 | |
| 207 | fn projection() -> EngineOwnerProjection { |
| 208 | EngineOwnerProjection { |
| 209 | schema_version: 1, |
| 210 | session_id: Some("session:opaque".into()), |
| 211 | cursor: 4, |
| 212 | observed: true, |
| 213 | freshness: OwnerFreshness::Fresh, |
| 214 | authoritative_presence: OwnerPresence::Working, |
| 215 | activity_kind: Some(OwnerActivityKind::Reading), |
| 216 | action_id: Some("read_file".into()), |
| 217 | observed_at_ms: Some(100.0), |
| 218 | parallel_agent_count: 0, |
| 219 | active_spans: vec![OwnerActiveSpan { |
| 220 | activity_kind: OwnerActivityKind::Reading, |
| 221 | action_id: Some("read_file".into()), |
| 222 | started_at_ms: 50.0, |
| 223 | }], |
| 224 | turn_id: Some("turn-1".into()), |
| 225 | turn_outcome: None, |
| 226 | done_effect_id: None, |
| 227 | failed_tool_age: None, |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn projection_accepts_trusted_scoped_activity_and_rejects_bad_clocks() { |
| 233 | assert!(projection().is_valid()); |
| 234 | for invalid in ["", "bad\nname", &"鲸".repeat(86)] { |
| 235 | let mut invalid_action = projection(); |
| 236 | invalid_action.action_id = Some(invalid.to_owned()); |
| 237 | assert!(!invalid_action.is_valid()); |
| 238 | } |
| 239 | |
| 240 | let mut future_span = projection(); |
| 241 | future_span.active_spans[0].started_at_ms = 101.0; |
| 242 | assert!(!future_span.is_valid()); |
| 243 | |
| 244 | let mut too_many = projection(); |
| 245 | too_many.active_spans = vec![too_many.active_spans[0].clone(); 5]; |
| 246 | assert!(!too_many.is_valid()); |
| 247 | } |
| 248 | |
| 249 | #[test] |
| 250 | fn projection_needs_authoritative_presence_for_wait_and_completed_turn_for_done() { |
| 251 | let mut waiting = projection(); |
| 252 | waiting.authoritative_presence = OwnerPresence::NeedsYou; |
| 253 | assert!(waiting.is_valid()); |
| 254 | |
| 255 | let mut done = projection(); |
| 256 | done.authoritative_presence = OwnerPresence::Done; |
| 257 | done.activity_kind = None; |
| 258 | done.action_id = None; |
| 259 | done.active_spans.clear(); |
| 260 | done.turn_outcome = Some(TurnOutcomeStatus::Completed); |
| 261 | done.done_effect_id = done.turn_id.clone(); |
| 262 | assert!(done.is_valid()); |
| 263 | |
| 264 | done.turn_outcome = Some(TurnOutcomeStatus::Interrupted); |
| 265 | assert!(!done.is_valid()); |
| 266 | done.turn_outcome = Some(TurnOutcomeStatus::Failed); |
| 267 | assert!(!done.is_valid()); |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn missing_and_stale_projection_cannot_claim_specific_activity() { |
| 272 | let missing = EngineOwnerProjection { |
| 273 | schema_version: 1, |
| 274 | session_id: None, |
| 275 | cursor: 0, |
| 276 | observed: false, |
| 277 | freshness: OwnerFreshness::Missing, |
| 278 | authoritative_presence: OwnerPresence::Unknown, |
| 279 | activity_kind: None, |
| 280 | action_id: None, |
| 281 | observed_at_ms: None, |
| 282 | parallel_agent_count: 0, |
| 283 | active_spans: Vec::new(), |
| 284 | turn_id: None, |
| 285 | turn_outcome: None, |
| 286 | done_effect_id: None, |
| 287 | failed_tool_age: None, |
| 288 | }; |
| 289 | assert!(missing.is_valid()); |
| 290 | |
| 291 | let mut stale = projection(); |
| 292 | stale.freshness = OwnerFreshness::Stale; |
| 293 | stale.authoritative_presence = OwnerPresence::Unknown; |
| 294 | stale.activity_kind = None; |
| 295 | stale.action_id = None; |
| 296 | stale.parallel_agent_count = 0; |
| 297 | stale.active_spans.clear(); |
| 298 | stale.failed_tool_age = None; |
| 299 | stale.done_effect_id = None; |
| 300 | assert!(stale.is_valid()); |
| 301 | |
| 302 | stale.activity_kind = Some(OwnerActivityKind::Reading); |
| 303 | assert!(!stale.is_valid()); |
| 304 | } |
| 305 | } |
| 306 |