Skip to main content

rpi_cli/
agent_session.rs

1//! `AgentSession` — the coding-agent product layer over the harness.
2//!
3//! Mirrors the role of `packages/coding-agent/src/core/agent-session.ts`: one
4//! object the CLI/TUI holds that unifies prompt/continue, queueing,
5//! model/thinking mutation, scoped models, compaction + retry, export,
6//! session switching / fork, usage + context stats, and name/label facts.
7//!
8//! Design notes (deliberate, vs the TS original):
9//!
10//! - **Composition, not inheritance.** TS `AgentSession` *is* the harness plus
11//!   a pile of product concerns. Here [`AgentSession`] owns an `AgentHarness`
12//!   and adds the product surface; the harness stays usable on its own for
13//!   SDK consumers who do not want the product layer. This keeps the
14//!   `rpi-harness` crate free of CLI concerns (provider catalogs, settings
15//!   paths, export formats).
16//! - **Sync-friendly handles.** The TUI key loop is a blocking thread, so the
17//!   mutating surface that the loop touches (`set_thinking_level`,
18//!   `scoped_models`) works off cached state or spawns onto the runtime; the
19//!   async surface (`prompt`, `compact`, `export`) is `async fn`.
20//! - **Retry/compaction policy lives in the harness.** The session exposes
21//!   `retry()`/`compact()` as intent, and the harness applies its own
22//!   `RetryPolicy`/`CompactionSettings`. TS keeps the auto-retry driver in the
23//!   session; we keep it in the harness so non-CLI callers get it for free.
24
25use 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/// Where a session content lives — used by export naming and `--continue`.
41#[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/// A snapshot of usage + context pressure for the footer/status line.
50#[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    /// Fraction of the rolled-up input tokens that came from cache. `None` when
61    /// no input tokens have been recorded yet (avoids a bogus `0 %`).
62    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/// One scoped-model entry: the routing id plus its human label.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct ScopedModel {
74    pub id: String,
75    pub label: String,
76}
77
78impl ScopedModel {
79    /// Parse the `provider/model[:thinking]` form used by `--model` and
80    /// `settings.json#scopedModels`.
81    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/// The product-level session. Cheap to clone — the harness is behind an `Arc`.
96#[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    /// Wrap an existing harness. `catalog` is the resolved model catalog the
106    /// session may switch within; `scoped_models` is the (possibly empty)
107    /// settings-driven subset used by Ctrl+P / `/model`.
108    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    /// The wrapped harness, for the call sites (TUI drain task, extension
123    /// bridge) that already speak the harness API.
124    pub fn harness(&self) -> &AgentHarness {
125        &self.harness
126    }
127
128    /// The `Arc` handle, for spawning work onto the runtime.
129    pub fn harness_arc(&self) -> Arc<AgentHarness> {
130        Arc::clone(&self.harness)
131    }
132
133    /// The main-lane runner.
134    pub fn lane(&self) -> Arc<dyn AgentLane> {
135        self.harness.lane("main")
136    }
137
138    /// The working directory the session was opened in.
139    pub fn cwd(&self) -> &Path {
140        &self.cwd
141    }
142
143    /// The resolved model catalog.
144    pub fn catalog(&self) -> &[Model] {
145        &self.catalog
146    }
147
148    /// The active scoped-model set (`[]` → the full catalog is in play).
149    pub fn scoped_models(&self) -> &[ScopedModel] {
150        &self.scoped_models
151    }
152
153    // -- prompt / continue / queue -------------------------------------------
154
155    /// Send a prompt with optional image attachments. Mirrors TS
156    /// `AgentSession.prompt`.
157    pub async fn prompt(&self, text: &str, images: Vec<ImageContent>) -> HarnessResult<RunResult> {
158        self.harness.prompt_text(text, images).await
159    }
160
161    /// Send an already-built user message. Mirrors TS
162    /// `AgentSession.sendUserMessage`.
163    pub async fn send_message(&self, message: AgentMessage) -> HarnessResult<RunResult> {
164        self.harness.prompt_message(message).await
165    }
166
167    /// Queue a steering message for the in-flight run. Mirrors TS
168    /// `AgentSession.steer`.
169    pub async fn steer(&self, message: AgentMessage) -> HarnessResult<()> {
170        self.harness.steer(message).await?;
171        Ok(())
172    }
173
174    /// Queue a follow-up message for after the in-flight run. Mirrors TS
175    /// `AgentSession.followUp`.
176    pub async fn follow_up(&self, message: AgentMessage) -> HarnessResult<()> {
177        self.harness.follow_up(message).await?;
178        Ok(())
179    }
180
181    /// Abort the in-flight run. Mirrors TS `AgentSession.abort`.
182    pub async fn abort(&self) -> HarnessResult<()> {
183        self.harness.abort().await?;
184        Ok(())
185    }
186
187    /// Cooperatively abort the active run and reconcile its durable terminal
188    /// result before returning. This is an explicit runtime-shutdown boundary;
189    /// it does not claim process-kill or exactly-once guarantees.
190    pub async fn abort_and_reconcile(&self) -> HarnessResult<AbortReconciliation> {
191        self.lane().abort_and_reconcile().await
192    }
193
194    // -- model / thinking ----------------------------------------------------
195
196    /// The current model.
197    pub async fn model(&self) -> HarnessResult<Model> {
198        self.harness.get_model().await
199    }
200
201    /// Switch the model. Mirrors TS `AgentSession.setModel`.
202    pub async fn set_model(&self, model: Model) -> HarnessResult<()> {
203        self.harness.set_model(model).await
204    }
205
206    /// The current thinking level.
207    pub async fn thinking_level(&self) -> HarnessResult<ThinkingLevel> {
208        self.harness.get_thinking_level().await
209    }
210
211    /// Set the thinking level. Mirrors TS `AgentSession.setThinkingLevel`.
212    pub async fn set_thinking_level(&self, level: ThinkingLevel) -> HarnessResult<()> {
213        self.harness.set_thinking_level(level).await
214    }
215
216    /// The effective model cycle order: the scoped set when configured, else
217    /// the full catalog. Mirrors TS `AgentSession.getScopedModels`.
218    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    // -- compaction / retry --------------------------------------------------
237
238    /// Explicit compaction. Mirrors TS `AgentSession.compact`.
239    pub async fn compact(&self, instructions: Option<&str>) -> HarnessResult<()> {
240        self.harness.compact(instructions).await?;
241        Ok(())
242    }
243
244    /// Retry the last turn. The harness owns the retry policy; this re-runs the
245    /// last user message when one exists. Mirrors TS `AgentSession.retry`.
246    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    // -- durable reads -------------------------------------------------------
254
255    /// The current leaf entry id.
256    pub async fn tip_id(&self) -> HarnessResult<Option<String>> {
257        self.harness.get_tip_id().await
258    }
259
260    /// All entries on the session, oldest first.
261    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    /// The lane read model. Mirrors the TS runtime lane snapshot.
271    pub async fn snapshot(&self) -> HarnessResult<LaneSnapshot> {
272        self.harness.snapshot().await
273    }
274
275    /// Observe the backend's physical history size when the selected storage
276    /// exposes one. This is owner-gated and deliberately remains an optional
277    /// observation, not a memory, I/O, or compaction guarantee.
278    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    /// Name/label facts. Mirrors TS `AgentSession.setName` / `setLabel`.
288    pub async fn name(&self) -> HarnessResult<Option<String>> {
289        self.harness.get_name().await
290    }
291
292    /// Set (or clear) the session name.
293    pub async fn set_name(&self, name: Option<&str>) -> HarnessResult<()> {
294        self.harness.set_name(name).await
295    }
296
297    /// Attach (or clear) a label on an entry.
298    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    /// Read a durable session value (see `rpi_harness::session::values`).
303    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    /// Persist a durable session value (latest-wins). Used for per-session
311    /// display preferences so they survive resume.
312    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    /// Rolled-up usage + context stats for the footer.
322    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    /// The summed usage across every assistant message (for `/context`).
334    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    /// The last finalized assistant text (for `/copy`). Mirrors TS
351    /// `AgentSession.getLastAssistantText`.
352    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    // -- export --------------------------------------------------------------
368
369    /// `exportToHtml()`. Mirrors TS `AgentSession.exportToHtml`.
370    pub async fn export_to_html(&self, path: &Path) -> HarnessResult<()> {
371        self.export(ExportFormat::Html, path).await
372    }
373
374    /// `exportToJsonl()`. Mirrors TS `AgentSession.exportToJsonl`.
375    pub async fn export_to_jsonl(&self, path: &Path) -> HarnessResult<()> {
376        self.export(ExportFormat::Jsonl, path).await
377    }
378
379    /// `exportToMarkdown()` — the local `/export` default.
380    pub async fn export_to_markdown(&self, path: &Path) -> HarnessResult<()> {
381        self.export(ExportFormat::Markdown, path).await
382    }
383
384    /// Export to `format`, deriving the default filename from the session
385    /// name/leaf when `path` is a directory.
386    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    /// The filename `/export` would write for `format`.
398    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    // -- fork / tree ---------------------------------------------------------
418
419    /// Fork the session at the current leaf into a labelled branch. The
420    /// navigation machinery creates the branch; the label tags its tip.
421    /// Mirrors TS `AgentSession.fork`.
422    pub async fn fork(&self, label: Option<&str>) -> HarnessResult<()> {
423        self.harness.navigate_tree(None, false, None, label).await?;
424        Ok(())
425    }
426
427    /// Read back the terminal outcome of a run by id. Mirrors TS
428    /// `AgentSession.getResult`.
429    pub async fn result(&self, run_id: &str) -> HarnessResult<Option<RunResult>> {
430        self.harness.get_result(run_id).await
431    }
432
433    // -- internals -----------------------------------------------------------
434
435    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
448/// The finalized text of an assistant message (text blocks only), joined with
449/// blank lines. Mirrors the TS print-mode/export concat.
450pub 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
462/// Whether a run outcome is terminal (i.e. produced a final assistant message).
463pub 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        // Latest-wins.
608        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}