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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
//! The session actor's side of durable turns (crate::turns): starting a turn in the durable runtime, answering a
//! generation's start with the request the TypeScript agent loop would send, noticing the end of a turn, aborting
//! one, and resuming one a dead worker left (projecting onto the transcript what the runtime committed and the
//! transcript had not, then letting the runtime continue).

use super::*;
use crate::turns::{Answer, Bridge, GenerationStart, Request, StartError, TurnCells, TurnModels};
use agent::AgentToolResult;
use durable::{ROOT_CONVERSATION_ID, SubmissionId, SubmissionStatus};
use harness::chat::{
    AgentChange, ChatHarness, ChatOptions, CompactionPolicy, ModelRef, QueueMode, Settings, SubmissionAbort,
    SubmissionDraft, ToolExecution, WhenBusy,
};
use harness::scheduler::{Cancel, Ctx, Registry};
use session_journal::ns::{OP_META, OP_STATE};
use std::sync::atomic::{AtomicBool, Ordering};

/// A round whose answer the transcript holds: its calls `(id, name)`, and the results reported before a restart.
type HeldRound = (Vec<(String, String)>, Vec<(String, AgentToolResult, bool)>);

/// Generation partials are not committed: the transcript has the progress frames, and a resent request replaces
/// whatever a dead worker was streaming.
const NO_PARTIALS_MS: u64 = 365 * 24 * 3600 * 1000;

/// The durable runtime of one session and what the actor keeps of it.
pub(super) struct Durable {
    pub chat: ChatHarness,
    pub root: harness::chat::Conversation,
    pub bridge: Arc<Bridge>,
    pub auto_retry: Arc<AtomicBool>,
    /// Cancelled when the session closes: idle waiters stop.
    pub stop: Cancel,
    /// The subagents running as child conversations (their usage root follows the root turn).
    pub children: Arc<crate::subagents::DurableChildren>,
}

fn harness_error(error: harness::scheduler::HarnessError) -> String {
    error.to_string()
}

/// Open the durable runtime over the session journal; its turns report to the actor through `tx`.
#[allow(clippy::too_many_arguments)]
pub(super) fn open_durable(
    session: &SharedSession,
    tx: &Sender<Input>,
    lane: &Lane,
    provider: Arc<Provider>,
    env: &RunEnv,
    keys: &crate::request_keys::Keys,
    queues: Arc<Mutex<Queues>>,
    children: Arc<crate::subagents::DurableChildren>,
    child_context: Arc<super::context_children::ChildContext>,
    image_budget: usize,
) -> Result<Durable, String> {
    let to_actor = tx.clone();
    let to_actor = Mutex::new(to_actor);
    let bridge = Bridge::new(Arc::new(move |request| {
        let _ = sync::lock(&to_actor).send(Input::Turn(request));
    }));
    let observed = child_context.clone();
    let committed: crate::turns::Committed = Arc::new(move |entry| observed.committed(entry));
    let storage = crate::durable_store::open(session.clone(), Some(crate::turns::observer(bridge.clone(), committed)))
        .map_err(|e| e.message().to_string())?;
    let auto_retry = Arc::new(AtomicBool::new(true));
    let retry = auto_retry.clone();
    // settings.json's `retry` (`getRetrySettings`); `set_auto_retry` turns it off for the session.
    let retry_settings = config::settings::SettingsManager::for_worker(&env.cwd, &env.agent_dir(), &env.home)
        .settings()
        .get("retry")
        .cloned()
        .unwrap_or(Value::Null);
    let settings_queues = queues;
    let live: LiveSettings = Arc::new(move |settings: &mut Settings| {
        let (steering, follow_up) = {
            let queues = sync::lock(&settings_queues);
            (queues.steering_all, queues.follow_up_all)
        };
        let mode = |all: bool| if all { QueueMode::All } else { QueueMode::OneAtATime };
        settings.retry = ai::retry::RetryPolicy::from_settings(&retry_settings, retry.load(Ordering::SeqCst));
        settings.steering_mode = mode(steering);
        settings.follow_up_mode = mode(follow_up);
    });
    let root_session = Arc::new(std::sync::OnceLock::new());
    // A subagent's model cost (`task.cost`: what its lane's responses reported), for the line its end leaves on the
    // cell that returns it (`onTaskEnd` -> `contextControl.taskEnded`, root-level subagents only).
    let child_costs: ChildCosts = Arc::default();
    let (ended_costs, ended_stack) = (child_costs.clone(), Arc::downgrade(&lane.stack));
    lane.stack.delegation.on_task_end(Arc::new(move |task: &Value| {
        let cost = task["id"].as_str().and_then(|id| sync::lock(&ended_costs).remove(id));
        if let Some(stack) = ended_stack.upgrade()
            && let Some(context) = stack.context.get()
        {
            context.task_ended(task, cost);
        }
    }));
    let context = child_context.clone();
    // Subagent lanes get clock lines and result footers as the root does (`clockLane`); typed agents and frames do not.
    let clock = lane::clock_enabled(env).then(|| lane::clock_zone(env));
    let started = lock_session(session).metadata().created_at;
    let footers = (lane.stack.config().result_footer && started > 0).then_some(started);
    let subagents = children.clone();
    let transform: crate::turns::TransformChild = Arc::new(move |conversation, messages: &mut Vec<ai::Message>| {
        context.transform_request(conversation, messages);
        let subagent = subagents.lane_of(conversation).is_some_and(|lane| {
            matches!(
                lanes::lane_names::parse_lane(&lane),
                Some(lanes::lane_names::LaneOwner::Child(_))
            )
        });
        if !subagent {
            return;
        }
        if let Some(zone) = &clock {
            add_clock_lines(messages, zone);
        }
        if let Some(started) = footers {
            lane::add_result_footers(messages, started);
        }
    });
    let mut options = child_chat_options(
        session,
        lane,
        &children,
        env,
        ChildTurns {
            bridge: bridge.clone(),
            provider,
            keys: keys.clone(),
            root_session: root_session.clone(),
            live,
            charged: Some(child_cost(children.clone(), child_costs)),
            transform: Some(transform),
            image_budget,
            fallback_system: crate::compose::Stack::system,
        },
    );
    // A subagent stopped by the gate fails with its root's limit text (`withLimitReason`).
    let (limit_children, limit_stack) = (children.clone(), Arc::downgrade(&lane.stack));
    lane.stack.delegation.set_limit_reason(Arc::new(move |task: &str| {
        let stack = limit_stack.upgrade()?;
        let root = limit_children.usage_root_of_lane(&lanes::lane_names::child_lane(task), &stack.agents);
        stack.usage.turn_budget_exhausted(root.as_deref()).ok().flatten()
    }));
    // `ctx` may trim a child conversation instead of compacting it (`before_compaction`).
    let trims = child_context.clone();
    options.hooks.before_compaction = Some(Arc::new(move |conversation, tokens, threshold| {
        trims.before_compaction(conversation, tokens, threshold)
    }));
    let chat = ChatHarness::open(storage, options).map_err(harness_error)?;
    let root = chat.root(None).map_err(harness_error)?;
    let provider_session = chat
        .snapshot(
            &harness::chat::docs::PROVIDER,
            durable::Owner::Conversation(ROOT_CONVERSATION_ID),
        )
        .map_err(harness_error)?
        .and_then(|state| state["sessionId"].as_str().map(str::to_string))
        .unwrap_or_default();
    let _ = root_session.set(provider_session);
    Ok(Durable {
        chat,
        root,
        bridge,
        auto_retry,
        stop: Cancel::new(),
        children,
    })
}

