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