1use bytes::Bytes;
4
5use crate::gojson::{self, DecodeError, GoJson, Node, ObjWriter};
6
7pub const ABI_VERSION: u32 = 1;
9pub const SCHEMA_VERSION: u32 = 6;
16pub const SCHEMA_STREAM_CHUNK_OMIT_REQUEST_BODY: u32 = 3;
17pub const SCHEMA_WEBSOCKET_RESPONSE_OBSERVER: u32 = 4;
18pub const SCHEMA_STREAM_CHUNK_OMIT_HISTORY: u32 = 5;
19pub const SCHEMA_RAW_MANAGEMENT_RESPONSE: u32 = 6;
20
21pub mod method {
22 pub const PLUGIN_REGISTER: &str = "plugin.register";
23 pub const PLUGIN_QUIESCE: &str = "plugin.quiesce";
24 pub const PLUGIN_RECONFIGURE: &str = "plugin.reconfigure";
25 pub const PLUGIN_SHUTDOWN: &str = "plugin.shutdown";
26
27 pub const MODEL_REGISTER: &str = "model.register";
28 pub const MODEL_STATIC: &str = "model.static";
29 pub const MODEL_FOR_AUTH: &str = "model.for_auth";
30
31 pub const AUTH_IDENTIFIER: &str = "auth.identifier";
32 pub const AUTH_PARSE: &str = "auth.parse";
33 pub const AUTH_LOGIN_START: &str = "auth.login.start";
34 pub const AUTH_LOGIN_POLL: &str = "auth.login.poll";
35 pub const AUTH_REFRESH: &str = "auth.refresh";
36
37 pub const FRONTEND_AUTH_IDENTIFIER: &str = "frontend_auth.identifier";
38 pub const FRONTEND_AUTH_AUTHENTICATE: &str = "frontend_auth.authenticate";
39
40 pub const SCHEDULER_PICK: &str = "scheduler.pick";
41 pub const MODEL_ROUTE: &str = "model.route";
42
43 pub const EXECUTOR_IDENTIFIER: &str = "executor.identifier";
44 pub const EXECUTOR_EXECUTE: &str = "executor.execute";
45 pub const EXECUTOR_EXECUTE_STREAM: &str = "executor.execute_stream";
46 pub const EXECUTOR_COUNT_TOKENS: &str = "executor.count_tokens";
47 pub const EXECUTOR_HTTP_REQUEST: &str = "executor.http_request";
48
49 pub const REQUEST_TRANSLATE: &str = "request.translate";
50 pub const REQUEST_NORMALIZE: &str = "request.normalize";
51 pub const REQUEST_INTERCEPT_BEFORE: &str = "request.intercept_before";
52 pub const REQUEST_INTERCEPT_AFTER: &str = "request.intercept_after";
53 pub const REQUEST_COMPLETE: &str = "request.complete";
54
55 pub const RESPONSE_TRANSLATE: &str = "response.translate";
56 pub const RESPONSE_NORMALIZE_BEFORE: &str = "response.normalize_before";
57 pub const RESPONSE_NORMALIZE_AFTER: &str = "response.normalize_after";
58 pub const RESPONSE_INTERCEPT_AFTER: &str = "response.intercept_after";
59 pub const RESPONSE_INTERCEPT_STREAM_CHUNK: &str = "response.intercept_stream_chunk";
60
61 pub const WEBSOCKET_RESPONSE_EVENT: &str = "websocket.response_event";
62
63 pub const THINKING_IDENTIFIER: &str = "thinking.identifier";
64 pub const THINKING_APPLY: &str = "thinking.apply";
65
66 pub const USAGE_HANDLE: &str = "usage.handle";
67
68 pub const COMMAND_LINE_REGISTER: &str = "command_line.register";
69 pub const COMMAND_LINE_EXECUTE: &str = "command_line.execute";
70
71 pub const MANAGEMENT_REGISTER: &str = "management.register";
72 pub const MANAGEMENT_HANDLE: &str = "management.handle";
73
74 pub const QUOTA_IDENTIFIER: &str = "quota.identifier";
75 pub const QUOTA_DESCRIBE: &str = "quota.describe";
76 pub const QUOTA_FETCH: &str = "quota.fetch";
77 pub const QUOTA_RESET: &str = "quota.reset";
78
79 pub const HOST_HTTP_DO: &str = "host.http.do";
80 pub const HOST_HTTP_DO_STREAM: &str = "host.http.do_stream";
81 pub const HOST_HTTP_OPERATION_OPEN: &str = "host.http.operation_open";
82 pub const HOST_HTTP_CANCEL: &str = "host.http.cancel";
83 pub const HOST_HTTP_STREAM_READ: &str = "host.http.stream_read";
84 pub const HOST_HTTP_STREAM_CLOSE: &str = "host.http.stream_close";
85 pub const HOST_MODEL_EXECUTE: &str = "host.model.execute";
86 pub const HOST_MODEL_EXECUTE_STREAM: &str = "host.model.execute_stream";
87 pub const HOST_MODEL_STREAM_READ: &str = "host.model.stream_read";
88 pub const HOST_MODEL_STREAM_CLOSE: &str = "host.model.stream_close";
89 pub const HOST_STREAM_EMIT: &str = "host.stream.emit";
90 pub const HOST_STREAM_CLOSE: &str = "host.stream.close";
91 pub const HOST_LOG: &str = "host.log";
92 pub const HOST_AUTH_LIST: &str = "host.auth.list";
93 pub const HOST_AUTH_GET: &str = "host.auth.get";
94 pub const HOST_AUTH_GET_RUNTIME: &str = "host.auth.get_runtime";
95 pub const HOST_AUTH_SAVE: &str = "host.auth.save";
96 pub const HOST_AFFINITY_LOOKUP: &str = "host.affinity.lookup";
97}
98
99#[derive(Debug, Clone, Default, PartialEq, Eq)]
101pub struct EnvelopeError {
102 pub code: String,
103 pub message: String,
104 pub retryable: bool,
105 pub http_status: i64,
107}
108
109crate::go_struct! {
110 pub struct WireError("pluginabi.Error") {
112 "code" => code: String,
113 "message" => message: String,
114 "retryable" omitempty => retryable: bool,
115 "http_status" omitempty => http_status: i64,
116 }
117}
118
119#[derive(Debug, Clone, Default, PartialEq)]
122pub struct Envelope {
123 pub ok: bool,
124 pub result: Option<Node>,
125 pub error: Option<EnvelopeError>,
126}
127
128impl Envelope {
129 pub fn parse(raw: &[u8]) -> Result<Self, DecodeError> {
133 let node = gojson::parse(raw)?;
134 let Node::Object(members) = &node else {
135 if node.is_null() {
136 return Ok(Self::default());
137 }
138 return Err(gojson::type_error(&node, "pluginabi.Envelope"));
139 };
140 let mut out = Envelope::default();
141 let mut wire: Option<WireError> = None;
142 let mut first_err = None;
143 for (key, value) in members {
144 let result = if key.eq_ignore_ascii_case("ok") {
145 out.ok
146 .decode_into(value)
147 .map_err(|e| gojson::in_field(e, "Envelope", "ok"))
148 } else if key.eq_ignore_ascii_case("result") {
149 out.result = Some(value.clone());
150 Ok(())
151 } else if key.eq_ignore_ascii_case("error") {
152 wire.decode_into(value)
153 .map_err(|e| gojson::in_field(e, "Envelope", "error"))
154 } else {
155 Ok(())
156 };
157 if let Err(e) = result {
158 first_err.get_or_insert(e);
159 }
160 }
161 if let Some(e) = first_err {
162 return Err(e);
163 }
164 out.error = wire.map(|wire| EnvelopeError {
165 code: wire.code,
166 message: wire.message,
167 retryable: wire.retryable,
168 http_status: wire.http_status,
169 });
170 Ok(out)
171 }
172
173 pub fn is_error(raw: &[u8]) -> bool {
175 Self::parse(raw).is_ok_and(|e| !e.ok && e.error.is_some())
176 }
177}
178
179pub fn ok_envelope<T: GoJson>(result: &T) -> Bytes {
181 ok_envelope_raw(&gojson::to_vec(result))
182}
183
184pub fn ok_envelope_raw(result: &[u8]) -> Bytes {
186 let mut out = Vec::with_capacity(result.len() + 24);
187 let mut w = ObjWriter::begin(&mut out);
188 w.field("ok", &true, false);
189 w.field(
190 "result",
191 &gojson::RawJson(Bytes::copy_from_slice(if result.is_empty() { b"{}" } else { result })),
192 true,
193 );
194 w.end();
195 Bytes::from(out)
196}
197
198pub fn error_envelope(code: &str, message: &str, http_status: u16) -> Bytes {
200 let mut out = Vec::new();
201 let mut w = ObjWriter::begin(&mut out);
202 w.field("ok", &false, false);
203 let error = WireError {
204 code: code.into(),
205 message: message.into(),
206 retryable: false,
207 http_status: i64::from(http_status),
208 };
209 w.field("error", &error, false);
210 w.end();
211 Bytes::from(out)
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn envelopes_match_go_bytes() {
220 assert_eq!(&ok_envelope_raw(b"{}")[..], br#"{"ok":true,"result":{}}"#);
221 assert_eq!(
222 &error_envelope("host_call_failed", "a<b", 0)[..],
223 br#"{"ok":false,"error":{"code":"host_call_failed","message":"a\u003cb"}}"#
224 );
225 assert_eq!(
226 &error_envelope("x", "y", 429)[..],
227 br#"{"ok":false,"error":{"code":"x","message":"y","http_status":429}}"#
228 );
229 let parsed = Envelope::parse(br#"{"OK":false,"Error":{"Code":"c","Message":"m","HTTP_STATUS":401}}"#).unwrap();
230 assert!(!parsed.ok);
231 assert_eq!(parsed.error.unwrap().http_status, 401);
232 assert!(
235 Envelope::parse(br#"{"ok":true,"ok":null,"result":{"x":1e400}}"#)
236 .unwrap()
237 .ok
238 );
239 let merged = Envelope::parse(br#"{"error":{"code":"a"},"error":{"message":"b"}}"#).unwrap();
240 let error = merged.error.unwrap();
241 assert_eq!((error.code.as_str(), error.message.as_str()), ("a", "b"));
242 }
243}