rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! One prompt's turn, run in a task the daemon owns, so it goes on when the
//! client that sent the prompt disconnects.
//!
//! The turn reports to a [`DaemonView`], which sends its events to the
//! session's attached clients (#1657) and opens and withdraws the session's
//! input requests as the turn asks (#1660): its job is `waiting_for_input`
//! while an approval, plan approval, or question is open, `running`
//! otherwise. A request is never denied because no client is attached.

use std::{
    future::Future,
    sync::{Arc, Weak},
    time::Duration,
};

use rho_protocol as wire;
use rho_sdk::{CancellationToken, UserInput};
use tokio::time::Instant;

use super::{
    super::{
        jobs::{JobId, JobRegistry, TurnEnd},
        wire::state_event,
    },
    budget::{self, Lending},
    cost,
    engine::Engine,
    held_context::UnsentContext,
    marks,
    opening::saved_replay,
    options::available_auths,
    start::StartedTurn,
    LoadedSession,
};
use crate::{
    app::{
        prompt_content::Prompt,
        pull_requests::unix_ms,
        session_commands::{
            self, BuiltInCommand, CommandScope, CommandSet, Hosting, PromptCommand,
        },
        session_events::{outcome, CompactionEnd},
        session_runtime::{
            model_scoped_config, CommandRejected, InsertedMessage, PromptScope, SessionRuntime,
            StartedBy, TitleJob, Turn, TurnOutcome, TurnStart, UnsavedCompaction, WorkflowStart,
        },
        workflow_cli::discover::WorkflowLaunch,
    },
    config::Config,
    session::tree::MessageKey,
};
use wake::WakePrompt;

/// How a prompt's turn began, as the request that sent the prompt, and one
/// that sends it again with its key, learn it. A turn that completed
/// `Began`. A turn the daemon's stop interrupted before it began stays
/// `Pending`: the request answers `DaemonStopping` once the stop begins.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum PromptStart {
    /// The turn has neither begun nor ended yet.
    Pending,
    /// The turn began: it saved its prompt, or, for `/compact`, its
    /// compaction started; or it must wait for capacity in the daemon-wide
    /// budget (see [`TurnTask::budget`]). It runs on.
    Began,
    /// The turn ended before it began, as this says: cancelled, timed out,
    /// or failed.
    Ended(wire::TurnOutcome),
}

/// A turn's time limit (#1669), counted from when the daemon took its
/// prompt, waiting for the session included: the limit is the caller's
/// wall clock.
#[derive(Clone, Copy, Debug)]
pub(super) struct TurnLimit {
    timeout_ms: u64,
    deadline: Instant,
}

impl TurnLimit {
    pub(super) fn starting_now(timeout_ms: u64) -> Self {
        Self {
            timeout_ms,
            deadline: Instant::now() + Duration::from_millis(timeout_ms),
        }
    }
}

/// Runs `turn` to its end, cancelling it once `limit` passes. The deadline
/// goes first, so a limit already past cancels the turn before it saves its
/// prompt. Returns, beside how it ended, the limit in milliseconds when it
/// cancelled the turn: not when a client's cancel came first and the turn
/// was still winding down at the deadline.
async fn within_limit<T>(
    session: &LoadedSession,
    limit: Option<TurnLimit>,
    cancel: &CancellationToken,
    turn: impl Future<Output = T>,
) -> (T, Option<u64>) {
    tokio::pin!(turn);
    tokio::select! {
        biased;
        timeout_ms = expired(limit) => {
            let timed_out = (!cancel.is_cancelled()).then_some(timeout_ms);
            session.cancel_turn();
            (turn.await, timed_out)
        }
        ended = &mut turn => (ended, None),
    }
}

/// Waits until `limit` passes, and returns it in milliseconds; forever
/// without one.
async fn expired(limit: Option<TurnLimit>) -> u64 {
    match limit {
        Some(TurnLimit {
            timeout_ms,
            deadline,
        }) => {
            tokio::time::sleep_until(deadline).await;
            timeout_ms
        }
        None => std::future::pending().await,
    }
}

/// The commands a daemon session runs, which its menu lists too: every
/// command a session host runs, so the TUI's own commands are the only ones
/// it refuses.
pub(in crate::app) const DAEMON_COMMANDS: CommandSet = CommandSet {
    built_ins: &[
        BuiltInCommand::Compact,
        BuiltInCommand::Init,
        BuiltInCommand::CreateAgent,
    ],
    workflows: Hosting::Runs,
    agents: Hosting::Runs,
    sessions_label: "daemon sessions",
};

