Skip to main content

subspace_agent/
failure.rs

1//! Why a Copilot turn failed, with the facts that help to report it. The
2//! runtime builds a [`TurnFailure`] from a `session.error` event, or when the
3//! Copilot runtime stops or stops answering, and the chat panel shows its
4//! title, its action and its details.
5//!
6//! A failure never holds the prompt, attachment contents or a credential: the
7//! message passes through the crate's token redaction, and the other fields
8//! are identifiers, counts and times.
9
10mod 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
24/// The Copilot SDK version Subspace is built with. Keep it equal to the
25/// `github-copilot-sdk` pin in this crate's `Cargo.toml`; a test checks it.
26pub const SDK_VERSION: &str = "1.0.34";
27
28/// What a chat reports when its event stream closes, which happens when the
29/// Copilot runtime process exits.
30pub const STREAM_CLOSED: &str = "The Copilot event stream closed. The runtime process exited.";
31/// What a chat reports when the runtime could not take a message.
32pub const SEND_FAILED: &str =
33    "The Copilot runtime could not take the message. The connection to the runtime is closed.";
34/// What every running turn reports when the runtime stops answering.
35pub const NOT_RESPONDING: &str =
36    "The Copilot runtime sent nothing for 90 seconds and did not answer a ping within 15 seconds.";
37
38/// What a message says when the SDK supplied none.
39const NO_MESSAGE: &str = "No error details were supplied by the SDK.";
40/// The error type of a `session.error` that had none.
41const NO_ERROR_TYPE: &str = "runtime";
42/// What replaces a submitted text in a failure.
43const REMOVED: &str = "[message text removed]";
44/// The shortest submitted text that is removed.
45const SCRUB_MIN_CHARS: usize = 4;
46/// How Details says whether a reply started, indexed by the flag.
47const YES_NO: [&str; 2] = ["no", "yes"];
48
49/// Why one turn failed, and the facts that help to report it.
50#[derive(Clone, Debug, PartialEq)]
51pub struct TurnFailure {
52    pub category: FailureCategory,
53    /// The SDK `errorType`, or `runtime_stopped` and `runtime_not_responding`.
54    pub error_type: String,
55    /// The SDK message, redacted.
56    pub message: String,
57    pub status_code: Option<i32>,
58    pub error_code: Option<String>,
59    /// The `x-github-request-id` of the failed call.
60    pub provider_call_id: Option<String>,
61    /// The `x-copilot-service-request-id` of the failed call.
62    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    /// The time since the turn was sent, when a turn ran.
71    pub elapsed: Option<Duration>,
72    pub delta_received: bool,
73    pub attachments: usize,
74    pub occurred_at: DateTime<Local>,
75}
76
77/// What every failure records about its turn.
78struct 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    /// A failure from a `session.error` payload. A missing field stays
88    /// absent; it is never invented.
89    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    /// A failure Subspace detected itself: the runtime stopped or stopped
117    /// answering.
118    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    /// The failure with every text the turn sent removed, so a message the
135    /// runtime echoes never puts the prompt or a context item in Details or
136    /// the log.
137    fn scrubbed(mut self, turn: &TurnContext) -> Self {
138        self.redact_with(|text| scrub(text, &turn.submitted));
139        self
140    }
141
142    /// A message the runtime refused before a turn could start, such as a
143    /// failed access check or a rejected send. `error_type` says which.
144    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    /// Applies `redact` to every text the failure shows or logs, such as a
157    /// replacement of the credentials the runtime knows.
158    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    /// The labelled facts the chat shows under Details, present fields only.
207    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    /// The details as `Label: value` lines, for Copy details.
238    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
250/// The rows that have a value, in order.
251fn 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
259/// A non-empty string field of an SDK payload, with credentials masked.
260fn text(data: &Value, field: &str) -> Option<String> {
261    data[field]
262        .as_str()
263        .filter(|value| !value.is_empty())
264        .map(clean)
265}
266
267/// `text` with each submitted text of at least [`SCRUB_MIN_CHARS`]
268/// characters replaced. A text of one to three characters is kept, so short
269/// fragments such as "ok" are not removed from every word they occur in.
270fn 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
278/// `text` with GitHub tokens, authorization headers and other credential
279/// patterns masked, by the runtime's and the logger's redactors.
280pub(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;