1mod category;
11#[cfg(feature = "copilot")]
13mod log;
14mod turn;
15
16pub use category::{FailureCategory, categorize};
17
18use std::time::Duration;
19
20use chrono::{DateTime, Local};
21use serde_json::Value;
22
23#[cfg(feature = "copilot")]
24pub(crate) use log::{log_failure, log_turn_done, log_turn_started};
25pub use turn::TurnContext;
26
27pub const SDK_VERSION: &str = "1.0.34";
30
31pub const STREAM_CLOSED: &str = "The Copilot event stream closed. The runtime process exited.";
34pub const SEND_FAILED: &str =
36 "The Copilot runtime could not take the message. The connection to the runtime is closed.";
37pub const NOT_RESPONDING: &str =
39 "The Copilot runtime sent nothing for 90 seconds and did not answer a ping within 15 seconds.";
40
41const NO_MESSAGE: &str = "No error details were supplied by the SDK.";
43const NO_ERROR_TYPE: &str = "runtime";
45const REMOVED: &str = "[message text removed]";
47const SCRUB_MIN_CHARS: usize = 4;
49const YES_NO: [&str; 2] = ["no", "yes"];
51
52#[derive(Clone, Debug, PartialEq)]
54pub struct TurnFailure {
55 pub category: FailureCategory,
56 pub error_type: String,
58 pub message: String,
60 pub status_code: Option<i32>,
61 pub error_code: Option<String>,
62 pub provider_call_id: Option<String>,
64 pub service_request_id: Option<String>,
66 pub originating_message_id: Option<String>,
67 pub remediation: Option<String>,
68 pub url: Option<String>,
69 pub model: Option<String>,
70 pub effort: Option<String>,
71 pub runtime_version: Option<String>,
72 pub sdk_version: &'static str,
73 pub elapsed: Option<Duration>,
75 pub delta_received: bool,
76 pub attachments: usize,
77 pub occurred_at: DateTime<Local>,
78}
79
80struct Basis<'a> {
82 category: FailureCategory,
83 error_type: String,
84 message: String,
85 turn: &'a TurnContext,
86 runtime: Option<&'a str>,
87}
88
89impl TurnFailure {
90 pub fn from_session_error(data: &Value, turn: &TurnContext, runtime: Option<&str>) -> Self {
93 let error_type = text(data, "errorType").unwrap_or_else(|| NO_ERROR_TYPE.to_owned());
94 let status_code = data["statusCode"]
95 .as_i64()
96 .and_then(|code| i32::try_from(code).ok());
97 let remediation = text(data, "remediation");
98 let category = categorize(&error_type, status_code, remediation.as_deref());
99 let message = text(data, "message").unwrap_or_else(|| NO_MESSAGE.to_owned());
100 Self {
101 status_code,
102 remediation,
103 error_code: text(data, "errorCode"),
104 provider_call_id: text(data, "providerCallId"),
105 service_request_id: text(data, "serviceRequestId"),
106 originating_message_id: text(data, "originatingMessageId"),
107 url: text(data, "url"),
108 ..Self::new(Basis {
109 category,
110 error_type,
111 message,
112 turn,
113 runtime,
114 })
115 }
116 .scrubbed(turn)
117 }
118
119 pub fn stopped(
122 category: FailureCategory,
123 message: &str,
124 turn: &TurnContext,
125 runtime: Option<&str>,
126 ) -> Self {
127 Self::new(Basis {
128 category,
129 error_type: category.runtime_error_type().to_owned(),
130 message: clean(message),
131 turn,
132 runtime,
133 })
134 .scrubbed(turn)
135 }
136
137 fn scrubbed(mut self, turn: &TurnContext) -> Self {
141 self.redact_with(|text| scrub(text, &turn.submitted));
142 self
143 }
144
145 pub fn rejected(
148 error_type: &str,
149 message: &str,
150 turn: &TurnContext,
151 runtime: Option<&str>,
152 ) -> Self {
153 Self {
154 error_type: error_type.to_owned(),
155 ..Self::stopped(FailureCategory::Unknown, message, turn, runtime)
156 }
157 }
158
159 pub fn redact_with(&mut self, redact: impl Fn(&str) -> String) {
162 self.message = redact(&self.message);
163 self.error_type = redact(&self.error_type);
164 for field in [
165 &mut self.error_code,
166 &mut self.provider_call_id,
167 &mut self.service_request_id,
168 &mut self.originating_message_id,
169 &mut self.remediation,
170 &mut self.url,
171 ]
172 .into_iter()
173 .flatten()
174 {
175 *field = redact(field);
176 }
177 }
178
179 fn new(basis: Basis<'_>) -> Self {
180 let Basis {
181 category,
182 error_type,
183 message,
184 turn,
185 runtime,
186 } = basis;
187 Self {
188 category,
189 error_type,
190 message,
191 status_code: None,
192 error_code: None,
193 provider_call_id: None,
194 service_request_id: None,
195 originating_message_id: None,
196 remediation: None,
197 url: None,
198 model: turn.model.clone(),
199 effort: turn.effort.clone(),
200 runtime_version: runtime.map(str::to_owned),
201 sdk_version: SDK_VERSION,
202 elapsed: turn.sent.map(|sent| sent.elapsed()),
203 delta_received: turn.delta_received,
204 attachments: turn.attachments,
205 occurred_at: Local::now(),
206 }
207 }
208
209 pub fn details(&self) -> Vec<(&'static str, String)> {
211 present([
212 ("Type", Some(self.error_type.clone())),
213 ("Message", Some(self.message.clone())),
214 ("Status", self.status_code.map(|code| code.to_string())),
215 ("Error code", self.error_code.clone()),
216 ("Request ID", self.provider_call_id.clone()),
217 ("Service request ID", self.service_request_id.clone()),
218 ("Message ID", self.originating_message_id.clone()),
219 ("Model", self.model.clone()),
220 ("Reasoning effort", self.effort.clone()),
221 ("Runtime", self.runtime_version.clone()),
222 ("SDK", Some(self.sdk_version.to_owned())),
223 (
224 "Time",
225 Some(self.occurred_at.format("%Y-%m-%d %H:%M:%S %:z").to_string()),
226 ),
227 (
228 "Elapsed",
229 self.elapsed
230 .map(|elapsed| format!("{:.1} s", elapsed.as_secs_f64())),
231 ),
232 (
233 "Reply started",
234 Some(YES_NO[usize::from(self.delta_received)].to_owned()),
235 ),
236 ("Attachments", Some(self.attachments.to_string())),
237 ])
238 }
239
240 pub fn details_text(&self) -> String {
242 lines(&self.details())
243 }
244}
245
246fn lines(rows: &[(&'static str, String)]) -> String {
247 rows.iter()
248 .map(|(label, value)| format!("{label}: {value}"))
249 .collect::<Vec<_>>()
250 .join("\n")
251}
252
253fn present<const N: usize>(
255 rows: [(&'static str, Option<String>); N],
256) -> Vec<(&'static str, String)> {
257 rows.into_iter()
258 .filter_map(|(label, value)| value.map(|value| (label, value)))
259 .collect()
260}
261
262fn text(data: &Value, field: &str) -> Option<String> {
264 data[field]
265 .as_str()
266 .filter(|value| !value.is_empty())
267 .map(clean)
268}
269
270fn scrub(text: &str, submitted: &[String]) -> String {
274 submitted
275 .iter()
276 .map(|sent| sent.trim())
277 .filter(|sent| sent.chars().count() >= SCRUB_MIN_CHARS)
278 .fold(text.to_owned(), |text, sent| text.replace(sent, REMOVED))
279}
280
281pub(crate) fn clean(text: &str) -> String {
284 subspace_core::log::redact(&crate::runtime::redact(text))
285}
286
287#[cfg(test)]
288mod record_tests;
289#[cfg(test)]
290mod tests;