/// How a prompt's turn ran, before the daemon records its end: a model
/// turn and a command that ran to its end both complete with an outcome.
pub(super) enum Ran {
    Completed(wire::TurnOutcome),
    Cancelled,
}

enum TurnInput {
    Prompt {
        input: Prompt,
        author: wire::PromptAuthor,
        /// The key the prompt's user message is saved under, if any (see
        /// [`StartedTurn::user_key`]).
        user_key: Option<MessageKey>,
    },
    /// A turn the daemon starts on its own.
    Daemon(DaemonTurn),
}

/// A turn the daemon starts on its own, with no client's prompt: what its
/// run starts from, and what clients are told as it begins. Its model input,
/// if any, is the daemon's, so clients are not shown it live as a user's
/// message: they see `notice` instead.
pub(super) struct DaemonTurn {
    pub(super) start: TurnStart,
    /// Told clients, as a notice, before the turn's run starts.
    pub(super) notice: Option<String>,
}

impl DaemonTurn {
    /// No prompt: the turn's first boundary delivers the background results
    /// that wait (see [`super::idle_wake`]), which clients see as cards. A
    /// session an agent of another runtime runs sends them as its run's
    /// prompt instead (see `acp_turns/daemon_turn.rs`).
    pub(super) fn delivery() -> Self {
        Self {
            start: TurnStart::Continue,
            notice: None,
        }
    }
}

/// One turn of a session whose job already recorded the turn's start.
pub(super) struct TurnTask {
    pub(super) session: Arc<LoadedSession>,
    /// The turn as it started: its id, its cancel, which a cancel sent for
    /// this turn trips even before the turn began its prompt, and its
    /// places in the queue on the session's runtime and, for a session
    /// another session started (#1714, see `budget`), in the daemon-wide
    /// budget's line.
    pub(super) turn: StartedTurn,
    /// Cancelled once the daemon stops: a turn cancelled then was
    /// interrupted, not cancelled by a client.
    pub(super) stopping: CancellationToken,
}

impl TurnTask {
    /// Runs the turn of `input`, which `author` sent, in a daemon task,
    /// which tells [`StartedTurn::start`] how the turn began.
    pub(super) fn spawn(self, input: Prompt, author: wire::PromptAuthor) {
        let user_key = self.turn.user_key.clone();
        tokio::spawn(self.run(TurnInput::Prompt {
            input,
            author,
            user_key,
        }));
    }

    /// Runs `turn`, which the daemon started on its own, in a daemon task.
    pub(super) fn spawn_daemon(self, turn: DaemonTurn) {
        tokio::spawn(self.run(TurnInput::Daemon(turn)));
    }