/// `withClockLines` over a request's messages: a clock line before each user message that opens the conversation or
/// follows a gap (derived from the messages' own timestamps, never stored).
fn add_clock_lines(messages: &mut Vec<ai::Message>, zone: &jsrt::localtime::Zone) {
    // The positional system prompt sections are no message of the conversation (TypeScript's system prompt is
    // not in the lane's messages): they neither get a line nor count as the message before one.
    let values: Vec<Value> = messages
        .iter()
        .map(|message| match message {
            ai::Message::System(_) => Value::Null,
            message => serde_json::to_value(message).unwrap_or(Value::Null),
        })
        .collect();
    for (index, line) in lane::clock_lines_in(&values, zone).into_iter().rev() {
        messages.insert(index, line);
    }
}

/// Model cost reported by each subagent's responses so far, by task id.
type ChildCosts = Arc<Mutex<std::collections::HashMap<String, f64>>>;

/// Adds each subagent response's cost to its task's.
fn child_cost(children: Arc<crate::subagents::DurableChildren>, costs: ChildCosts) -> crate::turns::ChargeTurn {
    Arc::new(move |conversation, message| {
        if conversation != ROOT_CONVERSATION_ID
            && let Some(lane) = children.lane_of(conversation)
            && let Some(lanes::lane_names::LaneOwner::Child(task)) = lanes::lane_names::parse_lane(&lane)
        {
            *sync::lock(&costs).entry(task.to_string()).or_insert(0.0) += message.usage.cost.total;
        }
    })
}

/// Changes the [`Settings`] a durable runtime reads before each generation to what the session sets now.
pub type LiveSettings = Arc<dyn Fn(&mut Settings) + Send + Sync>;

/// What one durable runtime's turns differ in: the native session's (which also runs the root's turns) and an
/// `ultron claude` server's (children only: claude-root's `durable_apis`).
pub struct ChildTurns {
    pub bridge: Arc<Bridge>,
    pub provider: Arc<Provider>,
    pub keys: crate::request_keys::Keys,
    /// The root conversation's provider session ID ([`TurnModels::root_session`]).
    pub root_session: Arc<std::sync::OnceLock<String>>,
    /// Retry and queue modes as the session sets them now.
    pub live: LiveSettings,
    /// Told of every response after the usage ledger charged it.
    pub charged: Option<crate::turns::ChargeTurn>,
    /// Changes a child conversation's request before its image budget applies.
    pub transform: Option<crate::turns::TransformChild>,
    pub image_budget: usize,
    /// A child conversation's system prompt when its lane has none of its own.
    pub fallback_system: fn(&crate::compose::Stack) -> String,
}

