Skip to main content

tracevault_cli/
api_client.rs

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    // Reserved for display (e.g. a future `repo status`/error message listing
36    // a codebase's linked repos by name); not read by any caller yet.
37    #[allow(dead_code)]
38    pub name: String,
39}
40
41// The server's RemoteDetailResponse flattens the remote fields at top level and
42// adds a `repos` array; serde ignores any other top-level fields.
43#[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/// Response shape for the `policies/agent-instructions` endpoint.
106#[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    /// 401 — token is missing or invalid.
124    Unauthorized,
125    /// Transport-level failure (DNS, TCP, TLS, timeout).
126    Network(String),
127    /// HTTP ≥ 400 other than 401, or malformed JSON.
128    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/// One project in `GET /api/v1/projects`. Server sends more
179/// fields; only these two are consumed today.
180#[derive(Debug, Deserialize)]
181pub struct ProjectListItem {
182    pub id: uuid::Uuid,
183    pub name: String,
184}
185
186/// A repo linked to a project (member of `ProjectDetail::repos`).
187#[derive(Debug, Deserialize)]
188pub struct ProjectRepoRef {
189    pub id: uuid::Uuid,
190}
191
192/// Full detail for a project. Server sends more fields; only `repos` is
193/// consumed today.
194#[derive(Debug, Deserialize)]
195pub struct ProjectDetail {
196    pub repos: Vec<ProjectRepoRef>,
197}
198
199/// Outcome of `ApiClient::resolve_project`, distinguishing "no project"
200/// (404) from "ambiguous, multiple candidates" (409) — unlike
201/// `resolve_remote`, which only distinguishes found/not-found.
202#[derive(Debug)]
203pub enum ResolveProjectOutcome {
204    Resolved(uuid::Uuid),
205    None,
206    Ambiguous,
207}
208
209/// Wire shape of a successful `resolve_project` response.
210#[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            // Send an explicit `Content-Length: 0`. reqwest/hyper omit the header
243            // entirely for a bodyless POST, and strict frontends (e.g. Google
244            // Front End) reject such requests with `411 Length Required`.
245            .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        // Explicit `Content-Length: 0` (see `device_start`): reqwest/hyper omit it
286        // for a bodyless POST, which strict frontends reject with 411.
287        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    /// Attach the bearer token (if configured) to a request. Shared by every
300    /// authenticated request builder so header attachment has exactly one
301    /// implementation.
302    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    /// Attach the bearer token and send `builder`. The shared first step of
310    /// every authenticated request; callers that need bespoke status-code
311    /// handling (e.g. treating 404/409 as non-error outcomes) use this
312    /// directly instead of `authed_send_json`.
313    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    /// Check that `resp`'s status is a success and deserialize its JSON
321    /// body; otherwise build an error as `"{err_prefix(status)}: {body}"`.
322    /// `err_prefix` receives the status so each caller can format its own
323    /// distinct message (parenthesized status, bare status, ...) — this
324    /// helper only supplies the shared "check status, else deserialize"
325    /// shape, not the message wording.
326    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    /// Attach the bearer token, send `builder`, and deserialize a successful
340    /// JSON response — the shared shape of every simple authenticated
341    /// request/response method (`send_authed` + `success_json`).
342    ///
343    /// NOTE: callers whose `err_prefix` renders the status as `"({status})"`
344    /// (e.g. `stream_event`'s `"Stream failed ({status})"`) produce error
345    /// strings containing `"(404 "`/`"(403 "`/etc. —
346    /// `commands::stream::is_deterministic_client_error` matches on exactly
347    /// that substring shape to classify a stream-send failure. If you change
348    /// how a status is rendered here, check that predicate (and its tests)
349    /// still pass.
350    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    /// GET `{base}{path}` with the bearer token, mapping failures into
364    /// `GetMeError` (401 → `Unauthorized`, transport → `Network`, other
365    /// non-2xx or bad JSON → `Server`). Shared by the credential-scoped GETs
366    /// so auth/error handling lives in one place.
367    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    /// GET /api/v1/auth/me — validates the bearer token and returns user
393    /// identity. Used by `tracevault status` to distinguish "logged out",
394    /// "expired token", and "server unreachable".
395    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    /// Project-scoped variant of `stream_event`: posts to the project's
465    /// stream endpoint with `repo_id` as a query param instead of a path
466    /// segment. The query is built with `Url::query_pairs_mut`, mirroring
467    /// `resolve_project`'s `?git_url=`, so `repo_id` is percent-encoded
468    /// rather than string-interpolated into the URL.
469    ///
470    /// Called from `commands::stream::send_stream_event` when a local
471    /// project binding resolves for the capturing event.
472    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    /// Resolve a git URL to its codebase (git remote) by NORMALIZED URL —
507    /// deduped, unlike an exact `github_url` match. `Ok(None)` if the
508    /// codebase isn't tracked: a genuine domain 404, identified by the
509    /// server's JSON error envelope (see [`is_domain_error_body`]). A bare
510    /// 404 with no such body — axum's built-in "no route matched" fallback
511    /// — is surfaced as `Err` instead, since it means this server doesn't
512    /// have this route at all (most plausibly a CLI/server version skew,
513    /// e.g. this CLI shipped ahead of a server that still uses the old
514    /// org-scoped paths) rather than an absent codebase.
515    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    /// Full detail for a remote (codebase): its display name, normalized URL,
536    /// clone status, and linked repos.
537    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    /// The repos linked to a remote (the codebase's members).
551    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    /// List all projects. `GET /api/v1/projects`.
559    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    /// Full detail for a project. `GET /api/v1/projects/{id}`.
570    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    /// Resolve a git URL to its project, distinguishing "no project" (a
581    /// genuine domain 404 — see [`is_domain_error_body`]) from "ambiguous,
582    /// multiple candidate projects" (409). A bare 404 with no domain-error
583    /// body is surfaced as `Err` instead of `None` (see `resolve_remote`'s
584    /// doc comment for why). `GET /api/v1/projects/resolve?git_url=`.
585    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
610/// Whether a 404 response body matches the server's JSON error envelope —
611/// `{"error": "...", ...}`, emitted by every domain-level `AppError` (see
612/// `tracevault-server`'s `error.rs`) — rather than the empty/plain body
613/// axum's built-in "no route matched" fallback sends when the server has no
614/// handler for the path at all. Used by `resolve_remote`/`resolve_project`
615/// to tell a genuine "not tracked"/"no project" 404 apart from a 404 that
616/// really means "this server doesn't have this route" (most plausibly a
617/// CLI/server version skew).
618fn 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
625/// The error for a 404 whose body doesn't match the server's JSON error
626/// envelope (see [`is_domain_error_body`]) — surfaced instead of silently
627/// treating the call as "not tracked"/"no project", since this shape is the
628/// CLI's best signal that the server doesn't recognize `what`'s route at
629/// all, rather than a genuine absence of the resource.
630fn 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
639/// Resolve server URL and auth token from multiple sources.
640/// Priority: env var > credentials file > project config.toml
641/// Returns (server_url, auth_token).
642pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
643    use crate::credentials::Credentials;
644
645    // 1. Env var API key
646    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
647
648    // 2. Credentials file
649    let creds = Credentials::load();
650
651    // 3. Project config
652    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    // Resolve server URL: env > creds > config
668    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    // Resolve token: env api key > creds token > config api key
674    let token = env_key
675        .or_else(|| creds.map(|c| c.token))
676        .or(config_api_key);
677
678    (server_url, token)
679}
680
681/// Resolve `project_root`'s credentials (via `resolve_credentials`) into a
682/// ready `ApiClient`, or the standard "no server URL configured" error when
683/// none of the credential sources yield a server URL. Shared by every
684/// command that needs a client from a project root, so this
685/// resolve-then-construct shape has exactly one implementation.
686pub 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}