    async fn run(self, input: TurnInput) {
        let Self {
            session,
            turn:
                StartedTurn {
                    id,
                    cancel,
                    runtime,
                    budget,
                    start,
                    message,
                    user_key: _,
                    limit,
                },
            stopping,
        } = self;
        let origin = match &input {
            TurnInput::Prompt { .. } => marks::TurnOrigin::Prompt { at: unix_ms() },
            TurnInput::Daemon(_) => marks::TurnOrigin::Daemon,
        };
        // Locked for the whole turn and released only after the turn's end
        // is recorded, so the daemon's stop, which waits for the lock, finds
        // every turn it waited for recorded. Free once the session's last
        // turn recorded its end and the settings changes counted before
        // this turn started applied (see `configure`).
        let mut runtime = runtime.acquire().await;
        // Declared after the lock, so even a panic records the end (see
        // `DaemonView`'s drop) before the lock is released.
        let mut view = DaemonView::new(Arc::clone(&session), id, start, message);
        // With the limit when it cancelled the turn (see `within_limit`).
        let (ended, timed_out) = match &mut *runtime {
            // The daemon began stopping while the turn waited for the
            // runtime, behind changes or the last turn: it ends interrupted
            // without beginning its prompt, as the turns the stop stops do.
            Some(_) if stopping.is_cancelled() => (Ok(Ran::Cancelled), None),
            Some(Engine::Acp(turns)) => {
                let turn = async {
                    let Ok(slot) = budget::admit(&mut view, budget, &cancel, &stopping).await
                    else {
                        return Ok(Ran::Cancelled);
                    };
                    let environment = session.environment.current();
                    let run = async {
                        match input {
                            TurnInput::Prompt {
                                input,
                                author: wire::PromptAuthor::Person,
                                ..
                            } => turns.run_turn(&mut view, input, environment, &cancel).await,
                            TurnInput::Prompt { .. } => Err(wire::TurnError {
                                kind: wire::TurnErrorKind::Other,
                                message: client_rejected().0,
                            }),
                            // A wake's delivery, or the turn that continues
                            // one a restart interrupted, where the session's
                            // client takes the daemon's turns.
                            TurnInput::Daemon(turn) => {
                                turns
                                    .run_daemon_turn(&mut view, turn, environment, &cancel)
                                    .await
                            }
                        }
                    };
                    // Its agent makes its own model requests, so it lends
                    // its slot only while the agent waits on the served
                    // tools alone. Boxed: nested unboxed, the agent's run
                    // overflowed the daemon's worker stack ("thread
                    // 'tokio-rt-worker' has overflowed its stack") on every
                    // ACP turn in a debug build, failing 23 `daemon_cli`
                    // ACP end-to-end tests with "the prompt starts a turn:
                    // Closed".
                    let lending = Lending::WhileAgentBlocked;
                    let run = slot.run_budgeted(&session, lending, Box::pin(run));
                    tokio::pin!(run);
                    // No runtime of Rho's hears the daemon's stop
                    // (`handle.close()`), so the turn cancels its agent's
                    // run itself, and ends interrupted.
                    tokio::select! {
                        biased;
                        ended = &mut run => ended,
                        () = stopping.cancelled() => {
                            session.cancel_turn();
                            run.await
                        }
                    }
                };
                within_limit(&session, limit, &cancel, turn).await
            }
            Some(Engine::Rho(runtime)) => {
                let (ended, timed_out) = {
                    let turn = async {
                        let Ok(slot) = budget::admit(&mut view, budget, &cancel, &stopping).await
                        else {
                            return Ok(Ran::Cancelled);
                        };
                        // Global settings that changed since the last turn,
                        // or while this one waited for its slot, reach the
                        // session now, before its prompt.
                        let config = session.config_for_turn(runtime).await;
                        let turn = async {
                            match input {
                                TurnInput::Prompt {
                                    input,
                                    author,
                                    user_key,
                                } => {
                                    let prompt = PromptTurn {
                                        input,
                                        author,
                                        user_key,
                                    };
                                    run_turn(runtime, &mut view, prompt, &config, &cancel).await
                                }
                                TurnInput::Daemon(turn) => {
                                    run_daemon_turn(runtime, &mut view, turn, &config, &cancel)
                                        .await
                                }
                            }
                        };
                        slot.run_budgeted(&session, Lending::WhileWaiting, turn)
                            .await
                    };
                    within_limit(&session, limit, &cancel, turn).await
                };
                // Before the end is recorded, so the state event that
                // reports it follows the transcript's cut: a client reset
                // from then on gets the saved turn, then how it ended.
                save_transcript(&session, runtime);
                session.attach_reloaded_mcp(runtime).await;
                // The turn may have left new skills, prompts, or MCP prompts
                // behind; clients see them before they see the turn end.
                session.refresh_options(runtime, &available_auths(runtime.credentials()).await);
                wake::prompt_ended(&session, runtime, &stopping).await;
                // After the turn's last save, so the mark is not before it.
                marks::turn_ended(&session, runtime, origin);
                (
                    ended.map_err(|error| failure(&session, runtime, &error)),
                    timed_out,
                )
            }
            // Only the daemon's stop takes the runtime, after its last turn.
            None => (Ok(Ran::Cancelled), None),
        };
        let (outcome, end) = match (ended, timed_out) {
            (Ok(Ran::Completed(outcome)), _) => (Some(outcome), TurnEnd::Completed),
            // The daemon's stop already detached every client, so none
            // hears how the turn ended; the job records it interrupted.
            (Ok(Ran::Cancelled), _) if stopping.is_cancelled() => (None, TurnEnd::Interrupted),
            (Ok(Ran::Cancelled), Some(timeout_ms)) => (
                Some(wire::TurnOutcome::TimedOut { timeout_ms }),
                TurnEnd::TimedOut { timeout_ms },
            ),
            (Ok(Ran::Cancelled), None) => (Some(wire::TurnOutcome::Cancelled), TurnEnd::Cancelled),
            (Err(error), _) => {
                let (outcome, end) = failed(error);
                (Some(outcome), end)
            }
        };
        view.end(outcome, end);
    }
}

