session_core/
swarm_ops.rs1use 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
19const CHILD_REQUESTS: [&str; 4] = ["rlm.collect", "rlm.results", "rlm.cancel", "rlm.delete_subagent"];
21
22pub struct SwarmOps {
23 children: Arc<DurableChildren>,
24 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 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 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 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 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 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}