use std::{
future::Future,
sync::{Arc, Weak},
time::{Duration, SystemTime},
};
use rho_protocol as wire;
use rho_sdk::{CancellationToken, RunEvent, UserInput};
use tokio::{
sync::{mpsc, watch},
time::Instant,
};
use super::{
super::jobs::TurnEnd,
budget, cost,
held_context::UnsentContext,
inputs::{Asker, Inputs},
marks,
options::available_auths,
saved_replay,
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, PlanReport, PromptScope,
SessionEvent, SessionRuntime, StartedBy, TitleJob, Turn, TurnControl, TurnIo,
TurnOutcome, TurnStart, TurnView, UnsavedCompaction, WorkflowStart,
},
workflow_cli::discover::WorkflowLaunch,
},
config::Config,
};
use wake::WakePrompt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum PromptStart {
Pending,
Began,
Ended(wire::TurnOutcome),
}
#[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),
}
}
}
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,
}
}
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",
};
pub(super) enum Ran {
Completed(wire::TurnOutcome),
Cancelled,
}
enum TurnInput {
Prompt {
input: Prompt,
author: wire::PromptAuthor,
},
Daemon(DaemonTurn),
}
pub(super) struct DaemonTurn {
pub(super) start: TurnStart,
pub(super) notice: Option<String>,
}
impl DaemonTurn {
pub(super) fn delivery() -> Self {
Self {
start: TurnStart::Continue,
notice: None,
}
}
}
pub(super) struct TurnTask {
pub(super) session: Arc<LoadedSession>,
pub(super) turn: StartedTurn,
pub(super) stopping: CancellationToken,
}
impl TurnTask {
pub(super) fn spawn(self, input: Prompt, author: wire::PromptAuthor) {
tokio::spawn(self.run(TurnInput::Prompt { input, author }));
}
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,
limit,
},
stopping,
} = self;
let origin = match &input {
TurnInput::Prompt { .. } => marks::TurnOrigin::Prompt { at: unix_ms() },
TurnInput::Daemon(_) => marks::TurnOrigin::Daemon,
};
let mut runtime = runtime.acquire().await;
let mut view = DaemonView::new(Arc::clone(&session), id, start);
let (ended, timed_out) = match &mut *runtime {
Some(_) if stopping.is_cancelled() => (Ok(Ran::Cancelled), None),
Some(runtime) => {
let (ended, timed_out) = {
let turn = async {
let Ok(slot) = budget::admit(&mut view, budget, &cancel, &stopping).await
else {
return Ok(Ran::Cancelled);
};
let config = session.config_for_turn(runtime).await;
let turn = async {
match input {
TurnInput::Prompt { input, author } => {
run_turn(runtime, &mut view, input, author, &config, &cancel)
.await
}
TurnInput::Daemon(turn) => {
run_daemon_turn(runtime, &mut view, turn, &config, &cancel)
.await
}
}
};
slot.lend_while_waiting(&session.jobs, &session.job, turn)
.await
};
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),
}
};
save_transcript(&session, runtime);
session.refresh_options(runtime, &available_auths(runtime.credentials()).await);
wake::prompt_ended(&session, runtime, &stopping).await;
marks::turn_ended(&session, runtime, origin);
(
ended.map_err(|error| failure(&session, runtime, &error)),
timed_out,
)
}
None => (Ok(Ran::Cancelled), None),
};
let (outcome, end) = match (ended, timed_out) {
(Ok(Ran::Completed(outcome)), _) => (Some(outcome), TurnEnd::Completed),
(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);
}
}
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)
}
pub(super) fn client_error(
session: &LoadedSession,
runtime: &SessionRuntime,
error: &anyhow::Error,
) -> wire::TurnError {
let model = model_scoped_config(&runtime.current_model(), &session.config());
outcome::turn_error(error, &model)
}
pub(super) fn save_transcript(session: &LoadedSession, runtime: &SessionRuntime) {
if let Some(saved) = saved_replay(&mut session.live(), runtime, &session.job) {
session.feed.end_turn(saved);
}
}
pub(super) async fn restart_transcript(session: &LoadedSession, runtime: &SessionRuntime) {
let (saved, usage) = {
let mut live = session.live();
live.forget_replayed();
if let Some(surfaces) = runtime.tools().surfaces() {
surfaces.reset();
}
(
saved_replay(&mut live, runtime, &session.job),
live.context_usage(runtime.context_estimate()),
)
};
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;
if let Err(error) = session.jobs.conversation_moved(&session.job) {
tracing::warn!(job = %session.job, %error, "could not rest the job after its conversation moved");
}
session.feed.restart(saved);
session.cache_warm_conversation_moved();
let rests = wire::SessionEvent::State {
state: wire::JobState::Idle,
turn: None,
};
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([rests].into_iter().chain(usage).chain(unread));
}
async fn report_title(session: Weak<LoadedSession>, title: TitleJob) {
if let Some(title) = title.generate().await {
if let Some(session) = session.upgrade() {
session
.feed
.publish([wire::SessionEvent::TitleChanged { title }]);
}
}
}
async fn run_turn(
runtime: &mut SessionRuntime,
view: &mut DaemonView,
prompt: Prompt,
author: wire::PromptAuthor,
config: &Config,
cancel: &CancellationToken,
) -> anyhow::Result<Ran> {
let Prompt {
person: input,
context,
} = prompt;
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,
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 cancel.is_cancelled() {
return Ok(Ran::Cancelled);
}
let origin = match wake_prompt {
WakePrompt::Prompt(origin) => origin,
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);
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?;
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;
}
};
view.session.live().prompt(&turn.display);
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,
})
}
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);
}
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,
})
}
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.session.feed.publish(started);
view.began();
let compacted = runtime.compact(scope, instructions).await;
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);
compacted?;
Ok(match summary {
Some(text) => Ran::Completed(wire::TurnOutcome::Answered {
text,
stop: wire::AnswerStop::EndTurn,
}),
None => Ran::Cancelled,
})
}
fn client_rejected() -> CommandRejected {
CommandRejected("only a workflow start may come from the client".into())
}
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 },
_ => StartedBy::Host,
};
let (notice, inserted, reply) = match runtime
.start_workflow(scope, by, launch, config)
.await
.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.session.feed.publish(shown);
view.began();
Ok(Ran::Completed(wire::TurnOutcome::Answered {
text: notice,
stop: wire::AnswerStop::EndTurn,
}))
}
fn failed(error: wire::TurnError) -> (wire::TurnOutcome, TurnEnd) {
let end = TurnEnd::Failed(error.message.clone());
(wire::TurnOutcome::Failed { error }, end)
}
const UNEXPECTED_STOP: &str = "the turn stopped unexpectedly; see the daemon log";
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";
pub(super) struct DaemonView {
pub(super) session: Arc<LoadedSession>,
turn: wire::TurnId,
start: watch::Sender<PromptStart>,
ended: bool,
}
impl DaemonView {
fn new(
session: Arc<LoadedSession>,
turn: wire::TurnId,
start: watch::Sender<PromptStart>,
) -> Self {
Self {
session,
turn,
start,
ended: false,
}
}
fn tell_start(&self, start: PromptStart) {
self.start.send_if_modified(|told| {
let first = *told == PromptStart::Pending;
if first {
*told = start;
}
first
});
}
fn end(mut self, outcome: Option<wire::TurnOutcome>, end: TurnEnd) {
self.finish(outcome, end);
}
fn finish(&mut self, outcome: Option<wire::TurnOutcome>, end: TurnEnd) {
let start = match end {
TurnEnd::Completed => Some(PromptStart::Began),
TurnEnd::Interrupted => None,
TurnEnd::Cancelled | TurnEnd::TimedOut { .. } | TurnEnd::Failed(_) => {
outcome.clone().map(PromptStart::Ended)
}
};
self.session.change_inputs(Inputs::withdraw_turn);
{
let _turn = self.session.turn();
if matches!(start, Some(PromptStart::Ended(_)))
&& *self.start.borrow() == PromptStart::Pending
{
self.session.peer_wake.forget();
}
self.session.end_turn(self.turn.clone(), outcome, end);
}
self.ended = true;
if let Some(wake) = &self.session.idle_wake {
wake.turn_ended();
}
if let Some(keep) = &self.session.cache_warm {
keep.turn_ended();
}
match start {
Some(PromptStart::Began) => self.began(),
Some(start @ PromptStart::Ended(_)) => self.tell_start(start),
Some(PromptStart::Pending) | None => {}
}
}
pub(super) fn began(&mut self) {
self.session.jobs.turn_began(&self.session.job, &self.turn);
self.tell_start(PromptStart::Began);
}
pub(super) fn accepted(&mut self) {
self.tell_start(PromptStart::Began);
}
async fn show(
&mut self,
mut events: mpsc::UnboundedReceiver<SessionEvent>,
control: mpsc::UnboundedSender<TurnControl>,
mut cost: cost::TurnCost,
) {
loop {
let event = if self.session.live().holds_previews() {
match tokio::time::timeout(PREVIEW_PAUSE, events.recv()).await {
Ok(event) => event,
Err(_) => {
let held = self.session.live().held_previews();
self.session.feed.publish(held);
continue;
}
}
} else {
events.recv().await
};
let event = match event {
Some(SessionEvent::TitleRequested(title)) => {
tokio::spawn(report_title(Arc::downgrade(&self.session), *title));
continue;
}
Some(event) => event,
None => break,
};
let wire = {
let mut live = self.session.live();
let mut wire = live.map(&event);
if matches!(event, SessionEvent::Run(RunEvent::UsageUpdated { .. })) {
wire.extend(live.streamed_usage());
}
wire
};
let wire = cost.priced(&event, wire, &self.session.id).await;
self.session.feed.publish(wire);
if let Some(keep) = &self.session.cache_warm {
match &event {
SessionEvent::RunStarted => keep.run_started(),
SessionEvent::Run(RunEvent::ModelCallCompleted { metrics, .. }) => {
keep.model_call_completed(metrics);
}
SessionEvent::Run(RunEvent::CompactionCompleted { .. }) => {
keep.prefix_rewritten();
}
_ => {}
}
}
if matches!(event, SessionEvent::MessageInserted(_)) {
self.began();
}
self.session.change_inputs(|inputs| {
inputs.note(Asker::Turn, &control, &event, SystemTime::now())
});
}
}
}
const PREVIEW_PAUSE: std::time::Duration = std::time::Duration::from_millis(250);
impl Drop for DaemonView {
fn drop(&mut self) {
if !self.ended {
let (outcome, end) = failed(wire::TurnError {
kind: wire::TurnErrorKind::Other,
message: UNEXPECTED_STOP.to_owned(),
});
self.finish(Some(outcome), end);
}
}
}
impl TurnView for DaemonView {
fn open_turn<'v>(
&'v mut self,
runtime: &SessionRuntime,
) -> (TurnIo, impl Future<Output = ()> + Send + use<'v>) {
let (events, event_receiver) = mpsc::unbounded_channel();
let (control_sender, control) = mpsc::unbounded_channel();
(
TurnIo { events, control },
self.show(
event_receiver,
control_sender,
cost::TurnCost::on(&runtime.current_model()),
),
)
}
fn report_plan(
&mut self,
runtime: &SessionRuntime,
_process_config: &Config,
report: PlanReport,
) -> impl Future<Output = ()> + Send {
let session = Arc::clone(&self.session);
let notice = match report {
PlanReport::Kept { notice } => Some(wire::SessionEvent::Notice { text: notice }),
PlanReport::Switched => {
session.turn().plan_switches += 1;
None
}
};
async move {
session.feed.publish(notice);
session.refresh_options(runtime, &available_auths(runtime.credentials()).await);
}
}
}
#[path = "turn_wake.rs"]
mod wake;
#[cfg(test)]
#[path = "turn_tests.rs"]
mod tests;