/// The chat options of a durable runtime over `session` for `lane`'s stack: the settings (stream options per request,
/// no partials, the root's compactions left to its owner), the models and cells, a child conversation's system
/// prompt, the per-root budget gate and a child conversation's compaction at its threshold. Every model response of
/// any conversation is charged to the usage ledger when it arrives, before the next request is prepared
/// (`recordTurn(usageRootForLane(lane, runId))` in session-worker.ts's `after_response` hook), so per-root turn,
/// token and cost limits count the whole tree and the budget gate sees every response.
pub fn child_chat_options(
    session: &SharedSession,
    lane: &Lane,
    children: &Arc<crate::subagents::DurableChildren>,
    env: &RunEnv,
    turns: ChildTurns,
) -> ChatOptions {
    let ChildTurns {
        bridge,
        provider,
        keys,
        root_session,
        live,
        charged,
        transform,
        image_budget,
        fallback_system,
    } = turns;
    let stream_provider = provider.clone();
    let settings: harness::chat::SettingsSource = Arc::new(move || {
        let mut settings = Settings {
            // A generation's checkpoint pins the stream options requests carry now, as the operation journal's
            // `streamOptions` (`providerRequestOptions`).
            stream: stream_provider
                .stream_options()
                .and_then(|options| options.as_object().cloned())
                .unwrap_or_default(),
            compaction: CompactionPolicy {
                enabled: false,
                ..CompactionPolicy::default()
            },
            partial_interval_ms: NO_PARTIALS_MS,
            tool_execution: ToolExecution::Parallel,
            // As the TypeScript agent loop: a steer continues the run before any follow-up is taken.
            follow_up_after_steer: true,
            ..Settings::default()
        };
        live(&mut settings);
        settings
    });
    let catalog_env = env.clone();
    let root_of = usage_root_of(children.clone(), lane.stack.clone());
    let (charge_root, charge_stack) = (root_of.clone(), lane.stack.clone());
    let models = TurnModels {
        bridge: bridge.clone(),
        provider: provider as Arc<dyn agent::StreamFn>,
        resolve: Arc::new(move |provider, id| lane::catalog_model(provider, id, &catalog_env).ok()),
        api_key: keys.request_keys(),
        root_session,
        charge: Some(Arc::new(move |conversation, message| {
            let root = charge_root(conversation);
            let _ = charge_stack.usage.record_turn(
                root.as_deref(),
                Some(message.usage.total_tokens as f64),
                Some(message.usage.cost.total),
            );
            if let Some(charged) = &charged {
                charged(conversation, message);
            }
        })),
        transform_child: Some(Arc::new(move |conversation, messages: &mut Vec<ai::Message>| {
            if let Some(transform) = &transform {
                transform(conversation, messages);
            }
            crate::view_images::apply_image_budget(messages, image_budget);
        })),
        trace: crate::request_trace::RequestTrace::from_env(&*env.var)
            .map(|trace| (trace, lock_session(session).id().to_string())),
    };
    let cells = TurnCells {
        bridge,
        tool: lane.tool.clone(),
        progress: lane.stack.cell_progress.clone(),
        stack: lane.stack.clone(),
        children: children.clone(),
    };
    // A child conversation's system prompt is its subagent's (the root's request is built by its owner).
    let (section_children, section_stack) = (children.clone(), lane.stack.clone());
    let sections: harness::chat::SectionSource = Arc::new(move |conversation, _| {
        let mut sections = indexmap::IndexMap::new();
        if conversation != ROOT_CONVERSATION_ID {
            let system = section_children
                .lane_of(conversation)
                .and_then(|lane| section_children.system_of(&lane))
                .unwrap_or_else(|| fallback_system(&section_stack));
            sections.insert("system".to_string(), system);
        }
        Ok(sections)
    });
    let mut options = ChatOptions::new(Registry::new(), Arc::new(models), Arc::new(cells));
    options.settings = Some(settings);
    options.sections = Some(sections);
    let gate = super::budget_gate::BudgetGate::new(lane.stack.usage.clone(), lane.stack.stats.clone(), root_of);
    let request_gate = gate.clone();
    options.hooks.gate_request = Some(Arc::new(move |run| request_gate.before_request(run)));
    options.hooks.gate_tool = Some(Arc::new(move |run, call| gate.before_tool(run, call)));
    // A child conversation compacts at its threshold as a TypeScript lane does (the harness's default policy; the
    // root's compactions are its owner's).
    options.hooks.compaction = Some(Arc::new(|conversation| {
        Some(CompactionPolicy {
            enabled: conversation != ROOT_CONVERSATION_ID,
            background_tokens: 0,
            ..CompactionPolicy::default()
        })
    }));
    options
}

/// The usage root a conversation's model turns are charged to (`usageRootForLane`): the root turn running now for the
/// root conversation, else the child's (crate::subagents::DurableChildren::usage_root).
fn usage_root_of(
    children: Arc<crate::subagents::DurableChildren>,
    stack: Arc<crate::compose::Stack>,
) -> super::budget_gate::RootOf {
    Arc::new(move |conversation| {
        if conversation == ROOT_CONVERSATION_ID {
            children.current_root()
        } else {
            children.usage_root(conversation, &stack.agents)
        }
    })
}

/// The text of a transcript message, for matching a placed user message to its queued item.
fn text_of(message: &Message) -> String {
    message_text(&serde_json::to_value(message).unwrap_or(Value::Null))
}

impl Core {
    /// The operation of the run in progress.
    pub(super) fn operation_id(&self) -> Option<String> {
        self.run
            .as_ref()
            .and_then(|run| run.journal.run())
            .map(|run| run.operation_id().to_string())
    }

    /// The submission a queued message is waiting as (request ID `<entry>#<attempt>`): the newest one, and the
    /// attempt a new submission would use.
    fn queued_submission(&self, entry_id: &str) -> (Option<durable::SubmissionRecord>, u64) {
        let mut found = None;
        let mut attempt = 0;
        loop {
            let request = format!("{entry_id}#{attempt}");
            let record = self
                .durable
                .chat
                .commit(|tx| Ok(tx.submission_by_request(ROOT_CONVERSATION_ID, &request)?))
                .ok()
                .flatten();
            match record {
                Some(record) => {
                    found = Some(record);
                    attempt += 1;
                }
                None => return (found, attempt),
            }
        }
    }

    /// Queue every queued message that is not waiting in the runtime's inbox yet (a run is in progress).
    pub(super) fn submit_queued(&mut self) -> Result<(), String> {
        // A message queued for the next run waits for it in the lane's inbox, never in the runtime's.
        let pending: Vec<Queued> = sync::lock(&self.queues)
            .items
            .iter()
            .filter(|q| q.submission.is_none() && q.kind != QueueKind::NextRun)
            .cloned()
            .collect();
        for queued in pending {
            let id = match self.queued_draft(&queued) {
                Ok(id) => id,
                Err(draft) => self.durable.root.submit(draft).map_err(harness_error)?.id,
            };
            self.mark_submitted(&queued.entry_id, id);
        }
        Ok(())
    }

