use crate::compose::{AgentStores, Stack, SubagentHost, child_setup};
use crate::durable_store::{SharedSession, lock};
use delegation::agents::{LaneReply, LaneRun, LaneRunner};
use delegation::host::{ChildRun, ChildRunner, ChildWaiter, Reattached};
use durable::{ConversationId, Cursor, ROOT_CONVERSATION_ID, TaskId, TaskQuery};
use harness::chat::children::{CHILD_KIND, ChildInput, child_report, spawn_child};
use harness::chat::{ChatHarness, ModelRef};
use harness::scheduler::{Cancel, Ctx};
use jsrt::sync;
use kernel::Signal;
use kernel::store::DocumentStore;
use serde_json::Value;
use services::SessionValues;
use session_journal::Write;
use session_journal::ns::{self, DEFINITIONS_ROOT, TASKS_ROOT, USAGE_ROOT};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
pub const CONVERSATION_LANE_PREFIX: &str = "ultron.conversation.";
pub const NAMES_NAMESPACE: &str = "ultron.subagent-names";
pub const CONTRACTS_NAMESPACE: &str = "ultron.subagent-contracts";
pub fn subagent_name(session: &SharedSession, task_id: &str) -> Option<String> {
lock(session)
.value(NAMES_NAMESPACE, task_id)
.and_then(Value::as_str)
.map(str::to_string)
}
pub fn value_store(session: &SharedSession, namespace: &str, key: &str) -> Box<dyn DocumentStore> {
Box::new(services::SessionValues::shared(session.clone()).document(namespace, key))
}
pub struct SessionUsageStore(pub SharedSession);
impl DocumentStore for SessionUsageStore {
fn read(&self) -> Result<Option<Value>, String> {
Ok(lock(&self.0).value(USAGE_ROOT.namespace, USAGE_ROOT.key).cloned())
}
fn write(&self, document: &Value) -> Result<(), String> {
let mut session = lock(&self.0);
let mut merged = document.clone();
if let Some(stored) = session.value(USAGE_ROOT.namespace, USAGE_ROOT.key).cloned() {
let count = |root: &Value| root["turns"]["count"].as_f64().unwrap_or(0.0);
for (id, root) in stored["roots"].as_object().into_iter().flatten() {
match merged["roots"].get(id) {
None if merged["roots"].is_object() => merged["roots"][id] = root.clone(),
Some(mine) if count(root) > count(mine) => merged["roots"][id]["turns"] = root["turns"].clone(),
_ => {}
}
}
}
session
.commit(&[Write::set(USAGE_ROOT.namespace, USAGE_ROOT.key, merged)])
.map(drop)
}
}
pub fn unfinished(session: &SharedSession) -> Vec<String> {
let session = lock(session);
session
.value(TASKS_ROOT.namespace, TASKS_ROOT.key)
.and_then(|document| document["tasks"].as_array().cloned())
.unwrap_or_default()
.iter()
.filter(|task| {
task["state"]
.as_str()
.and_then(harness::task_store::TaskState::parse)
.is_none_or(|state| !state.is_terminal())
})
.filter_map(|task| task["id"].as_str().map(str::to_string))
.collect()
}
#[derive(Default)]
pub struct DurableChildren {
chat: OnceLock<ChatHarness>,
systems: Mutex<HashMap<String, String>>,
root: Mutex<Option<String>>,
values: OnceLock<SessionValues>,
}
impl DurableChildren {
pub fn new() -> Arc<DurableChildren> {
Arc::new(DurableChildren::default())
}
pub fn attach(&self, chat: ChatHarness) {
let _ = self.chat.set(chat);
}
pub fn chat(&self) -> Option<ChatHarness> {
self.chat.get().cloned()
}
pub fn attach_session(&self, session: &SharedSession) {
let _ = self.values.set(services::SessionValues::shared(session.clone()));
}
pub fn host(self: &Arc<Self>, values: SessionValues) -> SubagentHost {
let session = values.session().clone();
let _ = self.values.set(values.clone());
let children = self.clone();
let lanes = self.clone();
let value = |namespace, key| Box::new(values.document(namespace, key)) as Box<dyn DocumentStore>;
SubagentHost {
store: value(TASKS_ROOT.namespace, TASKS_ROOT.key),
runner: Box::new(move |stack: Weak<Stack>| -> ChildRunner {
Arc::new(move |run: ChildRun| children.run(&stack, run))
}),
agents: Some(AgentStores {
tasks: value(ns::TASKS, "agents"),
definitions: value(DEFINITIONS_ROOT.namespace, DEFINITIONS_ROOT.key),
usage: Box::new(SessionUsageStore(session.clone())),
lanes: Box::new(move |stack: Weak<Stack>| -> LaneRunner {
Arc::new(move |run: LaneRun| lanes.run_lane(&stack, run))
}),
frames: Arc::new(crate::frames::SessionTraceStore(session.clone())),
}),
}
}
fn run(&self, stack: &Weak<Stack>, run: ChildRun) -> Result<String, String> {
let chat = self.chat.get().cloned().ok_or("The durable runtime is not open")?;
let stack = stack.upgrade().ok_or("The session is closed")?;
let setup = child_setup(&stack, &run);
sync::lock(&self.systems).insert(run.lane_name.clone(), setup.system);
if let Some(values) = self.values.get()
&& !values.handed_over()
{
let session = values.session();
let mut writes = vec![Write::set(NAMES_NAMESPACE, &run.task_id, run.name.clone().into())];
if let Some(contract) = run.host.contract_of(&run.task_id) {
writes.push(Write::set(CONTRACTS_NAMESPACE, &run.task_id, contract));
}
lock(session).commit(&writes)?;
}
let input = ChildInput {
name: run.lane_name.clone(),
prompt: run.prompt.clone(),
model: Some(ModelRef::new(&setup.model.provider, &setup.model.id)),
timeout_ms: Some(run.timeout_ms),
keep: false,
thinking: run.thinking.clone(),
cwd: run.cwd.clone(),
env: run.env.clone(),
agent: false,
usage_root: sync::lock(&self.root).clone(),
fork: run.fork_at.as_deref().and_then(parse_fork_anchor),
history: match run
.fork_at
.as_deref()
.and_then(|anchor| anchor.strip_prefix(ROOT_ANCHOR))
{
Some(entry) => self.root_history(entry)?,
None => Vec::new(),
},
};
let task = chat
.commit(|tx| spawn_child(tx, ROOT_CONVERSATION_ID, None, &input))
.map_err(|e| e.to_string())?;
let _ = chat.resume();
wait_child(&chat, task, &run.signal)
}
pub fn run_lane(&self, stack: &Weak<Stack>, run: LaneRun) -> Result<LaneReply, String> {
let chat = self.chat.get().cloned().ok_or("The durable runtime is not open")?;
let stack = stack.upgrade().ok_or("The session is closed")?;
if run.reuse
&& let Some(conversation) = crate::lane_reuse::lane_conversation(&chat, &run.lane)?
{
return crate::lane_reuse::continue_lane(&chat, conversation, &run);
}
let model = match run.model.as_deref().and_then(|spec| spec.split_once('/')) {
Some((provider, id)) => ModelRef::new(provider, id),
None => ModelRef::new(&stack.model().provider, &stack.model().id),
};
let lane_model = stack
.config()
.model(&model.provider, &model.model_id)
.unwrap_or_else(|| stack.model().clone());
sync::lock(&self.systems).insert(run.lane.clone(), stack.child_system(&lane_model));
let input = ChildInput {
name: run.lane.clone(),
prompt: run.prompt.clone(),
model: Some(model),
timeout_ms: Some(run.timeout_ms),
agent: true,
..ChildInput::default()
};
let task = chat
.commit(|tx| spawn_child(tx, ROOT_CONVERSATION_ID, None, &input))
.map_err(|e| e.to_string())?;
let _ = chat.resume();
let text = wait_child(&chat, task, &run.signal)?;
Ok(LaneReply {
text,
..LaneReply::default()
})
}
pub fn fork_point(&self, lane: &str) -> Result<Option<String>, String> {
if lane == session_journal::run::MAIN_LANE {
let entries = self.root_context()?;
let messages: Vec<(String, Vec<Value>)> = entries
.iter()
.map(|entry| {
let id = entry["id"].as_str().unwrap_or_default().to_string();
(id, session_journal::context::entry_context_messages(entry))
})
.collect();
let at = delegation::fork::fork_point(messages.iter().map(|(id, m)| (id.clone(), m.as_slice())));
return Ok(at.map(|entry| format!("{ROOT_ANCHOR}{entry}")));
}
let chat = self.chat.get().cloned().ok_or("The durable runtime is not open")?;
let conversation = match lane.strip_prefix(CONVERSATION_LANE_PREFIX) {
Some(id) => id.parse().ok().map(ConversationId),
None => self.conversation_of_lane(lane),
};
let conversation =
conversation.ok_or_else(|| format!("rlm.spawn fork=True: lane {lane} has no conversation"))?;
let handle = chat
.conversation(conversation)
.map_err(|e| e.to_string())?
.ok_or_else(|| format!("rlm.spawn fork=True: lane {lane} has no conversation"))?;
let entries = handle.entries().map_err(|e| e.to_string())?;
let start = entries
.iter()
.rposition(|e| e.kind == harness::chat::entries::RESET)
.map_or(0, |i| i + 1);
let at = delegation::fork::fork_point(
entries[start..]
.iter()
.map(|entry| (entry.id.0.to_string(), entry.model.as_deref().unwrap_or_default())),
);
Ok(at.map(|entry| format!("{}:{entry}", conversation.0)))
}
fn root_context(&self) -> Result<Vec<Value>, String> {
let session = self.values.get().ok_or("The session is not open")?.session();
let session = lock(session);
Ok(session_journal::context::build_context_entries(
&session.branch_entries(session_journal::run::MAIN_LANE)?,
))
}
fn root_history(&self, entry: &str) -> Result<Vec<Value>, String> {
let entries = self.root_context()?;
let end = entries
.iter()
.position(|e| e["id"] == entry)
.ok_or("rlm.spawn fork=True: the fork point is no longer in the root's context")?;
let applied = session_journal::context::apply_context_edits(&entries[..=end]);
let messages: Vec<Value> = applied
.iter()
.flat_map(session_journal::context::entry_context_messages)
.collect();
Ok(crate::lane::to_llm(&messages)
.into_iter()
.filter(|message| !matches!(message, ai::Message::System(_)))
.filter_map(|message| serde_json::to_value(message).ok())
.collect())
}
pub fn fork_point_hook(self: &Arc<Self>) -> delegation::fork::ForkPointHook {
let children = Arc::downgrade(self);
Arc::new(move |lane: &str| match children.upgrade() {
Some(children) => children.fork_point(lane),
None => Err("The session is closed".into()),
})
}
pub fn set_root(&self, root: Option<String>) {
*sync::lock(&self.root) = root;
}
pub fn current_root(&self) -> Option<String> {
sync::lock(&self.root).clone()
}
fn child_of_lane(&self, lane: &str) -> Option<(ChildInput, Option<ConversationId>)> {
let chat = self.chat.get()?;
chat.commit(|tx| {
let query = TaskQuery {
kind: Some(CHILD_KIND.to_string()),
..TaskQuery::default()
};
let mut cursor: Option<Cursor> = None;
loop {
let page = tx.scan_tasks(&query, 256, cursor.as_ref())?;
for task in page.items {
if task.input["name"].as_str() != Some(lane) {
continue;
}
let conversation = match &task.state {
durable::TaskState::Running { checkpoint }
| durable::TaskState::Pending { checkpoint }
| durable::TaskState::Waiting { checkpoint, .. } => checkpoint["conversation"].as_u64(),
_ => None,
};
let input = serde_json::from_value::<ChildInput>(task.input.clone()).ok();
return Ok(input.map(|input| (input, conversation.map(ConversationId))));
}
match page.next {
Some(next) => cursor = Some(next),
None => return Ok(None),
}
}
})
.ok()
.flatten()
}
pub fn session(&self) -> Option<SharedSession> {
self.values.get().map(|values| values.session().clone())
}
pub fn kept_child_of_lane(&self, lane: &str) -> Option<String> {
let chat = self.chat.get()?;
let children = child_tasks(chat).ok()?;
let (task, input, terminal) = children.get(lane)?;
(input.keep && !*terminal).then(|| task.0.to_string())
}
pub fn conversation_of_lane(&self, lane: &str) -> Option<ConversationId> {
self.child_of_lane(lane)?.1
}
pub fn usage_root_of_lane(&self, lane: &str, agents: &delegation::agents::Agents) -> Option<String> {
match self.child_of_lane(lane) {
Some((input, _)) if !input.agent => input.usage_root,
_ => agents.usage_root_for_lane(lane, ""),
}
}
pub fn usage_root(&self, conversation: ConversationId, agents: &delegation::agents::Agents) -> Option<String> {
let chat = self.chat.get()?;
let input = chat
.commit(|tx| {
let Some(owner) = tx.conversation(conversation)?.and_then(|record| record.owner) else {
return Ok(None);
};
Ok(tx
.task(owner.task_id)?
.filter(|task| task.kind == CHILD_KIND)
.and_then(|task| serde_json::from_value::<ChildInput>(task.input).ok()))
})
.ok()
.flatten()?;
if input.agent {
return agents.usage_root_for_lane(&input.name, "");
}
input.usage_root
}
pub fn lane_of(&self, conversation: ConversationId) -> Option<String> {
let chat = self.chat.get()?;
chat.commit(|tx| {
let Some(record) = tx.conversation(conversation)? else {
return Ok(None);
};
let Some(owner) = record.owner else {
return Ok((conversation != ROOT_CONVERSATION_ID)
.then(|| format!("{CONVERSATION_LANE_PREFIX}{}", conversation.0)));
};
Ok(tx
.task(owner.task_id)?
.filter(|task| task.kind == CHILD_KIND)
.and_then(|task| task.input["name"].as_str().map(str::to_string)))
})
.ok()
.flatten()
}
pub fn system_of(&self, lane: &str) -> Option<String> {
sync::lock(&self.systems).get(lane).cloned()
}
pub fn restore(&self, stack: &Stack, unfinished: &[String]) -> Result<Vec<String>, String> {
let Some(chat) = self.chat.get().cloned() else {
return Ok(Vec::new());
};
let children = child_tasks(&chat)?;
let reattached = stack.delegation.restore(unfinished, |id| {
let (task, input, _) = children.get(&lanes::lane_names::child_lane(id))?.clone();
if input.agent || input.keep {
return None;
}
let run = self.restore_lane(stack, id, &input);
let chat = chat.clone();
let (lanes, lane) = (stack.lanes.clone(), input.name.clone());
let contract = self
.session()
.and_then(|session| lock(&session).value(CONTRACTS_NAMESPACE, id).cloned());
Some(Reattached {
waiter: Box::new(move |signal: Signal| {
let reply = wait_child(&chat, task, &signal);
let _ = lanes.close_lane(&lane);
reply
}) as ChildWaiter,
contract,
run: Some(run),
})
})?;
for (name, (task, input, terminal)) in &children {
let ours = !terminal
&& (input.agent
|| matches!(lanes::lane_names::parse_lane(name),
Some(lanes::lane_names::LaneOwner::Child(id)) if !reattached.iter().any(|r| r == id)));
if ours && !input.keep {
let _ = chat.abort_task(*task, &Ctx::background());
}
}
Ok(reattached)
}
fn restore_lane(&self, stack: &Stack, id: &str, input: &ChildInput) -> ChildRun {
let run = ChildRun {
task_id: id.to_string(),
name: self
.session()
.and_then(|session| subagent_name(&session, id))
.unwrap_or_default(),
lane_name: input.name.clone(),
prompt: input.prompt.clone(),
level: 1,
allowance: 0,
model: input.model.as_ref().map(|m| format!("{}/{}", m.provider, m.model_id)),
thinking: input.thinking.clone(),
timeout_ms: input.timeout_ms.unwrap_or_default(),
cwd: input.cwd.clone(),
env: input.env.clone(),
fork_at: None,
signal: Signal::new(),
host: stack.delegation.clone(),
};
let setup = child_setup(stack, &run);
sync::lock(&self.systems).insert(input.name.clone(), setup.system);
run
}
}
fn parse_fork_anchor(anchor: &str) -> Option<harness::chat::children::ChildFork> {
let (conversation, entry) = anchor.split_once(':')?;
Some(harness::chat::children::ChildFork {
conversation: ConversationId(conversation.parse().ok()?),
entry: durable::EntryId(entry.parse().ok()?),
})
}
const ROOT_ANCHOR: &str = "root:";
fn child_tasks(chat: &ChatHarness) -> Result<HashMap<String, (TaskId, ChildInput, bool)>, String> {
chat.commit(|tx| {
let query = TaskQuery {
kind: Some(CHILD_KIND.to_string()),
..TaskQuery::default()
};
let mut found = HashMap::new();
let mut cursor: Option<Cursor> = None;
loop {
let page = tx.scan_tasks(&query, 256, cursor.as_ref())?;
for task in page.items {
let terminal = task.state.status() == durable::TaskStatus::Terminal;
if let Ok(input) = serde_json::from_value::<ChildInput>(task.input.clone()) {
found.insert(input.name.clone(), (task.id, input, terminal));
}
}
match page.next {
Some(next) => cursor = Some(next),
None => return Ok(found),
}
}
})
.map_err(|e| e.to_string())
}
fn wait_child(chat: &ChatHarness, task: TaskId, signal: &Signal) -> Result<String, String> {
let cancel = Cancel::new();
let target = cancel.clone();
let link = signal.link(move |_| target.abort());
let waited = chat.wait_for_task(task, &Ctx::with_signal(&cancel));
drop(link);
match waited {
Ok(record) => {
let report = child_report(&record).ok_or("The subagent ended without a result")?;
let result = &report["result"];
if result["status"] == "succeeded" {
Ok(match &result["value"] {
Value::String(text) => text.clone(),
Value::Null => String::new(),
other => other.to_string(),
})
} else {
Err(result["error"]
.as_str()
.map_or_else(|| format!("The subagent ended {}", result["status"]), str::to_string))
}
}
Err(error) => {
let reason = signal.reason().unwrap_or_else(|| error.to_string());
let _ = chat.abort_task(task, &Ctx::background());
Err(reason)
}
}
}