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
//! Daemon sessions whose turns an agent on an external runtime (Claude
//! Code, Antigravity) runs over ACP ([`SessionEngine::AcpSession`]). Each
//! turn is one run of the agent's process: the first starts the agent's own
//! session, which keeps the conversation, and each later one resumes it
//! (`session/resume`). Nothing runs between turns, so an unload or a daemon
//! restart needs nothing but what the turns saved.
//!
//! The session's file holds each prompt and reply, for listings, search and
//! reading. Its folder holds the agent's status, which names the agent's
//! session, and its attach journal, every turn's from its prompt, which the
//! session's feed replays as it reopens. A turn shows clients what its run
//! records, mapped as an external subagent run's is ([`ExternalEvents`]).
//!
//! The agent runs as it was bound, with its own tools, model and context:
//! Rho's tree, compaction, steering, MCP servers and hooks do not reach it
//! (see `engine.rs`). Its permission mode and model change from the next
//! turn on; the session's folder keeps them
//! ([`AGENT_SETTINGS_FILE`]). A person who attends the session answers what
//! the agent asks them (see `acp_asks.rs`). The session serves the agent
//! tools of rho's, whose calls run in the session (see `acp_tools.rs`), and
//! delivers the results of the work they start into its turns (see
//! `acp_background.rs`), and into the turns the daemon starts on its own
//! where the session's client takes them (see `acp_turns/daemon_turn.rs`).
//!
//! Its agent names no session, so rho's title agent names it from its first
//! message, as a session of rho's is named (see `session_runtime/title.rs`):
//! asked at the first prompt of a person's that the session saves while
//! loaded, on rho's model and the session's credentials, and never at a
//! turn the daemon starts. A failed turn does not ask again, as a session
//! of rho's does: what failed it was the agent, not rho's model.
use std::path::{Path, PathBuf};
use rho_protocol as wire;
use rho_sdk::{
model::{ContentBlock, Message, ModelIdentity},
CancellationToken, SessionId,
};
use rho_tools::cancellation::RunCancellation;
use tokio::sync::mpsc;
use super::{
acp_asks::{AllowedForSession, TurnAsks},
acp_background, acp_instructions,
acp_tools::{ServedTools, ToolsSetup, TurnBackground, TurnTools},
engine_replay::publish_journal,
feed::Feed,
open::Opening,
turn::{spawn_title, DaemonView, Ran},
LoadedSession,
};
use crate::{
acp_runtime::person::{Attendance, Heard, Person},
added_dirs::AddedDirs,
app::{
agent_binding::{CliRunInputs, ExternalAgent},
daemon_host::{jobs::JobRecord, wire::state_event},
prompt_content::Prompt,
session_events::{external_options, runtime_model, ExternalEvents},
session_runtime::{first_user_message, TitleJob, TitleState},
title_agent::TitleRequest,
},
cli_runtime::status_sink::RunObserver,
permission::PermissionMode,
run_artifacts::{AttachmentEvent, AttachmentReader, JournalStart, PromptRecord},
session::{Session as StoredSession, SessionEngine, SessionOrigin, SessionProvenance},
session_environment::Ambient,
subagent::{self, RunFailure, RunState, RunStatus, ATTACHMENT_FILE_NAME, RESULT_FILE_NAME},
};
mod daemon_turn;
mod unsent;
use unsent::UnsentPrompt;
/// The settings a session an agent runs keeps in its folder, which its
/// turns take over the agent's bound ones.
const AGENT_SETTINGS_FILE: &str = "settings.json";
/// What [`AGENT_SETTINGS_FILE`] keeps.
#[derive(Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
struct AgentSettings {
/// [`PermissionMode::as_str`].
#[serde(default, skip_serializing_if = "Option::is_none")]
permission_mode: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
model: Option<String>,
}
/// Who opens a session.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Opener {
/// A person, under no session-control limit.
Person,
/// An agent's session control, or a client under its limit.
SessionControl,
}
/// Opens what runs the turns of the session `opening` names, which `agent`,
/// on an external runtime, runs, as `opener` opens it, serving the agent
/// the tools `tools` sets up: a new session's file is written now. A mode
/// the agent's runtime refuses, the one it was bound in or one the session
/// keeps, is refused here, not as each turn starts.
pub(super) fn open(
opening: Opening,
agent: ExternalAgent,
opener: Opener,
tools: ToolsSetup<'_>,
) -> anyhow::Result<AcpTurns> {
let agent = agent.attended_as(attendance(&opening, opener)?);
let workspace = opening.cwd().to_path_buf();
let mut turns = match opening {
Opening::New { started_by, .. } => {
agent.admits(agent.permission_mode())?;
AcpTurns::create(
SessionId::new(),
workspace,
agent,
SessionProvenance {
origin: SessionOrigin::Daemon,
parent: None,
started_by: started_by.map(|session| session.to_string()),
},
)
}
Opening::Saved(file) => {
let engine = file
.engine()?
.ok_or_else(|| anyhow::anyhow!("the session was saved by Rho's own loop"))?;
AcpTurns::reopen(file, engine, agent)
}
Opening::Fork(_) => anyhow::bail!(
"its agent, of another runtime, keeps the conversation, which Rho cannot fork"
),
}?;
turns.tools = tools.serve(&turns.id, &turns.file, &turns.agent);
Ok(turns)
}
/// Whether a person attends the session `opening` opens, as `opener` opens
/// it: one a person opens that no session started, now or when it was
/// saved. Its agent asks that person what its policy leaves to one; nobody
/// answers in a session an agent started or opened.
fn attendance(opening: &Opening, opener: Opener) -> anyhow::Result<Attendance> {
let started = match opening {
Opening::New { started_by, .. } => started_by.is_some(),
Opening::Saved(stored) | Opening::Fork(stored) => stored.started_by()?.is_some(),
};
Ok(match (opener, started) {
(Opener::Person, false) => Attendance::Attended,
(Opener::Person, true) | (Opener::SessionControl, _) => Attendance::Unattended,
})
}
/// A loaded session an agent on an external runtime runs.
pub(super) struct AcpTurns {
id: SessionId,
workspace: PathBuf,
agent: ExternalAgent,
file: StoredSession,
/// The agent's status and attach journal.
artifacts: PathBuf,
/// The conversation the file holds: each prompt, and each reply.
history: Vec<Message>,
model: ModelIdentity,
/// The agent's own session, once a turn started one.
agent_session: Option<String>,
allowed: AllowedForSession,
/// The tools of rho's the session serves the agent, if any.
tools: Option<ServedTools>,
/// Whether the session asked rho's title agent to name it yet.
title: TitleState,
}
impl AcpTurns {
/// A new session `id` in `workspace`, from `provenance`, run by `agent`,
/// with its file written now.
pub(super) fn create(
id: SessionId,
workspace: PathBuf,
agent: ExternalAgent,
provenance: SessionProvenance,
) -> anyhow::Result<Self> {
let (file, artifacts) = StoredSession::create_on_agent(
&workspace,
id.as_str(),
(
agent.agent().id().as_str(),
&agent.agent().fingerprint().to_string(),
),
provenance,
agent.permission_mode().into(),
)?;
Ok(Self {
model: model_of(&agent),
id,
workspace,
agent,
file,
artifacts,
history: Vec::new(),
agent_session: None,
allowed: AllowedForSession::default(),
tools: None,
title: TitleState::Unasked,
})
}
/// Saved session `file`, which `engine` runs, reopened to run more
/// turns as `agent`, in the settings the session keeps: its
/// conversation, and the agent's session its last turn left.
pub(super) fn reopen(
file: StoredSession,
engine: SessionEngine,
mut agent: ExternalAgent,
) -> anyhow::Result<Self> {
let artifacts = match engine {
SessionEngine::AcpSession { artifacts, .. } => {
artifacts.directory(&crate::paths::rho_dir()?)
}
SessionEngine::Acp { .. } | SessionEngine::Unknown => {
anyhow::bail!("the session is not one an agent runs turn by turn")
}
};
let history = file
.active_display_history()?
.into_iter()
.map(|row| row.message)
.collect();
let agent_session = subagent::read_status(&artifacts.join(RESULT_FILE_NAME))
.and_then(|status| status.runtime_session_id);
restore_settings(&mut agent, &artifacts)?;
Ok(Self {
id: SessionId::from_string(file.id())?,
workspace: file.cwd().to_path_buf(),
model: model_of(&agent),
agent,
file,
artifacts,
history,
agent_session,
allowed: AllowedForSession::default(),
tools: None,
title: TitleState::Unasked,
})
}
/// Deletes the session, its file and the agent's artifacts, as for a
/// new session whose open was refused.
pub(super) fn discard(self) {
let id = self.id.clone();
// Its lease goes with it, so the delete takes the file.
drop(self);
if let Err(error) = StoredSession::delete_exact(id.as_str()) {
tracing::warn!(
session = %id,
error = format!("{error:#}"),
"could not delete a session whose open was refused"
);
}
}
pub(super) fn session_id(&self) -> &SessionId {
&self.id
}
/// The tools of rho's the session serves the agent, if any.
pub(super) fn served(&self) -> Option<&ServedTools> {
self.tools.as_ref()
}
/// [`Self::served`], to change them.
pub(super) fn served_mut(&mut self) -> Option<&mut ServedTools> {
self.tools.as_mut()
}
/// Stops what the tools the session serves the agent started.
pub(super) async fn shutdown(self) {
if let Some(tools) = self.tools {
tools.shutdown().await;
}
}
pub(super) fn workspace(&self) -> &Path {
&self.workspace
}
pub(super) fn agent_id(&self) -> &str {
self.agent.agent().id().as_str()
}
/// The runtime the agent runs on.
pub(super) fn runtime(&self) -> crate::agent::AgentRuntime {
self.agent.agent().definition().runtime.runtime()
}
/// The options the session shows: the agent's model, and its mode
/// among those its runtime's fence takes.
pub(super) fn options(&self) -> wire::SessionOptions {
let identity = self.agent.agent().artifact_identity();
let mut options = external_options(
&identity.provider,
identity.model.as_deref(),
self.agent.permission_mode().into(),
);
options.permission_mode.available = self
.agent
.permission_modes()
.into_iter()
.map(wire::PermissionMode::from)
.collect();
options
}
/// Runs later turns in `mode`, kept with the session; one the agent's
/// runtime refuses, or one the session could not keep, is refused, and
/// the mode stays as it was.
pub(super) fn set_permission_mode(&mut self, mode: PermissionMode) -> anyhow::Result<()> {
let mut next = self.agent.clone();
next.set_permission_mode(mode)?;
self.keep(next)
}
/// Rewires the tools the session serves its agent for its mode, with
/// the classifier models of `config`, as a client set the mode (see
/// [`ServedTools::reapply`]).
pub(super) async fn reapply_served_mode(&mut self, config: crate::config::Config) {
if let Some(tools) = &mut self.tools {
tools.reapply(self.agent.permission_mode(), config).await;
}
}
/// Runs later turns on `model`, kept with the session; one the session
/// could not keep is refused. The agent refuses a model it does not
/// offer as the next turn starts.
pub(super) fn set_model(&mut self, model: String) -> anyhow::Result<()> {
let mut next = self.agent.clone();
next.set_model(model);
self.keep(next)
}
/// Saves `agent`'s mode and model in the session's folder, then runs
/// later turns as it: a setting the folder did not take never runs.
fn keep(&mut self, agent: ExternalAgent) -> anyhow::Result<()> {
let settings = AgentSettings {
permission_mode: Some(agent.permission_mode().as_str().to_owned()),
model: agent.agent().artifact_identity().model,
};
subagent::ensure_private_directory(&self.artifacts)?;
let path = self.artifacts.join(AGENT_SETTINGS_FILE);
crate::config_writer::write_bytes_atomically(&path, &serde_json::to_vec(&settings)?)
.map_err(|error| anyhow::anyhow!("could not save {}: {error}", path.display()))?;
self.model = model_of(&agent);
self.agent = agent;
Ok(())
}
/// The feed of the session, its turns recorded on `job`: what the
/// agent showed in the turns before, from its attach journal, then how
/// the job's last turn ended, which a new session has neither of.
pub(super) fn opening_feed(&self, job: &JobRecord) -> Feed {
let last = job.moved();
let feed = Feed::new(
(&last.state).into(),
last.turn.clone(),
StoredSession::title(&self.workspace, self.id.as_str()).unwrap_or_else(|error| {
tracing::debug!(%error, "could not read the session's title");
None
}),
self.options(),
self.agent_id().to_owned(),
);
let journal = self.artifacts.join(ATTACHMENT_FILE_NAME);
if journal.exists() {
match AttachmentReader::new(journal).read_new() {
Ok(events) => publish_journal(&feed, &events),
Err(error) => tracing::warn!(
session = %self.id,
error = format!("{error:#}"),
"could not read the agent's journal; the session shows only its new turns"
),
}
}
if let (Some(outcome), Some(turn)) = (job.outcome.clone(), last.turn.clone()) {
feed.publish([
wire::SessionEvent::TurnEnded { turn, outcome },
state_event(&last),
]);
}
feed
}
/// Runs `prompt`'s turn, which `view` shows, as one run of the agent,
/// in `environment`, until it ends or `cancel` stops it.
pub(super) async fn run_turn(
&mut self,
view: &mut DaemonView,
prompt: Prompt,
environment: Ambient,
cancel: &CancellationToken,
) -> Result<Ran, wire::TurnError> {
let Prompt { person, context } = prompt;
let shown = text_of(&person)?;
let sent = text_of(&context.before(person))?;
if cancel.is_cancelled() {
return Ok(Ran::Cancelled);
}
let asked = TurnPrompt {
save: PromptSave::First(Message::user_text(&shown)),
sent,
record: PromptRecord::Shown,
};
// What the served tools' background work left rides ahead of it.
let background = self.tools.as_mut().map(ServedTools::deliver_into_turn);
self.run_asked(view, asked, background, environment, cancel)
.await
}
/// Runs `asked`'s turn, which `view` shows, as one run of the agent, in
/// `environment`, delivering `background` into it, until it ends or
/// `cancel` stops it, saving its prompt as `asked` says. A turn that
/// could not start its run, as one whose prompt the file did not take,
/// runs nothing, and puts `background`'s results back.
async fn run_asked(
&mut self,
view: &mut DaemonView,
asked: TurnPrompt,
background: Option<TurnBackground>,
environment: Ambient,
cancel: &CancellationToken,
) -> Result<Ran, wire::TurnError> {
let TurnPrompt { save, sent, record } = asked;
if let Err(error) = self.prepare(&save, &sent) {
if let (Some(tools), Some(background)) = (&mut self.tools, background) {
tools.put_back(background);
}
return Err(error);
}
// A person's prompt, saved: the session's name comes from its first.
if matches!(save, PromptSave::First(_)) {
if let Some(title) = self.request_title(&view.session).await {
spawn_title(&view.session, title);
}
}
let RunEnd { prompted, ended } = self
.run(view, sent, record, background, environment, cancel)
.await;
// The daemon's own prompt, once the agent got it, as its results.
if let (PromptSave::OnceSent(message), true) = (save, prompted) {
if let Err(error) = self.save_messages(vec![message]) {
tracing::warn!(
session = %self.id,
error = format!("{error:#}"),
"could not save the daemon's prompt to the session's file"
);
}
}
let (status, replies, left_plan_for) = ended?;
// The agent left plan mode as the person approved: so do its later
// turns, and the session's clients see it.
if let Some(mode) = left_plan_for {
if let Err(error) = self.set_permission_mode(mode) {
tracing::warn!(
session = %self.id,
error = format!("{error:#}"),
"could not keep the mode an approved plan moved the agent to"
);
}
view.session.feed.update_options(self.options());
}
if let Some(agent_session) = &status.runtime_session_id {
self.agent_session = Some(agent_session.clone());
}
// Every reply the run gave, in order: a follow-up turn the run sent
// for background results adds one after the first. The journal still
// holds the replies, which a reopen shows.
let answered: Vec<Message> = replies
.iter()
.map(|reply| Message::assistant_text(reply.as_str()))
.collect();
if let Err(error) = self.save_messages(answered) {
tracing::warn!(
session = %self.id,
error = format!("{error:#}"),
"could not save the agent's replies to the session's file"
);
}
match status.state {
// A run's status keeps its answer, not why the agent stopped.
RunState::Ok => Ok(Ran::Completed(wire::TurnOutcome::Answered {
text: status.result.unwrap_or_default(),
stop: wire::AnswerStop::EndTurn,
})),
RunState::Error => Err(wire::TurnError {
kind: match status.failure {
Some(RunFailure::ConversationNotRestored) => {
wire::TurnErrorKind::ConversationNotRestored
}
Some(RunFailure::Other) | None => wire::TurnErrorKind::Other,
},
message: status
.error
.unwrap_or_else(|| "the agent's run failed".to_owned()),
}),
// A cancel reached it, or the run returned before it ended.
RunState::Stopped | RunState::Queued | RunState::Starting | RunState::Running => {
Ok(Ran::Cancelled)
}
}
}
/// The job that names `session`, when it has yet to ask for one while
/// loaded, from the first message it saved, on the global config as it
/// is now, whose model is rho's. The job costs no model call once the
/// session has a title.
async fn request_title(&mut self, session: &LoadedSession) -> Option<TitleJob> {
if !self.title.ask() {
return None;
}
let first = first_user_message(&self.history)?;
// Fails only before any config loaded, when no session opens.
let config = session.settings.agent_config().await.ok()?;
Some(TitleJob::new(
TitleRequest {
config: (*config).clone(),
config_path: session.settings.agent_path().to_path_buf(),
cwd: self.workspace.clone(),
added_dirs: AddedDirs::default(),
environment: session.environment.clone(),
session: self.id.clone(),
input: crate::title::session_input(first),
},
self.file.id().to_owned(),
))
}
/// Readies the run of a turn whose prompt `save` says when to save and
/// whose run sends `sent`: saves a person's prompt, notes the prompt the
/// run has yet to send ([`UnsentPrompt`]), and writes the run's
/// starting status. Nothing ran if it fails.
fn prepare(&mut self, save: &PromptSave, sent: &str) -> Result<(), wire::TurnError> {
if let PromptSave::First(message) = save {
self.save_messages(vec![message.clone()])
.map_err(|error| failed(format!("could not save the prompt: {error:#}")))?;
}
subagent::ensure_private_directory(&self.artifacts)
.map_err(|error| failed(format!("could not make the agent's folder: {error}")))?;
UnsentPrompt::in_folder(&self.artifacts).track(save, sent);
subagent::initialize_status(&self.artifacts.join(RESULT_FILE_NAME), &self.started())
.map_err(|error| failed(format!("could not write the agent's status: {error}")))
}
/// The status a turn's run starts from. It keeps the agent's session
/// id, which a reopen reads from the status: a turn that ends before it
/// resumed the session must not forget it.
fn started(&self) -> RunStatus {
RunStatus {
runtime_session_id: self.agent_session.clone(),
..self.agent.agent().artifact_identity().starting_status()
}
}
/// Adds `messages` to the conversation, saved to the session's file;
/// none saves nothing. A save the file did not take leaves them out of
/// the history too, so the next save's revision still follows the
/// file's.
fn save_messages(&mut self, messages: Vec<Message>) -> anyhow::Result<()> {
if messages.is_empty() {
return Ok(());
}
let kept = self.history.len();
self.history.extend(messages.iter().cloned());
let saved = self
.file
.save_engine_history(&self.history, &messages, self.model.clone());
if saved.is_err() {
self.history.truncate(kept);
}
saved
}
/// Runs the agent once on `prompt`, which its journal records as
/// `record` says, delivering `background` into the run, showing what it
/// records and putting what it asks to the person who attends the
/// session. Its starting status is written already (see
/// [`Self::prepare`]).
async fn run(
&mut self,
view: &mut DaemonView,
prompt: String,
record: PromptRecord,
background: Option<TurnBackground>,
environment: Ambient,
cancel: &CancellationToken,
) -> RunEnd {
let output_file = self.artifacts.join(RESULT_FILE_NAME);
// Each turn after the first continues the journal.
let journal = match self.artifacts.join(ATTACHMENT_FILE_NAME).exists() {
true => JournalStart::Continue,
false => JournalStart::New,
};
let started = self.started();
let (status_tx, status) = tokio::sync::watch::channel(started.clone());
let cancellation = RunCancellation::new();
let search_path = environment.path();
let (news, mut heard) = mpsc::unbounded_channel();
let observer: Box<dyn RunObserver> = Box::new(TurnObserver {
news,
mapped: ExternalEvents::default(),
unsent: UnsentPrompt::in_folder(&self.artifacts),
});
let inputs = CliRunInputs {
prompt,
output_file,
cwd: self.workspace.clone(),
cancellation: cancellation.clone(),
status_tx: Some(status_tx),
started_status: Some(started),
environment,
};
let resume = self.agent_session.clone();
let (person, mut heard_by_person) = match self.agent.attendance() {
Attendance::Attended => {
let (person, heard) = Person::channel();
(Some(person), Some(heard))
}
Attendance::Unattended => (None, None),
};
let mut asks = TurnAsks::new(self.agent.agent().artifact_identity().runtime.as_str());
// What the served tools' background work left, and leaves while the
// turn runs, reaches the agent.
let (delivery, mailbox) = background.unzip();
let guide = match &self.tools {
Some(tools) => Some(tools.guide().await),
None => None,
};
let mode = self.agent.permission_mode();
let mut served = match &mut self.tools {
Some(tools) => Some(tools.turn(mode, search_path).await),
None => None,
};
let agent_tools = served.as_ref().map(TurnTools::agent_tools);
let mut left_plan_for = None;
let agent = &self.agent;
let artifacts = &self.artifacts;
let allowed = &mut self.allowed;
let run = async move {
let mut launch = agent.launch(inputs);
let overrides = launch.overrides_mut();
overrides.observer = Some(observer);
overrides.resume = resume;
overrides.journal = journal;
overrides.prompt_record = record;
overrides.person = person;
overrides.agent_tools = agent_tools;
let unkept = acp_instructions::instruct(&mut launch, artifacts, guide.as_ref());
if let Some(mailbox) = mailbox {
mailbox.install(&mut launch);
}
launch.run().await.map(|()| unkept)
};
let run = acp_background::alongside(delivery, run);
tokio::pin!(run);
let mut of_run = Told::default();
let mut cancelled = false;
let ran = loop {
tokio::select! {
biased;
() = cancel.cancelled(), if !cancelled => {
cancelled = true;
cancellation.cancel();
}
// Before asks: an ask names a tool call the run showed.
Some(news) = heard.recv() => of_run.show(view, news),
Some(told) = async { heard_by_person.as_mut()?.recv().await } => match told {
Heard::Asked(asked) => asks.put(&view.session, asked, allowed),
Heard::LeftPlan(mode) => left_plan_for = Some(mode),
},
Some(asked) = async { served.as_mut()?.next().await } => {
asks.put_served(&view.session, asked);
}
Some(answer) = asks.answer() => {
// The calls of rho's tools the agent makes once it
// leaves plan mode run in the mode it leaves for.
if let Some(plan) = asks.answered(answer, allowed) {
if let Some(served) = served.as_mut() {
served.leave_plan(plan.mode()).await;
}
plan.tell();
}
}
ran = &mut run => break ran,
}
};
let (ran, held) = ran;
drop(served);
if let Some(tools) = &mut self.tools {
tools.keep_notices(held);
}
// What the run recorded as it ended, and a plan exit it told the
// person of as it did; an ask still unread asks nobody now.
while let Ok(news) = heard.try_recv() {
of_run.show(view, news);
}
while let Some(Ok(told)) = heard_by_person.as_mut().map(|heard| heard.try_recv()) {
match told {
Heard::LeftPlan(mode) => left_plan_for = Some(mode),
Heard::Asked(_) => {}
}
}
let Told { replies, prompted } = of_run;
let ended = ran
.map_err(|error| failed(format!("{error:#}")))
.map(|unkept| {
let status = status.borrow().clone();
if let (RunState::Ok, Some(unkept)) = (&status.state, unkept) {
unkept.keep();
}
(status, replies, left_plan_for)
});
RunEnd { prompted, ended }
}
}
/// A turn's prompt: when the session's file saves it as the turn's user
/// message, what the agent is sent, and what the run's journal, which
/// clients see live and as it replays, records for it.
struct TurnPrompt {
save: PromptSave,
sent: String,
record: PromptRecord,
}
/// When the session's file saves a turn's prompt as its user message.
enum PromptSave {
/// Before the run, whatever the run does: a person's prompt.
First(Message),
/// Once the run sent it: the daemon's own, which a run that never sent
/// it, putting back what it carried, leaves unsaid.
OnceSent(Message),
/// Never: the file saved it with the turn a restart cut short before
/// that turn's run sent it, which this turn resends (see `unsent`).
Saved,
}
/// How a turn's run went.
struct RunEnd {
/// Whether the run sent the agent its prompt.
prompted: bool,
/// Its final status, its replies, one for each of its turns that gave
/// one, and the mode a plan the person approved moved it to; or why it
/// failed to run.
ended: Result<(RunStatus, Vec<String>, Option<PermissionMode>), wire::TurnError>,
}
/// What a turn's run tells the turn as it records it.
enum TurnNews {
Shown(Vec<wire::SessionEvent>),
/// The run is about to send its prompt.
Prompted,
Replied(String),
}
/// What the turn heard of its run: the replies the run gave, and whether
/// it sent its prompt.
#[derive(Default)]
struct Told {
replies: Vec<String>,
prompted: bool,
}
impl Told {
/// Shows `news` to the turn's clients through `view`, noting each reply
/// and the prompt's going out.
fn show(&mut self, view: &mut DaemonView, news: TurnNews) {
match news {
TurnNews::Shown(events) => {
let prompt = events
.iter()
.any(|event| matches!(event, wire::SessionEvent::UserMessage { .. }));
view.inserted(&events);
view.session.feed.publish(events);
// The run recorded its prompt: the turn began.
if prompt {
view.began();
}
}
TurnNews::Prompted => {
self.prompted = true;
// A prompt the journal hides begins its turn as it goes out.
view.began();
}
TurnNews::Replied(text) => self.replies.push(text),
}
}
}
/// Hears one turn's run, on the run's own task, and tells the turn.
struct TurnObserver {
news: mpsc::UnboundedSender<TurnNews>,
mapped: ExternalEvents,
/// Cleared as the run sends its prompt, on the run's task, so a daemon
/// stopped right after still finds it cleared.
unsent: UnsentPrompt,
}
impl RunObserver for TurnObserver {
fn recorded(&mut self, event: &AttachmentEvent) {
let events = self.mapped.map(event);
if !events.is_empty() {
// The turn went away: nobody shows the run any more.
let _ = self.news.send(TurnNews::Shown(events));
}
}
fn prompting(&mut self) {
self.unsent.sent();
let _ = self.news.send(TurnNews::Prompted);
}
fn replied(&mut self, reply: &str) {
let _ = self.news.send(TurnNews::Replied(reply.to_owned()));
}
fn ended(&mut self, reply: Option<&str>) {
if let Some(reply) = reply {
let _ = self.news.send(TurnNews::Replied(reply.to_owned()));
}
}
}
/// Takes back into `agent` the settings the session's folder `artifacts`
/// keeps. It fails closed: a mode the session keeps that the agent's
/// runtime refuses now, as when nobody attends a session a person set to
/// Supervised, fails the open rather than run in a looser one, as does a
/// file that cannot be read. With no mode kept, the agent's bound mode
/// must pass its fence.
fn restore_settings(agent: &mut ExternalAgent, artifacts: &Path) -> anyhow::Result<()> {
let path = artifacts.join(AGENT_SETTINGS_FILE);
let unreadable = |error: &dyn std::fmt::Display| {
anyhow::anyhow!("could not read {}: {error}", path.display())
};
let AgentSettings {
permission_mode,
model,
} = match std::fs::read(&path) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| unreadable(&error))?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => AgentSettings::default(),
Err(error) => return Err(unreadable(&error)),
};
if let Some(model) = model {
agent.set_model(model);
}
match permission_mode {
Some(mode) => {
let mode = mode
.parse::<PermissionMode>()
.map_err(|error| unreadable(&error))?;
agent.set_permission_mode(mode).map_err(|error| {
anyhow::anyhow!(
"the session keeps the {} mode, which its agent cannot run in now: {error:#}",
mode.as_str()
)
})
}
None => agent.admits(agent.permission_mode()),
}
}
/// The text of `input`: an agent of another runtime takes text alone.
fn text_of(input: &rho_sdk::UserInput) -> Result<String, wire::TurnError> {
input
.blocks()
.iter()
.map(|block| match block {
ContentBlock::Text(text) => Ok(text.as_str()),
ContentBlock::Image(_) | ContentBlock::ToolCall(_) => Err(failed(
"an agent of another runtime takes text prompts only".to_owned(),
)),
})
.collect::<Result<Vec<_>, _>>()
.map(|texts| texts.join("\n\n"))
}
fn failed(message: String) -> wire::TurnError {
wire::TurnError {
kind: wire::TurnErrorKind::Other,
message,
}
}
/// The model the session's file records its turns on.
fn model_of(agent: &ExternalAgent) -> ModelIdentity {
let identity = agent.agent().artifact_identity();
ModelIdentity::new(
identity.provider.clone(),
identity.runtime.as_str(),
runtime_model(identity.model.as_deref()),
)
}