Skip to main content

tea_cli/rpc/
types.rs

1use std::fmt;
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use tea_coding::{CodingError, CodingErrorCode};
5use tea_mcp::{McpError, McpErrorCode, McpServerId};
6use tea_policy::WorkspaceId;
7use tea_protocol::{
8    ApprovalDecision, ApprovalId, BranchId, CommandId, EventEnvelope, MessageId, ModelRef,
9    SessionId, SessionSequence,
10};
11
12use crate::session_views::{
13    McpServerView, SessionListItem, SessionSnapshotPage, SessionStateView, SessionStatsView,
14    SessionTreeView,
15};
16
17/// Current independent RPC schema version.
18pub const RPC_VERSION: &str = "1.0";
19const MAX_REQUEST_ID_BYTES: usize = 128;
20
21/// Bounded client-supplied response correlation identity.
22#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct RpcRequestId(String);
24
25impl RpcRequestId {
26    /// Creates a bounded, control-free request identity.
27    ///
28    /// # Errors
29    ///
30    /// Rejects empty, oversized, or control-containing values.
31    pub fn new(value: impl Into<String>) -> Result<Self, RpcError> {
32        let value = value.into();
33        if value.is_empty()
34            || value.len() > MAX_REQUEST_ID_BYTES
35            || value.chars().any(char::is_control)
36        {
37            return Err(RpcError::new(
38                RpcErrorCode::InvalidRequest,
39                "request id is invalid",
40            ));
41        }
42        Ok(Self(value))
43    }
44
45    /// Returns the correlation text.
46    #[must_use]
47    pub fn as_str(&self) -> &str {
48        &self.0
49    }
50}
51
52impl fmt::Display for RpcRequestId {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        formatter.write_str(&self.0)
55    }
56}
57
58impl Serialize for RpcRequestId {
59    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
60        serializer.serialize_str(&self.0)
61    }
62}
63
64impl<'de> Deserialize<'de> for RpcRequestId {
65    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
66        Self::new(String::deserialize(deserializer)?)
67            .map_err(|_| serde::de::Error::custom("request id is invalid"))
68    }
69}
70
71/// One strict versioned client request.
72#[derive(Debug, Clone, PartialEq, Deserialize)]
73#[serde(rename_all = "camelCase", deny_unknown_fields)]
74pub struct RpcRequest {
75    rpc_version: String,
76    #[serde(default)]
77    id: Option<RpcRequestId>,
78    #[serde(flatten)]
79    request: RpcRequestKind,
80}
81
82impl RpcRequest {
83    /// Returns the optional client correlation identity.
84    #[must_use]
85    pub const fn id(&self) -> Option<&RpcRequestId> {
86        self.id.as_ref()
87    }
88
89    /// Splits the request after validating the independent RPC version.
90    ///
91    /// # Errors
92    ///
93    /// Returns `unsupported_version` for any schema other than 1.0.
94    pub fn into_parts(self) -> Result<(Option<RpcRequestId>, RpcRequestKind), RpcError> {
95        if self.rpc_version != RPC_VERSION {
96            return Err(RpcError::new(
97                RpcErrorCode::UnsupportedVersion,
98                "RPC version is unsupported",
99            ));
100        }
101        Ok((self.id, self.request))
102    }
103}
104
105/// Supported command and host-query request families.
106#[derive(Debug, Clone, PartialEq, Deserialize)]
107#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
108pub enum RpcRequestKind {
109    /// Create and select a new durable session.
110    NewSession {},
111    /// Attach and select an existing durable session.
112    OpenSession {
113        /// Durable session identity.
114        #[serde(rename = "sessionId")]
115        session_id: SessionId,
116    },
117    /// Set or clear the selected session display name.
118    NameSession {
119        /// Optional bounded display name.
120        name: Option<String>,
121    },
122    /// Submit one user prompt as an owned long-running command.
123    Prompt {
124        /// User text.
125        text: String,
126    },
127    /// Steer the active run.
128    Steer {
129        /// Bounded steering text.
130        text: String,
131    },
132    /// Queue a user follow-up.
133    FollowUp {
134        /// Bounded user text.
135        text: String,
136    },
137    /// Cancel the active run.
138    Abort {},
139    /// Resolve a durable approval.
140    ResolveApproval {
141        /// Pending approval identity.
142        #[serde(rename = "approvalId")]
143        approval_id: ApprovalId,
144        /// Supported bounded decision.
145        decision: ApprovalDecision,
146    },
147    /// Select a model for future turns.
148    SetModel {
149        /// Registered provider-qualified model selector.
150        model: ModelRef,
151    },
152    /// Compact the selected session.
153    Compact {},
154    /// Fork and activate a new branch.
155    Fork {
156        /// Durable source message.
157        #[serde(rename = "fromMessageId")]
158        from_message_id: MessageId,
159        /// Client-assigned branch identity.
160        #[serde(rename = "branchId")]
161        branch_id: BranchId,
162    },
163    /// List durable sessions.
164    ListSessions {},
165    /// Query compact selected-session state.
166    QueryState {},
167    /// Query bounded canonical records after a durable cursor.
168    QuerySnapshot {
169        /// Last durable sequence already held by the client.
170        #[serde(default, rename = "afterSequence")]
171        after_sequence: Option<SessionSequence>,
172        /// Requested record count, clamped to the server maximum.
173        #[serde(default = "default_snapshot_limit")]
174        limit: usize,
175    },
176    /// Query transcript statistics.
177    QueryStats {},
178    /// Query the append-only branch tree.
179    QueryTree {},
180    /// List registered provider models.
181    ListModels {},
182    /// List safe MCP health and frozen catalog metadata.
183    ListMcpServers {},
184    /// Reconnect one MCP server only when discovery matches the frozen catalog.
185    ReconnectMcp {
186        /// Configured MCP server identity.
187        #[serde(rename = "serverId")]
188        server_id: McpServerId,
189    },
190}
191
192const fn default_snapshot_limit() -> usize {
193    32
194}
195
196/// Stable safe RPC failure classification.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
198#[serde(rename_all = "snake_case")]
199pub enum RpcErrorCode {
200    /// A complete LF frame was not valid request JSON.
201    ParseError,
202    /// Request fields or state were invalid.
203    InvalidRequest,
204    /// The independent RPC version is unsupported.
205    UnsupportedVersion,
206    /// A requested session or artifact does not exist.
207    NotFound,
208    /// The requested session already owns conflicting work.
209    Busy,
210    /// Policy rejected the operation.
211    PolicyDenied,
212    /// Durable state could not be read or committed.
213    Persistence,
214    /// Provider execution or selection failed.
215    Provider,
216    /// Work was cancelled.
217    Cancelled,
218    /// An internal boundary failed.
219    Internal,
220}
221
222/// Bounded path- and secret-independent RPC error.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
224#[serde(rename_all = "camelCase")]
225pub struct RpcError {
226    code: RpcErrorCode,
227    message: String,
228}
229
230impl RpcError {
231    /// Creates one safe error with bounded text.
232    #[must_use]
233    pub fn new(code: RpcErrorCode, message: impl Into<String>) -> Self {
234        let mut message = message.into();
235        if message.is_empty() {
236            "RPC request failed".clone_into(&mut message);
237        }
238        message.retain(|character| !character.is_control() || character == ' ');
239        if message.len() > 512 {
240            let mut boundary = 512;
241            while !message.is_char_boundary(boundary) {
242                boundary -= 1;
243            }
244            message.truncate(boundary);
245        }
246        Self { code, message }
247    }
248
249    /// Returns the stable code.
250    #[must_use]
251    pub const fn code(&self) -> RpcErrorCode {
252        self.code
253    }
254}
255
256impl From<CodingError> for RpcError {
257    fn from(error: CodingError) -> Self {
258        let code = match error.code() {
259            CodingErrorCode::InvalidInput => RpcErrorCode::InvalidRequest,
260            CodingErrorCode::NotFound => RpcErrorCode::NotFound,
261            CodingErrorCode::ProjectNotTrusted | CodingErrorCode::PolicyDenied => {
262                RpcErrorCode::PolicyDenied
263            }
264            CodingErrorCode::Persistence => RpcErrorCode::Persistence,
265            CodingErrorCode::Credential | CodingErrorCode::Provider => RpcErrorCode::Provider,
266            CodingErrorCode::Cancelled => RpcErrorCode::Cancelled,
267            CodingErrorCode::Runtime => RpcErrorCode::Internal,
268        };
269        Self::new(code, error.message())
270    }
271}
272
273impl From<McpError> for RpcError {
274    fn from(error: McpError) -> Self {
275        let (code, message) = match error.code() {
276            McpErrorCode::Configuration | McpErrorCode::PolicyDeclaration => {
277                (RpcErrorCode::InvalidRequest, "MCP configuration is invalid")
278            }
279            McpErrorCode::Descriptor | McpErrorCode::Identity | McpErrorCode::StaleCatalog => (
280                RpcErrorCode::InvalidRequest,
281                "MCP catalog changed; close and rebuild the CLI service",
282            ),
283            McpErrorCode::Unavailable => (RpcErrorCode::Busy, "MCP server is unavailable"),
284            McpErrorCode::Cancellation => (RpcErrorCode::Cancelled, "MCP operation was cancelled"),
285            _ => (RpcErrorCode::Internal, "MCP service operation failed"),
286        };
287        Self::new(code, message)
288    }
289}
290
291/// Successful or failed response payload correlated to one request.
292#[derive(Debug, Clone, PartialEq, Serialize)]
293#[serde(tag = "type", content = "data", rename_all = "snake_case")]
294pub enum RpcResponse {
295    /// An owned prompt/approval command was accepted.
296    CommandAccepted {
297        /// Server-generated command identity.
298        #[serde(rename = "commandId")]
299        command_id: CommandId,
300        /// Affected session.
301        #[serde(rename = "sessionId")]
302        session_id: SessionId,
303    },
304    /// A synchronous canonical mutation completed.
305    CommandCompleted {
306        /// Affected session.
307        #[serde(rename = "sessionId")]
308        session_id: SessionId,
309    },
310    /// The active session changed.
311    SessionSelected {
312        /// Compact authoritative state.
313        state: SessionStateView,
314        /// Clients must query a durable snapshot after rebinding.
315        #[serde(rename = "resnapshotRequired")]
316        resnapshot_required: bool,
317    },
318    /// Durable session catalog result.
319    Sessions {
320        /// Stable latest-updated ordering from `SessionCatalog`.
321        sessions: Vec<SessionListItem>,
322    },
323    /// Compact selected-session state.
324    State {
325        /// Authoritative host state.
326        state: SessionStateView,
327    },
328    /// Bounded canonical replay page.
329    Snapshot {
330        /// Durable records and tail cursor.
331        snapshot: SessionSnapshotPage,
332    },
333    /// Rebuildable transcript statistics.
334    Stats {
335        /// Aggregate counts.
336        stats: SessionStatsView,
337    },
338    /// Append-only branch tree.
339    Tree {
340        /// Stable branch projection.
341        tree: SessionTreeView,
342    },
343    /// Registered models.
344    Models {
345        /// Provider-advertised model selectors.
346        models: Vec<ModelRef>,
347    },
348    /// Safe MCP lifecycle and frozen-catalog projection.
349    McpServers {
350        /// Servers in canonical server-ID order.
351        servers: Vec<McpServerView>,
352    },
353    /// Stable safe request failure.
354    Error {
355        /// Machine-readable error.
356        error: RpcError,
357    },
358}
359
360/// One server output frame: correlated response or asynchronous canonical event.
361#[derive(Debug, Clone, PartialEq, Serialize)]
362#[serde(tag = "type", rename_all = "snake_case")]
363pub enum RpcOutput {
364    /// Initial connection metadata.
365    Ready {
366        /// Independent RPC schema version.
367        #[serde(rename = "rpcVersion")]
368        rpc_version: &'static str,
369        /// Initially selected session.
370        #[serde(rename = "sessionId")]
371        session_id: SessionId,
372        /// Safe canonical workspace identity.
373        #[serde(rename = "workspaceId")]
374        workspace_id: WorkspaceId,
375    },
376    /// Correlated request response.
377    Response {
378        /// Independent RPC schema version.
379        #[serde(rename = "rpcVersion")]
380        rpc_version: &'static str,
381        /// Optional client correlation identity.
382        #[serde(skip_serializing_if = "Option::is_none")]
383        id: Option<RpcRequestId>,
384        /// Typed response payload.
385        payload: RpcResponse,
386    },
387    /// Asynchronous canonical event.
388    Event {
389        /// Independent RPC schema version.
390        #[serde(rename = "rpcVersion")]
391        rpc_version: &'static str,
392        /// Unchanged canonical runtime event envelope.
393        payload: EventEnvelope,
394    },
395    /// Owned command task reached its terminal result.
396    CommandFinished {
397        /// Independent RPC schema version.
398        #[serde(rename = "rpcVersion")]
399        rpc_version: &'static str,
400        /// Accepted command identity.
401        #[serde(rename = "commandId")]
402        command_id: CommandId,
403        /// Affected session.
404        #[serde(rename = "sessionId")]
405        session_id: SessionId,
406        /// Safe failure when the command did not complete successfully.
407        #[serde(skip_serializing_if = "Option::is_none")]
408        error: Option<RpcError>,
409    },
410    /// The event subscription was replaced after a gap or rebind.
411    ResnapshotRequired {
412        /// Independent RPC schema version.
413        #[serde(rename = "rpcVersion")]
414        rpc_version: &'static str,
415        /// Session requiring canonical replay.
416        #[serde(rename = "sessionId")]
417        session_id: SessionId,
418        /// Current durable tail at notification time.
419        #[serde(rename = "tailSequence")]
420        tail_sequence: SessionSequence,
421    },
422}
423
424impl RpcOutput {
425    /// Creates initial connection metadata.
426    #[must_use]
427    pub const fn ready(session_id: SessionId, workspace_id: WorkspaceId) -> Self {
428        Self::Ready {
429            rpc_version: RPC_VERSION,
430            session_id,
431            workspace_id,
432        }
433    }
434
435    /// Creates one correlated response frame.
436    #[must_use]
437    pub const fn response(id: Option<RpcRequestId>, payload: RpcResponse) -> Self {
438        Self::Response {
439            rpc_version: RPC_VERSION,
440            id,
441            payload,
442        }
443    }
444
445    /// Creates one asynchronous canonical event frame.
446    #[must_use]
447    pub const fn event(payload: EventEnvelope) -> Self {
448        Self::Event {
449            rpc_version: RPC_VERSION,
450            payload,
451        }
452    }
453
454    /// Creates one asynchronous owned-command terminal notification.
455    #[must_use]
456    pub const fn command_finished(
457        command_id: CommandId,
458        session_id: SessionId,
459        error: Option<RpcError>,
460    ) -> Self {
461        Self::CommandFinished {
462            rpc_version: RPC_VERSION,
463            command_id,
464            session_id,
465            error,
466        }
467    }
468
469    /// Requires the client to rebuild from a durable snapshot page.
470    #[must_use]
471    pub const fn resnapshot_required(
472        session_id: SessionId,
473        tail_sequence: SessionSequence,
474    ) -> Self {
475        Self::ResnapshotRequired {
476            rpc_version: RPC_VERSION,
477            session_id,
478            tail_sequence,
479        }
480    }
481
482    /// Creates one safe error response.
483    #[must_use]
484    pub const fn error(id: Option<RpcRequestId>, error: RpcError) -> Self {
485        Self::response(id, RpcResponse::Error { error })
486    }
487}