Skip to main content

subspace_client_github/
copilot_agent_sessions.rs

1//! The Copilot agent session API: the session document and its log.
2//!
3//! These endpoints are undocumented and read-only. They live on the Copilot
4//! API host, which GraphQL names (`viewer { copilotEndpoints { api } }`), so
5//! nothing here hardcodes a host. They accept the gh CLI OAuth token only,
6//! so a run with `GH_TOKEN`, `GITHUB_TOKEN` or a config-file token is told
7//! what it needs rather than being sent to GitHub with a token that fails.
8
9use std::io::Read as _;
10
11use serde::Deserialize;
12use serde_json::json;
13use ureq::Body;
14use ureq::http::Response;
15
16use subspace_core::credentials::{Credential, Source};
17use subspace_core::http::status as http_status;
18use subspace_core::http::{Error, plain_https_url};
19
20use crate::Client;
21use crate::copilot_agents::validate_task_id;
22use crate::transport;
23
24mod log;
25mod model;
26
27pub use log::{LogEntry, SessionLog, parse_log};
28pub use model::CopilotAgentSession;
29
30/// The read limit for the session document, which is about 3 KB.
31const MAX_SESSION_BYTES: usize = 256 * 1024;
32/// The most of one log Subspace ever reads. A finished session's log is
33/// 240-730 KB, so this leaves room without letting one answer grow freely.
34pub const MAX_LOG_BYTES: usize = 2 * 1024 * 1024;
35
36const ENDPOINT_QUERY: &str = "query { viewer { copilotEndpoints { api } } }";
37
38/// What the user must do when the work credential is not an OAuth token,
39/// naming Sign in with GitHub only when the app offers it.
40pub fn needs_oauth_login(sign_in_offered: bool) -> String {
41    let lead = if sign_in_offered {
42        "Sign in with GitHub in Settings or run"
43    } else {
44        "Run"
45    };
46    format!(
47        "The session log needs a GitHub sign-in. {lead} `gh auth login` for the work account, \
48         and unset GH_TOKEN and GITHUB_TOKEN."
49    )
50}
51
52#[derive(Debug, Deserialize)]
53struct Endpoints {
54    viewer: Viewer,
55}
56
57#[derive(Debug, Deserialize)]
58#[serde(rename_all = "camelCase")]
59struct Viewer {
60    copilot_endpoints: CopilotEndpoints,
61}
62
63#[derive(Debug, Deserialize)]
64struct CopilotEndpoints {
65    #[serde(default)]
66    api: String,
67}
68
69/// A body read up to a cap, and whether the cap cut it.
70struct Limited {
71    bytes: Vec<u8>,
72    truncated: bool,
73}
74
75/// Reads at most `max` bytes. More than that is reported as a cut body
76/// rather than as an error, because a long log is still worth showing.
77fn read_capped(mut response: Response<Body>, max: usize) -> Result<Limited, Error> {
78    let mut bytes = Vec::new();
79    response
80        .body_mut()
81        .as_reader()
82        .take(max as u64 + 1)
83        .read_to_end(&mut bytes)
84        .map_err(|_| Error::Network("The Copilot session could not be read.".into()))?;
85    let truncated = bytes.len() > max;
86    bytes.truncate(max);
87    Ok(Limited { bytes, truncated })
88}
89
90impl Client {
91    /// The Copilot API base for the work account. GraphQL answers it, and
92    /// the answer is kept for the run, so one process asks once.
93    pub fn copilot_api_url(&self) -> Result<String, Error> {
94        match self.copilot_api.get() {
95            Some(url) => Ok(url.clone()),
96            None => self.resolve_copilot_api(),
97        }
98    }
99
100    fn resolve_copilot_api(&self) -> Result<String, Error> {
101        let login = self.work_login()?;
102        let data: Endpoints = self.graphql(Some(&login), ENDPOINT_QUERY, json!({}), false)?;
103        let url = plain_https_url(&data.viewer.copilot_endpoints.api)
104            .map_err(|_| transport::unexpected("Copilot API URL"))?;
105        Ok(self.copilot_api.get_or_init(|| url).clone())
106    }
107
108    /// The OAuth token of `login`: its Subspace sign-in or gh CLI token. An
109    /// environment or config-file token is refused here, before any request
110    /// leaves the process.
111    fn oauth_credential(&self, login: &str) -> Result<Credential, Error> {
112        let credential = self.credentials.github(Some(login))?;
113        match credential.source {
114            Source::GhCli { .. } | Source::SignedIn { .. } => Ok(credential),
115            _ => Err(Error::Status {
116                status: http_status::FORBIDDEN,
117                message: needs_oauth_login(self.credentials.sign_in_offered()),
118            }),
119        }
120    }
121
122    /// One session document. It carries the pull request number and state
123    /// the REST task artifact may be missing.
124    // qual:api
125    pub fn copilot_agent_session(&self, session_id: &str) -> Result<CopilotAgentSession, Error> {
126        let body = self.copilot_read(session_id, "", transport::JSON, MAX_SESSION_BYTES)?;
127        serde_json::from_slice(&body.bytes).map_err(|_| transport::unexpected("session"))
128    }
129
130    /// One session's log, parsed. `max_bytes` never goes above
131    /// [`MAX_LOG_BYTES`]; a log the cap cut says so.
132    // qual:api
133    pub fn copilot_agent_session_log(
134        &self,
135        session_id: &str,
136        max_bytes: usize,
137    ) -> Result<SessionLog, Error> {
138        let body = self.copilot_read(
139            session_id,
140            "/logs",
141            transport::EVENT_STREAM,
142            max_bytes.min(MAX_LOG_BYTES),
143        )?;
144        Ok(parse_log(
145            &String::from_utf8_lossy(&body.bytes),
146            body.truncated,
147        ))
148    }
149
150    fn copilot_read(
151        &self,
152        session_id: &str,
153        suffix: &str,
154        accept: &str,
155        max: usize,
156    ) -> Result<Limited, Error> {
157        validate_task_id(session_id)?;
158        let login = self.work_login()?;
159        let credential = self.oauth_credential(&login)?;
160        let base = self.copilot_api_url()?;
161        let url = format!("{base}/agents/sessions/{session_id}{suffix}");
162        let account = transport::account_label(&credential, Some(login.as_str()));
163        let response = transport::get_copilot(&url, &credential, &account, accept)?;
164        read_capped(response, max)
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use std::sync::Arc;
171    use std::time::Duration;
172
173    use subspace_core::config::Config;
174    use subspace_core::credentials::{Credentials, Environment, Runner};
175    use subspace_core::http::Error;
176
177    use super::{MAX_LOG_BYTES, needs_oauth_login};
178    use crate::Client;
179
180    struct EnvToken;
181    impl Environment for EnvToken {
182        fn var(&self, name: &str) -> Option<String> {
183            (name == "GH_TOKEN").then(|| "token".into())
184        }
185    }
186
187    struct NoRunner;
188    impl Runner for NoRunner {
189        fn run(&self, _: &str, _: &[&str], _: &[&str], _: Duration) -> Result<String, String> {
190            Err("unused".into())
191        }
192    }
193
194    #[test]
195    fn an_environment_token_is_refused_with_what_to_do_about_it() {
196        let credentials = Credentials::new(&Config::default(), EnvToken, NoRunner);
197        let client = Client::new(Arc::new(credentials));
198        let error = client.oauth_credential("work_emu").unwrap_err();
199        assert!(matches!(error, Error::Status { status: 403, .. }));
200        assert_eq!(error.to_string(), needs_oauth_login(false));
201        assert!(!needs_oauth_login(false).contains("Sign in with GitHub"));
202        assert!(needs_oauth_login(true).contains("Sign in with GitHub in Settings"));
203    }
204
205    #[test]
206    fn a_body_over_the_cap_is_cut_and_reported_rather_than_refused() {
207        let body = ureq::Body::builder().data("0123456789");
208        let cut = super::read_capped(ureq::http::Response::new(body), 4).unwrap();
209        assert_eq!(cut.bytes, b"0123");
210        assert!(cut.truncated);
211        let body = ureq::Body::builder().data("0123");
212        let whole = super::read_capped(ureq::http::Response::new(body), 4).unwrap();
213        assert_eq!(whole.bytes, b"0123");
214        assert!(!whole.truncated, "a body that just fits is not cut");
215        assert_eq!(MAX_LOG_BYTES, 2 * 1024 * 1024);
216    }
217}