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, RecoveryMode, SessionConfig,
13    SessionReadParams, SessionResumeParams, SessionResumeResult, SessionStartParams,
14    SessionStartResult,
15};
16use crate::session::{Session, SessionOpening, drop_unreadable_snapshot, resume_history_items};
17
18use super::{FacadeError, FacadeResult, MuseClient, invalid_frame, lock, protocol_error};
19
20/// The committed profile id a session object reports; `None` when it reports
21/// no permission state or a launch override with no id.
22fn committed_profile_id(session: &crate::msp::Session) -> Option<String> {
23    session.permission_state.as_ref()?.profile_id.clone()
24}
25
26/// Options for [`MuseClient::start_session`]. A field left `None` takes the
27/// server's default, except the workspace: with neither `workspace_root` nor
28/// `workspace_roots` set, the session has no workspace.
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
30pub struct StartSessionOptions {
31    /// The new session's id; the server mints one when `None`. This never
32    /// opens an existing session: an id the host already holds or has reserved
33    /// is refused.
34    pub session_id: Option<String>,
35    /// The session's working folder, as an absolute path.
36    pub workspace_root: Option<String>,
37    /// The session's workspace roots, as absolute paths; the first one is the
38    /// working folder. When `workspace_root` is also set, both must name the
39    /// same folder.
40    pub workspace_roots: Option<Vec<String>>,
41    /// The starting model.
42    pub model_id: Option<String>,
43    /// The starting provider.
44    pub provider_id: Option<String>,
45    /// The starting approval mode, one the host's configuration defines.
46    pub approval_mode: Option<ApprovalMode>,
47    /// Per-session configuration.
48    pub config: Option<SessionConfig>,
49    /// The permission profile to start under, by id; the host's default
50    /// applies when `None`. The host may still commit another profile, so set
51    /// `require_permission_profile` to refuse a start that did not apply it.
52    pub permission_profile: Option<String>,
53    /// When `true`, [`MuseClient::start_session`] proves the host committed
54    /// `permission_profile` before returning the session: from the start
55    /// result, else from one `session/read`. Any other committed profile, or
56    /// none reported, fails with
57    /// [`MuseError::PermissionProfileNotApplied`](crate::errors::MuseError::PermissionProfileNotApplied).
58    /// Setting it without `permission_profile` is refused before anything is
59    /// sent. This flag is never sent to the host.
60    pub require_permission_profile: bool,
61    /// Whether the session is built with recovery on or off; the host's
62    /// default applies when `None`.
63    pub recovery_mode: Option<RecoveryMode>,
64}
65
66/// Options for [`MuseClient::resume_session`].
67#[derive(Clone, Debug, Default, PartialEq, Eq)]
68pub struct ResumeSessionOptions {
69    /// The session to load.
70    pub session_id: String,
71    /// A view cursor this client observed earlier. When set, the server
72    /// returns only what follows it.
73    pub cursor: Option<String>,
74    /// When `true`, return the session's metadata and live state without its
75    /// history; page the history separately. Defaults to `false`.
76    pub exclude_items: Option<bool>,
77    /// Which form of history to return; the server chooses when `None`. It is
78    /// a preference: the server falls back to another form when this one does
79    /// not fit its budget. Ignored when `cursor` is set or `exclude_items` is
80    /// `Some(true)`.
81    pub history: Option<HistoryPreference>,
82    /// Per-session configuration, as at start.
83    pub config: Option<SessionConfig>,
84    /// The model to resume with; when `None`, the session keeps the model it
85    /// recorded.
86    pub model_id: Option<String>,
87    /// The permission profile to resume under, by id; when `None`, the
88    /// session keeps the authority it recorded.
89    pub permission_profile: Option<String>,
90    /// Whether the resumed session is built with recovery on or off; the
91    /// host's default applies when `None`.
92    pub recovery_mode: Option<RecoveryMode>,
93}
94
95impl MuseClient {
96    /// Starts a new session and returns its handle once the server accepts it.
97    pub async fn start_session(&self, options: StartSessionOptions) -> FacadeResult<Session> {
98        // A required selection names the profile it requires: refused before
99        // anything is sent, so the start never proceeds on the host default.
100        let required = match (
101            options.require_permission_profile,
102            &options.permission_profile,
103        ) {
104            (false, _) => None,
105            (true, Some(profile)) => Some(profile.clone()),
106            (true, None) => {
107                return Err(protocol_error(
108                    "require_permission_profile needs permission_profile: require the profile you pass",
109                ));
110            }
111        };
112        let command_id = self.shared.mint_command_id()?;
113        // A start that names its id subscribes it too, so it is noted before
114        // sending, like a resume.
115        let named = options
116            .session_id
117            .clone()
118            .map(|id| (self.shared.note_open(&id), id));
119        let params = SessionStartParams {
120            command_id,
121            recovery_mode: options.recovery_mode,
122            session_id: options.session_id,
123            workspace_root: options.workspace_root,
124            workspace_roots: options.workspace_roots,
125            model_id: options.model_id,
126            provider_id: options.provider_id,
127            approval_mode: options.approval_mode,
128            // Not exposed by the facade yet.
129            approval_rules: None,
130            config: options.config,
131            // The facade does not expose a spawner yet.
132            spawned_by: None,
133            // The SDK starts plain sessions; worktree starts stay
134            // an explicit experimental spelling the caller does not send.
135            worktree: None,
136            permission_profile: options.permission_profile,
137            // Not exposed by the facade yet.
138            limits: None,
139            // The SDK starts plain sessions, with no predecessor.
140            previous_session_id: None,
141            // The SDK starts plain sessions, never a `/clear`.
142            clear: None,
143            // The SDK starts root sessions; the switch policy belongs to
144            // a client that switches sessions.
145            switch_policy: None,
146            // The SDK starts sessions on the host's own machine.
147            nodes: None,
148            default_node: None,
149        };
150        let result = match self
151            .shared
152            .command::<_, SessionStartResult>("session/start", &params)
153            .await
154        {
155            Ok(result) => result,
156            Err(error) => {
157                if let Some((_, id)) = &named
158                    && matches!(error, FacadeError::Msp(_))
159                {
160                    self.shared.forget_open(id);
161                }
162                return Err(error);
163            }
164        };
165        let started_profile = committed_profile_id(&result.session);
166        let session = Session::from_opening(
167            Arc::clone(&self.shared),
168            SessionOpening::Start(Box::new(result)),
169            &[],
170            None,
171        );
172        // The server names the session. A requested id it did not keep was
173        // never subscribed, so its count is undone before the real id's.
174        let reopened = match named {
175            Some((reopened, id)) if id == session.session_id() => reopened,
176            Some((_, id)) => {
177                self.shared.forget_open(&id);
178                self.shared.note_open(session.session_id())
179            }
180            None => self.shared.note_open(session.session_id()),
181        };
182        self.shared.register(&session, reopened);
183        match required {
184            Some(requested) => {
185                match self
186                    .prove_profile(&session, started_profile, requested)
187                    .await
188                {
189                    Ok(()) => Ok(session),
190                    Err(error) => {
191                        self.shared.retract_open(&session);
192                        Err(error)
193                    }
194                }
195            }
196            None => Ok(session),
197        }
198    }
199
200    /// Succeeds only when the host committed `requested`: the profile the
201    /// start result reported, else one point-in-time `session/read`, which
202    /// never subscribes. Only the committed profile id is compared. On refusal
203    /// or a failed read-back the caller retracts the open and drops the
204    /// handle; the error names the session so the caller can resume it or
205    /// start again.
206    async fn prove_profile(
207        &self,
208        session: &Session,
209        started: Option<String>,
210        requested: String,
211    ) -> FacadeResult<()> {
212        let served = match started {
213            Some(started) => Some(started),
214            None => {
215                let read = self
216                    .shared
217                    .command::<_, Value>(
218                        "session/read",
219                        &SessionReadParams {
220                            session_id: session.session_id().to_owned(),
221                            exclude_items: None,
222                        },
223                    )
224                    .await?;
225                // Read structurally: a session shape this SDK cannot decode
226                // proves nothing, so it reads as unknown, never as applied.
227                read.get("session")
228                    .and_then(|session| session.get("permissionState"))
229                    .and_then(|state| state.get("profileId"))
230                    .and_then(Value::as_str)
231                    .map(str::to_owned)
232            }
233        };
234        if served.as_deref() == Some(requested.as_str()) {
235            return Ok(());
236        }
237        Err(FacadeError::PermissionProfileNotApplied {
238            requested,
239            served,
240            session_id: session.session_id().to_owned(),
241        })
242    }
243
244    /// Approvals the resume result lists as pending keep the no-handler path
245    /// fixed at handoff: each is denied when its payload arrives, and a later
246    /// `Session::on_approval` handles only other requests.
247    pub async fn resume_session(&self, options: ResumeSessionOptions) -> FacadeResult<Session> {
248        self.resume_with(options, |_| {}).await
249    }
250
251    /// Installs `handler` before route handoff, so it also answers approvals
252    /// the resume result lists as pending, even if `Session::on_approval`
253    /// replaces it later, unless the session has since settled
254    /// that approval's turn, which gets the rejecting choice.
255    pub async fn resume_session_with_approval_handler<Handler, HandlerFuture>(
256        &self,
257        options: ResumeSessionOptions,
258        handler: Handler,
259    ) -> FacadeResult<Session>
260    where
261        Handler: Fn(ApprovalRequestParams) -> HandlerFuture + Send + Sync + 'static,
262        HandlerFuture: Future<Output = ApprovalDecisionInput> + Send + 'static,
263    {
264        self.resume_with(options, |session| session.on_approval(handler))
265            .await
266    }
267
268    async fn resume_with(
269        &self,
270        options: ResumeSessionOptions,
271        before_handoff: impl FnOnce(&Session),
272    ) -> FacadeResult<Session> {
273        if lock(&self.shared.discarded_session_ids).contains(&options.session_id) {
274            return Err(FacadeError::SessionDiscarded(options.session_id));
275        }
276        let command_id = self.shared.mint_command_id()?;
277        // Recorded before sending: an abandoned resume may still have subscribed.
278        let reopened = self.shared.note_open(&options.session_id);
279        let params = SessionResumeParams {
280            command_id,
281            recovery_mode: options.recovery_mode,
282            session_id: options.session_id,
283            cursor: options.cursor,
284            exclude_items: options.exclude_items,
285            history: options.history,
286            config: options.config,
287            permission_profile: options.permission_profile,
288            model_id: options.model_id,
289            // A facade resume is programmatic, never the user's explicit
290            // Resume action, so it carries no explicit continuation.
291            continue_paused_source: None,
292            // Not exposed by the facade yet.
293            approval_rules: None,
294            // Not exposed by the facade yet.
295            missing_input_assets: None,
296            // Not exposed by the facade yet.
297            limits: None,
298            // Not exposed by the facade yet.
299            auto_recover: None,
300            // Not exposed by the facade yet.
301            workspace_root: None,
302            // Not exposed by the facade yet.
303            workspace_roots: None,
304        };
305        // Kept raw too: the fold seeds history from the raw item objects.
306        let mut raw = match self
307            .shared
308            .command::<_, Value>("session/resume", &params)
309            .await
310        {
311            Ok(raw) => raw,
312            Err(error) => {
313                if matches!(error, FacadeError::Msp(_)) {
314                    self.shared.forget_open(&params.session_id);
315                }
316                return Err(error);
317            }
318        };
319        let dropped_snapshot = drop_unreadable_snapshot(&mut raw);
320        let result = SessionResumeResult::deserialize(&raw).map_err(invalid_frame)?;
321        let history = resume_history_items(&raw, &result.history.mode);
322        let session = Session::from_opening(
323            Arc::clone(&self.shared),
324            SessionOpening::Resume(Box::new(result)),
325            history,
326            dropped_snapshot,
327        );
328        before_handoff(&session);
329        session.fix_resume_approval_routing();
330        self.shared.register(&session, reopened);
331        Ok(session)
332    }
333}