    /// A queued message's live submission in the runtime (`Ok`), or the draft that submits it (`Err`).
    fn queued_draft(&self, queued: &Queued) -> Result<SubmissionId, SubmissionDraft> {
        let (existing, attempt) = self.queued_submission(&queued.entry_id);
        match existing {
            Some(record) if matches!(record.status, SubmissionStatus::Queued | SubmissionStatus::Placed) => {
                Ok(record.id)
            }
            _ => {
                let when = match queued.kind {
                    QueueKind::Steer => WhenBusy::Steer,
                    QueueKind::FollowUp | QueueKind::NextRun => WhenBusy::FollowUp,
                };
                Err(SubmissionDraft::Input {
                    content: queued.message["content"].clone(),
                    when_busy: when,
                    request_id: Some(format!("{}#{attempt}", queued.entry_id)),
                })
            }
        }
    }

    fn mark_submitted(&self, entry_id: &str, id: SubmissionId) {
        if let Some(item) = sync::lock(&self.queues)
            .items
            .iter_mut()
            .find(|q| q.entry_id == entry_id)
        {
            item.submission = Some(id);
        }
    }

    /// Move the queued messages the runtime has placed (their submissions are `placed` or `done`) from the queue to
    /// `delivered` for `turn`, and return their entry ids in placement order. Matched by submission, never by text:
    /// two queued messages can say the same thing.
    fn take_placed(&self, turn: u64) -> Vec<String> {
        let waiting: Vec<(String, SubmissionId)> = sync::lock(&self.queues)
            .items
            .iter()
            .filter_map(|q| Some((q.entry_id.clone(), q.submission?)))
            .collect();
        let mut placed: Vec<(Option<durable::EntryId>, String)> = waiting
            .into_iter()
            .filter_map(|(entry_id, submission)| {
                let record = self
                    .durable
                    .chat
                    .commit(|tx| Ok(tx.submission(submission)?))
                    .ok()
                    .flatten()?;
                matches!(record.status, SubmissionStatus::Placed | SubmissionStatus::Done)
                    .then_some((record.entry, entry_id))
            })
            .collect();
        placed.sort();
        let mut queues = sync::lock(&self.queues);
        placed
            .into_iter()
            .filter_map(|(_, entry_id)| {
                let index = queues.items.iter().position(|q| q.entry_id == entry_id)?;
                let mut queued = queues.items.remove(index);
                queued.turn = turn;
                queues.delivered.push(queued);
                Some(entry_id)
            })
            .collect()
    }

    /// Take queued messages back out of the runtime's inbox (an aborted run: they wait for the user again).
    pub(super) fn withdraw_queued(&mut self, ids: &[String]) {
        let withdrawn: Vec<SubmissionId> = {
            let mut queues = sync::lock(&self.queues);
            queues
                .items
                .iter_mut()
                .filter(|q| ids.is_empty() || ids.contains(&q.entry_id))
                .filter_map(|q| q.submission.take())
                .collect()
        };
        for id in withdrawn {
            if let Ok(SubmissionAbort::NotFound) = self.durable.chat.abort_submission(id, Some(ROOT_CONVERSATION_ID)) {
                continue;
            }
        }
    }

    /// Start the durable turn of the admitted `prompt` (its transcript entry `prompt_entry`): the conversation's
    /// model, a fresh context, the prompt as input, then the queued messages behind it.
    pub(super) fn start_turn(&mut self, prompt: &Value, prompt_entry: &str) -> Result<SubmissionId, String> {
        self.durable.bridge.clear();
        self.durable.bridge.set_user_abort(false);
        let change = AgentChange {
            model: Some(Some(ModelRef::new(&self.model.provider, &self.model.id))),
            thinking_level: Some(Some(self.thinking.clone())),
        };
        self.durable.root.configure(&change).map_err(harness_error)?;
        self.durable.root.reset(None).map_err(harness_error)?;
        let draft = SubmissionDraft::Input {
            content: prompt["content"].clone(),
            when_busy: WhenBusy::FollowUp,
            request_id: Some(prompt_entry.to_string()),
        };
        // The agent loop polls steering once before its first request (`runLoop`): the first queued steer (every
        // one when steering is `all`) is placed after the prompt, in the run's first request.
        let steering: Vec<(String, SubmissionDraft)> = {
            let queues = sync::lock(&self.queues);
            let steers = queues
                .items
                .iter()
                .filter(|q| q.submission.is_none() && q.kind == QueueKind::Steer)
                .take(if queues.steering_all { usize::MAX } else { 1 })
                .cloned()
                .collect::<Vec<_>>();
            drop(queues);
            steers
                .iter()
                .filter_map(|q| self.queued_draft(q).err().map(|draft| (q.entry_id.clone(), draft)))
                .collect()
        };
        let (entries, drafts): (Vec<String>, Vec<SubmissionDraft>) = steering.into_iter().unzip();
        let submissions = self.durable.root.submit_run(draft, drafts).map_err(harness_error)?;
        let (first, steered) = submissions.split_first().ok_or("The runtime admitted no submission")?;
        for (entry_id, submission) in entries.iter().zip(steered) {
            self.mark_submitted(entry_id, submission.id);
        }
        self.submit_queued()?;
        Ok(first.id)
    }

    /// Notice when the runtime has nothing left to do for the turn.
    pub(super) fn spawn_waiter(&self) {
        let (root, stop, tx) = (self.durable.root.clone(), self.durable.stop.clone(), self.tx.clone());
        std::thread::spawn(move || {
            if root.wait_for_idle(&Ctx::with_signal(&stop)).is_ok() {
                let _ = tx.send(Input::HarnessIdle);
            }
        });
    }