/// The error a turn that failed with `error` on `runtime` reports. Logged
/// whole, to the daemon's own log only: the error it reports hides an
/// authentication failure's text, which may echo credentials, from clients.
/// The provider's diagnostic goes to clients first if it may show; one an
/// authentication failure withholds is logged here instead, so it can be
/// read somewhere.
fn failure(
    session: &LoadedSession,
    runtime: &SessionRuntime,
    error: &anyhow::Error,
) -> wire::TurnError {
    tracing::warn!(job = %session.job, error = format!("{error:#}"), "a turn failed");
    if let Some(diagnostic) = outcome::withheld_diagnostic(error) {
        tracing::warn!(
            job = %session.job,
            diagnostic,
            "the provider's diagnostic for the failed authentication, withheld from clients"
        );
    }
    session
        .feed
        .publish(outcome::diagnostic_notice(error).map(|text| wire::SessionEvent::Notice { text }));
    client_error(session, runtime, error)
}

/// `error` on `session`'s `runtime` as clients are told it, hiding an
/// authentication failure's text, which may echo credentials.
pub(super) fn client_error(
    session: &LoadedSession,
    runtime: &SessionRuntime,
    error: &anyhow::Error,
) -> wire::TurnError {
    // The model the turn ran on, which a configure may have switched from
    // the config's.
    let model = model_scoped_config(&runtime.current_model(), &session.config());
    outcome::turn_error(error, &model)
}

/// Moves what the session saved since the last call, a turn's rows or
/// context added between turns, into its feed transcript, so a client that
/// attaches from now on replays it from the saved rows.
pub(super) fn save_transcript(session: &LoadedSession, runtime: &SessionRuntime) {
    // A turn that saved no rows stays in the buffer, as one whose rows could
    // not be read does, until a later turn saves.
    if let Some(saved) = saved_replay(&mut session.live(), runtime, &session.job) {
        session.feed.end_turn(saved);
    }
}

/// Replaces the feed's transcript with the rows the session's file replays
/// now that its conversation moved to another node of its tree, and
/// detaches the session's clients to replay it (see [`Feed::restart`]).
/// The new stream then says that the session rests with no turn to show,
/// since the job's last turn may not be part of the conversation any more
/// and its answer must not show over it, and how full the context is now.
/// The job rests idle without that turn's outcome for the same reason, so
/// a reopened session's feed neither replays the outcome nor attaches its
/// clients to the turn.
///
/// [`Feed::restart`]: super::feed::Feed::restart
pub(super) async fn restart_transcript(session: &LoadedSession, runtime: &SessionRuntime) {
    let (saved, usage) = {
        let mut live = session.live();
        live.forget_replayed();
        // The branch's own `ui` calls show its surfaces, as the replay
        // below reaches them.
        if let Some(surfaces) = runtime.tools().surfaces() {
            surfaces.reset();
        }
        (
            saved_replay(&mut live, runtime, &session.job),
            live.context_usage(runtime.context_estimate()),
        )
    };
    // The conversation moved either way, so the old transcript cannot
    // stay. Rows that could not be read leave it empty, which must not
    // read as a conversation with nothing in it.
    let unread = saved.is_none()
        && runtime
            .saved_history()
            .is_some_and(|saved| saved.display_rows().is_err());
    let usage = cost::priced(vec![usage], &session.id).await;
    // A move waits for the turn under way, so the job is at rest. Rested
    // as the feed restarts, so a client that finds the job idle in the job
    // list attaches to the new stream, idle.
    // One that could not rest, as one whose next turn began meanwhile,
    // tells where it is instead.
    session.feed.restart(saved, || {
        let moved = session
            .jobs
            .conversation_moved(&session.job)
            .inspect_err(|error| {
                tracing::warn!(job = %session.job, %error, "could not rest the job after its conversation moved");
            })
            .ok()
            .or_else(|| session.jobs.get(&session.job).map(|record| record.moved()));
        moved.map(|moved| state_event(&moved))
    });
    session.cache_warm_conversation_moved();
    let unread = unread.then(|| wire::SessionEvent::Notice {
        text: "could not read the conversation's saved rows; the next turn still continues from it"
            .into(),
    });
    session.feed.publish(usage.into_iter().chain(unread));
}

