Skip to main content

zerolaunch_plugin_protocol/
error.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, thiserror::Error)]
4pub enum ProtocolError {
5    #[error("io: {0}")]
6    Io(#[from] std::io::Error),
7
8    #[error("serde: {0}")]
9    Serde(#[from] serde_json::Error),
10
11    #[error("toml: {0}")]
12    Toml(#[from] toml::de::Error),
13
14    #[error("semver: {0}")]
15    Semver(#[from] semver::Error),
16
17    #[error("invalid frame: {0}")]
18    InvalidFrame(String),
19
20    #[error("rpc error: code={code} message={message}")]
21    Rpc { code: i32, message: String },
22
23    #[error("timeout")]
24    Timeout,
25
26    #[error("transport closed")]
27    TransportClosed,
28
29    #[error("protocol version incompatible: plugin {plugin} declares {got}, host expects {expected} (major version must match)")]
30    ProtocolVersionIncompatible {
31        plugin: String,
32        expected: String,
33        got: String,
34    },
35
36    #[error("manifest error: {0}")]
37    Manifest(String),
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct JsonRpcError {
42    pub code: i32,
43    pub message: String,
44    #[serde(default)]
45    pub data: Option<serde_json::Value>,
46}
47
48impl JsonRpcError {
49    pub fn new(code: i32, message: impl Into<String>) -> Self {
50        Self {
51            code,
52            message: message.into(),
53            data: None,
54        }
55    }
56
57    pub fn with_data(mut self, data: serde_json::Value) -> Self {
58        self.data = Some(data);
59        self
60    }
61}
62
63/// JSON-RPC 2.0 标准与自定义错误码。
64pub mod codes {
65    /// 解析错误:消息体不是合法 JSON。
66    pub const PARSE_ERROR: i32 = -32700;
67    /// 无效请求:JSON 合法但不是合法的请求对象。
68    pub const INVALID_REQUEST: i32 = -32600;
69    /// 方法不存在。
70    pub const METHOD_NOT_FOUND: i32 = -32601;
71    /// 无效参数:参数缺失或类型不匹配。
72    pub const INVALID_PARAMS: i32 = -32602;
73    /// 内部错误:处理请求时发生未归类异常。
74    pub const INTERNAL_ERROR: i32 = -32603;
75    /// 插件执行错误:插件处理请求返回错误。
76    pub const PLUGIN_ERROR: i32 = -32000;
77    /// 插件进程崩溃/异常退出。
78    pub const PLUGIN_CRASHED: i32 = -32001;
79    /// 请求超时:插件在限时内未响应。
80    pub const TIMEOUT_ERROR: i32 = -32002;
81    /// 不支持的组件类型:插件声明了宿主未注册的组件。
82    pub const UNSUPPORTED_COMPONENT: i32 = -32003;
83    /// 模型不存在(model_id 未注册)。
84    pub const MODEL_NOT_FOUND: i32 = -32100;
85    /// 模型提供方不可达/未就绪(Ollama 未启动、网络失败等)。
86    pub const MODEL_PROVIDER_UNAVAILABLE: i32 = -32101;
87    /// 模型请求载荷非法。
88    pub const MODEL_INVALID_REQUEST: i32 = -32102;
89    /// 模型提供方不支持该操作。
90    pub const MODEL_NOT_SUPPORTED: i32 = -32103;
91    /// 模型传输失败。
92    pub const MODEL_TRANSPORT: i32 = -32104;
93}