    /// The runtime is idle: unless it has work again, the turn ends. What the turn started that still runs
    /// (subagents, shell jobs, detached cells) reports its end as a completion event (crate::async_events), which
    /// re-invokes the idle root as a run of its own, as the TypeScript dispatcher does.
    pub(super) fn harness_idle(&mut self) {
        if self.run.is_none() {
            return;
        }
        let live = self.durable.chat.live(ROOT_CONVERSATION_ID).unwrap_or(Value::Null);
        let queued = self
            .durable
            .chat
            .inbox(ROOT_CONVERSATION_ID)
            .map(|items| !items.is_empty())
            .unwrap_or(false);
        if !live["run"].is_null() || queued {
            self.spawn_waiter();
            return;
        }
        // The run may finish: its last checkpoint compacts first when the context crossed the threshold.
        if self.may_finish() {
            let _ = self.checkpoint_compaction();
        }
        self.run_end();
    }

    /// The run's operation is at a checkpoint that may finish it (its last answer committed without an error).
    fn may_finish(&self) -> bool {
        let Some(run) = self.run.as_ref() else {
            return false;
        };
        if run.cancelled || run.error.is_some() {
            return false;
        }
        let Some(operation) = run.journal.run().map(|r| r.operation_id().to_string()) else {
            return false;
        };
        // At the checkpoint, or in a compaction there that a dead worker left (it compacts again).
        lock_session(&self.session)
            .value(session_journal::ns::OP_STATE, &operation)
            .is_some_and(|state| {
                use session_journal::run::OpAt;
                let continuation = match OpAt::of(state) {
                    Some(OpAt::Checkpoint) => &state["continuation"],
                    Some(at) if at.is_summary() => &state["task"]["boundary"]["resumeAfter"]["continuation"],
                    _ => return false,
                };
                continuation["kind"] == "may_finish"
            })
    }

    /// The error the turn's prompt ended with when the runtime left it unanswered (faults; model errors and aborts
    /// are reported by their messages).
    pub(super) fn unanswered(&self, submission: Option<SubmissionId>) -> Option<String> {
        let submission = submission?;
        let record = self
            .durable
            .chat
            .commit(|tx| Ok(tx.submission(submission)?))
            .ok()
            .flatten()?;
        if record.status != SubmissionStatus::Unanswered {
            return None;
        }
        let reason = record.reason.clone().unwrap_or_default();
        if matches!(reason.as_str(), "aborted" | "model_error") {
            return None;
        }
        Some(
            record
                .detail
                .as_ref()
                .and_then(Value::as_str)
                .map_or(reason, str::to_string),
        )
    }

    /// The user aborted the turn: the runtime's run is aborted (off the actor thread: an abort joins the run) and
    /// the queued messages wait for the user again.
    pub(super) fn abort_turn(&mut self) {
        self.durable.bridge.set_user_abort(true);
        self.withdraw_queued(&[]);
        let chat = self.durable.chat.clone();
        std::thread::spawn(move || {
            let live = chat.live(ROOT_CONVERSATION_ID).unwrap_or(Value::Null);
            if let Some(task) = live["run"]["taskId"].as_u64() {
                let _ = chat.abort_task(durable::TaskId(task), &Ctx::background());
            }
        });
    }

    /// The branch's context entries (from the newest compaction), and how many of them come before the run in
    /// progress (`fromTipId`): the run is split by entry, so a context edit that omits or replaces an entry on
    /// either side never moves the boundary.
    fn context_entries(&self, source_tip: Option<&str>) -> Result<(Vec<Value>, usize), String> {
        // Borrowed walks: this runs before every request, and a long session's branch from the root is far larger
        // than its context (only the entries from the newest compaction are copied).
        let session = lock_session(&self.session);
        let before: std::collections::HashSet<&str> = session
            .state()
            .branch_path_refs(source_tip)?
            .into_iter()
            .filter_map(|entry| entry["id"].as_str())
            .collect();
        let entries = session_journal::context::build_context_entries(&session.branch_entry_refs(MAIN_LANE)?);
        let mut split = entries
            .iter()
            .take_while(|entry| entry["id"].as_str().is_some_and(|id| before.contains(id)))
            .count();
        // A compaction during the run: its summary and kept messages are the history, the run goes on after it.
        if split == 0 && entries.first().is_some_and(|entry| entry["type"] == "compaction") {
            split = 1;
        }
        Ok((entries, split))
    }

    /// The transcript messages of the run in progress, from its prompt, as committed: no context edits and no
    /// projected custom entries, so they match the durable runtime's own messages one to one.
    ///
    /// An error answer counts too, though it is never context: the runtime committed it as well (a retried attempt's
    /// answer commits with `assistant.retry_wait`), so a worker reopening during the wait must not take it for an
    /// answer the transcript lacks (it would commit it again and schedule another attempt).
    fn run_messages(&self, source_tip: Option<&str>) -> Result<Vec<Value>, String> {
        let (entries, split) = self.context_entries(source_tip)?;
        Ok(entries[split..]
            .iter()
            .flat_map(|entry| {
                let message = &entry["message"];
                if entry["type"] == "message" && message["role"] == "assistant" && message["stopReason"] == "error" {
                    return vec![message.clone()];
                }
                session_journal::context::entry_context_messages(entry)
            })
            .collect())
    }

    /// The branch's context messages as committed (from the newest compaction, its kept messages included).
    fn context_messages(&self, source_tip: Option<&str>) -> Result<Vec<Value>, String> {
        let (entries, _) = self.context_entries(source_tip)?;
        Ok(entries
            .iter()
            .flat_map(session_journal::context::entry_context_messages)
            .collect())
    }

