Skip to main content

rpi_cli/host/
mini_control.rs

1//! Optional, private Mini authority and bounded EPOCH-LOCAL operation records.
2//! This is not another Agent owner, execution loop or durable journal. All
3//! native effects use the sole HostService table and lifecycle reservation.
4use super::{
5    mini::{MiniLimits, MiniOutcome, MiniReceipt},
6    protocol::{self as wire, *},
7    service::{HostService, ServiceError, ServiceReservation},
8    AgentMode, HostStartupAgent,
9};
10use serde::Deserialize;
11use serde_json::{json, Value};
12use std::{
13    collections::{BTreeMap, BTreeSet},
14    sync::{Arc, Mutex},
15};
16
17fn operations() -> usize {
18    64
19}
20#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum MiniPermission {
23    Submit,
24    Cancel,
25    Close,
26}
27/// Only the owner loads this from a private configuration file. A command's
28/// scope/Agent identities are selectors, never grants. All rights default off.
29#[derive(Clone, Deserialize)]
30#[serde(deny_unknown_fields)]
31pub struct MiniControlConfig {
32    pub scope: ControlScopeId,
33    #[serde(default)]
34    pub allowed_agents: Vec<super::AgentId>,
35    #[serde(default)]
36    pub permissions: Vec<MiniPermission>,
37    #[serde(default = "operations")]
38    pub max_operations: usize,
39}
40impl MiniControlConfig {
41    pub(crate) fn valid(&self) -> bool {
42        (1..=64).contains(&self.max_operations)
43            && self.allowed_agents.len() <= super::MAX_TRUSTED_PROFILES
44            && self
45                .allowed_agents
46                .iter()
47                .copied()
48                .collect::<BTreeSet<_>>()
49                .len()
50                == self.allowed_agents.len()
51            && self
52                .permissions
53                .iter()
54                .copied()
55                .collect::<BTreeSet<_>>()
56                .len()
57                == self.permissions.len()
58    }
59    pub(crate) async fn preflight(
60        &self,
61        agents: &[HostStartupAgent],
62    ) -> Result<(), super::daemon::DaemonError> {
63        use super::daemon::DaemonError;
64        if !self.valid() || agents.len() > super::MAX_TRUSTED_PROFILES {
65            return Err(DaemonError::StartupAgent);
66        }
67        let mut ids = BTreeSet::new();
68        let mut mini = BTreeSet::new();
69        for agent in agents {
70            if !ids.insert(agent.spec.id) {
71                return Err(DaemonError::StartupAgent);
72            }
73            if agent.spec.mode == AgentMode::Mini {
74                if agent.limits.max_input_bytes == 0
75                    || agent.limits.max_input_bytes > 8 * 1024 * 1024
76                {
77                    return Err(DaemonError::StartupAgent);
78                }
79                agent
80                    .profile
81                    .preflight_mini(&agent.spec)
82                    .await
83                    .map_err(|_| DaemonError::StartupAgent)?;
84                mini.insert(agent.spec.id);
85            }
86        }
87        if !self.allowed_agents.iter().all(|id| mini.contains(id)) {
88            return Err(DaemonError::StartupAgent);
89        }
90        Ok(())
91    }
92}
93struct Job {
94    request: MiniRequest,
95    state: &'static str,
96    effect: Option<Value>,
97    code: Option<ErrorCode>,
98}
99struct Inner {
100    service: HostService,
101    config: MiniControlConfig,
102    jobs: Mutex<BTreeMap<RequestId, Job>>,
103}
104#[derive(Clone)]
105pub(crate) struct MiniControl {
106    inner: Arc<Inner>,
107}
108impl MiniControl {
109    pub(crate) fn new(service: HostService, config: MiniControlConfig) -> Self {
110        Self {
111            inner: Arc::new(Inner {
112                service,
113                config,
114                jobs: Mutex::new(BTreeMap::new()),
115            }),
116        }
117    }
118    fn authorize(
119        &self,
120        scope: ControlScopeId,
121        agent: wire::AgentId,
122        permission: MiniPermission,
123    ) -> Result<(), ErrorCode> {
124        let agent: super::AgentId = parse(agent)?;
125        if scope != self.inner.config.scope
126            || !self.inner.config.allowed_agents.contains(&agent)
127            || !self.inner.config.permissions.contains(&permission)
128        {
129            return Err(ErrorCode::Unauthorized);
130        }
131        Ok(())
132    }
133    fn authorize_request(&self, request: &MiniRequest) -> Result<(), ErrorCode> {
134        self.authorize(
135            request.scope,
136            request.action.agent(),
137            match request.action {
138                MiniAction::Submit { .. } => MiniPermission::Submit,
139                MiniAction::Cancel { .. } => MiniPermission::Cancel,
140                MiniAction::Close { .. } => MiniPermission::Close,
141            },
142        )
143    }
144    fn epoch_matches(&self, epoch: Epoch) -> bool {
145        epoch.to_string() == self.inner.service.catalog().epoch().to_string()
146    }
147    fn projection(job: &Job) -> Value {
148        json!({"durable":false,"volatile":true,"epoch":job.request.epoch,
149            "request_id":job.request.request_id,"agent_id":job.request.action.agent(),
150            "found":true,"operation":{"state":job.state,"effect":job.effect,"code":job.code}})
151    }
152    fn unknown(&self, epoch: Epoch, request_id: RequestId, reason: &str) -> Value {
153        json!({"durable":false,"volatile":true,"epoch":epoch,"owner_epoch":self.inner.service.catalog().epoch(),
154            "request_id":request_id,"found":false,"operation":{"state":"unknown","reason":reason}})
155    }
156    fn publish(&self, id: RequestId, effect: Result<Value, ErrorCode>) {
157        let mut jobs = self.inner.jobs.lock().unwrap_or_else(|p| p.into_inner());
158        if let Some(job) = jobs.get_mut(&id) {
159            match effect {
160                Ok(value) => {
161                    job.state = "succeeded";
162                    job.effect = Some(value);
163                }
164                Err(code) => {
165                    job.state = if code == ErrorCode::OutcomeUnknown {
166                        "unknown"
167                    } else {
168                        "failed"
169                    };
170                    job.code = Some(code);
171                }
172            }
173        }
174    }
175    pub(crate) async fn dispatch(&self, command: Command) -> Reply {
176        let result = match command {
177            Command::MiniExecute { request } => self.execute(request),
178            Command::MiniReceipt { request } => self.receipt(request),
179            Command::MiniResult {
180                scope,
181                epoch,
182                agent_id,
183                request_id,
184                run_id,
185                offset,
186                max_bytes,
187            } => {
188                self.result(
189                    scope,
190                    epoch,
191                    agent_id,
192                    request_id,
193                    run_id,
194                    (offset, max_bytes),
195                )
196                .await
197            }
198            _ => Err(ErrorCode::Unsupported),
199        };
200        match result {
201            Ok(data) => Reply::Data { data },
202            Err(code) => Reply::Error { code },
203        }
204    }
205    fn execute(&self, request: MiniRequest) -> Result<Value, ErrorCode> {
206        self.authorize_request(&request)?;
207        if !self.epoch_matches(request.epoch) {
208            return Err(ErrorCode::StaleEpoch);
209        }
210        if self.inner.service.is_stopping() {
211            return Err(ErrorCode::Busy);
212        }
213        if !request.valid() {
214            return Err(ErrorCode::InvalidRequest);
215        }
216        let reply = {
217            let mut jobs = self.inner.jobs.lock().unwrap_or_else(|p| p.into_inner());
218            if let Some(job) = jobs.get(&request.request_id) {
219                return if job.request == request {
220                    Ok(Self::projection(job))
221                } else {
222                    Err(ErrorCode::Conflict)
223                };
224            }
225            if jobs.len() >= self.inner.config.max_operations {
226                return Err(ErrorCode::Capacity);
227            }
228            let job = Job {
229                request: request.clone(),
230                state: "running",
231                effect: None,
232                code: None,
233            };
234            let data = Self::projection(&job);
235            jobs.insert(request.request_id, job);
236            data
237        };
238        let this = self.clone();
239        let service = self.inner.service.clone();
240        // No await between reservation and transfer to supervised ownership.
241        // Native effect AND publication hold one lifecycle reader. Stop cannot
242        // close storage halfway through; never reacquire the fair lock inside.
243        tokio::spawn(async move {
244            let publish = this.clone();
245            let id = request.request_id;
246            let result = service
247                .with_administration(move |reservation| {
248                    Box::pin(async move {
249                        let effect = Self::apply(&reservation, &request).await;
250                        publish.publish(id, effect);
251                        Ok(())
252                    })
253                })
254                .await;
255            if let Err(error) = result {
256                this.publish(id, Err(service_code(error)));
257            }
258        });
259        Ok(reply)
260    }
261    fn receipt(&self, request: MiniRequest) -> Result<Value, ErrorCode> {
262        self.authorize_request(&request)?;
263        if !request.valid() {
264            return Err(ErrorCode::InvalidRequest);
265        }
266        if !self.epoch_matches(request.epoch) {
267            return Ok(self.unknown(request.epoch, request.request_id, "owner_epoch_changed"));
268        }
269        let jobs = self.inner.jobs.lock().unwrap_or_else(|p| p.into_inner());
270        match jobs.get(&request.request_id) {
271            Some(job) if job.request == request => Ok(Self::projection(job)),
272            Some(_) => Err(ErrorCode::Conflict),
273            None => Ok(self.unknown(request.epoch, request.request_id, "not_observed_no_replay")),
274        }
275    }
276    async fn apply(
277        reservation: &ServiceReservation<'_>,
278        request: &MiniRequest,
279    ) -> Result<Value, ErrorCode> {
280        let id = parse(request.action.agent())?;
281        match &request.action {
282            MiniAction::Submit { prompt, .. } => {
283                let receipt = reservation
284                    .mini_client(id)
285                    .map_err(service_code)?
286                    .submit(
287                        parse(request.epoch)?,
288                        parse(request.request_id)?,
289                        prompt.clone(),
290                    )
291                    .await
292                    .map_err(backend_code)?;
293                Ok(
294                    json!({"state":"volatile_admitted","epoch":receipt.epoch,"agent_id":receipt.agent_id,
295                    "submitted_request_id":receipt.request_id,"run_id":receipt.run_id,
296                    "execution_complete":false}),
297                )
298            }
299            MiniAction::Cancel {
300                submitted_request_id,
301                run_id,
302                ..
303            } => {
304                let receipt = MiniReceipt {
305                    epoch: parse(request.epoch)?,
306                    agent_id: id,
307                    request_id: parse(*submitted_request_id)?,
308                    run_id: parse(*run_id)?,
309                };
310                let signalled = reservation
311                    .mini_client(id)
312                    .map_err(service_code)?
313                    .cancel(receipt)
314                    .await
315                    .map_err(backend_code)?;
316                Ok(json!({"cancel_signalled":signalled,"settlement_proven":false}))
317            }
318            MiniAction::Close { .. } => {
319                reservation.close_mini(id).await.map_err(service_code)?;
320                Ok(json!({"native_settled":true,"state":"lost"}))
321            }
322        }
323    }
324    async fn result(
325        &self,
326        scope: ControlScopeId,
327        epoch: Epoch,
328        agent: wire::AgentId,
329        request: RequestId,
330        run: Option<wire::RunId>,
331        page: (usize, usize),
332    ) -> Result<Value, ErrorCode> {
333        self.authorize(scope, agent, MiniPermission::Submit)?;
334        let (offset, max_bytes) = page;
335        if !(4..=MAX_RESULT_TEXT_BYTES).contains(&max_bytes) || (offset != 0 && run.is_none()) {
336            return Err(ErrorCode::InvalidRequest);
337        }
338        let missing = |reason| {
339            json!({"durable":false,"volatile":true,"epoch":epoch,"agent_id":agent,
340            "request_id":request,"found":false,"result":{"state":"unknown","reason":reason}})
341        };
342        if !self.epoch_matches(epoch) {
343            return Ok(missing("owner_epoch_changed"));
344        }
345        let client = match self.inner.service.mini_client(parse(agent)?) {
346            Ok(client) => client,
347            Err(ServiceError::NotLoaded) => return Ok(missing("owner_not_loaded_no_replay")),
348            Err(error) => return Err(service_code(error)),
349        };
350        let Some(result) = client
351            .request(parse(epoch)?, parse(agent)?, parse(request)?)
352            .await
353            .map_err(backend_code)?
354        else {
355            return Ok(missing("input_not_observed_no_replay"));
356        };
357        if run.is_some_and(|run| run.to_string() != result.receipt.run_id.to_string()) {
358            return Err(ErrorCode::InvalidRequest);
359        }
360        let state = match result.outcome {
361            MiniOutcome::Running => "running",
362            MiniOutcome::Succeeded => "completed",
363            MiniOutcome::Failed => "failed",
364            MiniOutcome::Aborted => "aborted",
365            MiniOutcome::OutputLimit => "output_limit",
366            MiniOutcome::Faulted => "faulted",
367        };
368        let text = &result.answer;
369        if offset > text.len() || !text.is_char_boundary(offset) {
370            return Err(ErrorCode::InvalidRequest);
371        }
372        let output = if result.outcome == MiniOutcome::Running {
373            None
374        } else {
375            let mut end = text.len().min(offset.saturating_add(max_bytes));
376            while !text.is_char_boundary(end) {
377                end -= 1;
378            }
379            Some(
380                json!({"text":&text[offset..end],"offset":offset,"next_offset":if end < text.len() { Some(end) } else { None },
381                "total_bytes":text.len(),"bytes":end-offset,"done":end == text.len()}),
382            )
383        };
384        Ok(
385            json!({"durable":false,"volatile":true,"epoch":epoch,"agent_id":agent,"request_id":request,"found":true,
386            "result":{"state":state,"run_id":result.receipt.run_id,"output":output}}),
387        )
388    }
389}
390fn parse<T: TryFrom<String>>(value: impl ToString) -> Result<T, ErrorCode> {
391    T::try_from(value.to_string()).map_err(|_| ErrorCode::InvalidRequest)
392}
393fn service_code(error: ServiceError) -> ErrorCode {
394    match error {
395        ServiceError::NotLoaded => ErrorCode::NotFound,
396        ServiceError::Busy | ServiceError::Stopping => ErrorCode::Busy,
397        ServiceError::AlreadyOwned => ErrorCode::Conflict,
398        ServiceError::Backend(error) => backend_code(error),
399        _ => ErrorCode::OutcomeUnknown,
400    }
401}
402fn backend_code(error: super::ordinary::BackendError) -> ErrorCode {
403    use super::ordinary::BackendError;
404    match error {
405        BackendError::Busy => ErrorCode::Busy,
406        BackendError::Closed => ErrorCode::NotFound,
407        BackendError::InputTooLarge | BackendError::Binding(_) => ErrorCode::InvalidRequest,
408        _ => ErrorCode::OutcomeUnknown,
409    }
410}
411
412pub(super) async fn start_minis(
413    service: &HostService,
414    agents: Vec<HostStartupAgent>,
415) -> Result<(), super::daemon::DaemonError> {
416    use super::daemon::DaemonError;
417    for agent in agents {
418        match service.catalog().get(agent.spec.id).await {
419            // An existing Mini is never restored, even when explicitly named
420            // in the same startup config after a crash/restart. Lost stays Lost.
421            Ok(record) if record.spec == agent.spec && record.state == super::AgentState::Lost => {
422                continue
423            }
424            Ok(_) => return Err(DaemonError::StartupAgent),
425            Err(super::CatalogError::UnknownAgent) => {}
426            Err(error) => return Err(DaemonError::Catalog(error)),
427        }
428        let record = service
429            .catalog()
430            .register(agent.spec)
431            .await
432            .map_err(DaemonError::Catalog)?;
433        service
434            .start_mini(
435                record.spec.id,
436                service.catalog().guard(&record),
437                agent.profile,
438                MiniLimits {
439                    max_input_bytes: agent.limits.max_input_bytes,
440                    ..Default::default()
441                },
442            )
443            .await
444            .map_err(|_| DaemonError::StartupAgent)?;
445    }
446    Ok(())
447}