rpi-cli 0.35.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
Documentation
//! Volatile RPC observations owned by the parent host.
use super::{now_ms, AgentEvent, IndependentRuns};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};

const MAX_CHILDREN: usize = 32;
const MAX_EVENTS: usize = 256;
const MAX_RETAINED_BYTES: usize = 1024 * 1024;
const MAX_EVENT_BYTES: usize = 32 * 1024;
const MAX_PAGE_COUNT: usize = 32;
const MAX_PAGE_BYTES: usize = 128 * 1024;

pub(crate) const COMMANDS: [&str; 3] = [
    "get_child_agents",
    "get_child_agent_events",
    "cancel_child_agent",
];

pub(crate) fn capabilities() -> Value {
    json!({
        "version":1, "listCommand":COMMANDS[0], "eventsCommand":COMMANDS[1],
        "cancelCommand":COMMANDS[2], "parentToolCallId":true, "retention":"volatile",
        "maxChildren":MAX_CHILDREN, "maxEvents":MAX_EVENTS, "maxEventBytes":MAX_EVENT_BYTES,
        "maxPageCount":MAX_PAGE_COUNT, "maxResponseBytes":MAX_PAGE_BYTES,
        "sequence":"childEpochSeq-v1"
    })
}

pub(super) struct Observations {
    epoch: String,
    children: VecDeque<Arc<ObservedChild>>,
}

impl Default for Observations {
    fn default() -> Self {
        Self {
            epoch: uuid::Uuid::new_v4().to_string(),
            children: VecDeque::new(),
        }
    }
}

impl Observations {
    pub(super) fn remember(&mut self, child: Arc<ObservedChild>) {
        if self.children.len() >= MAX_CHILDREN {
            // Execution admission allows fewer live runs than the retention cap.
            let Some(index) = self.children.iter().position(|child| {
                child
                    .state
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .finished_ms
                    .is_some()
            }) else {
                return;
            };
            self.children.remove(index);
        }
        self.children.push_back(child);
    }
}

pub(super) struct ObservedChild {
    id: String,
    parent: String,
    tool_call_id: Option<String>,
    task_preview: String,
    started_ms: u64,
    state: Mutex<ObservedState>,
}

#[derive(Default)]
struct ObservedState {
    finished_ms: Option<u64>,
    failed: bool,
    turns: u32,
    seq: u64,
    bytes: usize,
    events: VecDeque<(u64, Vec<u8>)>,
}

impl ObservedState {
    fn push(&mut self, bytes: Vec<u8>) {
        self.seq += 1;
        self.bytes += bytes.len();
        self.events.push_back((self.seq, bytes));
        while self.events.len() > MAX_EVENTS || self.bytes > MAX_RETAINED_BYTES {
            self.bytes -= self
                .events
                .pop_front()
                .expect("over retention budget")
                .1
                .len();
        }
    }

    fn earliest(&self) -> u64 {
        self.events.front().map_or(self.seq + 1, |(seq, _)| *seq)
    }

    fn status(&self) -> &'static str {
        match (self.finished_ms, self.failed) {
            (None, _) => "running",
            (Some(_), true) => "failed",
            (Some(_), false) => "done",
        }
    }
}

impl ObservedChild {
    pub(super) fn new(
        id: String,
        parent: String,
        tool_call_id: Option<String>,
        task: &str,
    ) -> Self {
        Self {
            id,
            parent,
            tool_call_id: tool_call_id.filter(|id| {
                !id.is_empty() && id.len() <= 200 && !id.chars().any(char::is_control)
            }),
            task_preview: task.chars().take(200).collect(),
            started_ms: now_ms(),
            state: Mutex::default(),
        }
    }

    pub(super) fn observe(&self, event: &AgentEvent) {
        let bytes = match crate::rpc::events::encode(
            event,
            crate::args::RpcMessageUpdates::CompactDeltas,
        ) {
            Ok(bytes) if bytes.len() <= MAX_EVENT_BYTES => bytes,
            _ => br#"{"type":"observation_gap","reason":"event_too_large"}"#.to_vec(),
        };
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if matches!(event, AgentEvent::TurnEnd { .. }) && state.finished_ms.is_none() {
            state.turns = state.turns.saturating_add(1);
        }
        state.push(bytes);
    }

