subspace_client_github/
copilot_agent_sessions.rs1use 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
30const MAX_SESSION_BYTES: usize = 256 * 1024;
32pub const MAX_LOG_BYTES: usize = 2 * 1024 * 1024;
35
36const ENDPOINT_QUERY: &str = "query { viewer { copilotEndpoints { api } } }";
37
38pub 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
69struct Limited {
71 bytes: Vec<u8>,
72 truncated: bool,
73}
74
75fn 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 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 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 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 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}