1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
4pub struct ErrorDetail {
5 pub code: String,
6 pub message: String,
7 #[serde(skip_serializing_if = "Option::is_none")]
8 pub retryable: Option<bool>,
9 #[serde(skip_serializing_if = "Option::is_none")]
10 pub hint: Option<String>,
11 #[serde(skip_serializing_if = "Option::is_none")]
12 pub context: Option<Box<crate::ErrorContext>>,
13}
14
15impl ErrorDetail {
16 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
17 Self {
18 code: code.into(),
19 message: message.into(),
20 retryable: None,
21 hint: None,
22 context: None,
23 }
24 }
25
26 pub fn retryable(mut self, retryable: bool) -> Self {
27 self.retryable = Some(retryable);
28 self
29 }
30
31 pub fn hint(mut self, hint: impl Into<String>) -> Self {
32 self.hint = Some(hint.into());
33 self
34 }
35
36 pub fn context(mut self, context: crate::ErrorContext) -> Self {
37 self.context = Some(Box::new(context));
38 self
39 }
40}
41
42#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
43pub struct ResponseMeta {
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub session: Option<String>,
46 #[serde(skip_serializing_if = "Option::is_none")]
47 pub cmd: Option<String>,
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub socket: Option<String>,
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub log: Option<String>,
52}
53
54impl ResponseMeta {
55 pub fn is_empty(&self) -> bool {
56 self.session.is_none() && self.cmd.is_none() && self.socket.is_none() && self.log.is_none()
57 }
58}
59
60#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
61pub struct Response {
62 pub ok: bool,
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub data: Option<serde_json::Value>,
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub error: Option<String>,
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub error_detail: Option<ErrorDetail>,
69 #[serde(skip_serializing_if = "Option::is_none")]
70 pub meta: Option<ResponseMeta>,
71}
72
73impl Response {
74 pub fn action_result(record: crate::OperationRecord) -> Self {
75 let detail = record.error.clone().or_else(|| {
76 record
77 .error_code
78 .as_ref()
79 .map(|code| ErrorDetail::new(code, "Historical operation detail unavailable"))
80 });
81 let result = crate::ActionResult::from(record);
82 let status = result.status;
83 let data = serde_json::to_value(result).expect("operation record is JSON serializable");
84 Self::completion(status, data, detail)
85 }
86
87 pub fn agent_result(result: crate::AgentStepResult) -> Self {
88 Self::completion(
89 result.status,
90 serde_json::json!(result),
91 result.operation_error.clone(),
92 )
93 }
94
95 fn completion(
96 status: crate::OperationStatus,
97 data: serde_json::Value,
98 detail: Option<ErrorDetail>,
99 ) -> Self {
100 let ok = status == crate::OperationStatus::VerifiedComplete;
101 let detail = detail.or_else(|| {
102 (!ok).then(|| {
103 ErrorDetail::new(
104 match status {
105 crate::OperationStatus::Running => "operation_pending",
106 crate::OperationStatus::NotDispatched => "not_dispatched",
107 _ => "outcome_unknown",
108 },
109 "Inspect the operation ID and dispatch evidence; do not repeat the action",
110 )
111 .retryable(false)
112 })
113 });
114 Self {
115 ok,
116 data: Some(data),
117 error: detail.as_ref().map(|e| e.message.clone()),
118 error_detail: detail,
119 meta: None,
120 }
121 }
122
123 pub fn exit_code(&self) -> i32 {
124 if let Some(status) = self
125 .data
126 .as_ref()
127 .and_then(|data| data.get("status"))
128 .and_then(|status| {
129 serde_json::from_value::<crate::OperationStatus>(status.clone()).ok()
130 })
131 {
132 return status.exit_code();
133 }
134 if self.ok {
135 return 0;
136 }
137 match self.error_detail.as_ref().map(|e| e.code.as_str()) {
138 Some("operation_pending") => 3,
139 Some("operation_transport_error" | "outcome_unknown") => 4,
140 _ => 1,
141 }
142 }
143 pub fn ok(data: impl Into<serde_json::Value>) -> Self {
144 Self {
145 ok: true,
146 data: Some(data.into()),
147 error: None,
148 error_detail: None,
149 meta: None,
150 }
151 }
152
153 pub fn ok_text(msg: impl Into<String>) -> Self {
154 Self::ok(serde_json::Value::String(msg.into()))
155 }
156
157 pub fn err(msg: impl Into<String>) -> Self {
158 let msg = msg.into();
159 Self {
160 ok: false,
161 data: None,
162 error: Some(msg.clone()),
163 error_detail: Some(classify_error(&msg)),
164 meta: None,
165 }
166 }
167
168 pub fn err_detail(detail: ErrorDetail) -> Self {
169 Self {
170 ok: false,
171 data: None,
172 error: Some(detail.message.clone()),
173 error_detail: Some(detail),
174 meta: None,
175 }
176 }
177
178 pub fn with_meta(mut self, meta: ResponseMeta) -> Self {
179 if !meta.is_empty() {
180 self.meta = Some(meta);
181 }
182 self
183 }
184}
185
186fn classify_error(message: &str) -> ErrorDetail {
187 let lower = message.to_ascii_lowercase();
188 if lower.contains("no browser open") {
189 return ErrorDetail::new("no_browser_open", message)
190 .retryable(true)
191 .hint("Run eoka open before browser observation or interaction commands.");
192 }
193 if lower.contains("unknown") || lower.contains("invalid") {
194 return ErrorDetail::new("invalid_input", message).retryable(false);
195 }
196 if lower.contains("daemon failed to start") || lower.contains("transport") {
197 return ErrorDetail::new("transport_error", message).retryable(true);
198 }
199 ErrorDetail::new("eoka_error", message)
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 #[test]
207 fn error_context_is_additive_and_round_trips_without_changing_legacy_data() {
208 let old: Response = serde_json::from_value(serde_json::json!({
209 "ok":false,"error":"missing", "error_detail":{"code":"missing","message":"missing"}
210 }))
211 .unwrap();
212 assert!(old.error_detail.unwrap().context.is_none());
213 let response = Response::err_detail(
214 ErrorDetail::new("download_wait_timeout", "Still running").context(
215 crate::ErrorContext {
216 download_id: Some("job".into()),
217 action_status: Some(crate::ActionStatus::MayHaveExecuted),
218 ..Default::default()
219 },
220 ),
221 );
222 let value = serde_json::to_value(&response).unwrap();
223 assert_eq!(value["error"], "Still running");
224 assert_eq!(
225 value["error_detail"]["context"]["action_status"],
226 "may_have_executed"
227 );
228 let restored: Response = serde_json::from_value(value).unwrap();
229 assert_eq!(
230 restored
231 .error_detail
232 .unwrap()
233 .context
234 .unwrap()
235 .download_id
236 .as_deref(),
237 Some("job")
238 );
239 }
240
241 #[test]
242 fn structured_error_keeps_legacy_error_string() {
243 let response = Response::err("No browser open. Use 'open' first.");
244
245 assert_eq!(
246 response.error.as_deref(),
247 Some("No browser open. Use 'open' first.")
248 );
249 let detail = response.error_detail.unwrap();
250 assert_eq!(detail.code, "no_browser_open");
251 assert_eq!(detail.retryable, Some(true));
252 assert!(detail.hint.unwrap().contains("eoka open"));
253 }
254
255 #[test]
256 fn empty_meta_is_not_serialized() {
257 let value =
258 serde_json::to_value(Response::ok("ok").with_meta(ResponseMeta::default())).unwrap();
259
260 assert!(value.get("meta").is_none());
261 }
262}