Skip to main content

session_core/
subagents.rs

1//! Subagents on the durable task journal. An `rlm.spawn` child runs as a child conversation of the session's durable
2//! runtime (`harness::chat::children`: an `ultron.child` task owning its conversation), so its model calls and
3//! cells are as durable as the root's: a worker that dies leaves it to the next one, which resumes it (a pinned
4//! request is resent, a running cell reports `interrupted`) and reattaches the delegation host's task to it.
5//!
6//! The delegation host keeps its task journal in the session, where the TypeScript product keeps it
7//! (`createSessionTaskStore`: value `ultron.tasks` / `root`), so finished results stay collectable after a restart,
8//! and `rlm.results()`, `rlm.collect` and `rlm.list_subagents()` read the same tasks.
9
10use 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
28/// The lane of another root conversation of the session (`ultron.conversation.<id>`).
29pub const CONVERSATION_LANE_PREFIX: &str = "ultron.conversation.";
30/// The `rlm.spawn(name=...)` of each subagent, a session value per task id (Rust-only: the task journal and the
31/// child task keep no name), so a revived subagent keeps its name.
32pub const NAMES_NAMESPACE: &str = "ultron.subagent-names";
33
34/// The contract (`role`, `contract`, `hop`) of each subagent spawned with one, a session value per task id as
35/// `delegation::host::Delegation::contract_of` describes it (Rust-only, like the names): a child reattached after a
36/// restart is still held to it. Sessions without these values reattach their children unchecked, as before.
37pub const CONTRACTS_NAMESPACE: &str = "ultron.subagent-contracts";
38
39/// The name subagent `task_id` was spawned with, if this session recorded it.
40pub 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
47/// A document kept as one session value (`createSessionTaskStore`, `createSessionDefinitionStore`) of a session no
48/// worker hands over (an `ultron claude` server's).
49pub 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
53/// The usage ledger's document (`ultron.usage` / `root`), which the operation journal also writes: each run counts
54/// its model turns there as it commits them. A ledger write keeps those counts: a root's `turns` are the stored
55/// ones when they are ahead of the ledger's.
56pub 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
82/// The subagent tasks the stored journal holds unfinished (read before the host reopens it, which records them
83/// interrupted).
84pub 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/// Subagents as child conversations of the session's durable runtime.
102#[derive(Default)]
103pub struct DurableChildren {
104    chat: OnceLock<ChatHarness>,
105    /// The system prompt of each lane this process started (a worktree child's names its worktree).
106    systems: Mutex<HashMap<String, String>>,
107    /// The usage root of the root turn in progress: a subagent it starts is charged to it.
108    root: Mutex<Option<String>>,
109    /// The session's values: its transcript is the root lane's history (a forked child of the root starts on it),
110    /// and its hand-over to a successor stops what this worker's hosts would still record (a waiter's "Harness is
111    /// closed" as the closing runtime fails its wait), so the successor finds its tasks unfinished and reattaches them.
112    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    /// The runtime the children run in, once it is open.
125    pub fn chat(&self) -> Option<ChatHarness> {
126        self.chat.get().cloned()
127    }
128
129    /// The children's records are values of `session`, which no worker hands over (an `ultron claude` server's,
130    /// whose subagents are not these children).
131    pub fn attach_session(&self, session: &SharedSession) {
132        let _ = self.values.set(services::SessionValues::shared(session.clone()));
133    }
134
135    /// The subagent host of a session: its journal in the session's `values`, its children run durably.
136    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                // One host per journal: the typed agents' tasks are a document of their own beside the subagents'.
149                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    /// Start `run` as a child conversation and wait for its answer.
161    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            // Kept before the child conversation exists, so a worker that dies after starting it leaves both.
172            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    /// A typed agent's `rlm` run, as a child conversation on the lane the task host named.
206    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        // A reused lane (a retained instance) continues its conversation.
210        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        // A typed agent's lane is never woken: it gets the subagent guide (crate::wake), for its model's tier.
220        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    /// `rlm.spawn(fork=True)` of `lane`: where its forked child starts (`forkPoint` over the lane's conversation),
245    /// none while it has no finished conversation. The root's history is the session transcript (its runtime
246    /// conversation starts afresh every turn): `root:<transcript entry>`; another conversation's is in the runtime:
247    /// `<conversation>:<entry>`.
248    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        // From the conversation's newest context start: what came before a reset is not its context.
274        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    /// The root lane's context entries (from its newest compaction), as the next root request would build them.
287    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    /// The root's history up to its transcript entry `entry`, as model messages for a forked child.
296    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    /// [`Self::fork_point`] as the delegation host's hook.
315    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    /// The usage root of the root turn now running (`None`: the ledger's default root).
324    pub fn set_root(&self, root: Option<String>) {
325        *sync::lock(&self.root) = root;
326    }
327
328    /// The usage root of the root turn running now (or last).
329    pub fn current_root(&self) -> Option<String> {
330        sync::lock(&self.root).clone()
331    }
332
333    /// The input of the unfinished child task that runs `lane`, and its conversation once started.
334    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    /// The session whose values these children's records are, once [`DurableChildren::host`] gave it.
368    pub fn session(&self) -> Option<SharedSession> {
369        self.values.get().map(|values| values.session().clone())
370    }
371
372    /// The persistent child (`keep=True`, unfinished) whose cells run on `lane` (its name), as its REPL id.
373    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    /// The conversation a child lane runs in, while its task is unfinished.
381    pub fn conversation_of_lane(&self, lane: &str) -> Option<ConversationId> {
382        self.child_of_lane(lane)?.1
383    }
384
385    /// The usage root of work started on a child lane: its task's (a typed agent's reservation, a subagent's root
386    /// turn), or the agents host's for a lane it runs.
387    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    /// The usage root a model turn of `conversation` (not the root conversation) is charged to, as
395    /// `usageRootForLane` charges every lane's responses: a typed agent's lane to its task's root, a subagent to the
396    /// root turn that started it, another root conversation to the ledger's default root.
397    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    /// The lane of a child conversation: the name of the child task that owns it.
418    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            // Another root conversation of the session has a REPL lane of its own.
425            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    /// The system prompt a child lane was started with in this process.
439    pub fn system_of(&self, lane: &str) -> Option<String> {
440        sync::lock(&self.systems).get(lane).cloned()
441    }
442
443    /// Reopen the delegation host's tasks after a restart, reattaching every unfinished child the runtime still
444    /// holds: its lane gets back its working directory (a worktree child's), environment and system prompt before
445    /// the runtime resumes it. Returns the reattached task ids.
446    ///
447    /// A typed agent's run (`agents.*`) is not reattached: as in TypeScript (`NativeRlmHost` reopens its journal
448    /// with every unfinished task `interrupted`, and its in-process lanes are gone), the agent task reads
449    /// `interrupted`, so the runtime's child conversation that ran it is aborted rather than left spending tokens
450    /// for a result nobody reads. So is any other unfinished subagent conversation the journal no longer runs.
451    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                    // The lane closes when its run ends, as a fresh child's does.
471                    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    /// The lane setup a reattached child had in the worker that started it: its worktree (working directory and
491    /// environment), thinking level and system prompt naming that directory. Returns the run, which a contract's
492    /// retry hop repeats.
493    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
519/// A fork anchor (`<conversation>:<entry>`, from [`DurableChildren::fork_point`]) as the child's fork.
520fn 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
528/// The fork anchor prefix of the root lane's transcript entries.
529const ROOT_ANCHOR: &str = "root:";
530
531/// The runtime's child tasks by name, with their input and whether they ended.
532fn 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
557/// Wait for a child task's answer. Cancelling its task (`signal`: a delete, its timeout, an ancestor's cancel, the
558/// host closing) aborts the child's work, as the journal records it cancelled.
559fn 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}