use std::fmt;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tea_coding::{CodingError, CodingErrorCode};
use tea_mcp::{McpError, McpErrorCode, McpServerId};
use tea_policy::WorkspaceId;
use tea_protocol::{
ApprovalDecision, ApprovalId, BranchId, CommandId, EventEnvelope, MessageId, ModelRef,
SessionId, SessionSequence,
};
use crate::session_views::{
McpServerView, SessionListItem, SessionSnapshotPage, SessionStateView, SessionStatsView,
SessionTreeView,
};
pub const RPC_VERSION: &str = "1.0";
const MAX_REQUEST_ID_BYTES: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RpcRequestId(String);
impl RpcRequestId {
pub fn new(value: impl Into<String>) -> Result<Self, RpcError> {
let value = value.into();
if value.is_empty()
|| value.len() > MAX_REQUEST_ID_BYTES
|| value.chars().any(char::is_control)
{
return Err(RpcError::new(
RpcErrorCode::InvalidRequest,
"request id is invalid",
));
}
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for RpcRequestId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl Serialize for RpcRequestId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for RpcRequestId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(deserializer)?)
.map_err(|_| serde::de::Error::custom("request id is invalid"))
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RpcRequest {
rpc_version: String,
#[serde(default)]
id: Option<RpcRequestId>,
#[serde(flatten)]
request: RpcRequestKind,
}
impl RpcRequest {
#[must_use]
pub const fn id(&self) -> Option<&RpcRequestId> {
self.id.as_ref()
}
pub fn into_parts(self) -> Result<(Option<RpcRequestId>, RpcRequestKind), RpcError> {
if self.rpc_version != RPC_VERSION {
return Err(RpcError::new(
RpcErrorCode::UnsupportedVersion,
"RPC version is unsupported",
));
}
Ok((self.id, self.request))
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
pub enum RpcRequestKind {
NewSession {},
OpenSession {
#[serde(rename = "sessionId")]
session_id: SessionId,
},
NameSession {
name: Option<String>,
},
Prompt {
text: String,
},
Steer {
text: String,
},
FollowUp {
text: String,
},
Abort {},
ResolveApproval {
#[serde(rename = "approvalId")]
approval_id: ApprovalId,
decision: ApprovalDecision,
},
SetModel {
model: ModelRef,
},
Compact {},
Fork {
#[serde(rename = "fromMessageId")]
from_message_id: MessageId,
#[serde(rename = "branchId")]
branch_id: BranchId,
},
ListSessions {},
QueryState {},
QuerySnapshot {
#[serde(default, rename = "afterSequence")]
after_sequence: Option<SessionSequence>,
#[serde(default = "default_snapshot_limit")]
limit: usize,
},
QueryStats {},
QueryTree {},
ListModels {},
ListMcpServers {},
ReconnectMcp {
#[serde(rename = "serverId")]
server_id: McpServerId,
},
}
const fn default_snapshot_limit() -> usize {
32
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RpcErrorCode {
ParseError,
InvalidRequest,
UnsupportedVersion,
NotFound,
Busy,
PolicyDenied,
Persistence,
Provider,
Cancelled,
Internal,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcError {
code: RpcErrorCode,
message: String,
}
impl RpcError {
#[must_use]
pub fn new(code: RpcErrorCode, message: impl Into<String>) -> Self {
let mut message = message.into();
if message.is_empty() {
"RPC request failed".clone_into(&mut message);
}
message.retain(|character| !character.is_control() || character == ' ');
if message.len() > 512 {
let mut boundary = 512;
while !message.is_char_boundary(boundary) {
boundary -= 1;
}
message.truncate(boundary);
}
Self { code, message }
}
#[must_use]
pub const fn code(&self) -> RpcErrorCode {
self.code
}
}
impl From<CodingError> for RpcError {
fn from(error: CodingError) -> Self {
let code = match error.code() {
CodingErrorCode::InvalidInput => RpcErrorCode::InvalidRequest,
CodingErrorCode::NotFound => RpcErrorCode::NotFound,
CodingErrorCode::ProjectNotTrusted | CodingErrorCode::PolicyDenied => {
RpcErrorCode::PolicyDenied
}
CodingErrorCode::Persistence => RpcErrorCode::Persistence,
CodingErrorCode::Credential | CodingErrorCode::Provider => RpcErrorCode::Provider,
CodingErrorCode::Cancelled => RpcErrorCode::Cancelled,
CodingErrorCode::Runtime => RpcErrorCode::Internal,
};
Self::new(code, error.message())
}
}
impl From<McpError> for RpcError {
fn from(error: McpError) -> Self {
let (code, message) = match error.code() {
McpErrorCode::Configuration | McpErrorCode::PolicyDeclaration => {
(RpcErrorCode::InvalidRequest, "MCP configuration is invalid")
}
McpErrorCode::Descriptor | McpErrorCode::Identity | McpErrorCode::StaleCatalog => (
RpcErrorCode::InvalidRequest,
"MCP catalog changed; close and rebuild the CLI service",
),
McpErrorCode::Unavailable => (RpcErrorCode::Busy, "MCP server is unavailable"),
McpErrorCode::Cancellation => (RpcErrorCode::Cancelled, "MCP operation was cancelled"),
_ => (RpcErrorCode::Internal, "MCP service operation failed"),
};
Self::new(code, message)
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RpcResponse {
CommandAccepted {
#[serde(rename = "commandId")]
command_id: CommandId,
#[serde(rename = "sessionId")]
session_id: SessionId,
},
CommandCompleted {
#[serde(rename = "sessionId")]
session_id: SessionId,
},
SessionSelected {
state: SessionStateView,
#[serde(rename = "resnapshotRequired")]
resnapshot_required: bool,
},
Sessions {
sessions: Vec<SessionListItem>,
},
State {
state: SessionStateView,
},
Snapshot {
snapshot: SessionSnapshotPage,
},
Stats {
stats: SessionStatsView,
},
Tree {
tree: SessionTreeView,
},
Models {
models: Vec<ModelRef>,
},
McpServers {
servers: Vec<McpServerView>,
},
Error {
error: RpcError,
},
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RpcOutput {
Ready {
#[serde(rename = "rpcVersion")]
rpc_version: &'static str,
#[serde(rename = "sessionId")]
session_id: SessionId,
#[serde(rename = "workspaceId")]
workspace_id: WorkspaceId,
},
Response {
#[serde(rename = "rpcVersion")]
rpc_version: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<RpcRequestId>,
payload: RpcResponse,
},
Event {
#[serde(rename = "rpcVersion")]
rpc_version: &'static str,
payload: EventEnvelope,
},
CommandFinished {
#[serde(rename = "rpcVersion")]
rpc_version: &'static str,
#[serde(rename = "commandId")]
command_id: CommandId,
#[serde(rename = "sessionId")]
session_id: SessionId,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<RpcError>,
},
ResnapshotRequired {
#[serde(rename = "rpcVersion")]
rpc_version: &'static str,
#[serde(rename = "sessionId")]
session_id: SessionId,
#[serde(rename = "tailSequence")]
tail_sequence: SessionSequence,
},
}
impl RpcOutput {
#[must_use]
pub const fn ready(session_id: SessionId, workspace_id: WorkspaceId) -> Self {
Self::Ready {
rpc_version: RPC_VERSION,
session_id,
workspace_id,
}
}
#[must_use]
pub const fn response(id: Option<RpcRequestId>, payload: RpcResponse) -> Self {
Self::Response {
rpc_version: RPC_VERSION,
id,
payload,
}
}
#[must_use]
pub const fn event(payload: EventEnvelope) -> Self {
Self::Event {
rpc_version: RPC_VERSION,
payload,
}
}
#[must_use]
pub const fn command_finished(
command_id: CommandId,
session_id: SessionId,
error: Option<RpcError>,
) -> Self {
Self::CommandFinished {
rpc_version: RPC_VERSION,
command_id,
session_id,
error,
}
}
#[must_use]
pub const fn resnapshot_required(
session_id: SessionId,
tail_sequence: SessionSequence,
) -> Self {
Self::ResnapshotRequired {
rpc_version: RPC_VERSION,
session_id,
tail_sequence,
}
}
#[must_use]
pub const fn error(id: Option<RpcRequestId>, error: RpcError) -> Self {
Self::response(id, RpcResponse::Error { error })
}
}