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