Skip to main content

session_core/
memory_children.rs

1//! Subagents run as in-memory agent loops (a session without the durable runtime: `ultron mcp`, whose root is
2//! Claude Code, with `--children ultron` or no `claude` installed). The same loop as `delegation::child::agent_runner`
3//! (the child's reply is its last assistant message's text; cancelling the child aborts the loop), with what a
4//! child lane of the session actor gets from its durable conversation:
5//!
6//! - agent-hub steering ([`MemoryChildren::steer`], the stack's `lane_steer`): a message for a running child is
7//!   queued as a steer of its loop, seen after the current turn's tool calls; a child that is not running is not
8//!   steered;
9//! - the context-pressure reminder (crate::context_reminder): the child lane's context use is the estimate of its
10//!   loop's conversation (`estimateContextTokens`: the newest answer's usage plus estimates after it), read while
11//!   the child runs.
12
13use crate::context_reminder::ContextReminders;
14use agent::{Agent, AgentControl, AgentEvent};
15use ai::{Message, UserMessage, UserMessageContent};
16use delegation::child::{ChildAgentFactory, run_to_text};
17use delegation::host::{ChildRun, ChildRunner};
18use jsrt::sync;
19use std::collections::HashMap;
20use std::sync::{Arc, Mutex, OnceLock};
21
22/// The running in-memory children, by lane.
23#[derive(Default)]
24pub struct MemoryChildren {
25    running: Mutex<HashMap<String, AgentControl>>,
26    reminders: OnceLock<Arc<ContextReminders>>,
27}
28
29impl MemoryChildren {
30    /// Child lanes' context use goes to `reminders` from the next child on.
31    pub fn attach_reminders(&self, reminders: Arc<ContextReminders>) {
32        let _ = self.reminders.set(reminders);
33    }
34
35    /// Steer the running child on `lane` with `message`; false when no child runs there.
36    pub fn steer(&self, lane: &str, message: &str) -> bool {
37        let Some(control) = sync::lock(&self.running).get(lane).cloned() else {
38            return false;
39        };
40        control.steer(Message::User(UserMessage {
41            content: UserMessageContent::Text(message.to_string()),
42            timestamp: jsrt::date::now_ms(),
43        }));
44        true
45    }
46
47    pub fn is_running(&self, lane: &str) -> bool {
48        sync::lock(&self.running).contains_key(lane)
49    }
50
51    pub fn runner(self: &Arc<Self>, factory: ChildAgentFactory) -> ChildRunner {
52        let children = self.clone();
53        Arc::new(move |run: ChildRun| children.run(&factory, run))
54    }
55
56    fn run(&self, factory: &ChildAgentFactory, run: ChildRun) -> Result<String, String> {
57        let (options, stream) = factory(&run);
58        let mut agent = Agent::new(options, stream);
59        // The conversation as the loop has it, for the lane's context meter.
60        let conversation = Arc::new(Mutex::new(agent.messages.clone()));
61        let seen = conversation.clone();
62        agent.subscribe(move |event| {
63            if let AgentEvent::MessageEnd { message } = event {
64                sync::lock(&seen).push(message.clone());
65            }
66        });
67        let lane = run.lane_name.clone();
68        if let Some(reminders) = self.reminders.get() {
69            let meter = conversation.clone();
70            reminders.set_lane_meter(
71                &lane,
72                Some(Arc::new(move || {
73                    Some(ai::transcript::estimate_context_tokens(&sync::lock(&meter)).tokens)
74                })),
75            );
76        }
77        sync::lock(&self.running).insert(lane.clone(), agent.control());
78        let reply = run_to_text(&mut agent, &run.prompt, &run.signal);
79        sync::lock(&self.running).remove(&lane);
80        if let Some(reminders) = self.reminders.get() {
81            reminders.set_lane_meter(&lane, None);
82        }
83        reply
84    }
85}