Skip to main content

vtcode_desktop_protocol/
session.rs

1//! Session lifecycle, history paging, and idle-session option DTOs.
2
3use serde::{Deserialize, Serialize};
4use vtcode_commons::history_scope::HistoryScope;
5
6/// Session execution and command confirmation policy.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "camelCase")]
9pub enum PermissionMode {
10    /// Preserve interactive confirmation for protected commands.
11    Ask,
12    /// Use the CLI's skip-confirmations behavior for commands.
13    AutoApproveCommands,
14    /// Run without the process sandbox or interactive approval prompts.
15    FullAccess,
16}
17
18impl PermissionMode {
19    /// Canonical English label shared by the CLI service and native clients.
20    #[must_use]
21    pub const fn label(self) -> &'static str {
22        match self {
23            Self::Ask => "Ask before protected actions",
24            Self::AutoApproveCommands => "Auto-approve commands",
25            Self::FullAccess => "Full access",
26        }
27    }
28
29    /// Desktop translation key for the canonical permission label.
30    #[must_use]
31    pub const fn label_key(self) -> &'static str {
32        match self {
33            Self::Ask => "app.composer.permission_ask",
34            Self::AutoApproveCommands => "app.composer.permission_auto",
35            Self::FullAccess => "app.composer.permission_full",
36        }
37    }
38
39    /// Explain the execution boundary without implying that explicit denies disappear.
40    #[must_use]
41    pub const fn description(self) -> &'static str {
42        match self {
43            Self::Ask => "Ask for approval before running protected commands.",
44            Self::AutoApproveCommands => "Skip command confirmations. Sandbox and tool authorization still apply.",
45            Self::FullAccess => "Run without the process sandbox or approval prompts. Explicit denies still apply.",
46        }
47    }
48
49    /// Desktop translation key for the permission explanation.
50    #[must_use]
51    pub const fn description_key(self) -> &'static str {
52        match self {
53            Self::Ask => "app.permissions.desc_ask",
54            Self::AutoApproveCommands => "app.permissions.desc_auto",
55            Self::FullAccess => "app.permissions.desc_full",
56        }
57    }
58}
59
60/// Runtime options exposed without credentials or complete configuration documents.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "camelCase")]
63pub struct SessionOptionsSnapshot {
64    /// Effective command confirmation policy.
65    pub permission_mode: PermissionMode,
66    /// Selected primary agent, such as build or plan.
67    pub mode: String,
68    /// Primary agents discovered by the CLI for this workspace.
69    #[serde(default)]
70    pub available_modes: Vec<AgentModeInfo>,
71    /// CLI reasoning effort identifier.
72    pub reasoning_effort: String,
73    /// Efforts supported by this exact provider/model route.
74    pub supported_efforts: Vec<String>,
75    /// Effective provider speed badge, when supported by this route.
76    pub speed: Option<String>,
77    /// Whether this exact provider/model route supports the CLI's fast setting.
78    #[serde(default)]
79    pub fast_mode_supported: bool,
80    /// Whether fast processing is currently enabled for this route.
81    #[serde(default)]
82    pub fast_mode_enabled: bool,
83    /// Label used by the CLI for the selected fast tier on this route.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub fast_mode_label: Option<String>,
86}
87
88/// Non-secret metadata for a selectable CLI primary agent.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "camelCase")]
91pub struct AgentModeInfo {
92    /// Canonical CLI primary-agent name.
93    pub name: String,
94    /// CLI display name.
95    pub display_name: String,
96    /// Short description of the agent's role.
97    pub description: String,
98}
99
100/// An explicit idle-session option change. Omitted values preserve existing choices.
101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase", deny_unknown_fields)]
103pub struct SessionOptionsSelectParams {
104    /// Change command confirmations, retaining sandbox and tool authorization.
105    pub permission_mode: Option<PermissionMode>,
106    /// Select a built-in build or plan agent.
107    pub mode: Option<String>,
108    /// Select a capability-validated reasoning effort.
109    pub reasoning_effort: Option<String>,
110    /// Select the CLI's fast processing tier for a compatible route.
111    pub fast_mode: Option<bool>,
112    /// One-shot attestation that the user completed the Full access
113    /// confirmation dialog (risk disclosure + explicit acknowledge) for this
114    /// request. Required when `permission_mode` is `FullAccess`; never
115    /// persisted, never merged into stored session options.
116    pub full_access_confirmed: Option<bool>,
117}
118
119/// Persist a built-in CLI theme selected in Desktop.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "camelCase", deny_unknown_fields)]
122pub struct ThemePreferenceSelectParams {
123    /// Built-in VT Code theme identifier.
124    pub theme: String,
125}
126
127/// A persisted session available for reload.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
129#[serde(rename_all = "camelCase")]
130pub struct SessionSummary {
131    /// Stable durable session identifier.
132    pub session_id: String,
133    /// Human-readable title when known.
134    pub title: Option<String>,
135    /// Session workspace path.
136    pub workspace: String,
137    /// Whether the last observed state was terminal.
138    pub completed: bool,
139    /// Whether this session can be continued using existing archive data.
140    pub resumable: bool,
141    /// Archive size in bytes, zero when unknown.
142    #[serde(default)]
143    pub size_bytes: u64,
144    /// Snapshot end time as unix seconds, absent when unknown.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub updated_at: Option<u64>,
147}
148
149/// Text restored from the durable message snapshot for a loaded session.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub struct SessionHistoryMessage {
153    /// Model-only context retained for archive indexing but hidden from the transcript.
154    #[serde(default)]
155    pub hidden: bool,
156    /// Stable zero-based index in the archived session snapshot.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub archive_index: Option<usize>,
159    /// Message role such as `user`, `assistant`, or `tool`.
160    pub role: String,
161    /// Recorded assistant phase, absent for older archives or non-assistant messages.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub phase: Option<String>,
164    /// Canonical event item identity, when retained in the archive.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub event_item_id: Option<String>,
167    /// Text projection of the persisted message content.
168    pub text: String,
169}
170
171/// Loaded durable session metadata and its bounded transcript projection.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(rename_all = "camelCase")]
174pub struct SessionLoadResult {
175    /// Selected session metadata.
176    pub session: SessionSummary,
177    /// Recent messages restored from the archive snapshot.
178    pub messages: Vec<SessionHistoryMessage>,
179    /// Index of the earliest restored message in the archive snapshot.
180    #[serde(default)]
181    pub history_start_index: usize,
182    /// Whether earlier archived messages can be requested.
183    #[serde(default)]
184    pub history_has_earlier: bool,
185    /// Recent file-change snapshots from canonical history, in persisted order.
186    #[serde(default, skip_serializing_if = "Vec::is_empty")]
187    pub review_items: Vec<vtcode_exec_events::ThreadItem>,
188    /// Whether bounded history projection omitted review evidence.
189    #[serde(default)]
190    pub review_history_incomplete: bool,
191    /// Recent canonical tool, command, and supporting activity snapshots.
192    #[serde(default, skip_serializing_if = "Vec::is_empty")]
193    pub activity_items: Vec<vtcode_exec_events::ThreadItem>,
194    /// Bounded cursors for archived tool output that can be loaded on demand.
195    #[serde(default, skip_serializing_if = "Vec::is_empty")]
196    pub activity_output_cursors: Vec<SessionOutputCursor>,
197    /// Whether bounded history projection omitted activity or output evidence.
198    #[serde(default)]
199    pub activity_history_incomplete: bool,
200    /// Ordered canonical event suffix for reconstructing transcript turns.
201    #[serde(default, skip_serializing_if = "Vec::is_empty")]
202    pub timeline_events: Vec<vtcode_exec_events::VersionedThreadEvent>,
203    /// Whether the event suffix omits earlier events.
204    #[serde(default)]
205    pub timeline_incomplete: bool,
206}
207
208/// Request an earlier bounded page of the selected archived conversation.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct SessionHistoryParams {
212    /// Durable session identifier.
213    pub session_id: String,
214    /// Request identity echoed by the service to reject stale pages.
215    pub request_id: String,
216    /// Exclusive end index for the page; use the earliest loaded archive index.
217    pub before_index: usize,
218    /// Number of messages requested, capped by [`MAX_SESSION_HISTORY_PAGE_MESSAGES`].
219    pub limit: usize,
220}
221
222/// One bounded earlier page from a durable conversation.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225pub struct SessionHistoryPage {
226    /// Durable session identifier that owns the page.
227    pub session_id: String,
228    /// Request identity echoed from [`SessionHistoryParams`].
229    pub request_id: String,
230    /// Index of the earliest message included in this page.
231    pub start_index: usize,
232    /// Messages in chronological order.
233    pub messages: Vec<SessionHistoryMessage>,
234    /// Whether the archive contains messages before this page.
235    pub has_earlier: bool,
236}
237
238/// One genuine user-typed prompt from a workspace session archive.
239///
240/// Mirrors the CLI history picker's archived entries: harness-generated
241/// follow-ups and enrichment wrappers are stripped server-side, so the client
242/// can merge these with the live thread without re-cleaning.
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244#[serde(rename_all = "camelCase")]
245pub struct RecentPrompt {
246    /// Cleaned user-typed prompt text.
247    pub content: String,
248    /// Durable session identifier that owns the prompt.
249    pub session_id: String,
250}
251
252/// Cursor for reading more of a restored tool-output capture.
253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255pub struct SessionOutputCursor {
256    /// Stable canonical activity item identity.
257    pub item_id: String,
258    /// Byte offset to request next; always a UTF-8 boundary for text output.
259    pub next_offset: u64,
260    /// Captured spool size observed during session restore.
261    pub total_bytes: u64,
262}
263
264/// Request one bounded page from a restored tool-output capture.
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266#[serde(rename_all = "camelCase")]
267pub struct SessionOutputReadParams {
268    /// Durable session that owns the output item.
269    pub session_id: String,
270    /// Request identity echoed by the service to reject stale pages.
271    pub request_id: String,
272    /// Stable canonical activity item identity.
273    pub item_id: String,
274    /// UTF-8 byte offset supplied by the current cursor.
275    pub offset: u64,
276}
277
278/// One bounded page from an archived tool-output capture.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(rename_all = "camelCase")]
281pub struct SessionOutputPage {
282    /// Durable session that owns the output item.
283    pub session_id: String,
284    /// Request identity echoed from [`SessionOutputReadParams`].
285    pub request_id: String,
286    /// Stable canonical activity item identity.
287    pub item_id: String,
288    /// Requested starting offset.
289    pub offset: u64,
290    /// Next UTF-8 boundary after the returned text.
291    pub next_offset: u64,
292    /// Captured spool size observed during this read.
293    pub total_bytes: u64,
294    /// Text captured in this page.
295    pub text: String,
296    /// Whether more captured bytes remain.
297    pub has_more: bool,
298}
299
300/// Parameters for creating an empty session.
301#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(rename_all = "camelCase")]
303pub struct SessionCreateParams {
304    /// Optional title shown in history.
305    pub title: Option<String>,
306}
307
308/// Parameters for loading a durable session.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310#[serde(rename_all = "camelCase")]
311pub struct SessionIdParams {
312    /// Durable session identifier.
313    pub session_id: String,
314}
315
316/// Parameters for listing recent sessions. The limit is a soft page size:
317/// omitted values keep the historical full-list behavior.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(rename_all = "camelCase")]
320pub struct SessionListParams {
321    /// Maximum sessions returned, newest first.
322    #[serde(default)]
323    pub limit: Option<usize>,
324}
325
326impl SessionListParams {
327    /// Clamp the requested limit into `1..=MAX_SESSION_LIST_LIMIT`.
328    #[must_use]
329    pub fn effective_limit(&self) -> usize {
330        self.limit.unwrap_or(MAX_SESSION_LIST_LIMIT).clamp(1, MAX_SESSION_LIST_LIMIT)
331    }
332}
333
334/// Maximum sessions returned by one `session/list` request.
335pub const MAX_SESSION_LIST_LIMIT: usize = 200;
336
337/// Parameters for listing recent cross-session prompts.
338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
339#[serde(rename_all = "camelCase", deny_unknown_fields)]
340pub struct RecentPromptsParams {
341    /// Which sessions contribute; omitted scopes to the current project.
342    #[serde(default = "default_recent_prompts_scope")]
343    pub scope: HistoryScope,
344}
345
346fn default_recent_prompts_scope() -> HistoryScope {
347    HistoryScope::Project
348}
349
350/// Maximum message count accepted by one desktop archive-history page request.
351pub const MAX_SESSION_HISTORY_PAGE_MESSAGES: usize = 160;
352
353/// Recent-prompts result. Echoes the requested scope so the client can
354/// match out-of-order responses when the scope changes mid-fetch.
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356#[serde(rename_all = "camelCase", deny_unknown_fields)]
357pub struct RecentPromptsResult {
358    /// Echo of the requested scope.
359    pub scope: HistoryScope,
360    /// Cleaned prompts, newest first, bounded by [`MAX_RECENT_PROMPTS`].
361    pub prompts: Vec<RecentPrompt>,
362}
363
364/// Maximum prompts returned by one recent-prompts request.
365pub const MAX_RECENT_PROMPTS: usize = 100;
366
367/// Maximum captured output returned by one on-demand desktop page.
368pub const MAX_SESSION_OUTPUT_PAGE_BYTES: usize = 32 * 1024;
369
370/// Marker appended while more archived tool output is available.
371pub const RESTORED_OUTPUT_TRUNCATION_SUFFIX: &str = "\n[Output truncated in restored history.]";