ultron-session-core 1.0.0

One session's runtime, shared by every mode through the session worker: the rlm lane (model, provider, system prompt, the single rlm tool), the composition root of its host stack, the format-4 run journal, session naming, Pi read views, and the session actor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Subagents on the durable task journal. An `rlm.spawn` child runs as a child conversation of the session's durable
//! runtime (`harness::chat::children`: an `ultron.child` task owning its conversation), so its model calls and
//! cells are as durable as the root's: a worker that dies leaves it to the next one, which resumes it (a pinned
//! request is resent, a running cell reports `interrupted`) and reattaches the delegation host's task to it.
//!
//! The delegation host keeps its task journal in the session, where the TypeScript product keeps it
//! (`createSessionTaskStore`: value `ultron.tasks` / `root`), so finished results stay collectable after a restart,
//! and `rlm.results()`, `rlm.collect` and `rlm.list_subagents()` read the same tasks.

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};

/// The lane of another root conversation of the session (`ultron.conversation.<id>`).
pub const CONVERSATION_LANE_PREFIX: &str = "ultron.conversation.";
/// The `rlm.spawn(name=...)` of each subagent, a session value per task id (Rust-only: the task journal and the
/// child task keep no name), so a revived subagent keeps its name.
pub const NAMES_NAMESPACE: &str = "ultron.subagent-names";

/// The contract (`role`, `contract`, `hop`) of each subagent spawned with one, a session value per task id as
/// `delegation::host::Delegation::contract_of` describes it (Rust-only, like the names): a child reattached after a
/// restart is still held to it. Sessions without these values reattach their children unchecked, as before.
pub const CONTRACTS_NAMESPACE: &str = "ultron.subagent-contracts";

/// The name subagent `task_id` was spawned with, if this session recorded it.
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)
}

/// A document kept as one session value (`createSessionTaskStore`, `createSessionDefinitionStore`) of a session no
/// worker hands over (an `ultron claude` server's).
pub fn value_store(session: &SharedSession, namespace: &str, key: &str) -> Box<dyn DocumentStore> {
    Box::new(services::SessionValues::shared(session.clone()).document(namespace, key))
}

/// The usage ledger's document (`ultron.usage` / `root`), which the operation journal also writes: each run counts
/// its model turns there as it commits them. A ledger write keeps those counts: a root's `turns` are the stored
/// ones when they are ahead of the ledger's.
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)
    }
}

/// The subagent tasks the stored journal holds unfinished (read before the host reopens it, which records them
/// interrupted).
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()
}

