Skip to main content

codetether_agent/session/
types.rs

1//! Core data types for [`Session`]: the session struct itself, its
2//! persistent metadata, and the image attachment helper used by multimodal
3//! prompts.
4
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11use crate::agent::ToolUse;
12use crate::provenance::ExecutionProvenance;
13use crate::provider::{Message, Usage};
14
15/// Default maximum agentic loop iterations when [`Session::max_steps`] is
16/// `None`.
17pub const DEFAULT_MAX_STEPS: usize = 250;
18
19/// An image attachment to include with a user message (e.g. pasted from the
20/// clipboard in the TUI).
21///
22/// # Examples
23///
24/// ```rust
25/// use codetether_agent::session::ImageAttachment;
26///
27/// let img = ImageAttachment {
28///     data_url: "data:image/png;base64,iVBORw0KGgo...".to_string(),
29///     mime_type: Some("image/png".to_string()),
30/// };
31/// assert!(img.data_url.starts_with("data:image/png;base64"));
32/// assert_eq!(img.mime_type.as_deref(), Some("image/png"));
33/// ```
34#[derive(Debug, Clone)]
35pub struct ImageAttachment {
36    /// Base64-encoded data URL, e.g. `"data:image/png;base64,iVBOR..."`.
37    pub data_url: String,
38    /// MIME type of the image, e.g. `"image/png"`.
39    pub mime_type: Option<String>,
40}
41
42/// A conversation session.
43///
44/// See the [`session`](crate::session) module docs for a usage overview.
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct Session {
47    /// UUID identifying this session on disk.
48    pub id: String,
49    /// Optional human-readable title. Auto-generated from the first user
50    /// message when absent; see [`Session::generate_title`](crate::session::Session::generate_title).
51    pub title: Option<String>,
52    /// When the session was first created.
53    pub created_at: DateTime<Utc>,
54    /// When the session was last modified.
55    pub updated_at: DateTime<Utc>,
56    /// Durable session configuration.
57    ///
58    /// Serialized *before* [`Self::messages`] so cheap workspace-match
59    /// prefiltering (see [`crate::session::header::SessionHeader`]) can
60    /// avoid lexing past the transcript.
61    pub metadata: SessionMetadata,
62    /// Name of the agent persona that owns this session.
63    pub agent: String,
64    /// Ordered conversation transcript.
65    #[serde(deserialize_with = "crate::session::tail_seed::deserialize_tail_vec")]
66    pub messages: Vec<Message>,
67    /// Per-tool-call audit records.
68    #[serde(deserialize_with = "crate::session::tail_seed::deserialize_tail_vec")]
69    pub tool_uses: Vec<ToolUse>,
70    /// Aggregate token usage across all completions in this session.
71    pub usage: Usage,
72    /// Maximum agentic loop steps. [`None`] falls back to
73    /// [`DEFAULT_MAX_STEPS`].
74    #[serde(skip)]
75    pub max_steps: Option<usize>,
76    /// Optional bus for publishing agent thinking/reasoning.
77    #[serde(skip)]
78    pub bus: Option<Arc<crate::bus::AgentBus>>,
79}
80
81/// Persistent, user-facing configuration for a [`Session`].
82#[derive(Clone, Default, Serialize, Deserialize)]
83pub struct SessionMetadata {
84    /// Workspace directory the session operates in.
85    pub directory: Option<PathBuf>,
86    /// Model selector in `"provider/model"` or `"model"` form.
87    pub model: Option<String>,
88    /// Optional snapshot of the workspace knowledge graph.
89    pub knowledge_snapshot: Option<PathBuf>,
90    /// Execution provenance for audit/traceability.
91    pub provenance: Option<ExecutionProvenance>,
92    /// When true, pending edit previews are auto-confirmed in the TUI.
93    #[serde(default)]
94    pub auto_apply_edits: bool,
95    /// When true, network-reaching tools are allowed.
96    #[serde(default)]
97    pub allow_network: bool,
98    /// When true, the TUI shows slash-command autocomplete.
99    #[serde(default = "default_slash_autocomplete")]
100    pub slash_autocomplete: bool,
101    /// When true, the CLI runs inside an isolated git worktree.
102    #[serde(default = "default_use_worktree")]
103    pub use_worktree: bool,
104    /// Whether this session has been shared publicly.
105    pub shared: bool,
106    /// Public share URL, if any.
107    pub share_url: Option<String>,
108    /// RLM (Recursive Language Model) settings active for this session.
109    ///
110    /// Seeded from [`crate::config::Config::rlm`] at session creation
111    /// (via [`crate::session::Session::apply_config`]) and persisted on
112    /// disk so subsequent runs honour the same thresholds, models, and
113    /// iteration limits. Existing sessions without this field load with
114    /// [`crate::rlm::RlmConfig::default`].
115    #[serde(default)]
116    pub rlm: crate::rlm::RlmConfig,
117    /// Pre-resolved subcall provider from
118    /// [`RlmConfig::subcall_model`](crate::rlm::RlmConfig::subcall_model).
119    ///
120    /// Not serialised — re-resolved from the provider registry each time
121    /// [`Session::apply_config`] runs. When `None`, all RLM iterations
122    /// use the root provider.
123    #[serde(skip)]
124    pub subcall_provider: Option<std::sync::Arc<dyn crate::provider::Provider>>,
125    /// Model name resolved alongside [`Self::subcall_provider`].
126    /// Not serialised.
127    #[serde(skip)]
128    pub subcall_model_name: Option<String>,
129}
130
131impl std::fmt::Debug for SessionMetadata {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        f.debug_struct("SessionMetadata")
134            .field("directory", &self.directory)
135            .field("model", &self.model)
136            .field("knowledge_snapshot", &self.knowledge_snapshot)
137            .field("provenance", &self.provenance)
138            .field("auto_apply_edits", &self.auto_apply_edits)
139            .field("allow_network", &self.allow_network)
140            .field("slash_autocomplete", &self.slash_autocomplete)
141            .field("use_worktree", &self.use_worktree)
142            .field("shared", &self.shared)
143            .field("share_url", &self.share_url)
144            .field("rlm", &self.rlm)
145            .field(
146                "subcall_provider",
147                &self.subcall_provider.as_ref().map(|_| "<provider>"),
148            )
149            .field("subcall_model_name", &self.subcall_model_name)
150            .finish()
151    }
152}
153
154fn default_slash_autocomplete() -> bool {
155    true
156}
157
158fn default_use_worktree() -> bool {
159    true
160}