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