/// Runs `title`, the job naming `session`, beside its turn (see
/// [`report_title`]).
pub(super) fn spawn_title(session: &Arc<LoadedSession>, title: TitleJob) {
    tokio::spawn(report_title(
        Arc::downgrade(session),
        Arc::clone(&session.jobs),
        session.job.clone(),
        title,
    ));
}

/// Generates the title the session's first prompt asked for, which saves
/// it, and tells the session's clients (#1670). It runs beside the turn
/// and lands seconds into it; a session the daemon unloaded by then is
/// titled all the same, with no clients to tell, and its job `job` in
/// `jobs` records the title for the job list. Holds the session weakly, so
/// a pending title never keeps an unloaded session's feed alive; a session
/// reloaded once the title saved starts its feed with it, and reports it on
/// attach.
async fn report_title(
    session: Weak<LoadedSession>,
    jobs: Arc<JobRegistry>,
    job: JobId,
    title: TitleJob,
) {
    let Some(title) = title.generate().await else {
        return;
    };
    match session.upgrade() {
        Some(session) => session.retitle(title),
        None => jobs.set_title(&job, &title),
    }
}

/// A client's prompt, as its turn runs it.
struct PromptTurn {
    input: Prompt,
    author: wire::PromptAuthor,
    /// The key its user message is saved under, if any.
    user_key: Option<MessageKey>,
}

/// Begins a prompt on `runtime` and runs it: the T3 wake watcher's wait
/// when it is one, its slash command when the person's message starts with
/// one the daemon runs, else a model turn on it. The prompt's context goes
/// to the model of a model turn or an agent's, never into the shown
/// message; a prompt that runs neither holds it for the next one. A
/// command the daemon cannot run fails the turn as a configuration error
/// before the prompt is saved, as does a prompt from the client, `author`,
/// that does not start a workflow.
async fn run_turn(
    runtime: &mut SessionRuntime,
    view: &mut DaemonView,
    PromptTurn {
        input: prompt,
        author,
        user_key,
    }: PromptTurn,
    config: &Config,
    cancel: &CancellationToken,
) -> anyhow::Result<Ran> {
    let Prompt {
        person: input,
        context,
    } = prompt;
    // Back to the session, for its next prompt, unless a model turn sends it.
    let context = UnsentContext::take(&view.session, context);
    let wake_prompt = wake::prompt_started(&view.session, &input).await;
    let scope = match runtime.begin_prompt(config).await {
        Ok(scope) => scope,
        // A daemon session loads again only once the daemon unloads it.
        Err(error) if error.is::<UnsavedCompaction>() => anyhow::bail!(UNSAVED_COMPACTION),
        Err(error) => return Err(error),
    };
    if scope.attached_tool_sources() {
        view.session.tool_sources_attached(runtime).await;
    }
    if let Some(key) = user_key {
        scope.key_user_message(key);
    }
    // A cancel sent before the prompt began only tripped `cancel`: the turn
    // ends here, before it saves the prompt or calls the model, and dropping
    // `scope` ends the prompt. A cancel from here on reaches the prompt
    // through the session's handle.
    if cancel.is_cancelled() {
        return Ok(Ran::Cancelled);
    }
    let origin = match wake_prompt {
        WakePrompt::Prompt(origin) => origin,
        // The wait shows its prompt as the person's message.
        WakePrompt::Watch(_) if author != wire::PromptAuthor::Person => {
            anyhow::bail!(client_rejected())
        }
        WakePrompt::Watch(signal) => return wake::watch(view, &scope, &input, signal?).await,
    };
    let home = crate::paths::home_dir();
    let command = {
        let commands = CommandScope::of(runtime, home.as_deref(), config);
        // Expansion can wait on an MCP server, so a cancel drops it.
        tokio::select! {
            biased;
            () = scope.cancellation().cancelled() => return Ok(Ran::Cancelled),
            command = session_commands::resolve(input.clone(), &commands, DAEMON_COMMANDS) => command,
        }
    };
    let command = command?;
    if author != wire::PromptAuthor::Person && !matches!(command, PromptCommand::StartWorkflow(_)) {
        anyhow::bail!(client_rejected());
    }
    let turn = match command {
        PromptCommand::Turn {
            input: model,
            calls,
        } => Turn {
            display: input,
            model: context.send().before(wake::model_input(&origin, model)),
            calls,
        },
        PromptCommand::RunAsAgent(task) => {
            runtime.rebind_agent(&scope, &task, config).await?;
            // Events map with the agent's tools from now on, and clients
            // see the agent's options, its model among them, before its
            // turn's output.
            view.session
                .live()
                .rebind_tools(runtime.tools(), runtime.configured_context_window());
            view.session
                .refresh_options(runtime, &available_auths(runtime.credentials()).await);
            Turn {
                display: input,
                model: context.send().before(task.input),
                calls: Vec::new(),
            }
        }
        PromptCommand::Compact { instructions } => {
            return compact(runtime, view, &scope, &input, instructions).await;
        }
        PromptCommand::StartWorkflow(start) => {
            return start_workflow(runtime, view, &scope, input, author, start, config).await;
        }
    };
    // The command stays the shown message; the model gets its expansion.
    view.session.live().prompt(&turn.display);
    // A turn builds a large future; keep it on the heap.
    let ended = Box::pin(runtime.run_prompt_turn(view, &scope, turn, config)).await?;
    Ok(match ended {
        TurnOutcome::Completed(run) => Ran::Completed(outcome::finished(&run)),
        TurnOutcome::Cancelled => Ran::Cancelled,
    })
}