/// Subagents as child conversations of the session's durable runtime.
#[derive(Default)]
pub struct DurableChildren {
    chat: OnceLock<ChatHarness>,
    /// The system prompt of each lane this process started (a worktree child's names its worktree).
    systems: Mutex<HashMap<String, String>>,
    /// The usage root of the root turn in progress: a subagent it starts is charged to it.
    root: Mutex<Option<String>>,
    /// The session's values: its transcript is the root lane's history (a forked child of the root starts on it),
    /// and its hand-over to a successor stops what this worker's hosts would still record (a waiter's "Harness is
    /// closed" as the closing runtime fails its wait), so the successor finds its tasks unfinished and reattaches them.
    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);
    }

    /// The runtime the children run in, once it is open.
    pub fn chat(&self) -> Option<ChatHarness> {
        self.chat.get().cloned()
    }

    /// The children's records are values of `session`, which no worker hands over (an `ultron claude` server's,
    /// whose subagents are not these children).
    pub fn attach_session(&self, session: &SharedSession) {
        let _ = self.values.set(services::SessionValues::shared(session.clone()));
    }

    /// The subagent host of a session: its journal in the session's `values`, its children run durably.
    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 {
                // One host per journal: the typed agents' tasks are a document of their own beside the subagents'.
                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())),
            }),
        }
    }

    /// Start `run` as a child conversation and wait for its answer.
    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())];
            // Kept before the child conversation exists, so a worker that dies after starting it leaves both.
            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)
    }

    /// A typed agent's `rlm` run, as a child conversation on the lane the task host named.
    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")?;
        // A reused lane (a retained instance) continues its conversation.
        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),
        };
        // A typed agent's lane is never woken: it gets the subagent guide (crate::wake), for its model's tier.
        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()
        })
    }

    /// `rlm.spawn(fork=True)` of `lane`: where its forked child starts (`forkPoint` over the lane's conversation),
    /// none while it has no finished conversation. The root's history is the session transcript (its runtime
    /// conversation starts afresh every turn): `root:<transcript entry>`; another conversation's is in the runtime:
    /// `<conversation>:<entry>`.
    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())?;
        // From the conversation's newest context start: what came before a reset is not its context.
        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)))
    }

    /// The root lane's context entries (from its newest compaction), as the next root request would build them.
    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)?,
        ))
    }

    /// The root's history up to its transcript entry `entry`, as model messages for a forked child.
    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())
    }

    /// [`Self::fork_point`] as the delegation host's hook.
    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()),
        })
    }

    /// The usage root of the root turn now running (`None`: the ledger's default root).
    pub fn set_root(&self, root: Option<String>) {
        *sync::lock(&self.root) = root;
    }

    /// The usage root of the root turn running now (or last).
    pub fn current_root(&self) -> Option<String> {
        sync::lock(&self.root).clone()
    }

    /// The input of the unfinished child task that runs `lane`, and its conversation once started.
    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()
    }

    /// The session whose values these children's records are, once [`DurableChildren::host`] gave it.
    pub fn session(&self) -> Option<SharedSession> {
        self.values.get().map(|values| values.session().clone())
    }

    /// The persistent child (`keep=True`, unfinished) whose cells run on `lane` (its name), as its REPL id.
    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())
    }

    /// The conversation a child lane runs in, while its task is unfinished.
    pub fn conversation_of_lane(&self, lane: &str) -> Option<ConversationId> {
        self.child_of_lane(lane)?.1
    }

    /// The usage root of work started on a child lane: its task's (a typed agent's reservation, a subagent's root
    /// turn), or the agents host's for a lane it runs.
    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, ""),
        }
    }

    /// The usage root a model turn of `conversation` (not the root conversation) is charged to, as
    /// `usageRootForLane` charges every lane's responses: a typed agent's lane to its task's root, a subagent to the
    /// root turn that started it, another root conversation to the ledger's default root.
    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
    }

    /// The lane of a child conversation: the name of the child task that owns it.
    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);
            };
            // Another root conversation of the session has a REPL lane of its own.
            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()
    }

    /// The system prompt a child lane was started with in this process.
    pub fn system_of(&self, lane: &str) -> Option<String> {
        sync::lock(&self.systems).get(lane).cloned()
    }

    /// Reopen the delegation host's tasks after a restart, reattaching every unfinished child the runtime still
    /// holds: its lane gets back its working directory (a worktree child's), environment and system prompt before
    /// the runtime resumes it. Returns the reattached task ids.
    ///
    /// A typed agent's run (`agents.*`) is not reattached: as in TypeScript (`NativeRlmHost` reopens its journal
    /// with every unfinished task `interrupted`, and its in-process lanes are gone), the agent task reads
    /// `interrupted`, so the runtime's child conversation that ran it is aborted rather than left spending tokens
    /// for a result nobody reads. So is any other unfinished subagent conversation the journal no longer runs.
    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);
                    // The lane closes when its run ends, as a fresh child's does.
                    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)
    }

    /// The lane setup a reattached child had in the worker that started it: its worktree (working directory and
    /// environment), thinking level and system prompt naming that directory. Returns the run, which a contract's
    /// retry hop repeats.
    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
    }
}

/// A fork anchor (`<conversation>:<entry>`, from [`DurableChildren::fork_point`]) as the child's fork.
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()?),
    })
}

/// The fork anchor prefix of the root lane's transcript entries.
const ROOT_ANCHOR: &str = "root:";

/// The runtime's child tasks by name, with their input and whether they ended.
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())
}

/// Wait for a child task's answer. Cancelling its task (`signal`: a delete, its timeout, an ancestor's cancel, the
/// host closing) aborts the child's work, as the journal records it cancelled.
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)
        }
    }
}