Skip to main content

a3s_code_core/store/
session_data.rs

1use crate::llm::{Message, TokenUsage, ToolDefinition};
2use crate::planning::Task;
3use crate::prompts::PlanningMode;
4use crate::queue::SessionQueueConfig;
5use serde::{Deserialize, Serialize};
6
7// ============================================================================
8// Serializable Session Data
9// ============================================================================
10
11/// Session state persisted with saved sessions.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
13pub enum SessionState {
14    #[default]
15    Unknown = 0,
16    Active = 1,
17    Paused = 2,
18    Completed = 3,
19    Error = 4,
20}
21
22/// Context usage statistics persisted with saved sessions.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct ContextUsage {
25    pub used_tokens: usize,
26    pub max_tokens: usize,
27    pub percent: f32,
28    pub turns: usize,
29}
30
31impl Default for ContextUsage {
32    fn default() -> Self {
33        Self {
34            used_tokens: 0,
35            max_tokens: 200_000,
36            percent: 0.0,
37            turns: 0,
38        }
39    }
40}
41
42/// Default auto-compact threshold (80% of context window).
43pub const DEFAULT_AUTO_COMPACT_THRESHOLD: f32 = 0.80;
44
45pub(crate) fn default_auto_compact_threshold() -> f32 {
46    DEFAULT_AUTO_COMPACT_THRESHOLD
47}
48
49fn is_false(value: &bool) -> bool {
50    !*value
51}
52
53/// Serializable session configuration.
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct SessionConfig {
56    pub name: String,
57    pub workspace: String,
58    pub system_prompt: Option<String>,
59    pub max_context_length: u32,
60    pub auto_compact: bool,
61    /// Context usage percentage threshold to trigger auto-compaction (0.0 - 1.0).
62    /// Only used when `auto_compact` is true. Default: 0.80 (80%).
63    #[serde(default = "default_auto_compact_threshold")]
64    pub auto_compact_threshold: f32,
65    /// Storage type for this session.
66    #[serde(default)]
67    pub storage_type: crate::config::StorageBackend,
68    /// Optional advanced queue configuration.
69    ///
70    /// Queue infrastructure is initialized only when this is set. Ordinary
71    /// sessions stay queue-free.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub queue_config: Option<SessionQueueConfig>,
74    /// Confirmation policy (optional, uses defaults if None).
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub confirmation_policy: Option<crate::hitl::ConfirmationPolicy>,
77    /// Permission policy (optional, uses defaults if None).
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub permission_policy: Option<crate::permissions::PermissionPolicy>,
80    /// Whether active skill `allowed-tools` restrict ordinary session tools.
81    #[serde(default, skip_serializing_if = "is_false")]
82    pub enforce_active_skill_tool_restrictions: bool,
83    /// Maximum sibling branches/tools to run concurrently.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub max_parallel_tasks: Option<usize>,
86    /// Automatic subagent delegation settings.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub auto_delegation: Option<crate::config::AutoDelegationConfig>,
89    /// Parent session ID (for delegated child sessions).
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub parent_id: Option<String>,
92    /// Security configuration (optional, enables security features).
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub security_config: Option<crate::security::SecurityConfig>,
95    /// Shared hook engine for lifecycle events.
96    #[serde(skip)]
97    pub hook_engine: Option<std::sync::Arc<dyn crate::hooks::HookExecutor>>,
98    /// Enable planning phase before execution.
99    #[serde(default)]
100    pub planning_mode: PlanningMode,
101    /// Enable goal tracking.
102    #[serde(default)]
103    pub goal_tracking: bool,
104    /// Exact deterministic Tool-result projection policy pinned by the host.
105    #[serde(default)]
106    pub tool_result_transform_policy: crate::tools::ToolResultTransformPolicyV1,
107}
108
109impl Default for SessionConfig {
110    fn default() -> Self {
111        Self {
112            name: String::new(),
113            workspace: String::new(),
114            system_prompt: None,
115            max_context_length: 0,
116            auto_compact: false,
117            auto_compact_threshold: DEFAULT_AUTO_COMPACT_THRESHOLD,
118            storage_type: crate::config::StorageBackend::default(),
119            queue_config: None,
120            confirmation_policy: None,
121            permission_policy: None,
122            enforce_active_skill_tool_restrictions: false,
123            max_parallel_tasks: None,
124            auto_delegation: None,
125            parent_id: None,
126            security_config: None,
127            hook_engine: None,
128            planning_mode: PlanningMode::default(),
129            goal_tracking: false,
130            tool_result_transform_policy: crate::tools::ToolResultTransformPolicyV1::default(),
131        }
132    }
133}
134
135/// Serializable session data for persistence
136///
137/// Contains only the fields that can be serialized.
138/// Non-serializable fields (event_tx, command_queue, etc.) are rebuilt on load.
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct SessionData {
141    /// Session ID
142    pub id: String,
143
144    /// Session configuration
145    pub config: SessionConfig,
146
147    /// Current state
148    pub state: SessionState,
149
150    /// Conversation history
151    pub messages: Vec<Message>,
152
153    /// Context usage statistics
154    pub context_usage: ContextUsage,
155
156    /// Total token usage
157    pub total_usage: TokenUsage,
158
159    /// Cumulative dollar cost for this session
160    #[serde(default)]
161    pub total_cost: f64,
162
163    /// Model name for cost calculation
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub model_name: Option<String>,
166
167    /// LLM cost records for this session
168    #[serde(default)]
169    pub cost_records: Vec<crate::telemetry::LlmCostRecord>,
170
171    /// Tool definitions (names only, rebuilt from executor on load)
172    pub tool_names: Vec<String>,
173
174    /// Whether thinking mode is enabled
175    pub thinking_enabled: bool,
176
177    /// Thinking budget if set
178    pub thinking_budget: Option<usize>,
179
180    /// Creation timestamp (Unix epoch seconds)
181    pub created_at: i64,
182
183    /// Last update timestamp (Unix epoch seconds)
184    pub updated_at: i64,
185
186    /// LLM configuration for per-session client (if set)
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub llm_config: Option<LlmConfigData>,
189
190    /// Task list for tracking
191    #[serde(default, alias = "todos")]
192    pub tasks: Vec<Task>,
193
194    /// Parent session ID (for delegated child sessions)
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub parent_id: Option<String>,
197
198    /// Multi-tenant identifier. The framework only transports this string;
199    /// the host decides what "tenant" means and how to
200    /// aggregate/bill on it.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub tenant_id: Option<String>,
203
204    /// Identity of the principal that triggered this session (user id,
205    /// service account, etc). Framework treats as opaque; emitted to
206    /// hooks/traces for accounting and audit.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub principal: Option<String>,
209
210    /// Logical identifier of the agent template / definition the session
211    /// was instantiated from. Lets the host aggregate sessions by
212    /// "which agent recipe" independent of the concrete session id.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub agent_template_id: Option<String>,
215
216    /// Distributed-trace correlation id. Propagated through hooks/traces
217    /// so a session's events can be joined with upstream/downstream work
218    /// in the host's observability pipeline.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub correlation_id: Option<String>,
221
222    /// Exact A3S Use cognitive-package generation bound to this session.
223    ///
224    /// The provider/lease is intentionally not serialized. A resume host must
225    /// inject a provider with this byte-equivalent binding; Code never resolves
226    /// a replacement or `latest` generation.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub cognitive_package_binding: Option<crate::cognitive_context::CognitivePackageBindingV1>,
229}
230
231/// Serializable LLM configuration
232#[derive(Debug, Clone, Serialize, Deserialize)]
233pub struct LlmConfigData {
234    pub provider: String,
235    pub model: String,
236    /// API key is NOT stored - must be provided on session resume
237    #[serde(skip_serializing, default)]
238    pub api_key: Option<String>,
239    pub base_url: Option<String>,
240}
241
242impl SessionData {
243    /// Extract tool names from definitions
244    pub fn tool_names_from_definitions(tools: &[ToolDefinition]) -> Vec<String> {
245        tools.iter().map(|t| t.name.clone()).collect()
246    }
247}