Skip to main content

rpi_cli/host/
mini.rs

1//! Session-free native owner. Results are bounded, volatile and incarnation
2//! scoped; no admission journal, Harness, Session, writer or replay exists here.
3//! Only HostService owns this backend. A client is a weak observer, never an
4//! abort handle for the supervised prompt future or a second owner registry.
5
6use super::{
7    bindings::{NativeBindingProfile, NativeMiniAgent},
8    ordinary::{BackendError, BackendResult},
9    AgentId, AgentMode, AgentRecord, AgentState, CatalogGuard, HostCatalog, HostEpoch,
10    NativeExtensionCustody, RequestId, RunId,
11};
12use futures::FutureExt;
13use sha2::{Digest, Sha256};
14use std::{
15    collections::BTreeMap,
16    future::Future,
17    panic::AssertUnwindSafe,
18    sync::{
19        atomic::{AtomicBool, Ordering},
20        Arc, Weak,
21    },
22};
23use tokio::sync::{watch, Mutex};
24use tokio_util::sync::CancellationToken;
25
26#[derive(Clone, Copy)]
27pub struct MiniLimits {
28    pub max_input_bytes: usize,
29    pub max_results: usize,
30    pub max_output_bytes: usize,
31}
32impl Default for MiniLimits {
33    fn default() -> Self {
34        Self {
35            max_input_bytes: 256 * 1024,
36            max_results: 64,
37            max_output_bytes: 1024 * 1024,
38        }
39    }
40}
41
42/// A volatile identity, NOT a durable admission/receipt or execution success.
43/// The random run ID also fences reuse of an Agent identity within one epoch.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct MiniReceipt {
46    pub epoch: HostEpoch,
47    pub agent_id: AgentId,
48    pub request_id: RequestId,
49    pub run_id: RunId,
50}
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum MiniOutcome {
53    Running,
54    Succeeded,
55    Failed,
56    Aborted,
57    OutputLimit,
58    Faulted,
59}
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct MiniResult {
62    pub receipt: MiniReceipt,
63    pub outcome: MiniOutcome,
64    /// Exact final assistant text. Oversized results are explicitly OutputLimit,
65    /// never truncated or silently evicted. Provider diagnostics stay private.
66    pub answer: String,
67}
68struct Entry {
69    digest: [u8; 32],
70    result: MiniResult,
71}
72struct Active {
73    receipt: MiniReceipt,
74    cancel: CancellationToken,
75}
76struct Control {
77    record: AgentRecord,
78    results: BTreeMap<RequestId, Entry>,
79    active: Option<Active>,
80    output_bytes: usize,
81    closing: bool,
82    faulted: bool,
83    closed: bool,
84}
85struct Backend {
86    native: NativeMiniAgent,
87    catalog: HostCatalog,
88    limits: MiniLimits,
89    stopping: Arc<AtomicBool>,
90    control: Mutex<Control>,
91    close_gate: Mutex<()>,
92    changed: watch::Sender<()>,
93}
94pub(super) struct MiniAgent {
95    inner: Arc<Backend>,
96}
97#[derive(Clone)]
98pub struct MiniClient {
99    inner: Weak<Backend>,
100}
101
102impl MiniAgent {
103    pub(super) async fn start(
104        catalog: HostCatalog,
105        id: AgentId,
106        guard: CatalogGuard,
107        profile: NativeBindingProfile,
108        limits: MiniLimits,
109        custody: Arc<NativeExtensionCustody>,
110        stopping: Arc<AtomicBool>,
111    ) -> BackendResult<Self> {
112        if limits.max_input_bytes == 0
113            || limits.max_input_bytes > 8 * 1024 * 1024
114            || limits.max_results == 0
115            || limits.max_results > 64
116            || limits.max_output_bytes == 0
117            || limits.max_output_bytes > 1024 * 1024
118        {
119            return Err(BackendError::Binding("invalid Mini budgets"));
120        }
121        let record = catalog.get(id).await?;
122        if record.spec.mode != AgentMode::Mini || record.spec.session.is_some() {
123            return Err(BackendError::Binding(
124                "Mini requires explicit Session-free metadata",
125            ));
126        }
127        let record = catalog.transition(id, guard, AgentState::Starting).await?;
128        // Service has already reserved Starting and retained this exact custody.
129        // Any error/panic leaves reconciliation with that same service entry.
130        let native = profile
131            .bind_mini_agent(record.spec.clone(), catalog.clone(), custody)
132            .await?;
133        let record = catalog
134            .transition(id, catalog.guard(&record), AgentState::Idle)
135            .await?;
136        let (changed, _) = watch::channel(());
137        Ok(Self {
138            inner: Arc::new(Backend {
139                native,
140                catalog,
141                limits,
142                stopping,
143                control: Mutex::new(Control {
144                    record,
145                    results: BTreeMap::new(),
146                    active: None,
147                    output_bytes: 0,
148                    closing: false,
149                    faulted: false,
150                    closed: false,
151                }),
152                close_gate: Mutex::new(()),
153                changed,
154            }),
155        })
156    }
157    pub(super) fn client(&self) -> MiniClient {
158        MiniClient {
159            inner: Arc::downgrade(&self.inner),
160        }
161    }
162    pub(super) async fn close(&self) -> BackendResult<()> {
163        self.inner.close().await
164    }
165}
166impl MiniClient {
167    fn upgrade(&self) -> BackendResult<Arc<Backend>> {
168        self.inner.upgrade().ok_or(BackendError::Closed)
169    }
170    pub async fn submit(
171        &self,
172        epoch: HostEpoch,
173        request_id: RequestId,
174        prompt: String,
175    ) -> BackendResult<MiniReceipt> {
176        let inner = self.upgrade()?;
177        owned(async move { inner.submit(epoch, request_id, prompt).await }).await
178    }
179    /// Lookup only within this already-owned incarnation; never loads or
180    /// replays input when an admission reply was lost.
181    pub async fn request(
182        &self,
183        epoch: HostEpoch,
184        agent_id: AgentId,
185        request_id: RequestId,
186    ) -> BackendResult<Option<MiniResult>> {
187        let inner = self.upgrade()?;
188        let control = inner.control.lock().await;
189        inner.validate(&control, epoch, agent_id)?;
190        Ok(control
191            .results
192            .get(&request_id)
193            .map(|entry| entry.result.clone()))
194    }
195    pub async fn result(&self, receipt: MiniReceipt) -> BackendResult<Option<MiniResult>> {
196        let inner = self.upgrade()?;
197        let control = inner.control.lock().await;
198        inner.validate(&control, receipt.epoch, receipt.agent_id)?;
199        Ok(control
200            .results
201            .get(&receipt.request_id)
202            .filter(|entry| entry.result.receipt == receipt)
203            .map(|entry| entry.result.clone()))
204    }
205    /// Only signal this exact volatile run. Neither true nor cancellation of a
206    /// query proves settlement; late callbacks still belong to the owner.
207    pub async fn cancel(&self, receipt: MiniReceipt) -> BackendResult<bool> {
208        let inner = self.upgrade()?;
209        let control = inner.control.lock().await;
210        inner.validate(&control, receipt.epoch, receipt.agent_id)?;
211        match &control.active {
212            Some(active) if active.receipt == receipt => {
213                active.cancel.cancel();
214                Ok(true)
215            }
216            _ => Ok(false),
217        }
218    }
219}
220impl Backend {
221    fn validate(&self, control: &Control, epoch: HostEpoch, id: AgentId) -> BackendResult<()> {
222        if epoch != self.catalog.epoch() || id != control.record.spec.id {
223            return Err(BackendError::Binding("Mini owner identity mismatch"));
224        }
225        Ok(())
226    }
227    async fn submit(
228        self: Arc<Self>,
229        epoch: HostEpoch,
230        request_id: RequestId,
231        prompt: String,
232    ) -> BackendResult<MiniReceipt> {
233        let mut control = self.control.lock().await;
234        self.validate(&control, epoch, control.record.spec.id)?;
235        if control.closing || control.closed || self.stopping.load(Ordering::Acquire) {
236            return Err(BackendError::Closed);
237        }
238        if control.faulted {
239            return Err(BackendError::Faulted);
240        }
241        if prompt.trim().is_empty() || prompt.len() > self.limits.max_input_bytes {
242            return Err(BackendError::InputTooLarge);
243        }
244        let digest: [u8; 32] = Sha256::digest(prompt.as_bytes()).into();
245        if let Some(entry) = control.results.get(&request_id) {
246            return if entry.digest == digest {
247                Ok(entry.result.receipt)
248            } else {
249                Err(BackendError::Binding("Mini request intent conflict"))
250            };
251        }
252        if control.active.is_some() {
253            return Err(BackendError::Busy);
254        }
255        if control.results.len() >= self.limits.max_results {
256            return Err(BackendError::Binding("Mini result capacity exhausted"));
257        }
258        control.record = self
259            .catalog
260            .transition(
261                control.record.spec.id,
262                self.catalog.guard(&control.record),
263                AgentState::Running,
264            )
265            .await?;
266        let receipt = MiniReceipt {
267            epoch,
268            agent_id: control.record.spec.id,
269            request_id,
270            run_id: RunId::new(),
271        };
272        let cancel = CancellationToken::new();
273        control.active = Some(Active {
274            receipt,
275            cancel: cancel.clone(),
276        });
277        control.results.insert(
278            request_id,
279            Entry {
280                digest,
281                result: MiniResult {
282                    receipt,
283                    outcome: MiniOutcome::Running,
284                    answer: String::new(),
285                },
286            },
287        );
288        // No await between publishing Active and transferring the entire prompt
289        // future to its owner. Caller cancellation can only lose the response.
290        let owner = self.clone();
291        tokio::spawn(async move {
292            owner.run(receipt, prompt, cancel).await;
293        });
294        Ok(receipt)
295    }
296    async fn run(self: Arc<Self>, receipt: MiniReceipt, prompt: String, cancel: CancellationToken) {
297        let completed = AssertUnwindSafe(async {
298            let first_message = self.native.agent().state().messages.len();
299            let prompt = self.native.agent().prompt(prompt);
300            tokio::pin!(prompt);
301            let result = tokio::select! {
302                // Poll native start BEFORE observing a pre-existing cancel. An
303                // abort before start_active_run would miss the new run entirely.
304                biased;
305                result = &mut prompt => result,
306                _ = cancel.cancelled() => { self.native.cancel(); prompt.await }
307            };
308            let state = self.native.agent().state();
309            let last = state.messages[first_message..].iter().rev().find_map(|m| {
310                if let rpi_agent::AgentMessage::Assistant(m) = m {
311                    Some(m)
312                } else {
313                    None
314                }
315            });
316            let outcome = match (&result, last.map(|m| m.stop_reason)) {
317                (Err(rpi_agent::AgentError::Abort), _) | (_, Some(rpi_ai::StopReason::Aborted)) => {
318                    MiniOutcome::Aborted
319                }
320                (Err(_), _) | (_, Some(rpi_ai::StopReason::Error)) => MiniOutcome::Failed,
321                (Ok(()), Some(rpi_ai::StopReason::Stop | rpi_ai::StopReason::Length))
322                    if state.error_message.is_none() =>
323                {
324                    MiniOutcome::Succeeded
325                }
326                _ => MiniOutcome::Failed,
327            };
328            let mut answer = String::new();
329            if let Some(last) = last {
330                for block in &last.content {
331                    if let rpi_ai::Content::Text(text) = block {
332                        if answer.len().saturating_add(text.text.len())
333                            > self.limits.max_output_bytes
334                        {
335                            return (MiniOutcome::OutputLimit, String::new());
336                        }
337                        answer.push_str(&text.text);
338                    }
339                }
340            }
341            (outcome, answer)
342        })
343        .catch_unwind()
344        .await;
345        let mut control = self.control.lock().await;
346        let (mut outcome, mut answer) = completed.unwrap_or_else(|_| {
347            control.faulted = true;
348            (MiniOutcome::Faulted, String::new())
349        });
350        if !control.faulted {
351            match self
352                .catalog
353                .transition(
354                    receipt.agent_id,
355                    self.catalog.guard(&control.record),
356                    AgentState::Idle,
357                )
358                .await
359            {
360                Ok(record) => control.record = record,
361                Err(_) => {
362                    control.faulted = true;
363                    outcome = MiniOutcome::Faulted;
364                    answer.clear();
365                }
366            }
367        }
368        if control.output_bytes.saturating_add(answer.len()) > self.limits.max_output_bytes {
369            outcome = MiniOutcome::OutputLimit;
370            answer.clear();
371        }
372        control.output_bytes += answer.len();
373        if let Some(entry) = control.results.get_mut(&receipt.request_id) {
374            entry.result.outcome = outcome;
375            entry.result.answer = answer;
376        }
377        control.active = None;
378        self.changed.send_replace(());
379    }
380    async fn close(&self) -> BackendResult<()> {
381        let _close = self.close_gate.lock().await;
382        let mut changed = self.changed.subscribe();
383        loop {
384            let mut control = self.control.lock().await;
385            control.closing = true;
386            if control.closed {
387                return Ok(());
388            }
389            if let Some(active) = &control.active {
390                active.cancel.cancel();
391                drop(control);
392                changed
393                    .changed()
394                    .await
395                    .map_err(|_| BackendError::TaskStopped)?;
396                continue;
397            }
398            // A panic is not native settlement, even if the request task exited.
399            if control.faulted {
400                return Err(BackendError::Faulted);
401            }
402            if control.record.state != AgentState::Closing {
403                control.record = self
404                    .catalog
405                    .transition(
406                        control.record.spec.id,
407                        self.catalog.guard(&control.record),
408                        AgentState::Closing,
409                    )
410                    .await?;
411            }
412            drop(control);
413            self.native.close().await?;
414            let mut control = self.control.lock().await;
415            control.record = self
416                .catalog
417                .transition(
418                    control.record.spec.id,
419                    self.catalog.guard(&control.record),
420                    AgentState::Lost,
421                )
422                .await?;
423            control.closed = true;
424            return Ok(());
425        }
426    }
427}
428async fn owned<T: Send + 'static>(
429    future: impl Future<Output = BackendResult<T>> + Send + 'static,
430) -> BackendResult<T> {
431    tokio::spawn(AssertUnwindSafe(future).catch_unwind())
432        .await
433        .map_err(|_| BackendError::TaskStopped)?
434        .map_err(|_| BackendError::TaskStopped)?
435}