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            // Not exposed by the facade yet.
93            limits: None,
94        };
95        let result = match self
96            .shared
97            .command::<_, SessionStartResult>("session/start", &params)
98            .await
99        {
100            Ok(result) => result,
101            Err(error) => {
102                if let Some((_, id)) = &named
103                    && matches!(error, FacadeError::Msp(_))
104                {
105                    self.shared.forget_open(id);
106                }
107                return Err(error);
108            }
109        };
110        let session = Session::from_opening(
111            Arc::clone(&self.shared),
112            SessionOpening::Start(Box::new(result)),
113            &[],
114            None,
115        );
116        // The server names the session. A requested id it did not keep was
117        // never subscribed, so its count is undone before the real id's.
118        let reopened = match named {
119            Some((reopened, id)) if id == session.session_id() => reopened,
120            Some((_, id)) => {
121                self.shared.forget_open(&id);
122                self.shared.note_open(session.session_id())
123            }
124            None => self.shared.note_open(session.session_id()),
125        };
126        self.shared.register(&session, reopened);
127        Ok(session)
128    }
129
130    /// Approvals the resume result lists as pending keep the no-handler path
131    /// fixed at handoff: each is denied when its payload arrives, and a later
132    /// `Session::on_approval` handles only other requests.
133    pub async fn resume_session(&self, options: ResumeSessionOptions) -> FacadeResult<Session> {
134        self.resume_with(options, |_| {}).await
135    }
136
137    /// Installs `handler` before route handoff, so it also answers approvals
138    /// the resume result lists as pending, even if `Session::on_approval`
139    /// replaces it later, unless the session has since settled
140    /// that approval's turn, which gets the rejecting choice.
141    pub async fn resume_session_with_approval_handler<Handler, HandlerFuture>(
142        &self,
143        options: ResumeSessionOptions,
144        handler: Handler,
145    ) -> FacadeResult<Session>
146    where
147        Handler: Fn(ApprovalRequestParams) -> HandlerFuture + Send + Sync + 'static,
148        HandlerFuture: Future<Output = ApprovalDecisionInput> + Send + 'static,
149    {
150        self.resume_with(options, |session| session.on_approval(handler))
151            .await
152    }
153
154    async fn resume_with(
155        &self,
156        options: ResumeSessionOptions,
157        before_handoff: impl FnOnce(&Session),
158    ) -> FacadeResult<Session> {
159        if lock(&self.shared.discarded_session_ids).contains(&options.session_id) {
160            return Err(FacadeError::SessionDiscarded(options.session_id));
161        }
162        let command_id = self.shared.mint_command_id()?;
163        // Recorded before sending: an abandoned resume may still have subscribed.
164        let reopened = self.shared.note_open(&options.session_id);
165        let params = SessionResumeParams {
166            command_id,
167            // Not exposed by the facade yet.
168            recovery_mode: None,
169            session_id: options.session_id,
170            cursor: options.cursor,
171            exclude_items: options.exclude_items,
172            history: options.history,
173            config: options.config,
174            // The Rust SDK does not expose the resume-time profile
175            // pick yet (same as the start selection
176            // above); the resume restores retained authority only.
177            permission_profile: None,
178        };
179        // Kept raw too: the fold seeds history from the raw item objects.
180        let mut raw = match self
181            .shared
182            .command::<_, Value>("session/resume", &params)
183            .await
184        {
185            Ok(raw) => raw,
186            Err(error) => {
187                if matches!(error, FacadeError::Msp(_)) {
188                    self.shared.forget_open(&params.session_id);
189                }
190                return Err(error);
191            }
192        };
193        let dropped_snapshot = drop_unreadable_snapshot(&mut raw);
194        let result = SessionResumeResult::deserialize(&raw).map_err(invalid_frame)?;
195        let history = resume_history_items(&raw, &result.history.mode);
196        let session = Session::from_opening(
197            Arc::clone(&self.shared),
198            SessionOpening::Resume(Box::new(result)),
199            history,
200            dropped_snapshot,
201        );
202        before_handoff(&session);
203        session.fix_resume_approval_routing();
204        self.shared.register(&session, reopened);
205        Ok(session)
206    }
207}