use std::io::Read as _;
use serde::Deserialize;
use serde_json::json;
use ureq::Body;
use ureq::http::Response;
use subspace_core::credentials::{Credential, Source};
use subspace_core::http::status as http_status;
use subspace_core::http::{Error, plain_https_url};
use crate::Client;
use crate::PinnedWork;
use crate::copilot_agents::validate_task_id;
use crate::transport;
mod log;
mod model;
pub use log::{LogEntry, SessionLog, parse_log};
pub use model::CopilotAgentSession;
const MAX_SESSION_BYTES: usize = 256 * 1024;
pub const MAX_LOG_BYTES: usize = 2 * 1024 * 1024;
const ENDPOINT_QUERY: &str = "query { viewer { copilotEndpoints { api } } }";
pub fn needs_oauth_login(sign_in_offered: bool) -> String {
let lead = if sign_in_offered {
"Sign in with GitHub in Settings or run"
} else {
"Run"
};
format!(
"The session log needs a GitHub sign-in. {lead} `gh auth login` for the work account, \
and unset GH_TOKEN and GITHUB_TOKEN."
)
}
#[derive(Debug, Deserialize)]
struct Endpoints {
viewer: Viewer,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Viewer {
copilot_endpoints: CopilotEndpoints,
}
#[derive(Debug, Deserialize)]
struct CopilotEndpoints {
#[serde(default)]
api: String,
}
struct Limited {
bytes: Vec<u8>,
truncated: bool,
}
fn read_capped(mut response: Response<Body>, max: usize) -> Result<Limited, Error> {
let mut bytes = Vec::new();
response
.body_mut()
.as_reader()
.take(max as u64 + 1)
.read_to_end(&mut bytes)
.map_err(|_| Error::Network("The Copilot session could not be read.".into()))?;
let truncated = bytes.len() > max;
bytes.truncate(max);
Ok(Limited { bytes, truncated })
}
fn require_oauth(credential: &Credential, sign_in_offered: bool) -> Result<(), Error> {
match credential.source {
Source::GhCli { .. } | Source::SignedIn { .. } => Ok(()),
_ => Err(Error::Status {
status: http_status::FORBIDDEN,
message: needs_oauth_login(sign_in_offered),
}),
}
}
impl Client {
pub fn copilot_api_url(&self) -> Result<String, Error> {
match self.copilot_api.get() {
Some(url) => Ok(url.clone()),
None => self.pin_work()?.copilot_api_url(),
}
}
pub fn copilot_agent_session(&self, session_id: &str) -> Result<CopilotAgentSession, Error> {
validate_task_id(session_id)?;
self.pin_work()?.copilot_agent_session(session_id)
}
pub fn copilot_agent_session_log(
&self,
session_id: &str,
max_bytes: usize,
) -> Result<SessionLog, Error> {
validate_task_id(session_id)?;
self.pin_work()?
.copilot_agent_session_log(session_id, max_bytes)
}
}
impl PinnedWork<'_> {
fn copilot_api_url(&self) -> Result<String, Error> {
if let Some(url) = self.client.copilot_api.get() {
return Ok(url.clone());
}
let data: Endpoints = self.graphql(ENDPOINT_QUERY, json!({}))?;
let url = plain_https_url(&data.viewer.copilot_endpoints.api)
.map_err(|_| transport::unexpected("Copilot API URL"))?;
Ok(self.client.copilot_api.get_or_init(|| url).clone())
}
pub fn copilot_agent_session(&self, session_id: &str) -> Result<CopilotAgentSession, Error> {
let body = self.copilot_read(session_id, "", transport::JSON, MAX_SESSION_BYTES)?;
serde_json::from_slice(&body.bytes).map_err(|_| transport::unexpected("session"))
}
pub fn copilot_agent_session_log(
&self,
session_id: &str,
max_bytes: usize,
) -> Result<SessionLog, Error> {
let body = self.copilot_read(
session_id,
"/logs",
transport::EVENT_STREAM,
max_bytes.min(MAX_LOG_BYTES),
)?;
Ok(parse_log(
&String::from_utf8_lossy(&body.bytes),
body.truncated,
))
}
fn copilot_read(
&self,
session_id: &str,
suffix: &str,
accept: &str,
max: usize,
) -> Result<Limited, Error> {
validate_task_id(session_id)?;
require_oauth(&self.credential, self.client.credentials.sign_in_offered())?;
let base = self.copilot_api_url()?;
let url = format!("{base}/agents/sessions/{session_id}{suffix}");
let response = self.checked(transport::get_copilot(
&url,
&self.credential,
&self.account(),
accept,
))?;
read_capped(response, max)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use subspace_core::config::Config;
use subspace_core::credentials::{Credentials, Environment, Runner};
use subspace_core::http::Error;
use super::{MAX_LOG_BYTES, needs_oauth_login, require_oauth};
struct EnvToken;
impl Environment for EnvToken {
fn var(&self, name: &str) -> Option<String> {
(name == "GH_TOKEN").then(|| "token".into())
}
}
struct NoRunner;
impl Runner for NoRunner {
fn run(&self, _: &str, _: &[&str], _: &[&str], _: Duration) -> Result<String, String> {
Err("unused".into())
}
}
#[test]
fn an_environment_token_is_refused_with_what_to_do_about_it() {
let credentials = Credentials::new(&Config::default(), EnvToken, NoRunner);
let credential = credentials.github(Some("work_emu")).unwrap();
let error = require_oauth(&credential, credentials.sign_in_offered()).unwrap_err();
assert!(matches!(error, Error::Status { status: 403, .. }));
assert_eq!(error.to_string(), needs_oauth_login(false));
assert!(!needs_oauth_login(false).contains("Sign in with GitHub"));
assert!(needs_oauth_login(true).contains("Sign in with GitHub in Settings"));
}
#[test]
fn a_body_over_the_cap_is_cut_and_reported_rather_than_refused() {
let body = ureq::Body::builder().data("0123456789");
let cut = super::read_capped(ureq::http::Response::new(body), 4).unwrap();
assert_eq!(cut.bytes, b"0123");
assert!(cut.truncated);
let body = ureq::Body::builder().data("0123");
let whole = super::read_capped(ureq::http::Response::new(body), 4).unwrap();
assert_eq!(whole.bytes, b"0123");
assert!(!whole.truncated, "a body that just fits is not cut");
assert_eq!(MAX_LOG_BYTES, 2 * 1024 * 1024);
}
}