    /// The request the agent loop would send now: the system message, the history before the run's prompt with
    /// its clock lines, then the run's messages; context edits applied across both, notes projected, and the notes
    /// and pinned items a compaction cut off shown again after its summary.
    fn request_messages(&self, source_tip: Option<&str>) -> Result<Vec<Message>, String> {
        let (entries, split) = self.context_entries(source_tip)?;
        let applied = session_journal::context::apply_context_edits(&entries);
        let project =
            |entries: &[Value]| session_journal::context::project_context_entries(entries, context_lane::PROJECTORS);
        let mut history = project(&applied[..split]);
        let run = project(&applied[split..]);
        if let Ok(Some(kept)) = self.context.transform_context(MAIN_LANE, &history) {
            history = kept;
        }
        // The clock lines are placed over the history and the run's first message (a compaction during the run
        // leaves the run nothing before its next answer).
        let first = run.first().cloned();
        history.extend(first.clone());
        if lane::clock_enabled(&self.env)
            && let Some(lined) = lane::with_clock_lines_in(&history, &lane::clock_zone(&self.env))
        {
            history = lined;
        }
        if first.is_some() {
            history.pop();
        }
        let mut messages: Vec<Message> = self
            .lane
            .system_message(&self.runtime.system.current())
            .into_iter()
            .collect();
        messages.extend(lane::to_llm(&history));
        messages.extend(lane::to_llm(&run));
        let started = lock_session(&self.session).metadata().created_at;
        if self.runtime.config.result_footer && started > 0 {
            lane::add_result_footers(&mut messages, started);
        }
        // Old view_image results beyond the image budget leave the request (image-budget.ts).
        crate::view_images::apply_image_budget(&mut messages, self.runtime.config.context_images);
        Ok(messages)
    }

    /// Whether the root lane's system message (the system prompt with the runtime guide, and the
    /// `rlm` tool schema) leaves the conversation room under the model's window and compaction settings.
    fn prompt_budget(&self) -> Result<(), String> {
        let Some(system) = self.lane.system_message(&self.runtime.system.current()) else {
            return Ok(());
        };
        let system = serde_json::to_value(&system).map_err(|error| error.to_string())?;
        crate::prompt_budget::check_prompt_budget(
            crate::prompt_budget::PromptSize::of(&system),
            self.model.context_window,
            &self.compaction_settings(),
            &format!("{}/{}", self.model.provider, self.model.id),
        )
    }

    /// A generation is about to request the model: the turn's `turn_start`, the user messages it takes (queued ones
    /// commit with its `assistant.ready`), and the request it sends.
    pub(super) fn generation(&mut self, users: Vec<Message>, answer: Answer<Result<GenerationStart, StartError>>) {
        let Some(run) = self.run.as_ref() else {
            return answer.give(Err(StartError::Request("No run is in progress".into())));
        };
        // The run's prompt (admitted with the run) is announced first, then the checkpoint before the request
        // compacts when due (crate::core::auto_compact).
        if run.prompt_pending {
            // The queued messages its admission placed come first, as they are on the branch (already committed).
            let (captured, run_id) = (run.captured.clone(), run.id.clone());
            for message in captured {
                self.emit(WatchEvent::MessageStart {
                    run_id: Some(run_id.clone()),
                    lane: MAIN_LANE.into(),
                    message: message.clone(),
                });
                self.emit(WatchEvent::MessageEnd {
                    run_id: Some(run_id.clone()),
                    lane: MAIN_LANE.into(),
                    message,
                });
            }
            let prompt = self.run.as_ref().map(|r| r.prompt.clone()).unwrap_or(Value::Null);
            if let Ok(message) = serde_json::from_value::<Message>(prompt) {
                self.on_agent_event(AgentEvent::MessageStart {
                    message: message.clone(),
                });
                self.on_agent_event(AgentEvent::MessageEnd { message });
            }
        }
        if let Err(error) = self.checkpoint_compaction() {
            return answer.give(Err(StartError::Checkpoint(error)));
        }
        if let Err(error) = self.prompt_budget() {
            return answer.give(Err(StartError::Checkpoint(error)));
        }
        let Some(run) = self.run.as_ref() else {
            return answer.give(Err(StartError::Request("No run is in progress".into())));
        };
        let source_tip = run.journal.run().and_then(|r| r.source_tip().map(str::to_string));
        // Placed users the transcript already holds (the prompt, or what an earlier attempt of this request took),
        // also when a compaction during the run keeps them in its retained tail (a retried request).
        let mut committed: Vec<String> = match self.context_messages(source_tip.as_deref()) {
            Ok(messages) => {
                let start = messages
                    .iter()
                    .rposition(|m| m["role"] == "assistant" || m["role"] == "toolResult")
                    .map_or(0, |i| i + 1);
                messages[start..]
                    .iter()
                    .filter(|m| m["role"] == "user")
                    .map(message_text)
                    .collect()
            }
            Err(_) => Vec::new(),
        };
        let mut fresh = Vec::new();
        for user in users {
            let text = text_of(&user);
            match committed.iter().position(|t| *t == text) {
                Some(index) => {
                    committed.remove(index);
                }
                None => fresh.push(user),
            }
        }
        let turn = self.run.as_ref().map_or(0, |r| r.turns) + 1;
        // The queued messages the runtime placed for this request are the newest fresh users, in placement order.
        let placed = self.take_placed(turn);
        let queued_from = fresh.len().saturating_sub(placed.len());
        let skip = placed.len().saturating_sub(fresh.len());
        let mut placed = placed.into_iter().skip(skip);
        self.on_agent_event(AgentEvent::TurnStart);
        for (index, message) in fresh.into_iter().enumerate() {
            let queued = if index >= queued_from { placed.next() } else { None };
            let value = super::stored(&message);
            self.on_agent_event(AgentEvent::MessageStart { message });
            self.user_message_end(value, queued);
        }
        // The root lane's context reminder follows its model and compaction settings as of this request.
        let settings = self.compaction_settings();
        self.lane.stack.context_reminders.set_limit(
            MAIN_LANE,
            crate::context_reminder::lane_limit(&self.model, settings.enabled, settings.reserve_tokens),
        );
        let start = self
            .request_messages(source_tip.as_deref())
            .map(|messages| GenerationStart { messages })
            .map_err(StartError::Request);
        if let Ok(start) = &start {
            self.observer_generation(&start.messages);
        }
        answer.give(start);
    }

