Skip to main content

session_core/
swarm_ops.rs

1//! The session's shared world for the REPL (`swarm_api.py`): `swarm.*` (who holds what, durable peer messages),
2//! `board.*` (the task board), `notes.*` (shared notes), and persistent children (`rlm.spawn(..., keep=True)`,
3//! `rlm.ask`). They are served by `harness::chat::host_ops` over the session's durable runtime, as the calling lane's
4//! conversation: `main` is the root conversation, a subagent lane its child conversation, another root conversation
5//! its own. Ordinary subagents stay with the delegation host; `rlm.collect`, `rlm.results`, `rlm.cancel` and
6//! `rlm.delete_subagent` come here only when every child they name is a persistent one.
7
8use crate::compose::Stack;
9use crate::kept_contracts::KeptContracts;
10use crate::subagents::{CONVERSATION_LANE_PREFIX, DurableChildren};
11use durable::{ConversationId, ROOT_CONVERSATION_ID, TaskId};
12use harness::chat::CellCall;
13use harness::chat::children::CHILD_KIND;
14use harness::chat::host_ops::HostOps;
15use kernel::Signal;
16use serde_json::{Map, Value, json};
17use std::sync::{Arc, Weak};
18
19/// Child requests that come here when every child they name is persistent.
20const CHILD_REQUESTS: [&str; 4] = ["rlm.collect", "rlm.results", "rlm.cancel", "rlm.delete_subagent"];
21
22pub struct SwarmOps {
23    children: Arc<DurableChildren>,
24    /// Contracts of persistent children (crate::kept_contracts), once the session's stack is known.
25    contracts: Option<KeptContracts>,
26}
27
28impl SwarmOps {
29    pub fn new(children: Arc<DurableChildren>) -> SwarmOps {
30        SwarmOps {
31            children,
32            contracts: None,
33        }
34    }
35
36    /// Persistent children may be spawned with `role=` / `contract=` / `hop=`: each of their answers is checked.
37    pub fn with_contracts(mut self, stack: Weak<Stack>) -> SwarmOps {
38        self.contracts = Some(KeptContracts::new(self.children.clone(), stack));
39        self
40    }
41
42    fn conversation(&self, lane: &str) -> Option<ConversationId> {
43        if lane == session_journal::run::MAIN_LANE {
44            return Some(ROOT_CONVERSATION_ID);
45        }
46        if let Some(id) = lane.strip_prefix(CONVERSATION_LANE_PREFIX) {
47            return id.parse().ok().map(ConversationId);
48        }
49        self.children.conversation_of_lane(lane)
50    }
51
52    /// Whether `selector` names a persistent child of the durable runtime.
53    fn persistent(&self, selector: &Value) -> bool {
54        let id = match selector {
55            Value::String(text) => text.parse::<u64>().ok(),
56            Value::Number(number) => number.as_u64(),
57            _ => None,
58        };
59        let Some(chat) = self.children.chat() else { return false };
60        id.and_then(|id| chat.get_task(TaskId(id)).ok().flatten())
61            .is_some_and(|task| task.kind == CHILD_KIND && task.input["keep"] == true)
62    }
63
64    fn serves(&self, kind: &str, payload: &Map<String, Value>) -> bool {
65        if kind == "rlm.ask" || harness::chat::host_ops::SWARM_KINDS.contains(&kind) {
66            return true;
67        }
68        if kind == "rlm.spawn" {
69            let keep = |v: Option<&Value>| v == Some(&Value::Bool(true));
70            return keep(payload.get("keep")) || keep(payload.get("kwargs").and_then(|k| k.get("keep")));
71        }
72        if CHILD_REQUESTS.contains(&kind) {
73            let named: Vec<&Value> = match (payload.get("selectors"), payload.get("selector").or(payload.get("id"))) {
74                (Some(Value::Array(list)), _) => list.iter().collect(),
75                (_, Some(one)) => vec![one],
76                _ => Vec::new(),
77            };
78            return !named.is_empty() && named.iter().all(|s| self.persistent(s));
79        }
80        false
81    }
82
83    /// Serve `kind` for `lane`; `None` when it is not served here.
84    pub fn handle(
85        &self,
86        lane: &str,
87        kind: &str,
88        payload: &Map<String, Value>,
89        signal: &Signal,
90    ) -> Option<Result<Value, String>> {
91        // A kept child's verdict, when it was spawned with a contract (others go to the delegation host).
92        if kind == "rlm.finish" {
93            return self.contracts.as_ref()?.finish(lane, payload);
94        }
95        if !self.serves(kind, payload) {
96            return None;
97        }
98        let serve = |kind: &str, payload: &Map<String, Value>| self.serve(lane, kind, payload, signal);
99        let Some(contracts) = &self.contracts else {
100            return Some(serve(kind, payload));
101        };
102        Some(match kind {
103            "rlm.spawn" => contracts.spawn(payload, &serve).unwrap_or_else(|| serve(kind, payload)),
104            "rlm.ask" => {
105                let child = payload.get("child").map(|c| match c {
106                    Value::String(text) => text.clone(),
107                    other => other.to_string(),
108                });
109                if let Some(child) = &child {
110                    contracts.before_ask(child);
111                }
112                serve(kind, payload).map(|answer| match &child {
113                    Some(child) => contracts.ask_answer(child, answer, lane, signal, &serve),
114                    None => answer,
115                })
116            }
117            "rlm.collect" | "rlm.results" => {
118                serve(kind, payload).map(|answer| contracts.reported(answer, lane, signal, &serve))
119            }
120            _ => serve(kind, payload),
121        })
122    }
123
124    /// Serve `kind` for `lane` from the durable runtime's host operations.
125    fn serve(&self, lane: &str, kind: &str, payload: &Map<String, Value>, signal: &Signal) -> Result<Value, String> {
126        let chat = self.children.chat().ok_or("The durable runtime is not open")?;
127        let conversation = self
128            .conversation(lane)
129            .ok_or_else(|| format!("The lane {lane} has no conversation"))?;
130        let call = CellCall {
131            conversation_id: conversation,
132            task_id: TaskId(0),
133            call_id: String::new(),
134            name: "rlm".into(),
135            arguments: json!({"lane": lane}),
136        };
137        HostOps::new(chat)
138            .handler(call, None)
139            .handle(kind, payload.clone(), signal)
140    }
141}