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