Skip to main content

muse_code_sdk/
lib.rs

1//! Async, caller-runtime-owned Rust client for the Muse Stream Protocol.
2//!
3//! The SDK can spawn a `muse serve` host, or attach to a caller-owned
4//! [`DuplexTransport`]. Both constructors complete the initialization
5//! handshake before returning a [`client::MuseClientConnection`], including
6//! any warning-only schema fingerprint mismatch.
7//!
8//! A [`session::Session`] submits turns
9//! ([`session::Session::send_user_turn`]), answers approvals through a
10//! handler ([`session::Session::on_approval`]) and questions
11//! ([`session::Session::answer_user_input`]), and keeps a fold of the events
12//! it applied, read through [`session::Session::fold`]. After a transport
13//! drop on a durable client, [`session::Session::pending`] lists the
14//! submissions it never saw settle, and
15//! [`session::Session::resolve_reconnect`] resends them on the resumed
16//! session.
17//!
18//! ```no_run
19//! use muse_code_sdk::client::{MuseClient, StartSessionOptions};
20//! use muse_code_sdk::msp::{TurnInputPart, TurnInputPartType};
21//! use muse_code_sdk::session::SendUserTurnOptions;
22//! use muse_code_sdk::spawn::SpawnOptions;
23//! use muse_code_sdk::turn::TurnOutcome;
24//!
25//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
26//! let connection = MuseClient::spawn(SpawnOptions::default()).await?;
27//! let client = connection.client;
28//! let session = client.start_session(StartSessionOptions::default()).await?;
29//! let turn = session
30//!     .send_user_turn(SendUserTurnOptions {
31//!         input: vec![text_part("Summarize this repository.")],
32//!         ..SendUserTurnOptions::default()
33//!     })
34//!     .await?;
35//!
36//! let mut items = turn.items();
37//! while let Some(item) = items.recv().await? {
38//!     drop(item);
39//! }
40//! match turn.completed().await? {
41//!     TurnOutcome::Completed { params, .. } => println!("turn ended as {:?}", params.terminal),
42//!     TurnOutcome::Unqueued(params) => println!("turn {} was unqueued", params.turn_id),
43//!     _ => println!("turn ended"),
44//! }
45//! client.close().await;
46//! # Ok(())
47//! # }
48//! #
49//! # fn text_part(text: impl Into<String>) -> TurnInputPart {
50//! #     TurnInputPart {
51//! #         part_type: TurnInputPartType::Text,
52//! #         text: Some(text.into()),
53//! #         media_type: None,
54//! #         base64_data: None,
55//! #         width: None,
56//! #         height: None,
57//! #         selector: None,
58//! #         arguments: None,
59//! #         upload_id: None,
60//! #         client_ref: None,
61//! #         source: None,
62//! #     }
63//! # }
64//! ```
65
66use std::future::Future;
67use std::io;
68use std::pin::Pin;
69
70/// Outside this crate, every public enum in the SDK's own API (errors,
71/// outcomes and states) is `#[non_exhaustive]`, so a later release can add a
72/// variant without breaking your build. A `match` on one needs a catch-all arm;
73/// an exhaustive match without one does not compile.
74///
75/// ```compile_fail,E0004
76/// use muse_code_sdk::turn::TurnOutcome;
77///
78/// fn name(outcome: &TurnOutcome) -> &'static str {
79///     match outcome {
80///         TurnOutcome::Completed { .. } => "completed",
81///         TurnOutcome::Unqueued(_) => "unqueued",
82///         TurnOutcome::Ended(_) => "ended",
83///     }
84/// }
85/// ```
86///
87/// ```compile_fail,E0004
88/// use muse_code_sdk::turn::TurnWaitError;
89///
90/// fn name(error: &TurnWaitError) -> &'static str {
91///     match error {
92///         TurnWaitError::SourceClosed => "source closed",
93///         TurnWaitError::ClientClosed => "client closed",
94///         TurnWaitError::EventSourceFailed { .. } => "event source failed",
95///     }
96/// }
97/// ```
98///
99/// With the catch-all arm, both compile:
100///
101/// ```
102/// use muse_code_sdk::turn::{TurnOutcome, TurnWaitError};
103///
104/// fn outcome(outcome: &TurnOutcome) -> &'static str {
105///     match outcome {
106///         TurnOutcome::Completed { .. } => "completed",
107///         TurnOutcome::Unqueued(_) => "unqueued",
108///         _ => "other",
109///     }
110/// }
111///
112/// fn error(error: &TurnWaitError) -> &'static str {
113///     match error {
114///         TurnWaitError::SourceClosed => "source closed",
115///         TurnWaitError::ClientClosed => "client closed",
116///         TurnWaitError::EventSourceFailed { .. } => "event source failed",
117///         _ => "other",
118///     }
119/// }
120/// ```
121#[cfg(doctest)]
122pub struct OpenEnumsNeedACatchAllArm;
123
124pub mod approval;
125pub mod client;
126pub mod connection;
127pub mod errors;
128pub mod fingerprint;
129pub mod fold;
130pub mod gap;
131pub mod handshake;
132pub mod host_death;
133pub mod msp;
134pub mod pending;
135pub mod session;
136pub mod spawn;
137pub mod turn;
138
139/// A two-way stream of decoded UTF-8 chunks and outgoing newline-framed MSP.
140///
141/// Inbound chunks may be empty or split at any point; the connection assembles
142/// frames. `write` means a frame was handed to the transport, not that the
143/// server completed the command. The implementer decodes bytes incrementally.
144/// Neither method creates a runtime: callers drive both on their Tokio runtime.
145pub trait DuplexTransport: Send {
146    /// Returns the next decoded chunk, or `None` after transport EOF.
147    fn read_chunk(
148        &mut self,
149    ) -> Pin<Box<dyn Future<Output = io::Result<Option<String>>> + Send + '_>>;
150
151    /// Submits an already newline-framed outgoing message.
152    fn write(&mut self, frame: &str) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + '_>>;
153}