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::PinnedWork;
22use crate::copilot_agents::validate_task_id;
23use crate::transport;
24
25mod log;
26mod model;
27
28pub use log::{LogEntry, SessionLog, parse_log};
29pub use model::CopilotAgentSession;
30
31const MAX_SESSION_BYTES: usize = 256 * 1024;
33pub const MAX_LOG_BYTES: usize = 2 * 1024 * 1024;
36
37const ENDPOINT_QUERY: &str = "query { viewer { copilotEndpoints { api } } }";
38
39pub fn needs_oauth_login(sign_in_offered: bool) -> String {
42 let lead = if sign_in_offered {
43 "Sign in with GitHub in Settings or run"
44 } else {
45 "Run"
46 };
47 format!(
48 "The session log needs a GitHub sign-in. {lead} `gh auth login` for the work account, \
49 and unset GH_TOKEN and GITHUB_TOKEN."
50 )
51}
52
53#[derive(Debug, Deserialize)]
54struct Endpoints {
55 viewer: Viewer,
56}
57
58#[derive(Debug, Deserialize)]
59#[serde(rename_all = "camelCase")]
60struct Viewer {
61 copilot_endpoints: CopilotEndpoints,
62}
63
64#[derive(Debug, Deserialize)]
65struct CopilotEndpoints {
66 #[serde(default)]
67 api: String,
68}
69
70struct Limited {
72 bytes: Vec<u8>,
73 truncated: bool,
74}
75
76fn read_capped(mut response: Response<Body>, max: usize) -> Result<Limited, Error> {
79 let mut bytes = Vec::new();
80 response
81 .body_mut()
82 .as_reader()
83 .take(max as u64 + 1)
84 .read_to_end(&mut bytes)
85 .map_err(|_| Error::Network("The Copilot session could not be read.".into()))?;
86 let truncated = bytes.len() > max;
87 bytes.truncate(max);
88 Ok(Limited { bytes, truncated })
89}
90
91fn require_oauth(credential: &Credential, sign_in_offered: bool) -> Result<(), Error> {
95 match credential.source {
96 Source::GhCli { .. } | Source::SignedIn { .. } => Ok(()),
97 _ => Err(Error::Status {
98 status: http_status::FORBIDDEN,
99 message: needs_oauth_login(sign_in_offered),
100 }),
101 }
102}
103
104impl Client {
105 pub fn copilot_api_url(&self) -> Result<String, Error> {
108 match self.copilot_api.get() {
109 Some(url) => Ok(url.clone()),
110 None => self.pin_work()?.copilot_api_url(),
111 }
112 }
113
114 pub fn copilot_agent_session(&self, session_id: &str) -> Result<CopilotAgentSession, Error> {
119 validate_task_id(session_id)?;
120 self.pin_work()?.copilot_agent_session(session_id)
121 }
122
123 pub fn copilot_agent_session_log(
128 &self,
129 session_id: &str,
130 max_bytes: usize,
131 ) -> Result<SessionLog, Error> {
132 validate_task_id(session_id)?;
133 self.pin_work()?
134 .copilot_agent_session_log(session_id, max_bytes)
135 }
136}
137
138impl PinnedWork<'_> {
139 fn copilot_api_url(&self) -> Result<String, Error> {
142 if let Some(url) = self.client.copilot_api.get() {
143 return Ok(url.clone());
144 }
145 let data: Endpoints = self.graphql(ENDPOINT_QUERY, json!({}))?;
146 let url = plain_https_url(&data.viewer.copilot_endpoints.api)
147 .map_err(|_| transport::unexpected("Copilot API URL"))?;
148 Ok(self.client.copilot_api.get_or_init(|| url).clone())
149 }
150
151 pub fn copilot_agent_session(&self, session_id: &str) -> Result<CopilotAgentSession, Error> {
154 let body = self.copilot_read(session_id, "", transport::JSON, MAX_SESSION_BYTES)?;
155 serde_json::from_slice(&body.bytes).map_err(|_| transport::unexpected("session"))
156 }
157
158 pub fn copilot_agent_session_log(
162 &self,
163 session_id: &str,
164 max_bytes: usize,
165 ) -> Result<SessionLog, Error> {
166 let body = self.copilot_read(
167 session_id,
168 "/logs",
169 transport::EVENT_STREAM,
170 max_bytes.min(MAX_LOG_BYTES),
171 )?;
172 Ok(parse_log(
173 &String::from_utf8_lossy(&body.bytes),
174 body.truncated,
175 ))
176 }
177
178 fn copilot_read(
179 &self,
180 session_id: &str,
181 suffix: &str,
182 accept: &str,
183 max: usize,
184 ) -> Result<Limited, Error> {
185 validate_task_id(session_id)?;
186 require_oauth(&self.credential, self.client.credentials.sign_in_offered())?;
187 let base = self.copilot_api_url()?;
188 let url = format!("{base}/agents/sessions/{session_id}{suffix}");
189 let response = self.checked(transport::get_copilot(
190 &url,
191 &self.credential,
192 &self.account(),
193 accept,
194 ))?;
195 read_capped(response, max)
196 }
197}
198
199#[cfg(test)]
200mod tests {
201 use std::time::Duration;
202
203 use subspace_core::config::Config;
204 use subspace_core::credentials::{Credentials, Environment, Runner};
205 use subspace_core::http::Error;
206
207 use super::{MAX_LOG_BYTES, needs_oauth_login, require_oauth};
208
209 struct EnvToken;
210 impl Environment for EnvToken {
211 fn var(&self, name: &str) -> Option<String> {
212 (name == "GH_TOKEN").then(|| "token".into())
213 }
214 }
215
216 struct NoRunner;
217 impl Runner for NoRunner {
218 fn run(&self, _: &str, _: &[&str], _: &[&str], _: Duration) -> Result<String, String> {
219 Err("unused".into())
220 }
221 }
222
223 #[test]
224 fn an_environment_token_is_refused_with_what_to_do_about_it() {
225 let credentials = Credentials::new(&Config::default(), EnvToken, NoRunner);
226 let credential = credentials.github(Some("work_emu")).unwrap();
227 let error = require_oauth(&credential, credentials.sign_in_offered()).unwrap_err();
228 assert!(matches!(error, Error::Status { status: 403, .. }));
229 assert_eq!(error.to_string(), needs_oauth_login(false));
230 assert!(!needs_oauth_login(false).contains("Sign in with GitHub"));
231 assert!(needs_oauth_login(true).contains("Sign in with GitHub in Settings"));
232 }
233
234 #[test]
235 fn a_body_over_the_cap_is_cut_and_reported_rather_than_refused() {
236 let body = ureq::Body::builder().data("0123456789");
237 let cut = super::read_capped(ureq::http::Response::new(body), 4).unwrap();
238 assert_eq!(cut.bytes, b"0123");
239 assert!(cut.truncated);
240 let body = ureq::Body::builder().data("0123");
241 let whole = super::read_capped(ureq::http::Response::new(body), 4).unwrap();
242 assert_eq!(whole.bytes, b"0123");
243 assert!(!whole.truncated, "a body that just fits is not cut");
244 assert_eq!(MAX_LOG_BYTES, 2 * 1024 * 1024);
245 }
246}