    pub(super) fn on_turn(&mut self, request: Request) {
        match request {
            Request::Generation { users, answer } => self.generation(users, answer),
            Request::Event(event) => self.on_agent_event(*event),
            Request::Overflow { message, answer } => self.overflow(*message, answer),
            Request::RoundEnded { calls, failed, answer } => {
                self.turn_ended(calls, failed);
                answer.give(());
            }
        }
    }

    /// Resume the operation a dead worker left open: the run continues in the runtime (a pinned request is resent,
    /// a cell that was running reports `interrupted`), after the transcript catches up with what the runtime had
    /// committed. Returns the resumed run's id.
    pub(super) fn reopen_run(&mut self, operation_id: &str) -> Result<String, String> {
        let model = (self.model.max_tokens, self.model.context_window);
        let (mut journal, meta, state) = {
            let session = lock_session(&self.session);
            (
                RunJournal::reopen(&session, operation_id, model)?,
                session.value(OP_META, operation_id).cloned().unwrap_or(Value::Null),
                session.value(OP_STATE, operation_id).cloned().unwrap_or(Value::Null),
            )
        };
        let prompt_entry = meta["intent"]["promptEntryIds"][0]
            .as_str()
            .unwrap_or_default()
            .to_string();
        let prompt = lock_session(&self.session)
            .state()
            .entry(&prompt_entry)
            .map(|entry| entry["message"].clone())
            .unwrap_or(Value::Null);
        let cancelled = state["control"]["status"] == "cancel_requested";
        // An overflow compaction the worker died in compacts again at the next checkpoint, before the request.
        let resume_overflow = session_journal::run::Run::open_compaction(&lock_session(&self.session), operation_id)
            .filter(|open| open.reason == "overflow")
            .map(|open| open.resume_after);
        journal.ledger_counts_turns();
        let id = jsrt::random::uuid_v7(now_ms());
        let source_tip = meta["sourceTipId"].as_str().map(str::to_string);
        let unreported = journal.run().map(|r| r.unreported_calls()).unwrap_or_default();
        let submission = self
            .durable
            .chat
            .commit(|tx| Ok(tx.submission_by_request(ROOT_CONVERSATION_ID, &prompt_entry)?))
            .map_err(harness_error)?;
        self.lane.stack.agents.begin_root_turn(operation_id);
        self.durable
            .children
            .set_root(self.lane.stack.agents.usage_root_for_lane(MAIN_LANE, operation_id));
        self.branches.run_started();
        // Per-turn guard times start from zero (`fileHooks.beginTurn()` on the root lane's `run_start`).
        self.lane.stack.host.begin_turn();
        self.run = Some(Running {
            id: id.clone(),
            signal: AbortSignal::new(),
            journal,
            prompt_pending: false,
            turns: 0,
            started_tip: source_tip.clone().map_or(Value::Null, Value::from),
            error: None,
            waiter: None,
            cancelled,
            prompt: prompt.clone(),
            captured: Vec::new(),
            submission: submission.as_ref().map(|s| s.id),
            compaction_failed: false,
            resume_overflow,
            hiding: false,
            ending: false,
        });
        self.lane.stack.begin_turn();
        self.lane.stack.stats.touch();
        self.emit(WatchEvent::RunStart {
            run_id: id.clone(),
            started_at: now_ms(),
            lane: MAIN_LANE.into(),
        });
        // A prompt admitted to the transcript but not to the runtime is submitted now (idempotent by its entry).
        if submission.is_none() && !cancelled {
            self.durable.bridge.clear();
            let draft = SubmissionDraft::Input {
                content: prompt["content"].clone(),
                when_busy: WhenBusy::FollowUp,
                request_id: Some(prompt_entry.clone()),
            };
            let submitted = self.durable.root.submit(draft).map_err(harness_error)?;
            if let Some(run) = self.run.as_mut() {
                run.submission = Some(submitted.id);
            }
        } else {
            self.catch_up(source_tip.as_deref(), &unreported)?;
        }
        if !cancelled {
            self.submit_queued()?;
        }
        self.durable.chat.resume().map_err(harness_error)?;
        if cancelled {
            self.abort_turn();
        }
        self.spawn_waiter();
        Ok(id)
    }