/// Runs `turn`, a model turn the daemon starts on its own, with normal
/// persistence, child boundary delivery, cancellation, and plan handoff.
async fn run_daemon_turn(
    runtime: &mut SessionRuntime,
    view: &mut DaemonView,
    DaemonTurn { start, notice }: DaemonTurn,
    config: &Config,
    cancel: &CancellationToken,
) -> anyhow::Result<Ran> {
    let scope = runtime.begin_prompt(config).await?;
    if scope.attached_tool_sources() {
        view.session.tool_sources_attached(runtime).await;
    }
    if cancel.is_cancelled() {
        return Ok(Ran::Cancelled);
    }
    // The turn's input is never noted as a prompt (see
    // `LiveEvents::prompt`), so clients are shown no user message for it
    // live, as for a plan's implementation turn; they see the notice. The
    // session still saves the input as the turn's user message, which a
    // later replay shows as one.
    view.session
        .feed
        .publish(notice.map(|text| wire::SessionEvent::Notice { text }));
    let ended = Box::pin(runtime.run_prompt_turn(view, &scope, start, config)).await?;
    Ok(match ended {
        TurnOutcome::Completed(run) => Ran::Completed(outcome::finished(&run)),
        TurnOutcome::Cancelled => Ran::Cancelled,
    })
}

/// Runs `/compact` within `scope`, with optional `instructions` on what to
/// keep. Clients see the command, `display`, then the compaction as a model
/// turn's automatic compaction shows (the runtime's compaction reports no
/// run events), then what it did as an agent message, which the turn
/// answers with too. Neither message is saved: the runtime saves the
/// compacted context alone, which a reload replays as its own row.
async fn compact(
    runtime: &mut SessionRuntime,
    view: &mut DaemonView,
    scope: &PromptScope,
    display: &UserInput,
    instructions: Option<String>,
) -> anyhow::Result<Ran> {
    let started = {
        let mut live = view.session.live();
        let mut shown = vec![live.shown_prompt(display, &InsertedMessage::Unreplayed)];
        shown.extend(live.compaction_started(wire::CompactionTrigger::Command));
        shown
    };
    view.inserted(&started);
    view.session.feed.publish(started);
    // Nothing rejects the command from here on; the prompt's request need
    // not wait for the compaction.
    view.began();
    let compacted = runtime.compact(scope, instructions).await;
    // A compaction that was cancelled or failed left the prefix as it was.
    if let (Ok(Some(_)), Some(keep)) = (&compacted, &view.session.cache_warm) {
        keep.prefix_rewritten();
    }
    if compacted.as_ref().is_ok_and(|outcome| {
        outcome
            .as_ref()
            .is_some_and(crate::compaction::outcome_reduced_context)
    }) {
        let mut turn = view.session.turn();
        turn.compacted_prompt = Some(turn.prompts);
    }
    let end = match &compacted {
        Ok(Some(outcome)) => CompactionEnd::Completed(outcome),
        Ok(None) => CompactionEnd::Cancelled,
        Err(error) => CompactionEnd::Failed(client_error(&view.session, runtime, error).message),
    };
    let summary = compacted
        .as_ref()
        .ok()
        .and_then(Option::as_ref)
        .map(crate::compaction::outcome_summary);
    let ended = {
        let mut live = view.session.live();
        let mut ended = live.compaction_ended(end);
        ended.extend(
            summary
                .clone()
                .map(|text| live.shown_reply(&InsertedMessage::Unreplayed, text)),
        );
        ended
    };
    let ended = cost::priced(ended, &view.session.id).await;
    view.session.feed.publish(ended);
    // A failure's error reaches clients again, redacted, in the turn's end.
    compacted?;
    Ok(match summary {
        Some(text) => Ran::Completed(wire::TurnOutcome::Answered {
            text,
            stop: wire::AnswerStop::Command,
        }),
        None => Ran::Cancelled,
    })
}