    pub(super) fn finished(&self, failed: bool, turns: u32) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.finished_ms = Some(now_ms().max(self.started_ms));
        state.failed = failed;
        state.turns = turns;
        let event = json!({"type":"child_status", "status":state.status()});
        state.push(serde_json::to_vec(&event).expect("child status serializes"));
    }

    fn row(&self) -> Value {
        let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        json!({"childId":self.id, "status":state.status(), "turns":state.turns,
            "role":"independent", "taskPreview":self.task_preview, "parentToolCallId":self.tool_call_id,
            "startedMs":self.started_ms, "finishedMs":state.finished_ms,
            "earliestSeq":state.earliest(), "lastSeq":state.seq})
    }

    fn page(&self, epoch: &str, after: u64, limit: usize) -> Result<Value, String> {
        let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if after > state.seq || !(1..=MAX_PAGE_COUNT).contains(&limit) {
            return Err("invalid child event cursor or page limit".into());
        }
        let mut events = Vec::new();
        // Reserve the actual encoded envelope plus room for the sequence fields.
        let mut bytes = serde_json::to_vec(&json!([self.parent, self.id, epoch]))
            .expect("child observation identity serializes")
            .len()
            + 1024;
        let mut next = after;
        for (seq, event) in state
            .events
            .iter()
            .filter(|(seq, _)| *seq > after)
            .take(limit)
        {
            bytes += event.len() + 64;
            if bytes > MAX_PAGE_BYTES {
                break;
            }
            let event: Value = serde_json::from_slice(event).expect("retained event is JSON");
            events.push(json!({"seq":seq, "event":event}));
            next = *seq;
        }
        Ok(
            json!({"version":1, "parentSessionId":self.parent, "epoch":epoch,
            "childId":self.id, "retention":"volatile", "afterSeq":after, "nextSeq":next,
            "earliestSeq":state.earliest(), "lastSeq":state.seq, "hasMore":next < state.seq,
            "resyncRequired":after.saturating_add(1) < state.earliest(), "events":events}),
        )
    }
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all_fields = "camelCase", deny_unknown_fields)]
enum Query {
    #[serde(rename = "get_child_agents")]
    List {
        version: u32,
        parent_session_id: String,
    },
    #[serde(rename = "get_child_agent_events")]
    Events {
        version: u32,
        parent_session_id: String,
        epoch: String,
        child_id: String,
        after_seq: u64,
        limit: usize,
    },
    #[serde(rename = "cancel_child_agent")]
    Cancel {
        version: u32,
        parent_session_id: String,
        epoch: String,
        child_id: String,
    },
}

impl IndependentRuns {
    pub(in crate::extensions_actions) fn query_observations(
        &self,
        parent: &str,
        mut request: Value,
    ) -> Result<Value, String> {
        request
            .as_object_mut()
            .ok_or("child request must be an object")?
            .remove("id");
        let query: Query = serde_json::from_value(request)
            .map_err(|error| format!("invalid child request: {error}"))?;
        let (version, scope) = match &query {
            Query::List {
                version,
                parent_session_id,
            }
            | Query::Events {
                version,
                parent_session_id,
                ..
            }
            | Query::Cancel {
                version,
                parent_session_id,
                ..
            } => (*version, parent_session_id),
        };
        if version != 1 || scope != parent {
            return Err(
                "child request does not match the current parent or protocol version".into(),
            );
        }

        let observations = self.observations.lock().unwrap_or_else(|e| e.into_inner());
        let (epoch, child_id) = match &query {
            Query::List { .. } => {
                let children: Vec<_> = observations
                    .children
                    .iter()
                    .rev()
                    .filter(|child| child.parent == parent)
                    .map(|child| child.row())
                    .collect();
                return Ok(json!({"version":1, "parentSessionId":parent,
                    "epoch":observations.epoch, "retention":"volatile", "children":children}));
            }
            Query::Events {
                epoch, child_id, ..
            }
            | Query::Cancel {
                epoch, child_id, ..
            } => (epoch, child_id),
        };
        if *epoch != observations.epoch {
            return Err("child observation epoch changed; list again".into());
        }
        let child = observations
            .children
            .iter()
            .find(|child| child.id == *child_id && child.parent == parent)
            .cloned()
            .ok_or("child unavailable or evicted in this parent session")?;
        drop(observations);

        match query {
            Query::Events {
                epoch,
                after_seq,
                limit,
                ..
            } => child.page(&epoch, after_seq, limit),
            Query::Cancel {
                epoch, child_id, ..
            } => {
                let job = self
                    .jobs
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .get(&child_id)
                    .filter(|job| Arc::ptr_eq(&job.observation, &child))
                    .cloned();
                let cancelled = job.is_some_and(|job| job.fail("child cancelled by user"));
                Ok(
                    json!({"version":1,"parentSessionId":parent,"epoch":epoch,"childId":child_id,
                    "status":if cancelled {"cancelled"} else {"already-finished"}}),
                )
            }
            Query::List { .. } => unreachable!("roster handled above"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn observation_retention_reports_eviction_and_bounds_pages() {
        let child = ObservedChild::new("child".into(), "parent".into(), None, "fixture");
        for _ in 0..=MAX_EVENTS {
            child.observe(&AgentEvent::AgentStart);
        }
        let page = child.page("epoch", 0, MAX_PAGE_COUNT).unwrap();
        assert_eq!(page["resyncRequired"], true);
        assert_eq!(page["earliestSeq"], 2);
        assert_eq!(page["events"].as_array().unwrap().len(), MAX_PAGE_COUNT);
        assert!(child.page("epoch", 0, MAX_PAGE_COUNT + 1).is_err());
        assert!(child.page("epoch", MAX_EVENTS as u64 + 2, 1).is_err());

        let event =
            serde_json::to_vec(&json!({"type":"fixture","data":"x".repeat(30_000)})).unwrap();
        for _ in 0..50 {
            child.state.lock().unwrap().push(event.clone());
        }
        assert!(child.state.lock().unwrap().bytes <= MAX_RETAINED_BYTES);
        let page = child.page("epoch", 0, MAX_PAGE_COUNT).unwrap();
        assert_eq!(page["resyncRequired"], true);
        assert_eq!(page["hasMore"], true);
        assert!(serde_json::to_vec(&page).unwrap().len() <= MAX_PAGE_BYTES);
    }
}