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
17pub const RPC_VERSION: &str = "1.0";
19const MAX_REQUEST_ID_BYTES: usize = 128;
20
21#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct RpcRequestId(String);
24
25impl RpcRequestId {
26 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 #[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#[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 #[must_use]
85 pub const fn id(&self) -> Option<&RpcRequestId> {
86 self.id.as_ref()
87 }
88
89 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#[derive(Debug, Clone, PartialEq, Deserialize)]
107#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
108pub enum RpcRequestKind {
109 NewSession {},
111 OpenSession {
113 #[serde(rename = "sessionId")]
115 session_id: SessionId,
116 },
117 NameSession {
119 name: Option<String>,
121 },
122 Prompt {
124 text: String,
126 },
127 Steer {
129 text: String,
131 },
132 FollowUp {
134 text: String,
136 },
137 Abort {},
139 ResolveApproval {
141 #[serde(rename = "approvalId")]
143 approval_id: ApprovalId,
144 decision: ApprovalDecision,
146 },
147 SetModel {
149 model: ModelRef,
151 },
152 Compact {},
154 Fork {
156 #[serde(rename = "fromMessageId")]
158 from_message_id: MessageId,
159 #[serde(rename = "branchId")]
161 branch_id: BranchId,
162 },
163 ListSessions {},
165 QueryState {},
167 QuerySnapshot {
169 #[serde(default, rename = "afterSequence")]
171 after_sequence: Option<SessionSequence>,
172 #[serde(default = "default_snapshot_limit")]
174 limit: usize,
175 },
176 QueryStats {},
178 QueryTree {},
180 ListModels {},
182 ListMcpServers {},
184 ReconnectMcp {
186 #[serde(rename = "serverId")]
188 server_id: McpServerId,
189 },
190}
191
192const fn default_snapshot_limit() -> usize {
193 32
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
198#[serde(rename_all = "snake_case")]
199pub enum RpcErrorCode {
200 ParseError,
202 InvalidRequest,
204 UnsupportedVersion,
206 NotFound,
208 Busy,
210 PolicyDenied,
212 Persistence,
214 Provider,
216 Cancelled,
218 Internal,
220}
221
222#[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Serialize)]
293#[serde(tag = "type", content = "data", rename_all = "snake_case")]
294pub enum RpcResponse {
295 CommandAccepted {
297 #[serde(rename = "commandId")]
299 command_id: CommandId,
300 #[serde(rename = "sessionId")]
302 session_id: SessionId,
303 },
304 CommandCompleted {
306 #[serde(rename = "sessionId")]
308 session_id: SessionId,
309 },
310 SessionSelected {
312 state: SessionStateView,
314 #[serde(rename = "resnapshotRequired")]
316 resnapshot_required: bool,
317 },
318 Sessions {
320 sessions: Vec<SessionListItem>,
322 },
323 State {
325 state: SessionStateView,
327 },
328 Snapshot {
330 snapshot: SessionSnapshotPage,
332 },
333 Stats {
335 stats: SessionStatsView,
337 },
338 Tree {
340 tree: SessionTreeView,
342 },
343 Models {
345 models: Vec<ModelRef>,
347 },
348 McpServers {
350 servers: Vec<McpServerView>,
352 },
353 Error {
355 error: RpcError,
357 },
358}
359
360#[derive(Debug, Clone, PartialEq, Serialize)]
362#[serde(tag = "type", rename_all = "snake_case")]
363pub enum RpcOutput {
364 Ready {
366 #[serde(rename = "rpcVersion")]
368 rpc_version: &'static str,
369 #[serde(rename = "sessionId")]
371 session_id: SessionId,
372 #[serde(rename = "workspaceId")]
374 workspace_id: WorkspaceId,
375 },
376 Response {
378 #[serde(rename = "rpcVersion")]
380 rpc_version: &'static str,
381 #[serde(skip_serializing_if = "Option::is_none")]
383 id: Option<RpcRequestId>,
384 payload: RpcResponse,
386 },
387 Event {
389 #[serde(rename = "rpcVersion")]
391 rpc_version: &'static str,
392 payload: EventEnvelope,
394 },
395 CommandFinished {
397 #[serde(rename = "rpcVersion")]
399 rpc_version: &'static str,
400 #[serde(rename = "commandId")]
402 command_id: CommandId,
403 #[serde(rename = "sessionId")]
405 session_id: SessionId,
406 #[serde(skip_serializing_if = "Option::is_none")]
408 error: Option<RpcError>,
409 },
410 ResnapshotRequired {
412 #[serde(rename = "rpcVersion")]
414 rpc_version: &'static str,
415 #[serde(rename = "sessionId")]
417 session_id: SessionId,
418 #[serde(rename = "tailSequence")]
420 tail_sequence: SessionSequence,
421 },
422}
423
424impl RpcOutput {
425 #[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 #[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 #[must_use]
447 pub const fn event(payload: EventEnvelope) -> Self {
448 Self::Event {
449 rpc_version: RPC_VERSION,
450 payload,
451 }
452 }
453
454 #[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 #[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 #[must_use]
484 pub const fn error(id: Option<RpcRequestId>, error: RpcError) -> Self {
485 Self::response(id, RpcResponse::Error { error })
486 }
487}