1use std::path::{Path, PathBuf};
26use std::sync::Arc;
27
28use rpi_agent::AgentMessage;
29use rpi_ai::types::{AssistantMessage, Content, ImageContent, Usage};
30use rpi_ai::{Model, ThinkingLevel};
31use rpi_harness::agent_harness::{
32 AbortReconciliation, AgentHarness, AgentLane, HarnessRunOutcome, LaneSnapshot, RunResult,
33};
34use rpi_harness::durable::{DurableActor, DurableService};
35use rpi_harness::result::{HarnessError, HarnessResult};
36use rpi_harness::session::types::{Entry, EntryOrder, EntryQuery};
37
38use crate::export::{export_session, ExportFormat};
39
40#[derive(Debug, Clone)]
42pub struct SessionDescriptor {
43 pub id: String,
44 pub name: Option<String>,
45 pub path: Option<PathBuf>,
46 pub cwd: PathBuf,
47}
48
49#[derive(Debug, Clone, Default)]
51pub struct SessionUsageStats {
52 pub message_count: u64,
53 pub total_tokens: i64,
54 pub cached_tokens: i64,
55 pub uncached_tokens: i64,
56 pub cost_total: f64,
57}
58
59impl SessionUsageStats {
60 pub fn cache_hit_ratio(&self) -> Option<f64> {
63 let input = self.cached_tokens + self.uncached_tokens;
64 if input <= 0 {
65 return None;
66 }
67 Some(self.cached_tokens as f64 / input as f64)
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct ScopedModel {
74 pub id: String,
75 pub label: String,
76}
77
78impl ScopedModel {
79 pub fn parse(raw: &str) -> Self {
82 let id = raw.trim().to_string();
83 let label = id
84 .rsplit('/')
85 .next()
86 .unwrap_or(&id)
87 .split(':')
88 .next()
89 .unwrap_or(&id)
90 .to_string();
91 Self { id, label }
92 }
93}
94
95#[derive(Clone)]
97pub struct AgentSession {
98 harness: Arc<AgentHarness>,
99 catalog: Arc<Vec<Model>>,
100 scoped_models: Arc<Vec<ScopedModel>>,
101 cwd: PathBuf,
102}
103
104impl AgentSession {
105 pub fn new(
109 harness: AgentHarness,
110 catalog: Vec<Model>,
111 scoped_models: Vec<ScopedModel>,
112 cwd: impl Into<PathBuf>,
113 ) -> Self {
114 Self {
115 harness: Arc::new(harness),
116 catalog: Arc::new(catalog),
117 scoped_models: Arc::new(scoped_models),
118 cwd: cwd.into(),
119 }
120 }
121
122 pub fn harness(&self) -> &AgentHarness {
125 &self.harness
126 }
127
128 pub fn harness_arc(&self) -> Arc<AgentHarness> {
130 Arc::clone(&self.harness)
131 }
132
133 pub fn lane(&self) -> Arc<dyn AgentLane> {
135 self.harness.lane("main")
136 }
137
138 pub fn cwd(&self) -> &Path {
140 &self.cwd
141 }
142
143 pub fn catalog(&self) -> &[Model] {
145 &self.catalog
146 }
147
148 pub fn scoped_models(&self) -> &[ScopedModel] {
150 &self.scoped_models
151 }
152
153 pub async fn prompt(&self, text: &str, images: Vec<ImageContent>) -> HarnessResult<RunResult> {
158 self.harness.prompt_text(text, images).await
159 }
160
161 pub async fn send_message(&self, message: AgentMessage) -> HarnessResult<RunResult> {
164 self.harness.prompt_message(message).await
165 }
166
167 pub async fn steer(&self, message: AgentMessage) -> HarnessResult<()> {
170 self.harness.steer(message).await?;
171 Ok(())
172 }
173
174 pub async fn follow_up(&self, message: AgentMessage) -> HarnessResult<()> {
177 self.harness.follow_up(message).await?;
178 Ok(())
179 }
180
181 pub async fn abort(&self) -> HarnessResult<()> {
183 self.harness.abort().await?;
184 Ok(())
185 }
186
187 pub async fn abort_and_reconcile(&self) -> HarnessResult<AbortReconciliation> {
191 self.lane().abort_and_reconcile().await
192 }
193
194 pub async fn model(&self) -> HarnessResult<Model> {
198 self.harness.get_model().await
199 }
200
201 pub async fn set_model(&self, model: Model) -> HarnessResult<()> {
203 self.harness.set_model(model).await
204 }
205
206 pub async fn thinking_level(&self) -> HarnessResult<ThinkingLevel> {
208 self.harness.get_thinking_level().await
209 }
210
211 pub async fn set_thinking_level(&self, level: ThinkingLevel) -> HarnessResult<()> {
213 self.harness.set_thinking_level(level).await
214 }
215
216 pub fn cycle_catalog(&self) -> Vec<Model> {
219 if self.scoped_models.is_empty() {
220 return self.catalog.to_vec();
221 }
222 let mut out = Vec::new();
223 for scoped in self.scoped_models.iter() {
224 let bare = scoped.id.split(':').next().unwrap_or(&scoped.id);
225 if let Some(model) = self.catalog.iter().find(|m| {
226 m.id == bare
227 || format!("{}/{}", m.provider, m.id) == bare
228 || format!("{}/{}", m.provider, m.id) == scoped.id
229 }) {
230 out.push(model.clone());
231 }
232 }
233 out
234 }
235
236 pub async fn compact(&self, instructions: Option<&str>) -> HarnessResult<()> {
240 self.harness.compact(instructions).await?;
241 Ok(())
242 }
243
244 pub async fn retry(&self) -> HarnessResult<Option<RunResult>> {
247 let Some(last_user) = self.last_user_message().await? else {
248 return Ok(None);
249 };
250 self.harness.prompt_message(last_user).await.map(Some)
251 }
252
253 pub async fn tip_id(&self) -> HarnessResult<Option<String>> {
257 self.harness.get_tip_id().await
258 }
259
260 pub async fn entries(&self) -> HarnessResult<Vec<Entry>> {
262 self.harness
263 .find_entries(&EntryQuery {
264 order: Some(EntryOrder::OldestFirst),
265 ..Default::default()
266 })
267 .await
268 }
269
270 pub async fn snapshot(&self) -> HarnessResult<LaneSnapshot> {
272 self.harness.snapshot().await
273 }
274
275 pub async fn history_physical_bytes(&self) -> HarnessResult<Option<u64>> {
279 let actor = DurableActor::owner("agent-session")
280 .map_err(|error| HarnessError::io(error.to_string()))?;
281 DurableService::bind(&self.harness, actor)
282 .history_physical_bytes()
283 .await
284 .map_err(|error| HarnessError::io(error.to_string()))
285 }
286
287 pub async fn name(&self) -> HarnessResult<Option<String>> {
289 self.harness.get_name().await
290 }
291
292 pub async fn set_name(&self, name: Option<&str>) -> HarnessResult<()> {
294 self.harness.set_name(name).await
295 }
296
297 pub async fn set_label(&self, target_id: &str, label: Option<&str>) -> HarnessResult<()> {
299 self.harness.set_label(target_id, label).await
300 }
301
302 pub async fn value(&self, key: &str) -> HarnessResult<Option<serde_json::Value>> {
304 let values = rpi_harness::session::SessionValues::load(self.harness.session())
305 .await
306 .map_err(|e| HarnessError::io(e.to_string()))?;
307 Ok(values.get(key).cloned())
308 }
309
310 pub async fn set_value(&self, key: &str, value: serde_json::Value) -> HarnessResult<()> {
313 let writer = rpi_harness::session::SessionValueWriter::new(self.harness.session().clone());
314 writer
315 .set(key, value)
316 .await
317 .map_err(|e| HarnessError::io(e.to_string()))?;
318 Ok(())
319 }
320
321 pub async fn usage_stats(&self) -> HarnessResult<SessionUsageStats> {
323 let stats = self.harness.get_stats().await?;
324 Ok(SessionUsageStats {
325 message_count: stats.message_count,
326 total_tokens: stats.total_tokens,
327 cached_tokens: stats.cached_tokens,
328 uncached_tokens: stats.uncached_tokens,
329 cost_total: stats.cost_total,
330 })
331 }
332
333 pub async fn total_usage(&self) -> HarnessResult<Usage> {
335 let mut total = Usage::zero();
336 for entry in self.entries().await? {
337 if let Entry::Message(me) = entry {
338 if let AgentMessage::Assistant(a) = &me.message {
339 total.input += a.usage.input;
340 total.output += a.usage.output;
341 total.cache_read += a.usage.cache_read;
342 total.cache_write += a.usage.cache_write;
343 total.total_tokens += a.usage.total_tokens;
344 }
345 }
346 }
347 Ok(total)
348 }
349
350 pub async fn last_assistant_text(&self) -> HarnessResult<Option<String>> {
353 let entries = self.entries().await?;
354 for entry in entries.into_iter().rev() {
355 if let Entry::Message(me) = entry {
356 if let AgentMessage::Assistant(a) = me.message {
357 let text = assistant_text(&a);
358 if !text.is_empty() {
359 return Ok(Some(text));
360 }
361 }
362 }
363 }
364 Ok(None)
365 }
366
367 pub async fn export_to_html(&self, path: &Path) -> HarnessResult<()> {
371 self.export(ExportFormat::Html, path).await
372 }
373
374 pub async fn export_to_jsonl(&self, path: &Path) -> HarnessResult<()> {
376 self.export(ExportFormat::Jsonl, path).await
377 }
378
379 pub async fn export_to_markdown(&self, path: &Path) -> HarnessResult<()> {
381 self.export(ExportFormat::Markdown, path).await
382 }
383
384 pub async fn export(&self, format: ExportFormat, path: &Path) -> HarnessResult<()> {
387 let target = if path.is_dir() {
388 path.join(self.default_export_file_name(format.clone()).await)
389 } else {
390 path.to_path_buf()
391 };
392 export_session(&self.harness, format, &target)
393 .await
394 .map_err(HarnessError::io)
395 }
396
397 pub async fn default_export_file_name(&self, format: ExportFormat) -> String {
399 let extension = match format {
400 ExportFormat::Markdown => "md",
401 ExportFormat::Html => "html",
402 ExportFormat::Jsonl => "jsonl",
403 };
404 let name = self.name().await.ok().flatten().unwrap_or_default();
405 if !name.is_empty() {
406 return format!("{name}.{extension}");
407 }
408 let id = self
409 .tip_id()
410 .await
411 .ok()
412 .flatten()
413 .unwrap_or_else(|| "session".to_string());
414 format!("{id}.{extension}")
415 }
416
417 pub async fn fork(&self, label: Option<&str>) -> HarnessResult<()> {
423 self.harness.navigate_tree(None, false, None, label).await?;
424 Ok(())
425 }
426
427 pub async fn result(&self, run_id: &str) -> HarnessResult<Option<RunResult>> {
430 self.harness.get_result(run_id).await
431 }
432
433 async fn last_user_message(&self) -> HarnessResult<Option<AgentMessage>> {
436 let entries = self.entries().await?;
437 for entry in entries.into_iter().rev() {
438 if let Entry::Message(me) = entry {
439 if matches!(me.message, AgentMessage::User(_)) {
440 return Ok(Some(me.message));
441 }
442 }
443 }
444 Ok(None)
445 }
446}
447
448pub fn assistant_text(message: &AssistantMessage) -> String {
451 message
452 .content
453 .iter()
454 .filter_map(|c| match c {
455 Content::Text(t) => Some(t.text.as_str()),
456 _ => None,
457 })
458 .collect::<Vec<_>>()
459 .join("\n")
460}
461
462pub fn outcome_is_completed(outcome: &HarnessRunOutcome) -> bool {
464 matches!(outcome, HarnessRunOutcome::Completed { .. })
465}
466
467#[cfg(test)]
468mod tests {
469 use super::*;
470 use rpi_ai::Api;
471 use rpi_harness::agent_harness::AgentHarness;
472 use rpi_harness::session::memory::{InMemorySessionStorage, SystemClock};
473 use rpi_harness::session::session::{DefaultIdGenerator, Session};
474 use rpi_harness::session::types::SessionMetadata;
475 use rpi_harness::types::{
476 AgentHarnessOptions, AgentHarnessResources, DrivingMode, HarnessToolExecution, RetryPolicy,
477 };
478
479 fn test_session() -> Session {
480 Session::new(
481 std::sync::Arc::new(InMemorySessionStorage::new(
482 SessionMetadata {
483 id: "s-agent-session".to_string(),
484 created_at: 0,
485 parent_session_id: None,
486 },
487 std::sync::Arc::new(SystemClock),
488 std::sync::Arc::new(DefaultIdGenerator::new()),
489 )),
490 None,
491 )
492 }
493
494 async fn test_harness() -> AgentHarness {
495 AgentHarness::create(AgentHarnessOptions {
496 model: Model::new("m", "m", Api::Faux, "faux", "http://x"),
497 thinking_level: Default::default(),
498 active_tool_names: Vec::new(),
499 tools: Vec::new(),
500 system_prompt: None,
501 resources: AgentHarnessResources::default(),
502 stream_options: Default::default(),
503 retry: RetryPolicy::default(),
504 compaction: Default::default(),
505 steering_mode: Default::default(),
506 follow_up_mode: Default::default(),
507 tool_execution: HarnessToolExecution::default(),
508 drive: DrivingMode::default(),
509 session: test_session(),
510 allow_existing_session: true,
511 require_native_durable: false,
512 models: Vec::new(),
513 to_provider_messages: None,
514 entry_projectors: Default::default(),
515 agent_emitter: None,
516 before_tool_call: None,
517 after_tool_call: None,
518 transform_context: None,
519 entry_transforms: Vec::new(),
520 provider_hooks: None,
521 })
522 .await
523 .unwrap()
524 }
525
526 #[test]
527 fn scoped_model_parses_provider_and_thinking_forms() {
528 let m = ScopedModel::parse("anthropic/claude-opus-4-8:high");
529 assert_eq!(m.id, "anthropic/claude-opus-4-8:high");
530 assert_eq!(m.label, "claude-opus-4-8");
531
532 let bare = ScopedModel::parse("gpt-5");
533 assert_eq!(bare.label, "gpt-5");
534 }
535
536 #[test]
537 fn cache_hit_ratio_is_none_without_input() {
538 let stats = SessionUsageStats::default();
539 assert!(stats.cache_hit_ratio().is_none());
540
541 let stats = SessionUsageStats {
542 cached_tokens: 75,
543 uncached_tokens: 25,
544 ..Default::default()
545 };
546 assert_eq!(stats.cache_hit_ratio(), Some(0.75));
547 }
548
549 #[test]
550 fn assistant_text_joins_text_blocks_only() {
551 let mut msg =
552 rpi_ai::types::AssistantMessage::empty(rpi_ai::Api::AnthropicMessages, "p", "m", 0);
553 msg.content = vec![
554 Content::Thinking(rpi_ai::types::ThinkingContent {
555 kind: rpi_ai::types::ThinkingContentType,
556 thinking: "hidden".into(),
557 thinking_signature: None,
558 redacted: false,
559 }),
560 Content::Text(rpi_ai::types::TextContent {
561 kind: rpi_ai::types::TextContentType,
562 text: "hello".into(),
563 text_signature: None,
564 }),
565 Content::Text(rpi_ai::types::TextContent {
566 kind: rpi_ai::types::TextContentType,
567 text: "world".into(),
568 text_signature: None,
569 }),
570 ];
571 assert_eq!(assistant_text(&msg), "hello\nworld");
572 }
573
574 #[tokio::test]
575 async fn product_layer_preserves_optional_physical_size_for_memory() {
576 let session = AgentSession::new(test_harness().await, Vec::new(), Vec::new(), ".");
577 assert_eq!(session.history_physical_bytes().await.unwrap(), None);
578 }
579
580 #[tokio::test]
581 async fn abort_and_reconcile_preserves_idle_lane_error_at_the_product_layer() {
582 let session = AgentSession::new(test_harness().await, Vec::new(), Vec::new(), ".");
583 assert!(matches!(
584 session.abort_and_reconcile().await,
585 Err(HarnessError::NoActiveRun { lane, .. }) if lane == "main"
586 ));
587 }
588
589 #[tokio::test]
590 async fn session_values_round_trip_through_the_product_layer() {
591 let session = AgentSession::new(test_harness().await, Vec::new(), Vec::new(), ".");
592 assert!(session
593 .value("display.hide_thinking")
594 .await
595 .unwrap()
596 .is_none());
597
598 session
599 .set_value("display.hide_thinking", serde_json::json!(true))
600 .await
601 .unwrap();
602 assert_eq!(
603 session.value("display.hide_thinking").await.unwrap(),
604 Some(serde_json::json!(true))
605 );
606
607 session
609 .set_value("display.hide_thinking", serde_json::json!(false))
610 .await
611 .unwrap();
612 assert_eq!(
613 session.value("display.hide_thinking").await.unwrap(),
614 Some(serde_json::json!(false))
615 );
616 }
617
618 #[tokio::test]
619 async fn usage_stats_and_snapshot_read_from_the_empty_session() {
620 let session = AgentSession::new(test_harness().await, Vec::new(), Vec::new(), ".");
621 let stats = session.usage_stats().await.unwrap();
622 assert_eq!(stats.message_count, 0);
623 assert_eq!(stats.total_tokens, 0);
624 assert!(stats.cache_hit_ratio().is_none());
625
626 let snapshot = session.snapshot().await.unwrap();
627 assert_eq!(snapshot.lane, "main");
628 assert!(snapshot.active.is_none());
629 }
630
631 #[tokio::test]
632 async fn export_writes_every_supported_format() {
633 let session = AgentSession::new(test_harness().await, Vec::new(), Vec::new(), ".");
634 let dir = tempfile::tempdir().unwrap();
635
636 for (format, ext) in [
637 (ExportFormat::Markdown, "md"),
638 (ExportFormat::Html, "html"),
639 (ExportFormat::Jsonl, "jsonl"),
640 ] {
641 let name = session.default_export_file_name(format.clone()).await;
642 assert!(name.ends_with(&format!(".{ext}")), "unexpected name {name}");
643 let path = dir.path().join(&name);
644 session.export(format, &path).await.unwrap();
645 assert!(path.exists(), "{ext} export missing at {}", path.display());
646 }
647 }
648}