Skip to main content

codex_app_server_protocol/
rpc.rs

1//! We do not do true JSON-RPC 2.0, as we neither send nor expect the
2//! "jsonrpc": "2.0" field.
3
4use codex_protocol::protocol::W3cTraceContext;
5use schemars::JsonSchema;
6use serde::Deserialize;
7use serde::Serialize;
8use std::fmt;
9use ts_rs::TS;
10
11pub const JSONRPC_VERSION: &str = "2.0";
12
13#[derive(
14    Debug, Clone, PartialEq, PartialOrd, Ord, Deserialize, Serialize, Hash, Eq, JsonSchema, TS,
15)]
16#[serde(untagged)]
17pub enum RequestId {
18    String(String),
19    #[ts(type = "number")]
20    Integer(i64),
21}
22
23impl fmt::Display for RequestId {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        match self {
26            Self::String(value) => f.write_str(value),
27            Self::Integer(value) => write!(f, "{value}"),
28        }
29    }
30}
31
32pub type Result = serde_json::Value;
33
34/// Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.
35#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
36#[serde(untagged)]
37pub enum JSONRPCMessage {
38    Request(JSONRPCRequest),
39    Notification(JSONRPCNotification),
40    Response(JSONRPCResponse),
41    Error(JSONRPCError),
42}
43
44/// A request that expects a response.
45#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
46pub struct JSONRPCRequest {
47    pub id: RequestId,
48    pub method: String,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    #[ts(optional)]
51    pub params: Option<serde_json::Value>,
52    /// Optional W3C Trace Context for distributed tracing.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    #[ts(optional)]
55    pub trace: Option<W3cTraceContext>,
56}
57
58/// A notification which does not expect a response.
59#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
60pub struct JSONRPCNotification {
61    pub method: String,
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    #[ts(optional)]
64    pub params: Option<serde_json::Value>,
65}
66
67/// A successful (non-error) response to a request.
68#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
69pub struct JSONRPCResponse {
70    pub id: RequestId,
71    pub result: Result,
72}
73
74/// A response to a request that indicates an error occurred.
75#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
76pub struct JSONRPCError {
77    pub error: JSONRPCErrorError,
78    pub id: RequestId,
79}
80
81#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
82pub struct JSONRPCErrorError {
83    pub code: i64,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    #[ts(optional)]
86    pub data: Option<serde_json::Value>,
87    pub message: String,
88}