Skip to main content

muse_code_sdk/client/
open.rs

1//! Opening sessions over `session/start` and `session/resume`, including
2//! the per-id open count behind the fold's re-open rule.
3
4use std::future::Future;
5use std::sync::Arc;
6
7use serde::Deserialize;
8use serde_json::Value;
9
10use crate::approval::ApprovalDecisionInput;
11use crate::msp::{
12    ApprovalMode, ApprovalRequestParams, HistoryPreference, SessionConfig, SessionResumeParams,
13    SessionResumeResult, SessionStartParams, SessionStartResult,
14};
15use crate::session::{Session, SessionOpening, drop_unreadable_snapshot, resume_history_items};
16
17use super::{FacadeError, FacadeResult, MuseClient, invalid_frame, lock};
18
19/// Options for [`MuseClient::start_session`]. A field left `None` takes the
20/// server's default, except the workspace: with neither `workspace_root` nor
21/// `workspace_roots` set, the session has no workspace.
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
23pub struct StartSessionOptions {
24    /// The new session's id; the server mints one when `None`. This never
25    /// opens an existing session: an id the host already holds or has reserved
26    /// is refused.
27    pub session_id: Option<String>,
28    /// The session's working folder, as an absolute path.
29    pub workspace_root: Option<String>,
30    /// The session's workspace roots, as absolute paths; the first one is the
31    /// working folder. When `workspace_root` is also set, both must name the
32    /// same folder.
33    pub workspace_roots: Option<Vec<String>>,
34    /// The starting model.
35    pub model_id: Option<String>,
36    /// The starting provider.
37    pub provider_id: Option<String>,
38    /// The starting approval mode, one the host's configuration defines.
39    pub approval_mode: Option<ApprovalMode>,
40    /// Per-session configuration.
41    pub config: Option<SessionConfig>,
42}
43
44/// Options for [`MuseClient::resume_session`].
45#[derive(Clone, Debug, Default, PartialEq, Eq)]
46pub struct ResumeSessionOptions {
47    /// The session to load.
48    pub session_id: String,
49    /// A view cursor this client observed earlier. When set, the server
50    /// returns only what follows it.
51    pub cursor: Option<String>,
52    /// When `true`, return the session's metadata and live state without its
53    /// history; page the history separately. Defaults to `false`.
54    pub exclude_items: Option<bool>,
55    /// Which form of history to return; the server chooses when `None`. It is
56    /// a preference: the server falls back to another form when this one does
57    /// not fit its budget. Ignored when `cursor` is set or `exclude_items` is
58    /// `Some(true)`.
59    pub history: Option<HistoryPreference>,
60    /// Per-session configuration, as at start.
61    pub config: Option<SessionConfig>,
62}
63
64impl MuseClient {
65    /// Starts a new session and returns its handle once the server accepts it.
66    pub async fn start_session(&self, options: StartSessionOptions) -> FacadeResult<Session> {
67        let command_id = self.shared.mint_command_id()?;
68        // A start that names its id subscribes it too, so it is noted before
69        // sending, like a resume.
70        let named = options
71            .session_id
72            .clone()
73            .map(|id| (self.shared.note_open(&id), id));
74        let params = SessionStartParams {
75            command_id,
76            // Not exposed by the facade yet.
77            recovery_mode: None,
78            session_id: options.session_id,
79            workspace_root: options.workspace_root,
80            workspace_roots: options.workspace_roots,
81            model_id: options.model_id,
82            provider_id: options.provider_id,
83            approval_mode: options.approval_mode,
84            config: options.config,
85            // The SDK starts plain sessions; worktree starts stay
86            // an explicit experimental spelling the caller does not send.
87            worktree: None,
88            // The Rust SDK does not expose the start-time profile
89            // selection yet; the session starts under the
90            // host's default.
91            permission_profile: None,
92        };
93        let result = match self
94            .shared
95            .command::<_, SessionStartResult>("session/start", &params)
96            .await
97        {
98            Ok(result) => result,
99            Err(error) => {
100                if let Some((_, id)) = &named
101                    && matches!(error, FacadeError::Msp(_))
102                {
103                    self.shared.forget_open(id);
104                }
105                return Err(error);
106            }
107        };
108        let session = Session::from_opening(
109            Arc::clone(&self.shared),
110            SessionOpening::Start(Box::new(result)),
111            &[],
112            None,
113        );
114        // The server names the session. A requested id it did not keep was
115        // never subscribed, so its count is undone before the real id's.
116        let reopened = match named {
117            Some((reopened, id)) if id == session.session_id() => reopened,
118            Some((_, id)) => {
119                self.shared.forget_open(&id);
120                self.shared.note_open(session.session_id())
121            }
122            None => self.shared.note_open(session.session_id()),
123        };
124        self.shared.register(&session, reopened);
125        Ok(session)
126    }
127
128    /// Approvals the resume result lists as pending keep the no-handler path
129    /// fixed at handoff: each is denied when its payload arrives, and a later
130    /// `Session::on_approval` handles only other requests.
131    pub async fn resume_session(&self, options: ResumeSessionOptions) -> FacadeResult<Session> {
132        self.resume_with(options, |_| {}).await
133    }
134
135    /// Installs `handler` before route handoff, so it also answers approvals
136    /// the resume result lists as pending, even if `Session::on_approval`
137    /// replaces it later, unless the session has since settled
138    /// that approval's turn, which gets the rejecting choice.
139    pub async fn resume_session_with_approval_handler<Handler, HandlerFuture>(
140        &self,
141        options: ResumeSessionOptions,
142        handler: Handler,
143    ) -> FacadeResult<Session>
144    where
145        Handler: Fn(ApprovalRequestParams) -> HandlerFuture + Send + Sync + 'static,
146        HandlerFuture: Future<Output = ApprovalDecisionInput> + Send + 'static,
147    {
148        self.resume_with(options, |session| session.on_approval(handler))
149            .await
150    }
151
152    async fn resume_with(
153        &self,
154        options: ResumeSessionOptions,
155        before_handoff: impl FnOnce(&Session),
156    ) -> FacadeResult<Session> {
157        if lock(&self.shared.discarded_session_ids).contains(&options.session_id) {
158            return Err(FacadeError::SessionDiscarded(options.session_id));
159        }
160        let command_id = self.shared.mint_command_id()?;
161        // Recorded before sending: an abandoned resume may still have subscribed.
162        let reopened = self.shared.note_open(&options.session_id);
163        let params = SessionResumeParams {
164            command_id,
165            // Not exposed by the facade yet.
166            recovery_mode: None,
167            session_id: options.session_id,
168            cursor: options.cursor,
169            exclude_items: options.exclude_items,
170            history: options.history,
171            config: options.config,
172            // The Rust SDK does not expose the resume-time profile
173            // pick yet (same as the start selection
174            // above); the resume restores retained authority only.
175            permission_profile: None,
176        };
177        // Kept raw too: the fold seeds history from the raw item objects.
178        let mut raw = match self
179            .shared
180            .command::<_, Value>("session/resume", &params)
181            .await
182        {
183            Ok(raw) => raw,
184            Err(error) => {
185                if matches!(error, FacadeError::Msp(_)) {
186                    self.shared.forget_open(&params.session_id);
187                }
188                return Err(error);
189            }
190        };
191        let dropped_snapshot = drop_unreadable_snapshot(&mut raw);
192        let result = SessionResumeResult::deserialize(&raw).map_err(invalid_frame)?;
193        let session = Session::from_opening(
194            Arc::clone(&self.shared),
195            SessionOpening::Resume(Box::new(result)),
196            resume_history_items(&raw),
197            dropped_snapshot,
198        );
199        before_handoff(&session);
200        session.fix_resume_approval_routing();
201        self.shared.register(&session, reopened);
202        Ok(session)
203    }
204}