/// The refusal of a prompt from the client that does not start a workflow:
/// only a workflow start runs without the person's message, and any other
/// would reach the model, or show as the person's, without them sending it.
fn client_rejected() -> CommandRejected {
    CommandRejected("only a workflow start may come from the client".into())
}

/// Starts `launch`'s workflow run within `scope`, without a model turn. The
/// runtime saves the start's notice, after the prompt, `display`, when the
/// person sent it; clients see what was saved as a reload replays it, and
/// the turn answers with the notice. A start the client sent on the
/// person's behalf, as a workflow hub's, has no user message, as in
/// process.
async fn start_workflow(
    runtime: &mut SessionRuntime,
    view: &mut DaemonView,
    scope: &PromptScope,
    display: UserInput,
    author: wire::PromptAuthor,
    launch: WorkflowLaunch,
    config: &Config,
) -> anyhow::Result<Ran> {
    let by = match author {
        wire::PromptAuthor::Person => StartedBy::Person { display: &display },
        // `prompt` refuses an author it does not know.
        _ => StartedBy::Host,
    };
    let (notice, inserted, reply) = match runtime
        .start_workflow(scope, by, launch, config)
        .await
        // The command was refused, or failed as it started: either way no
        // model ran, and sending it again is the person's call.
        .map_err(|error| CommandRejected(format!("{error:#}")))?
    {
        WorkflowStart::Started {
            notice,
            inserted,
            reply,
        } => (notice, inserted, reply),
        WorkflowStart::Cancelled => return Ok(Ran::Cancelled),
    };
    let shown = {
        let mut live = view.session.live();
        let prompt = inserted.map(|inserted| live.shown_prompt(&display, &inserted));
        prompt
            .into_iter()
            .chain([live.shown_reply(&reply, notice.clone())])
            .collect::<Vec<_>>()
    };
    view.inserted(&shown);
    view.session.feed.publish(shown);
    view.began();
    Ok(Ran::Completed(wire::TurnOutcome::Answered {
        text: notice,
        stop: wire::AnswerStop::Command,
    }))
}

/// The outcome of a turn that failed with `error`, and the end its job
/// records: failed, with the error's message.
fn failed(error: wire::TurnError) -> (wire::TurnOutcome, TurnEnd) {
    let end = TurnEnd::Failed(error.message.clone());
    (wire::TurnOutcome::Failed { error }, end)
}

/// The message a turn records, and a prompt still waiting for it gets,
/// when its task stops without ending it.
const UNEXPECTED_STOP: &str = "the turn stopped unexpectedly; see the daemon log";

/// Why a session whose compacted context could not be saved refuses every
/// prompt, and what reloads it from its file.
const UNSAVED_COMPACTION: &str =
    "could not continue session: its compacted context was not saved; \
detach every client and wait for the daemon to unload the idle session, so the next prompt or \
attach reopens it from its file";

#[path = "turn_view.rs"]
mod view;
pub(super) use view::DaemonView;

#[path = "turn_wake.rs"]
mod wake;

#[cfg(test)]
#[path = "turn_tests.rs"]
mod tests;