1use crate::compose::{AgentStores, Stack, SubagentHost, child_setup};
11use crate::durable_store::{SharedSession, lock};
12use delegation::agents::{LaneReply, LaneRun, LaneRunner};
13use delegation::host::{ChildRun, ChildRunner, ChildWaiter, Reattached};
14use durable::{ConversationId, Cursor, ROOT_CONVERSATION_ID, TaskId, TaskQuery};
15use harness::chat::children::{CHILD_KIND, ChildInput, child_report, spawn_child};
16use harness::chat::{ChatHarness, ModelRef};
17use harness::scheduler::{Cancel, Ctx};
18use jsrt::sync;
19use kernel::Signal;
20use kernel::store::DocumentStore;
21use serde_json::Value;
22use services::SessionValues;
23use session_journal::Write;
24use session_journal::ns::{self, DEFINITIONS_ROOT, TASKS_ROOT, USAGE_ROOT};
25use std::collections::HashMap;
26use std::sync::{Arc, Mutex, OnceLock, Weak};
27
28pub const CONVERSATION_LANE_PREFIX: &str = "ultron.conversation.";
30pub const NAMES_NAMESPACE: &str = "ultron.subagent-names";
33
34pub const CONTRACTS_NAMESPACE: &str = "ultron.subagent-contracts";
38
39pub fn subagent_name(session: &SharedSession, task_id: &str) -> Option<String> {
41 lock(session)
42 .value(NAMES_NAMESPACE, task_id)
43 .and_then(Value::as_str)
44 .map(str::to_string)
45}
46
47pub fn value_store(session: &SharedSession, namespace: &str, key: &str) -> Box<dyn DocumentStore> {
50 Box::new(services::SessionValues::shared(session.clone()).document(namespace, key))
51}
52
53pub struct SessionUsageStore(pub SharedSession);
57
58impl DocumentStore for SessionUsageStore {
59 fn read(&self) -> Result<Option<Value>, String> {
60 Ok(lock(&self.0).value(USAGE_ROOT.namespace, USAGE_ROOT.key).cloned())
61 }
62
63 fn write(&self, document: &Value) -> Result<(), String> {
64 let mut session = lock(&self.0);
65 let mut merged = document.clone();
66 if let Some(stored) = session.value(USAGE_ROOT.namespace, USAGE_ROOT.key).cloned() {
67 let count = |root: &Value| root["turns"]["count"].as_f64().unwrap_or(0.0);
68 for (id, root) in stored["roots"].as_object().into_iter().flatten() {
69 match merged["roots"].get(id) {
70 None if merged["roots"].is_object() => merged["roots"][id] = root.clone(),
71 Some(mine) if count(root) > count(mine) => merged["roots"][id]["turns"] = root["turns"].clone(),
72 _ => {}
73 }
74 }
75 }
76 session
77 .commit(&[Write::set(USAGE_ROOT.namespace, USAGE_ROOT.key, merged)])
78 .map(drop)
79 }
80}
81
82pub fn unfinished(session: &SharedSession) -> Vec<String> {
85 let session = lock(session);
86 session
87 .value(TASKS_ROOT.namespace, TASKS_ROOT.key)
88 .and_then(|document| document["tasks"].as_array().cloned())
89 .unwrap_or_default()
90 .iter()
91 .filter(|task| {
92 task["state"]
93 .as_str()
94 .and_then(harness::task_store::TaskState::parse)
95 .is_none_or(|state| !state.is_terminal())
96 })
97 .filter_map(|task| task["id"].as_str().map(str::to_string))
98 .collect()
99}
100
101#[derive(Default)]
103pub struct DurableChildren {
104 chat: OnceLock<ChatHarness>,
105 systems: Mutex<HashMap<String, String>>,
107 root: Mutex<Option<String>>,
109 values: OnceLock<SessionValues>,
113}
114
115impl DurableChildren {
116 pub fn new() -> Arc<DurableChildren> {
117 Arc::new(DurableChildren::default())
118 }
119
120 pub fn attach(&self, chat: ChatHarness) {
121 let _ = self.chat.set(chat);
122 }
123
124 pub fn chat(&self) -> Option<ChatHarness> {
126 self.chat.get().cloned()
127 }
128
129 pub fn attach_session(&self, session: &SharedSession) {
132 let _ = self.values.set(services::SessionValues::shared(session.clone()));
133 }
134
135 pub fn host(self: &Arc<Self>, values: SessionValues) -> SubagentHost {
137 let session = values.session().clone();
138 let _ = self.values.set(values.clone());
139 let children = self.clone();
140 let lanes = self.clone();
141 let value = |namespace, key| Box::new(values.document(namespace, key)) as Box<dyn DocumentStore>;
142 SubagentHost {
143 store: value(TASKS_ROOT.namespace, TASKS_ROOT.key),
144 runner: Box::new(move |stack: Weak<Stack>| -> ChildRunner {
145 Arc::new(move |run: ChildRun| children.run(&stack, run))
146 }),
147 agents: Some(AgentStores {
148 tasks: value(ns::TASKS, "agents"),
150 definitions: value(DEFINITIONS_ROOT.namespace, DEFINITIONS_ROOT.key),
151 usage: Box::new(SessionUsageStore(session.clone())),
152 lanes: Box::new(move |stack: Weak<Stack>| -> LaneRunner {
153 Arc::new(move |run: LaneRun| lanes.run_lane(&stack, run))
154 }),
155 frames: Arc::new(crate::frames::SessionTraceStore(session.clone())),
156 }),
157 }
158 }
159
160 fn run(&self, stack: &Weak<Stack>, run: ChildRun) -> Result<String, String> {
162 let chat = self.chat.get().cloned().ok_or("The durable runtime is not open")?;
163 let stack = stack.upgrade().ok_or("The session is closed")?;
164 let setup = child_setup(&stack, &run);
165 sync::lock(&self.systems).insert(run.lane_name.clone(), setup.system);
166 if let Some(values) = self.values.get()
167 && !values.handed_over()
168 {
169 let session = values.session();
170 let mut writes = vec![Write::set(NAMES_NAMESPACE, &run.task_id, run.name.clone().into())];
171 if let Some(contract) = run.host.contract_of(&run.task_id) {
173 writes.push(Write::set(CONTRACTS_NAMESPACE, &run.task_id, contract));
174 }
175 lock(session).commit(&writes)?;
176 }
177 let input = ChildInput {
178 name: run.lane_name.clone(),
179 prompt: run.prompt.clone(),
180 model: Some(ModelRef::new(&setup.model.provider, &setup.model.id)),
181 timeout_ms: Some(run.timeout_ms),
182 keep: false,
183 thinking: run.thinking.clone(),
184 cwd: run.cwd.clone(),
185 env: run.env.clone(),
186 agent: false,
187 usage_root: sync::lock(&self.root).clone(),
188 fork: run.fork_at.as_deref().and_then(parse_fork_anchor),
189 history: match run
190 .fork_at
191 .as_deref()
192 .and_then(|anchor| anchor.strip_prefix(ROOT_ANCHOR))
193 {
194 Some(entry) => self.root_history(entry)?,
195 None => Vec::new(),
196 },
197 };
198 let task = chat
199 .commit(|tx| spawn_child(tx, ROOT_CONVERSATION_ID, None, &input))
200 .map_err(|e| e.to_string())?;
201 let _ = chat.resume();
202 wait_child(&chat, task, &run.signal)
203 }
204
205 pub fn run_lane(&self, stack: &Weak<Stack>, run: LaneRun) -> Result<LaneReply, String> {
207 let chat = self.chat.get().cloned().ok_or("The durable runtime is not open")?;
208 let stack = stack.upgrade().ok_or("The session is closed")?;
209 if run.reuse
211 && let Some(conversation) = crate::lane_reuse::lane_conversation(&chat, &run.lane)?
212 {
213 return crate::lane_reuse::continue_lane(&chat, conversation, &run);
214 }
215 let model = match run.model.as_deref().and_then(|spec| spec.split_once('/')) {
216 Some((provider, id)) => ModelRef::new(provider, id),
217 None => ModelRef::new(&stack.model().provider, &stack.model().id),
218 };
219 let lane_model = stack
221 .config()
222 .model(&model.provider, &model.model_id)
223 .unwrap_or_else(|| stack.model().clone());
224 sync::lock(&self.systems).insert(run.lane.clone(), stack.child_system(&lane_model));
225 let input = ChildInput {
226 name: run.lane.clone(),
227 prompt: run.prompt.clone(),
228 model: Some(model),
229 timeout_ms: Some(run.timeout_ms),
230 agent: true,
231 ..ChildInput::default()
232 };
233 let task = chat
234 .commit(|tx| spawn_child(tx, ROOT_CONVERSATION_ID, None, &input))
235 .map_err(|e| e.to_string())?;
236 let _ = chat.resume();
237 let text = wait_child(&chat, task, &run.signal)?;
238 Ok(LaneReply {
239 text,
240 ..LaneReply::default()
241 })
242 }
243
244 pub fn fork_point(&self, lane: &str) -> Result<Option<String>, String> {
249 if lane == session_journal::run::MAIN_LANE {
250 let entries = self.root_context()?;
251 let messages: Vec<(String, Vec<Value>)> = entries
252 .iter()
253 .map(|entry| {
254 let id = entry["id"].as_str().unwrap_or_default().to_string();
255 (id, session_journal::context::entry_context_messages(entry))
256 })
257 .collect();
258 let at = delegation::fork::fork_point(messages.iter().map(|(id, m)| (id.clone(), m.as_slice())));
259 return Ok(at.map(|entry| format!("{ROOT_ANCHOR}{entry}")));
260 }
261 let chat = self.chat.get().cloned().ok_or("The durable runtime is not open")?;
262 let conversation = match lane.strip_prefix(CONVERSATION_LANE_PREFIX) {
263 Some(id) => id.parse().ok().map(ConversationId),
264 None => self.conversation_of_lane(lane),
265 };
266 let conversation =
267 conversation.ok_or_else(|| format!("rlm.spawn fork=True: lane {lane} has no conversation"))?;
268 let handle = chat
269 .conversation(conversation)
270 .map_err(|e| e.to_string())?
271 .ok_or_else(|| format!("rlm.spawn fork=True: lane {lane} has no conversation"))?;
272 let entries = handle.entries().map_err(|e| e.to_string())?;
273 let start = entries
275 .iter()
276 .rposition(|e| e.kind == harness::chat::entries::RESET)
277 .map_or(0, |i| i + 1);
278 let at = delegation::fork::fork_point(
279 entries[start..]
280 .iter()
281 .map(|entry| (entry.id.0.to_string(), entry.model.as_deref().unwrap_or_default())),
282 );
283 Ok(at.map(|entry| format!("{}:{entry}", conversation.0)))
284 }
285
286 fn root_context(&self) -> Result<Vec<Value>, String> {
288 let session = self.values.get().ok_or("The session is not open")?.session();
289 let session = lock(session);
290 Ok(session_journal::context::build_context_entries(
291 &session.branch_entries(session_journal::run::MAIN_LANE)?,
292 ))
293 }
294
295 fn root_history(&self, entry: &str) -> Result<Vec<Value>, String> {
297 let entries = self.root_context()?;
298 let end = entries
299 .iter()
300 .position(|e| e["id"] == entry)
301 .ok_or("rlm.spawn fork=True: the fork point is no longer in the root's context")?;
302 let applied = session_journal::context::apply_context_edits(&entries[..=end]);
303 let messages: Vec<Value> = applied
304 .iter()
305 .flat_map(session_journal::context::entry_context_messages)
306 .collect();
307 Ok(crate::lane::to_llm(&messages)
308 .into_iter()
309 .filter(|message| !matches!(message, ai::Message::System(_)))
310 .filter_map(|message| serde_json::to_value(message).ok())
311 .collect())
312 }
313
314 pub fn fork_point_hook(self: &Arc<Self>) -> delegation::fork::ForkPointHook {
316 let children = Arc::downgrade(self);
317 Arc::new(move |lane: &str| match children.upgrade() {
318 Some(children) => children.fork_point(lane),
319 None => Err("The session is closed".into()),
320 })
321 }
322
323 pub fn set_root(&self, root: Option<String>) {
325 *sync::lock(&self.root) = root;
326 }
327
328 pub fn current_root(&self) -> Option<String> {
330 sync::lock(&self.root).clone()
331 }
332
333 fn child_of_lane(&self, lane: &str) -> Option<(ChildInput, Option<ConversationId>)> {
335 let chat = self.chat.get()?;
336 chat.commit(|tx| {
337 let query = TaskQuery {
338 kind: Some(CHILD_KIND.to_string()),
339 ..TaskQuery::default()
340 };
341 let mut cursor: Option<Cursor> = None;
342 loop {
343 let page = tx.scan_tasks(&query, 256, cursor.as_ref())?;
344 for task in page.items {
345 if task.input["name"].as_str() != Some(lane) {
346 continue;
347 }
348 let conversation = match &task.state {
349 durable::TaskState::Running { checkpoint }
350 | durable::TaskState::Pending { checkpoint }
351 | durable::TaskState::Waiting { checkpoint, .. } => checkpoint["conversation"].as_u64(),
352 _ => None,
353 };
354 let input = serde_json::from_value::<ChildInput>(task.input.clone()).ok();
355 return Ok(input.map(|input| (input, conversation.map(ConversationId))));
356 }
357 match page.next {
358 Some(next) => cursor = Some(next),
359 None => return Ok(None),
360 }
361 }
362 })
363 .ok()
364 .flatten()
365 }
366
367 pub fn session(&self) -> Option<SharedSession> {
369 self.values.get().map(|values| values.session().clone())
370 }
371
372 pub fn kept_child_of_lane(&self, lane: &str) -> Option<String> {
374 let chat = self.chat.get()?;
375 let children = child_tasks(chat).ok()?;
376 let (task, input, terminal) = children.get(lane)?;
377 (input.keep && !*terminal).then(|| task.0.to_string())
378 }
379
380 pub fn conversation_of_lane(&self, lane: &str) -> Option<ConversationId> {
382 self.child_of_lane(lane)?.1
383 }
384
385 pub fn usage_root_of_lane(&self, lane: &str, agents: &delegation::agents::Agents) -> Option<String> {
388 match self.child_of_lane(lane) {
389 Some((input, _)) if !input.agent => input.usage_root,
390 _ => agents.usage_root_for_lane(lane, ""),
391 }
392 }
393
394 pub fn usage_root(&self, conversation: ConversationId, agents: &delegation::agents::Agents) -> Option<String> {
398 let chat = self.chat.get()?;
399 let input = chat
400 .commit(|tx| {
401 let Some(owner) = tx.conversation(conversation)?.and_then(|record| record.owner) else {
402 return Ok(None);
403 };
404 Ok(tx
405 .task(owner.task_id)?
406 .filter(|task| task.kind == CHILD_KIND)
407 .and_then(|task| serde_json::from_value::<ChildInput>(task.input).ok()))
408 })
409 .ok()
410 .flatten()?;
411 if input.agent {
412 return agents.usage_root_for_lane(&input.name, "");
413 }
414 input.usage_root
415 }
416
417 pub fn lane_of(&self, conversation: ConversationId) -> Option<String> {
419 let chat = self.chat.get()?;
420 chat.commit(|tx| {
421 let Some(record) = tx.conversation(conversation)? else {
422 return Ok(None);
423 };
424 let Some(owner) = record.owner else {
426 return Ok((conversation != ROOT_CONVERSATION_ID)
427 .then(|| format!("{CONVERSATION_LANE_PREFIX}{}", conversation.0)));
428 };
429 Ok(tx
430 .task(owner.task_id)?
431 .filter(|task| task.kind == CHILD_KIND)
432 .and_then(|task| task.input["name"].as_str().map(str::to_string)))
433 })
434 .ok()
435 .flatten()
436 }
437
438 pub fn system_of(&self, lane: &str) -> Option<String> {
440 sync::lock(&self.systems).get(lane).cloned()
441 }
442
443 pub fn restore(&self, stack: &Stack, unfinished: &[String]) -> Result<Vec<String>, String> {
452 let Some(chat) = self.chat.get().cloned() else {
453 return Ok(Vec::new());
454 };
455 let children = child_tasks(&chat)?;
456 let reattached = stack.delegation.restore(unfinished, |id| {
457 let (task, input, _) = children.get(&lanes::lane_names::child_lane(id))?.clone();
458 if input.agent || input.keep {
459 return None;
460 }
461 let run = self.restore_lane(stack, id, &input);
462 let chat = chat.clone();
463 let (lanes, lane) = (stack.lanes.clone(), input.name.clone());
464 let contract = self
465 .session()
466 .and_then(|session| lock(&session).value(CONTRACTS_NAMESPACE, id).cloned());
467 Some(Reattached {
468 waiter: Box::new(move |signal: Signal| {
469 let reply = wait_child(&chat, task, &signal);
470 let _ = lanes.close_lane(&lane);
472 reply
473 }) as ChildWaiter,
474 contract,
475 run: Some(run),
476 })
477 })?;
478 for (name, (task, input, terminal)) in &children {
479 let ours = !terminal
480 && (input.agent
481 || matches!(lanes::lane_names::parse_lane(name),
482 Some(lanes::lane_names::LaneOwner::Child(id)) if !reattached.iter().any(|r| r == id)));
483 if ours && !input.keep {
484 let _ = chat.abort_task(*task, &Ctx::background());
485 }
486 }
487 Ok(reattached)
488 }
489
490 fn restore_lane(&self, stack: &Stack, id: &str, input: &ChildInput) -> ChildRun {
494 let run = ChildRun {
495 task_id: id.to_string(),
496 name: self
497 .session()
498 .and_then(|session| subagent_name(&session, id))
499 .unwrap_or_default(),
500 lane_name: input.name.clone(),
501 prompt: input.prompt.clone(),
502 level: 1,
503 allowance: 0,
504 model: input.model.as_ref().map(|m| format!("{}/{}", m.provider, m.model_id)),
505 thinking: input.thinking.clone(),
506 timeout_ms: input.timeout_ms.unwrap_or_default(),
507 cwd: input.cwd.clone(),
508 env: input.env.clone(),
509 fork_at: None,
510 signal: Signal::new(),
511 host: stack.delegation.clone(),
512 };
513 let setup = child_setup(stack, &run);
514 sync::lock(&self.systems).insert(input.name.clone(), setup.system);
515 run
516 }
517}
518
519fn parse_fork_anchor(anchor: &str) -> Option<harness::chat::children::ChildFork> {
521 let (conversation, entry) = anchor.split_once(':')?;
522 Some(harness::chat::children::ChildFork {
523 conversation: ConversationId(conversation.parse().ok()?),
524 entry: durable::EntryId(entry.parse().ok()?),
525 })
526}
527
528const ROOT_ANCHOR: &str = "root:";
530
531fn child_tasks(chat: &ChatHarness) -> Result<HashMap<String, (TaskId, ChildInput, bool)>, String> {
533 chat.commit(|tx| {
534 let query = TaskQuery {
535 kind: Some(CHILD_KIND.to_string()),
536 ..TaskQuery::default()
537 };
538 let mut found = HashMap::new();
539 let mut cursor: Option<Cursor> = None;
540 loop {
541 let page = tx.scan_tasks(&query, 256, cursor.as_ref())?;
542 for task in page.items {
543 let terminal = task.state.status() == durable::TaskStatus::Terminal;
544 if let Ok(input) = serde_json::from_value::<ChildInput>(task.input.clone()) {
545 found.insert(input.name.clone(), (task.id, input, terminal));
546 }
547 }
548 match page.next {
549 Some(next) => cursor = Some(next),
550 None => return Ok(found),
551 }
552 }
553 })
554 .map_err(|e| e.to_string())
555}
556
557fn wait_child(chat: &ChatHarness, task: TaskId, signal: &Signal) -> Result<String, String> {
560 let cancel = Cancel::new();
561 let target = cancel.clone();
562 let link = signal.link(move |_| target.abort());
563 let waited = chat.wait_for_task(task, &Ctx::with_signal(&cancel));
564 drop(link);
565 match waited {
566 Ok(record) => {
567 let report = child_report(&record).ok_or("The subagent ended without a result")?;
568 let result = &report["result"];
569 if result["status"] == "succeeded" {
570 Ok(match &result["value"] {
571 Value::String(text) => text.clone(),
572 Value::Null => String::new(),
573 other => other.to_string(),
574 })
575 } else {
576 Err(result["error"]
577 .as_str()
578 .map_or_else(|| format!("The subagent ended {}", result["status"]), str::to_string))
579 }
580 }
581 Err(error) => {
582 let reason = signal.reason().unwrap_or_else(|| error.to_string());
583 let _ = chat.abort_task(task, &Ctx::background());
584 Err(reason)
585 }
586 }
587}