    /// Project onto the transcript what the runtime committed for the run that the transcript does not hold yet:
    /// answers (with their tool starts), cell results, and the user messages a committed answer took. Everything
    /// goes through the actor's input in commit order, ahead of what the resumed runtime reports.
    fn catch_up(&mut self, source_tip: Option<&str>, unreported: &[String]) -> Result<(), String> {
        let entries = self.durable.root.entries().map_err(harness_error)?;
        let start = entries
            .iter()
            .rposition(|e| e.kind == harness::chat::entries::RESET)
            .map_or(0, |i| i + 1);
        let harness_messages: Vec<(String, Value)> = entries[start..]
            .iter()
            .filter_map(|e| Some((e.kind.clone(), e.model.as_ref()?.first()?.clone())))
            .collect();
        let transcript = self.run_messages(source_tip)?;
        let bridge = self.durable.bridge.clone();
        let mut position = 0;
        let mut pending_users: Vec<Message> = Vec::new();
        // The round whose answer the transcript holds: its calls, the results reported before the worker died, and
        // whether the bridge knows the round yet.
        let mut round: Option<HeldRound> = None;
        for (kind, message) in harness_messages {
            let role = message["role"].as_str().unwrap_or_default().to_string();
            let held = transcript.get(position).is_some_and(|t| t["role"] == role.as_str());
            match kind.as_str() {
                harness::chat::entries::USER => {
                    if held {
                        position += 1;
                    } else if let Ok(user) = serde_json::from_value::<Message>(message) {
                        pending_users.push(user);
                    }
                }
                harness::chat::entries::ASSISTANT => {
                    let Ok(answer) = serde_json::from_value::<ai::AssistantMessage>(message) else {
                        continue;
                    };
                    if held {
                        position += 1;
                        let calls = answer
                            .content
                            .iter()
                            .filter_map(|c| match c {
                                ai::AssistantContent::ToolCall(call) => Some((call.id.clone(), call.name.clone())),
                                _ => None,
                            })
                            .collect();
                        round = Some((calls, Vec::new()));
                        continue;
                    }
                    // The answer of a generation whose start the transcript never saw.
                    round = None;
                    bridge.request(Request::Generation {
                        users: std::mem::take(&mut pending_users),
                        answer: Answer::default(),
                    });
                    bridge.answer_committed(answer);
                }
                harness::chat::entries::TOOL_RESULT => {
                    if held {
                        position += 1;
                        continue;
                    }
                    let call_id = message["toolCallId"].as_str().unwrap_or_default().to_string();
                    if let Some((calls, mut done)) = round.take() {
                        if !unreported.contains(&call_id) {
                            // Reported before the worker died: its result is pending in the operation's batch.
                            done.push((
                                call_id,
                                AgentToolResult {
                                    content: serde_json::from_value(message["content"].clone()).unwrap_or_default(),
                                    details: message.get("details").cloned().unwrap_or_else(|| json!({})),
                                    usage: None,
                                    terminate: None,
                                },
                                message["isError"] == true,
                            ));
                            round = Some((calls, done));
                            continue;
                        }
                        bridge.resume_round(calls, done);
                    }
                    bridge.result_committed(&message);
                }
                _ => {}
            }
        }
        if let Some((calls, done)) = round.take() {
            bridge.resume_round(calls, done);
        }
        Ok(())
    }

    /// A new ownerless root conversation on the session's model, with `message` as its first input.
    pub(super) fn start_conversation(&mut self, message: &str) -> Result<Value, String> {
        let change = AgentChange {
            model: Some(Some(ModelRef::new(&self.model.provider, &self.model.id))),
            thinking_level: Some(Some(self.thinking.clone())),
        };
        let conversation = self
            .durable
            .chat
            .create_conversation(durable::ConversationOwnership::Ownerless, Some(&change))
            .map_err(harness_error)?;
        conversation
            .submit(SubmissionDraft::input(json!([{"type": "text", "text": message}])))
            .map_err(harness_error)?;
        Ok(json!({"conversationId": conversation.id.0}))
    }

    fn other_conversation(&self, id: u64) -> Result<harness::chat::Conversation, String> {
        let id = durable::ConversationId(id);
        if id == ROOT_CONVERSATION_ID {
            return Err("The session's own conversation takes prompts, not conversation inputs".into());
        }
        self.durable
            .chat
            .conversation(id)
            .map_err(harness_error)?
            .ok_or_else(|| format!("Unknown conversation {}", id.0))
    }

    pub(super) fn conversation_input(&mut self, id: u64, message: &str) -> Result<(), String> {
        self.other_conversation(id)?
            .submit(SubmissionDraft::input(json!([{"type": "text", "text": message}])))
            .map(drop)
            .map_err(harness_error)
    }

    /// A conversation as clients read it: whether it runs, and its messages' roles and texts.
    fn conversation_view(&self, conversation: &harness::chat::Conversation) -> Result<Value, String> {
        let messages: Vec<Value> = conversation
            .entries()
            .map_err(harness_error)?
            .iter()
            .filter_map(|entry| entry.model.as_ref()?.first().cloned())
            .filter(|message| matches!(message["role"].as_str(), Some("user" | "assistant" | "toolResult")))
            .map(|message| json!({"role": message["role"], "text": message_text(&message)}))
            .collect();
        let live = self.durable.chat.live(conversation.id).map_err(harness_error)?;
        let queued = !self
            .durable
            .chat
            .inbox(conversation.id)
            .map_err(harness_error)?
            .is_empty();
        Ok(json!({"id": conversation.id.0, "busy": !live["run"].is_null() || queued, "messages": messages}))
    }

    pub(super) fn conversations(&self, id: Option<u64>) -> Result<Value, String> {
        if let Some(id) = id {
            return self.conversation_view(&self.other_conversation(id)?);
        }
        let ids = self
            .durable
            .chat
            .commit(|tx| {
                let mut ids = Vec::new();
                let mut cursor: Option<durable::Cursor> = None;
                loop {
                    let page = tx.committed(|storage| {
                        storage.scan_conversations(&durable::ConversationQuery::default(), 256, cursor.as_ref())
                    })?;
                    ids.extend(
                        page.items
                            .into_iter()
                            .filter(|c| c.owner.is_none() && c.parent.is_none() && c.id != ROOT_CONVERSATION_ID)
                            .map(|c| c.id),
                    );
                    match page.next {
                        Some(next) => cursor = Some(next),
                        None => return Ok(ids),
                    }
                }
            })
            .map_err(harness_error)?;
        let mut views = Vec::new();
        for id in ids {
            if let Some(conversation) = self.durable.chat.conversation(id).map_err(harness_error)? {
                views.push(self.conversation_view(&conversation)?);
            }
        }
        Ok(json!({"conversations": views}))
    }
}