1use serde::{Deserialize, Serialize};
2use std::error::Error;
3use std::path::Path;
4use url::Url;
5
6pub struct ApiClient {
7 base_url: String,
8 api_key: Option<String>,
9 client: reqwest::Client,
10}
11
12#[derive(Serialize)]
13pub struct RegisterRepoRequest {
14 pub repo_name: String,
15 pub github_url: Option<String>,
16}
17
18#[derive(Debug, Deserialize)]
19pub struct RegisterRepoResponse {
20 pub repo_id: uuid::Uuid,
21}
22
23#[derive(Debug, Deserialize)]
24pub struct ResolveRemoteResponse {
25 pub remote_id: uuid::Uuid,
26 #[serde(default)]
27 pub name: Option<String>,
28 pub normalized_url: String,
29 pub clone_status: String,
30}
31
32#[derive(Deserialize)]
33pub struct RemoteRepoRef {
34 pub id: uuid::Uuid,
35 #[allow(dead_code)]
38 pub name: String,
39}
40
41#[derive(Deserialize)]
44pub struct RemoteDetail {
45 #[serde(default)]
46 pub name: Option<String>,
47 pub normalized_url: String,
48 pub clone_status: String,
49 pub repos: Vec<RemoteRepoRef>,
50}
51
52#[derive(Deserialize)]
53pub struct DeviceAuthResponse {
54 pub token: String,
55}
56
57#[derive(Deserialize)]
58pub struct DeviceStatusResponse {
59 pub status: String,
60 pub token: Option<String>,
61 pub email: Option<String>,
62}
63
64#[derive(Debug, Serialize)]
65pub struct CheckPoliciesRequest {
66 pub sessions: Vec<SessionCheckData>,
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub commit_sha: Option<String>,
69}
70
71#[derive(Debug, Serialize)]
72pub struct SessionCheckData {
73 pub session_id: String,
74 pub tool_calls: Option<serde_json::Value>,
75 pub files_modified: Option<Vec<String>>,
76 pub total_tool_calls: Option<i32>,
77}
78
79#[derive(Debug, Deserialize)]
80pub struct CheckPoliciesResponse {
81 pub passed: bool,
82 pub results: Vec<CheckResultItem>,
83 pub blocked: bool,
84}
85
86#[derive(Debug, Deserialize)]
87pub struct CheckResultItem {
88 pub rule_name: String,
89 pub result: String,
90 pub action: String,
91 pub severity: String,
92 pub details: String,
93}
94
95#[derive(Debug, Deserialize)]
96pub struct RepoListItem {
97 pub id: uuid::Uuid,
98 pub name: String,
99 #[serde(default)]
100 pub github_url: Option<String>,
101 #[serde(default)]
102 pub clone_status: Option<String>,
103}
104
105#[derive(Debug, Clone, Deserialize)]
107pub struct AgentInstructionsResponse {
108 #[allow(dead_code)]
109 pub format: String,
110 pub content: String,
111}
112
113#[derive(Debug, Deserialize)]
114pub struct MeResponse {
115 #[allow(dead_code)]
116 pub user_id: uuid::Uuid,
117 pub email: String,
118 pub name: Option<String>,
119}
120
121#[derive(Debug)]
122pub enum GetMeError {
123 Unauthorized,
125 Network(String),
127 Server(String),
129}
130
131impl std::fmt::Display for GetMeError {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 match self {
134 Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
135 Self::Network(m) => write!(f, "network error: {m}"),
136 Self::Server(m) => write!(f, "server error: {m}"),
137 }
138 }
139}
140
141impl std::error::Error for GetMeError {}
142
143#[derive(Debug, Serialize)]
144pub struct CiVerifyRequest {
145 pub commits: Vec<String>,
146}
147
148#[derive(Debug, Deserialize)]
149pub struct CiVerifyResponse {
150 pub status: String,
151 pub total_commits: usize,
152 pub registered_commits: usize,
153 pub sealed_commits: usize,
154 pub policy_passed_commits: usize,
155 pub results: Vec<CommitVerifyResult>,
156}
157
158#[derive(Debug, Deserialize)]
159pub struct CommitVerifyResult {
160 pub commit_sha: String,
161 pub status: String,
162 pub registered: bool,
163 pub sealed: bool,
164 pub signature_valid: bool,
165 pub chain_valid: bool,
166 pub policy_results: Vec<CiPolicyResult>,
167}
168
169#[derive(Debug, Deserialize)]
170pub struct CiPolicyResult {
171 pub rule_name: String,
172 pub result: String,
173 pub action: String,
174 pub severity: String,
175 pub details: String,
176}
177
178#[derive(Debug, Deserialize)]
181pub struct ProjectListItem {
182 pub id: uuid::Uuid,
183 pub name: String,
184}
185
186#[derive(Debug, Deserialize)]
188pub struct ProjectRepoRef {
189 pub id: uuid::Uuid,
190}
191
192#[derive(Debug, Deserialize)]
195pub struct ProjectDetail {
196 pub repos: Vec<ProjectRepoRef>,
197}
198
199#[derive(Debug)]
203pub enum ResolveProjectOutcome {
204 Resolved(uuid::Uuid),
205 None,
206 Ambiguous,
207}
208
209#[derive(Deserialize)]
211struct ResolveProjectResponse {
212 project_id: uuid::Uuid,
213}
214
215impl ApiClient {
216 pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
217 Self {
218 base_url: base_url.trim_end_matches('/').to_string(),
219 api_key: api_key.map(String::from),
220 client: reqwest::Client::builder()
221 .timeout(std::time::Duration::from_secs(60))
222 .build()
223 .unwrap_or_default(),
224 }
225 }
226
227 pub async fn register_repo(
228 &self,
229 req: RegisterRepoRequest,
230 ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
231 let builder = self
232 .client
233 .post(format!("{}/api/v1/repos", self.base_url))
234 .json(&req);
235 self.authed_send_json(builder, |status| format!("Server returned {status}"))
236 .await
237 }
238
239 pub async fn device_start(&self) -> Result<DeviceAuthResponse, Box<dyn Error>> {
240 let resp = self
241 .client
242 .post(format!("{}/api/v1/auth/device", self.base_url))
246 .header(reqwest::header::CONTENT_LENGTH, "0")
247 .send()
248 .await?;
249
250 if !resp.status().is_success() {
251 let status = resp.status();
252 let body = resp.text().await.unwrap_or_default();
253 return Err(format!("Server returned {status}: {body}").into());
254 }
255
256 Ok(resp.json().await?)
257 }
258
259 pub async fn device_status(&self, token: &str) -> Result<DeviceStatusResponse, Box<dyn Error>> {
260 let resp = self
261 .client
262 .get(format!(
263 "{}/api/v1/auth/device/{token}/status",
264 self.base_url
265 ))
266 .send()
267 .await?;
268
269 if !resp.status().is_success() {
270 let status = resp.status();
271 let body = resp.text().await.unwrap_or_default();
272 return Err(format!("Server returned {status}: {body}").into());
273 }
274
275 Ok(resp.json().await?)
276 }
277
278 pub async fn logout(&self) -> Result<(), Box<dyn Error>> {
279 let mut builder = self
280 .client
281 .post(format!("{}/api/v1/auth/logout", self.base_url));
282 if let Some(key) = &self.api_key {
283 builder = builder.header("Authorization", format!("Bearer {key}"));
284 }
285 let resp = builder
288 .header(reqwest::header::CONTENT_LENGTH, "0")
289 .send()
290 .await?;
291 if !resp.status().is_success() {
292 let status = resp.status();
293 let body = resp.text().await.unwrap_or_default();
294 return Err(format!("Server returned {status}: {body}").into());
295 }
296 Ok(())
297 }
298
299 fn attach_auth(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
303 match &self.api_key {
304 Some(key) => builder.header("Authorization", format!("Bearer {key}")),
305 None => builder,
306 }
307 }
308
309 async fn send_authed(
314 &self,
315 builder: reqwest::RequestBuilder,
316 ) -> Result<reqwest::Response, Box<dyn Error>> {
317 Ok(self.attach_auth(builder).send().await?)
318 }
319
320 async fn success_json<T, F>(resp: reqwest::Response, err_prefix: F) -> Result<T, Box<dyn Error>>
327 where
328 T: serde::de::DeserializeOwned,
329 F: FnOnce(reqwest::StatusCode) -> String,
330 {
331 let status = resp.status();
332 if !status.is_success() {
333 let body = resp.text().await.unwrap_or_default();
334 return Err(format!("{}: {}", err_prefix(status), body).into());
335 }
336 Ok(resp.json().await?)
337 }
338
339 async fn authed_send_json<T, F>(
351 &self,
352 builder: reqwest::RequestBuilder,
353 err_prefix: F,
354 ) -> Result<T, Box<dyn Error>>
355 where
356 T: serde::de::DeserializeOwned,
357 F: FnOnce(reqwest::StatusCode) -> String,
358 {
359 let resp = self.send_authed(builder).await?;
360 Self::success_json(resp, err_prefix).await
361 }
362
363 async fn authed_get_json<T: serde::de::DeserializeOwned>(
368 &self,
369 path: &str,
370 ) -> Result<T, GetMeError> {
371 let builder = self.attach_auth(self.client.get(format!("{}{}", self.base_url, path)));
372
373 let resp = builder
374 .send()
375 .await
376 .map_err(|e| GetMeError::Network(e.to_string()))?;
377
378 let status = resp.status();
379 if status == reqwest::StatusCode::UNAUTHORIZED {
380 return Err(GetMeError::Unauthorized);
381 }
382 if !status.is_success() {
383 let body = resp.text().await.unwrap_or_default();
384 return Err(GetMeError::Server(format!("{status}: {body}")));
385 }
386
387 resp.json::<T>()
388 .await
389 .map_err(|e| GetMeError::Server(e.to_string()))
390 }
391
392 pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
396 self.authed_get_json("/api/v1/auth/me").await
397 }
398
399 pub async fn list_repos(&self) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
400 let builder = self.client.get(format!("{}/api/v1/repos", self.base_url));
401 self.authed_send_json(builder, |status| format!("Failed to list repos ({status})"))
402 .await
403 }
404
405 pub async fn get_agent_instructions(
406 &self,
407 repo_id: &uuid::Uuid,
408 ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
409 let builder = self.client.get(format!(
410 "{}/api/v1/repos/{}/policies/agent-instructions",
411 self.base_url, repo_id
412 ));
413 self.authed_send_json(builder, |status| {
414 format!("Failed to fetch agent instructions ({status})")
415 })
416 .await
417 }
418
419 pub async fn verify_commits(
420 &self,
421 repo_id: &uuid::Uuid,
422 req: CiVerifyRequest,
423 ) -> Result<CiVerifyResponse, Box<dyn Error>> {
424 let builder = self
425 .client
426 .post(format!(
427 "{}/api/v1/repos/{}/ci/verify",
428 self.base_url, repo_id
429 ))
430 .json(&req);
431 self.authed_send_json(builder, |status| format!("CI verify failed ({status})"))
432 .await
433 }
434
435 pub async fn push_commit(
436 &self,
437 repo_id: &str,
438 req: &tracevault_protocol::streaming::CommitPushRequest,
439 ) -> Result<tracevault_protocol::streaming::CommitPushResponse, Box<dyn Error>> {
440 let builder = self
441 .client
442 .post(format!(
443 "{}/api/v1/repos/{}/commits",
444 self.base_url, repo_id
445 ))
446 .json(req);
447 self.authed_send_json(builder, |status| format!("Commit push failed ({status})"))
448 .await
449 }
450
451 pub async fn stream_event(
452 &self,
453 repo_id: &str,
454 req: &tracevault_protocol::streaming::StreamEventRequest,
455 ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
456 let builder = self
457 .client
458 .post(format!("{}/api/v1/repos/{}/stream", self.base_url, repo_id))
459 .json(req);
460 self.authed_send_json(builder, |status| format!("Stream failed ({status})"))
461 .await
462 }
463
464 pub async fn stream_event_for_project(
473 &self,
474 project_id: uuid::Uuid,
475 repo_id: &str,
476 req: &tracevault_protocol::streaming::StreamEventRequest,
477 ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
478 let mut url = Url::parse(&format!(
479 "{}/api/v1/projects/{}/stream",
480 self.base_url, project_id
481 ))?;
482 url.query_pairs_mut().append_pair("repo_id", repo_id);
483 let builder = self.client.post(url).json(req);
484 self.authed_send_json(builder, |status| {
485 format!("Project stream failed ({status})")
486 })
487 .await
488 }
489
490 pub async fn check_policies(
491 &self,
492 repo_id: &uuid::Uuid,
493 req: CheckPoliciesRequest,
494 ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
495 let builder = self
496 .client
497 .post(format!(
498 "{}/api/v1/repos/{}/policies/check",
499 self.base_url, repo_id
500 ))
501 .json(&req);
502 self.authed_send_json(builder, |status| format!("Policy check failed ({status})"))
503 .await
504 }
505
506 pub async fn resolve_remote(
516 &self,
517 git_url: &str,
518 ) -> Result<Option<ResolveRemoteResponse>, Box<dyn std::error::Error>> {
519 let mut url = Url::parse(&format!("{}/api/v1/remotes/resolve", self.base_url))?;
520 url.query_pairs_mut().append_pair("git_url", git_url);
521 let resp = self.send_authed(self.client.get(url)).await?;
522 if resp.status() == reqwest::StatusCode::NOT_FOUND {
523 let body = resp.text().await.unwrap_or_default();
524 return if is_domain_error_body(&body) {
525 Ok(None)
526 } else {
527 Err(version_skew_404_error("resolve_remote"))
528 };
529 }
530 let parsed: ResolveRemoteResponse =
531 Self::success_json(resp, |status| format!("resolve_remote failed ({status})")).await?;
532 Ok(Some(parsed))
533 }
534
535 pub async fn get_remote_detail(
538 &self,
539 remote_id: uuid::Uuid,
540 ) -> Result<RemoteDetail, Box<dyn std::error::Error>> {
541 let builder = self
542 .client
543 .get(format!("{}/api/v1/remotes/{}", self.base_url, remote_id));
544 self.authed_send_json(builder, |status| {
545 format!("get_remote_detail failed ({status})")
546 })
547 .await
548 }
549
550 pub async fn get_remote_repos(
552 &self,
553 remote_id: uuid::Uuid,
554 ) -> Result<Vec<RemoteRepoRef>, Box<dyn std::error::Error>> {
555 Ok(self.get_remote_detail(remote_id).await?.repos)
556 }
557
558 pub async fn list_projects(&self) -> Result<Vec<ProjectListItem>, Box<dyn Error>> {
560 let builder = self
561 .client
562 .get(format!("{}/api/v1/projects", self.base_url));
563 self.authed_send_json(builder, |status| {
564 format!("Failed to list projects ({status})")
565 })
566 .await
567 }
568
569 pub async fn get_project(&self, id: uuid::Uuid) -> Result<ProjectDetail, Box<dyn Error>> {
571 let builder = self
572 .client
573 .get(format!("{}/api/v1/projects/{}", self.base_url, id));
574 self.authed_send_json(builder, |status| {
575 format!("Failed to get project ({status})")
576 })
577 .await
578 }
579
580 pub async fn resolve_project(
586 &self,
587 git_url: &str,
588 ) -> Result<ResolveProjectOutcome, Box<dyn std::error::Error>> {
589 let mut url = Url::parse(&format!("{}/api/v1/projects/resolve", self.base_url))?;
590 url.query_pairs_mut().append_pair("git_url", git_url);
591 let resp = self.send_authed(self.client.get(url)).await?;
592 let status = resp.status();
593 if status == reqwest::StatusCode::NOT_FOUND {
594 let body = resp.text().await.unwrap_or_default();
595 return if is_domain_error_body(&body) {
596 Ok(ResolveProjectOutcome::None)
597 } else {
598 Err(version_skew_404_error("resolve_project"))
599 };
600 }
601 if status == reqwest::StatusCode::CONFLICT {
602 return Ok(ResolveProjectOutcome::Ambiguous);
603 }
604 let parsed: ResolveProjectResponse =
605 Self::success_json(resp, |status| format!("resolve_project failed ({status})")).await?;
606 Ok(ResolveProjectOutcome::Resolved(parsed.project_id))
607 }
608}
609
610fn is_domain_error_body(body: &str) -> bool {
619 serde_json::from_str::<serde_json::Value>(body)
620 .ok()
621 .and_then(|v| v.get("error").map(|_| ()))
622 .is_some()
623}
624
625fn version_skew_404_error(what: &str) -> Box<dyn std::error::Error> {
631 format!(
632 "{what} got a 404 with no recognizable error body — this endpoint may not exist on \
633 this server yet. This usually means the CLI is newer than the server (a CLI/server \
634 version mismatch); confirm the server has been upgraded and retry."
635 )
636 .into()
637}
638
639pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
643 use crate::credentials::Credentials;
644
645 let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
647
648 let creds = Credentials::load();
650
651 let config_path = crate::config::TracevaultConfig::config_path(project_root);
653 let config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
654
655 let config_server_url = config_content
656 .lines()
657 .find(|l| l.starts_with("server_url"))
658 .and_then(|l| l.split('=').nth(1))
659 .map(|s| s.trim().trim_matches('"').to_string());
660
661 let config_api_key = config_content
662 .lines()
663 .find(|l| l.starts_with("api_key"))
664 .and_then(|l| l.split('=').nth(1))
665 .map(|s| s.trim().trim_matches('"').to_string());
666
667 let server_url = std::env::var("TRACEVAULT_SERVER_URL")
669 .ok()
670 .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
671 .or(config_server_url);
672
673 let token = env_key
675 .or_else(|| creds.map(|c| c.token))
676 .or(config_api_key);
677
678 (server_url, token)
679}
680
681pub fn resolve_client(project_root: &Path) -> Result<ApiClient, Box<dyn Error>> {
687 let (server_url, token) = resolve_credentials(project_root);
688 let server_url = server_url
689 .ok_or("no server URL configured: set TRACEVAULT_SERVER_URL or run `tracevault login`")?;
690 Ok(ApiClient::new(&server_url, token.as_deref()))
691}