Skip to main content

muse_code_sdk/session/
submit.rs

1//! Turn submission: `send_user_turn`, `unqueue_turn`, and the shared
2//! `turn/start` path that `resolve_reconnect` also resends through.
3
4use std::sync::Arc;
5
6use super::{PendingCommandGuard, Session, SessionInner, SessionOpening};
7use crate::client::{FacadeError, FacadeResult, lock};
8use crate::errors::ProtocolError;
9use crate::msp::{
10    CommandStatus, IfBusy, LastTurn, ReasoningEffort, TurnInputPart, TurnStartDisposition,
11    TurnStartParams, TurnStartResult, TurnUnqueueParams, TurnUnqueueResult, TurnUserShell,
12};
13use crate::turn::{Turn, TurnHandle};
14
15/// What one `turn/start` sends.
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct SendUserTurnOptions {
18    /// The prompt as ordered content parts; the server requires at least one.
19    pub input: Vec<TurnInputPart>,
20    /// What to do when a turn is already running; `None` sends nothing, and
21    /// the server queues the turn.
22    pub if_busy: Option<IfBusy>,
23    /// The prompt's transcript form, never shown to the model.
24    pub display_text: Option<String>,
25    /// This turn's reasoning tier; `None` uses the session's current tier.
26    pub reasoning_effort: Option<ReasoningEffort>,
27    // No `tokenBudget`: the member is experimental-gated (v1
28    // membership unruled) and this SDK serves the stable surface only.
29    /// Replaces the session's workspace roots from this turn on; `None` keeps
30    /// them.
31    pub workspace_roots: Option<Vec<String>>,
32    /// A shell command riding this turn, run at the next model-call boundary.
33    /// It excludes text and skill input, so `input` may then be empty. The
34    /// host serves it only on a connection granted the `userShell`
35    /// capability. [`MuseClient`](crate::client::MuseClient) requests no
36    /// capabilities yet, so a real host refuses such a turn with
37    /// `capabilityRequired` ([`MuseError::Msp`](crate::errors::MuseError::Msp)).
38    pub user_shell: Option<TurnUserShell>,
39}
40
41impl Session {
42    /// Sends one `turn/start` under a fresh command id and returns the turn
43    /// it started or queued, or the running turn it steered into. A call
44    /// refused at entry (session discarded, client closed, transport
45    /// already ended) records nothing, so [`Session::pending`] does not
46    /// list it. Once recorded, on a durable client only a server refusal
47    /// ([`MuseError::Msp`](crate::errors::MuseError::Msp)) drops the
48    /// submission; any other failure, a `TransportEnded` included, keeps it
49    /// listed, since the server may have taken the turn. A call the caller
50    /// cancels keeps nothing.
51    ///
52    /// A same-command retry (a command id minted again after a reconnect)
53    /// that the server answers with the turn the resume restates as
54    /// `lastTurn` returns once every notification received before that
55    /// answer has been handed to the session. Its `Turn` settles on that
56    /// turn's terminal if this session applied it before the claim, as it
57    /// does one received before the answer unless a pending view-gap fill
58    /// holds that one back; otherwise it replays the turn's held history and
59    /// settles as [`TurnOutcome::Ended`](crate::turn::TurnOutcome::Ended),
60    /// unless the session's event source has failed, or it keeps no route for
61    /// that turn and already follows as many turns as it can, when the `Turn`
62    /// fails instead.
63    pub async fn send_user_turn(&self, options: SendUserTurnOptions) -> FacadeResult<Turn> {
64        self.inner.ensure_available()?;
65        let command_id = self.inner.client.mint_command_id()?;
66        let mut pending_command =
67            PendingCommandGuard::begin(&self.inner, command_id.clone(), options.clone());
68        let result = self
69            .inner
70            .submit_turn(&command_id, options, &mut pending_command)
71            .await?;
72        let ended = self.inner.restated_last_turn(&result.turn_id);
73        if ended.is_some() {
74            // The answer names a turn that ended before the resume. Its own
75            // terminal, if one arrived before this answer, settles the retry,
76            // so every notification received first is handed over before the
77            // claim looks for it. A cancel while waiting keeps nothing, like
78            // any other cancel of this call.
79            pending_command.forget_submission_on_cancel();
80            self.inner.client.notifications_received_applied().await;
81            pending_command.keep_submission();
82        }
83        Ok(self
84            .inner
85            .follow_submitted_turn(&command_id, &result, ended))
86    }
87
88    /// Reclaims a queued turn before it launches (`turn/unqueue`).
89    ///
90    /// The result is admission only: the queued [`Turn`] settles as
91    /// [`TurnOutcome::Unqueued`](crate::turn::TurnOutcome::Unqueued) when the
92    /// server's `turn/unqueued` arrives. A turn that already launched is
93    /// refused with [`MuseError::Msp`](crate::errors::MuseError::Msp) and keeps
94    /// running to its terminal. Pass `turn_id` exactly as the server minted it
95    /// ([`Turn::turn_id`] or snapshot `queuedTurns`): the echoed id is compared
96    /// byte for byte.
97    pub async fn unqueue_turn(&self, turn_id: &str) -> FacadeResult<TurnUnqueueResult> {
98        self.inner.ensure_available()?;
99        let command_id = self.inner.client.mint_command_id()?;
100        let params = TurnUnqueueParams {
101            session_id: self.inner.session_id.clone(),
102            command_id: command_id.clone(),
103            turn_id: turn_id.to_owned(),
104        };
105        let result = self
106            .inner
107            .client
108            .command::<_, TurnUnqueueResult>("turn/unqueue", &params)
109            .await?;
110        if result.command_id != command_id {
111            return Err(ProtocolError::new(
112                format!(
113                    "turn/unqueue echoed command id {}, expected {command_id}",
114                    result.command_id
115                ),
116                None,
117            )
118            .into());
119        }
120        if result.turn_id != turn_id {
121            return Err(ProtocolError::new(
122                format!(
123                    "turn/unqueue echoed turn id {}, expected {turn_id}",
124                    result.turn_id
125                ),
126                None,
127            )
128            .into());
129        }
130        require_accepted("turn/unqueue", &result.status)?;
131        Ok(result)
132    }
133}
134
135impl SessionInner {
136    pub(super) fn ensure_available(&self) -> FacadeResult<()> {
137        if lock(&self.state).discarded {
138            Err(FacadeError::SessionDiscarded(self.session_id.clone()))
139        } else {
140            Ok(())
141        }
142    }
143
144    /// Sends one `turn/start` under `command_id` and checks the answer's echo.
145    pub(super) async fn submit_turn(
146        self: &Arc<Self>,
147        command_id: &str,
148        options: SendUserTurnOptions,
149        pending_command: &mut PendingCommandGuard,
150    ) -> FacadeResult<TurnStartResult> {
151        let params = TurnStartParams {
152            session_id: self.session_id.clone(),
153            command_id: command_id.to_owned(),
154            input: options.input,
155            if_busy: options.if_busy,
156            display_text: options.display_text,
157            reasoning_effort: options.reasoning_effort,
158            // Experimental-gated: never sent by this SDK.
159            token_budget: None,
160            user_shell: options.user_shell,
161            workspace_roots: options.workspace_roots,
162        };
163        let result = self
164            .client
165            .command::<_, TurnStartResult>("turn/start", &params)
166            .await;
167        let result = match result {
168            Ok(result) => result,
169            Err(error) => {
170                match error {
171                    FacadeError::TransportEnded | FacadeError::Transport(_) => {
172                        pending_command.retain_for_retry();
173                    }
174                    // Only a server refusal answers the submission; any other
175                    // failure may follow a written intake.
176                    FacadeError::Msp(_) => {}
177                    _ => pending_command.keep_submission(),
178                }
179                return Err(error);
180            }
181        };
182        pending_command.keep_submission();
183        if result.command_id != command_id {
184            return Err(ProtocolError::new(
185                format!(
186                    "turn/start echoed command id {}, expected {command_id}",
187                    result.command_id
188                ),
189                None,
190            )
191            .into());
192        }
193        require_accepted("turn/start", &result.status)?;
194        Ok(result)
195    }
196
197    /// Follows an answered `turn/start`. `ended` is the resume's `lastTurn`
198    /// when the answer names it and the caller has waited for the
199    /// notifications received before the answer; `resolve_reconnect`, which
200    /// answers that case itself, passes `None`.
201    pub(super) fn follow_submitted_turn(
202        self: &Arc<Self>,
203        command_id: &str,
204        result: &TurnStartResult,
205        ended: Option<LastTurn>,
206    ) -> Turn {
207        if let Some(last_turn) = ended {
208            return self.follow_ended_turn(command_id, result, last_turn);
209        }
210        let turn = match &result.disposition {
211            TurnStartDisposition::Started | TurnStartDisposition::Queued => {
212                self.submitted_turn(&result.turn_id, command_id.to_owned())
213            }
214            TurnStartDisposition::Steered => self.claim_turn(&result.turn_id),
215            // A disposition this build does not know: follow the turn the
216            // server named, as the submission's own only when it says it
217            // started a new one; otherwise join it the way `Steered` does.
218            TurnStartDisposition::Unknown(_) if result.started_new_turn => {
219                self.submitted_turn(&result.turn_id, command_id.to_owned())
220            }
221            TurnStartDisposition::Unknown(_) => self.claim_turn(&result.turn_id),
222        };
223        lock(&self.state).acknowledge_submission(command_id, &result.turn_id);
224        turn
225    }
226
227    /// Follows an answer that names the turn the resume restates as `lastTurn`,
228    /// under one session-state guard, so no notification can land between
229    /// reading the kept route, the claim and the settle.
230    fn follow_ended_turn(
231        self: &Arc<Self>,
232        command_id: &str,
233        result: &TurnStartResult,
234        last_turn: LastTurn,
235    ) -> Turn {
236        let mut state = lock(&self.state);
237        if let Some(handle) = state.last_turn_settled.clone() {
238            // This session already retired the turn's route and keeps it past
239            // the alias hold. Its own terminal settles the retry, even after
240            // a failed event source. A local fault that retired it applies no
241            // terminal, so the retry settles from the resume's restatement,
242            // unless the event source has failed: then it keeps a failure,
243            // through the claim below, as for any turn.
244            let turn = if handle.has_server_outcome() {
245                Some(handle.turn_with_keepalive(Arc::clone(self)))
246            } else if state.event_source_failure.is_none() {
247                Some(self.ended_turn(&handle, last_turn.clone()))
248            } else {
249                None
250            };
251            if let Some(turn) = turn {
252                // Settled from server evidence, however long ago its route
253                // retired.
254                state.forget_submission(command_id);
255                return turn;
256            }
257        }
258        // Every turn returned here is settled under this guard, so it needs no
259        // discard owner.
260        let turn = self.claim_turn_locked(&mut state, &result.turn_id);
261        // No terminal for it was applied before this claim, and the resume says
262        // it already ended: settle the route the claim opened from the resume's
263        // own restatement. A claim the session refused opens no route, so its
264        // failure stands.
265        state.settle_and_retire_turn(&result.turn_id, |handle| handle.settle_ended(last_turn));
266        state.acknowledge_submission(command_id, &result.turn_id);
267        turn
268    }
269
270    /// A turn settled `Ended` from `last_turn`, carrying what `retired` held:
271    /// its items, in order, and whether it saw `turn/started`.
272    fn ended_turn(self: &Arc<Self>, retired: &TurnHandle, last_turn: LastTurn) -> Turn {
273        let ended = TurnHandle::new(&last_turn.turn_id);
274        if retired.observed_start() {
275            ended.mark_started();
276        }
277        for item in retired.held_items() {
278            ended.push_item(item);
279        }
280        ended.settle_ended(last_turn);
281        ended.turn_with_keepalive(Arc::clone(self))
282    }
283
284    /// The resume's `lastTurn`, when it names `turn_id`.
285    pub(super) fn restated_last_turn(&self, turn_id: &str) -> Option<LastTurn> {
286        match &self.opening {
287            SessionOpening::Resume(result) => result
288                .last_turn
289                .as_ref()
290                .filter(|last_turn| last_turn.turn_id == turn_id)
291                .cloned(),
292            SessionOpening::Start(_) => None,
293        }
294    }
295
296    pub(super) fn finish_command(&self, command_id: &str) {
297        lock(&self.state).finish_pending_command(command_id);
298    }
299}
300
301/// An ack whose status is not `accepted` does not say the host took the
302/// command, so the call fails as a protocol error. Only a newer host's word
303/// reaches the `Unknown` arm, so its message says to update the SDK, because
304/// an app may show it as the turn's failure; the match is exhaustive, so a
305/// status this SDK learns later cannot fall into that message.
306pub(in crate::session) fn require_accepted(
307    method: &str,
308    status: &CommandStatus,
309) -> Result<(), ProtocolError> {
310    match status {
311        CommandStatus::Accepted => Ok(()),
312        CommandStatus::Unknown(word) => Err(ProtocolError::new(
313            format!(
314                "{method} answered status {word:?}, which this SDK does not know: the host is \
315                 newer than this SDK, so update the SDK"
316            ),
317            None,
318        )),
319    }
320}