Skip to main content

originlm_cli/
mcp.rs

1//! `originlm mcp`: the built-in Model Context Protocol server.
2//!
3//! Newline-delimited JSON-RPC 2.0 over stdio (the MCP stdio transport). It
4//! serves read-only tools over the same native service the broker uses, so
5//! usage numbers come from the provider adapters' own quota probes (Claude
6//! Code `get_usage`, Codex `account/rateLimits/read`), never from estimates.
7//! The handshake mirrors the SDK's `createCachedUsageMcp`: `initialize`, then
8//! `notifications/initialized`, then `tools/list` / `tools/call`.
9use originlm_contracts::{DomainError, ErrorCode, Result};
10use originlm_service::NativeService;
11use serde_json::{Value, json};
12use std::{collections::BTreeSet, path::PathBuf, sync::Arc};
13use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
14
15pub const CLIENT: &str = "mcp-owner";
16const PROTOCOL_VERSION: &str = "2025-06-18";
17const MAX_LINE_BYTES: usize = 1 << 20;
18/// A reading this young that was (re)confirmed by this call is reported as live.
19const LIVE_AGE_SECONDS: i64 = 90;
20/// Upper bound for one usage read across every provider.
21const PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(60);
22
23pub struct McpServer {
24    service: Arc<NativeService>,
25    /// Providers this server may probe (the `--allow-metadata` grants).
26    providers: BTreeSet<String>,
27    home: Option<PathBuf>,
28    identity: bool,
29    phase: Phase,
30    discovered: bool,
31}
32
33#[derive(PartialEq)]
34enum Phase {
35    New,
36    Offered,
37    Ready,
38}
39
40pub fn tool_definitions() -> Value {
41    let read_only = json!({"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":true});
42    json!([
43        {
44            "name": "usage",
45            "title": "Provider plan usage",
46            "description": "Every AI provider and profile OriginLM detects on this machine, with plan usage wherever a usage source exists (Claude Code, Codex, Cursor, OpenCode, Muse, Grok, Antigravity, Gemini CLI, GitHub Copilot, Pi): percent used and remaining per window (5-hour, weekly, model-specific, monthly credits), reset times, account and plan. Reads the providers' own usage endpoints through their installed clients; never starts a model turn. Each provider says whether its numbers are live or cached and how old they are. A detected provider without a usage source is still listed and marked so. A missing window is unknown, not zero.",
47            "inputSchema": {
48                "type": "object",
49                "properties": {
50                    "providers": {
51                        "type": "array",
52                        "items": {"type": "string"},
53                        "description": "Provider ids to include, e.g. [\"claude_code\",\"codex\"]. Default: every detected provider."
54                    },
55                    "refresh": {
56                        "type": "boolean",
57                        "description": "Bypass OriginLM's 60-second probe cache and re-read the provider now."
58                    }
59                },
60                "additionalProperties": false
61            },
62            "annotations": read_only,
63        },
64        {
65            "name": "providers",
66            "title": "Provider connections",
67            "description": "Locally installed AI clients OriginLM found (passive discovery), with sign-in state, account, plan and whether usage has been read. Does not contact providers; call `usage` for quota numbers.",
68            "inputSchema": {"type": "object", "properties": {}, "additionalProperties": false},
69            "annotations": {"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false},
70        },
71        {
72            "name": "usage_history",
73            "title": "Local token history",
74            "description": "Token totals per model from the supported clients' local session history files (Claude Code, Codex and others) (input, cached input, cache writes, output, reasoning). These are token counts from this machine only, not plan quota; prompts and outputs are never read.",
75            "inputSchema": {"type": "object", "properties": {}, "additionalProperties": false},
76            "annotations": {"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false},
77        }
78    ])
79}
80
81impl McpServer {
82    pub fn new(
83        service: Arc<NativeService>,
84        providers: BTreeSet<String>,
85        home: Option<PathBuf>,
86        identity: bool,
87    ) -> Self {
88        Self {
89            service,
90            providers,
91            home,
92            identity,
93            phase: Phase::New,
94            discovered: false,
95        }
96    }
97
98    /// Handle one decoded JSON-RPC message. Notifications return `None`.
99    pub async fn handle(&mut self, message: Value) -> Option<Value> {
100        let id = message.get("id").cloned();
101        let valid_id = matches!(&id, Some(Value::String(s)) if s.len() <= 128)
102            || matches!(&id, Some(Value::Number(n)) if n.is_i64() || n.is_u64());
103        let reply_id = if valid_id {
104            id.clone().unwrap()
105        } else {
106            Value::Null
107        };
108        let error = |code: i64, text: &str| {
109            Some(
110                json!({"jsonrpc":"2.0","id":reply_id.clone(),"error":{"code":code,"message":text}}),
111            )
112        };
113        let Some(method) = message["method"].as_str().map(str::to_owned) else {
114            return error(-32600, "Invalid MCP request");
115        };
116        if message["jsonrpc"] != "2.0"
117            || message
118                .get("params")
119                .is_some_and(|p| !p.is_object() && !p.is_null())
120        {
121            return error(-32600, "Invalid MCP request");
122        }
123        let params = message.get("params").cloned().unwrap_or(json!({}));
124        if id.is_none() {
125            if method == "notifications/initialized" && self.phase == Phase::Offered {
126                self.phase = Phase::Ready;
127            }
128            return None;
129        }
130        if !valid_id {
131            return error(-32600, "Invalid MCP request ID");
132        }
133        let success =
134            |result: Value| Some(json!({"jsonrpc":"2.0","id":reply_id.clone(),"result":result}));
135        match method.as_str() {
136            "ping" => success(json!({})),
137            "initialize" => {
138                if self.phase != Phase::New {
139                    return error(-32600, "Already initialized");
140                }
141                if !params["protocolVersion"].is_string() {
142                    return error(-32602, "Invalid initialization");
143                }
144                self.phase = Phase::Offered;
145                success(json!({
146                    "protocolVersion": PROTOCOL_VERSION,
147                    "capabilities": {"tools": {"listChanged": false}},
148                    "serverInfo": {"name": "originlm", "title": "OriginLM", "version": env!("CARGO_PKG_VERSION")},
149                    "instructions": "Use `usage` to answer how much Claude / Codex plan quota is left and when it resets. `providers` lists connected clients; `usage_history` gives local token totals."
150                }))
151            }
152            _ if self.phase == Phase::New => error(-32002, "Initialize MCP first"),
153            "tools/list" => success(json!({"tools": tool_definitions()})),
154            "tools/call" => {
155                let name = params["name"].as_str().unwrap_or_default().to_owned();
156                let arguments = match params.get("arguments") {
157                    None | Some(Value::Null) => json!({}),
158                    Some(value) if value.is_object() => value.clone(),
159                    Some(_) => return error(-32602, "Tool arguments must be an object"),
160                };
161                let outcome = match name.as_str() {
162                    "usage" => self.usage(&arguments).await,
163                    "providers" => self.providers_tool(&arguments).await,
164                    "usage_history" => self.history(&arguments),
165                    _ => return error(-32602, "Unknown tool"),
166                };
167                Some(match outcome {
168                    Ok((text, data)) => json!({"jsonrpc":"2.0","id":reply_id,"result":{
169                        "content":[{"type":"text","text":text}],
170                        "structuredContent":data,
171                        "isError":false
172                    }}),
173                    Err(failure) => json!({"jsonrpc":"2.0","id":reply_id,"result":{
174                        "content":[{"type":"text","text":format!("{}: {}", code(&failure), failure.message)}],
175                        "isError":true
176                    }}),
177                })
178            }
179            _ => error(-32601, "MCP method unavailable"),
180        }
181    }
182
183    async fn discover(&mut self, force: bool) -> Result<()> {
184        if self.discovered && !force {
185            return Ok(());
186        }
187        self.service
188            .handle(CLIENT, "discovery.refresh", json!({"level":"passive"}))
189            .await?;
190        self.discovered = true;
191        Ok(())
192    }
193
194    async fn snapshot(&self) -> Result<Value> {
195        self.service.handle(CLIENT, "snapshot.get", json!({})).await
196    }
197
198    async fn usage(&mut self, arguments: &Value) -> Result<(String, Value)> {
199        allow(arguments, &["providers", "refresh"])?;
200        let refresh = match arguments.get("refresh") {
201            None | Some(Value::Null) => false,
202            Some(Value::Bool(value)) => *value,
203            Some(_) => return Err(invalid("`refresh` must be a boolean")),
204        };
205        let filter = provider_filter(arguments.get("providers"))?;
206        let report = collect_usage(
207            &self.service,
208            CLIENT,
209            &self.providers,
210            filter.as_ref(),
211            refresh,
212            !self.discovered || refresh,
213            self.identity,
214        )
215        .await?;
216        self.discovered = true;
217        let text = usage_text(&report);
218        let mut report = report;
219        // Some clients (Claude Code) show only structuredContent when present,
220        // so the readable summary travels inside it as well.
221        report["summary"] = json!(text);
222        Ok((text, report))
223    }
224
225    async fn providers_tool(&mut self, arguments: &Value) -> Result<(String, Value)> {
226        allow(arguments, &[])?;
227        self.discover(false).await?;
228        let snapshot = self.snapshot().await?;
229        let report = providers_report(&snapshot, &self.providers, self.identity);
230        let mut text = String::new();
231        for row in report["providers"].as_array().into_iter().flatten() {
232            text.push_str(&format!(
233                "{} ({}) — {}; auth {}; account {}; plan {}; {} usage window(s){}\n",
234                row["providerName"].as_str().unwrap_or("?"),
235                row["providerId"].as_str().unwrap_or("?"),
236                row["status"].as_str().unwrap_or("?"),
237                row["auth"].as_str().unwrap_or("unknown"),
238                row["account"].as_str().unwrap_or(if self.identity {
239                    "unknown"
240                } else {
241                    "hidden (start with --allow-identity)"
242                }),
243                row["plan"].as_str().unwrap_or("unknown"),
244                row["usageWindows"],
245                if row["usageGranted"] == true {
246                    ""
247                } else {
248                    " (usage not granted)"
249                },
250            ));
251        }
252        if text.is_empty() {
253            text.push_str("No provider clients were found on this machine.\n");
254        }
255        Ok((text, report))
256    }
257
258    fn history(&self, arguments: &Value) -> Result<(String, Value)> {
259        allow(arguments, &[])?;
260        let limits = originlm_discovery::history::Limits::default();
261        let history = match &self.home {
262            Some(home) => originlm_discovery::history::read_usage(home, limits),
263            None => {
264                let environment = originlm_discovery::ScanEnvironment::from_process()?;
265                originlm_discovery::history::read_usage_for_environment(&environment, limits)
266            }
267        };
268        let value = json!(history);
269        let text = history_text(&value);
270        Ok((text, value))
271    }
272}
273
274/// Readable local token totals (`usage_history` tool, `usage --history`).
275pub fn history_text(value: &Value) -> String {
276    let mut text =
277        String::from("Local session-history token totals (this machine only; not plan quota):\n");
278    for provider in value["providers"].as_array().into_iter().flatten() {
279        let t = &provider["totals"];
280        text.push_str(&format!(
281            "{}: input {} · cached input {} · cache writes {} · output {} (reasoning {}) across {} file(s){}\n",
282            provider["providerId"].as_str().unwrap_or("?"),
283            t["inputTokens"], t["cachedInputTokens"], t["cacheCreationTokens"],
284            t["outputTokens"], t["reasoningTokens"], provider["filesRead"],
285            if provider["truncated"] == true { " (truncated)" } else { "" },
286        ));
287    }
288    text
289}
290
291/// Discover (when asked), probe every granted connection of `wanted`, and
292/// shape the snapshot into the usage report. Shared by the MCP `usage` tool
293/// and the `originlm usage` / `olm usage` command so both show the same numbers.
294pub async fn collect_usage(
295    service: &Arc<NativeService>,
296    client: &str,
297    granted: &BTreeSet<String>,
298    filter: Option<&BTreeSet<String>>,
299    refresh: bool,
300    discover: bool,
301    identity: bool,
302) -> Result<Value> {
303    let started = chrono::Utc::now();
304    if discover {
305        service
306            .handle(client, "discovery.refresh", json!({"level":"passive"}))
307            .await?;
308    }
309    let listed = service
310        .handle(client, "connections.list", json!({}))
311        .await?;
312    // (provider, connection id, is the provider's default profile)
313    let mut targets: Vec<(String, String, bool)> = vec![];
314    for connection in listed.as_array().into_iter().flatten() {
315        if let (Some(provider), Some(id)) =
316            (connection["providerId"].as_str(), connection["id"].as_str())
317            && granted.contains(provider)
318            && filter.is_none_or(|filter| filter.contains(provider))
319        {
320            let default = connection["displayName"]
321                .as_str()
322                .is_some_and(|name| name.contains("Default profile"));
323            targets.push((provider.to_owned(), id.to_owned(), default));
324        }
325    }
326    // Each probe starts that provider's own client, and starting them all at
327    // once starves the slow ones (Claude Code allows 10 s for its usage
328    // answer) into timeouts. So: Claude Code and Codex default profiles
329    // first, alone; then every other provider's first profile, three at a
330    // time; then additional profiles. One provider's profiles never run at
331    // the same time, because a probe may refresh that provider's credentials.
332    targets.sort_by_key(|(provider, _, default)| (!*default, provider.clone()));
333    let mut seen = BTreeSet::new();
334    let mut waves: [Vec<(String, String)>; 3] = Default::default();
335    for (provider, id, _) in targets {
336        let wave = if !seen.insert(provider.clone()) {
337            2
338        } else if matches!(provider.as_str(), "claude_code" | "codex") {
339            0
340        } else {
341            1
342        };
343        waves[wave].push((provider, id));
344    }
345    // One bound for the whole read, so a client that hangs costs its own row,
346    // not the answer: what has been read by then is reported, the rest is a
347    // timeout with any earlier reading shown as cached.
348    let deadline = tokio::time::Instant::now() + PROBE_DEADLINE;
349    let mut probes = std::collections::BTreeMap::new();
350    for wave in waves {
351        let mut by_provider: std::collections::BTreeMap<String, Vec<String>> = Default::default();
352        for (provider, id) in wave {
353            by_provider.entry(provider).or_default().push(id);
354        }
355        let slots = Arc::new(tokio::sync::Semaphore::new(3));
356        let mut checks = tokio::task::JoinSet::new();
357        for ids in by_provider.into_values() {
358            let service = service.clone();
359            let client = client.to_owned();
360            let slots = slots.clone();
361            checks.spawn(async move {
362                let _slot = tokio::time::timeout_at(deadline, slots.acquire_owned()).await;
363                let mut results = vec![];
364                for id in ids {
365                    let outcome = tokio::time::timeout_at(
366                        deadline,
367                        service.handle(
368                            &client,
369                            "connections.probe",
370                            json!({"connectionId": id, "force": refresh}),
371                        ),
372                    )
373                    .await
374                    .unwrap_or_else(|_| {
375                        Err(DomainError::new(ErrorCode::Timeout, "Usage read timed out"))
376                    });
377                    results.push((id, outcome));
378                }
379                results
380            });
381        }
382        while let Some(joined) = checks.join_next().await {
383            for (id, outcome) in joined.unwrap_or_default() {
384                probes.insert(
385                    id,
386                    match outcome {
387                        Ok(value) => ProbeOutcome::Ok(value["status"].as_str() == Some("cached")),
388                        Err(error) => {
389                            ProbeOutcome::Failed(code(&error), detail_codes(&error.message))
390                        }
391                    },
392                );
393            }
394        }
395    }
396    let snapshot = service.handle(client, "snapshot.get", json!({})).await?;
397    Ok(usage_report(
398        &snapshot,
399        granted,
400        filter,
401        &probes,
402        started,
403        chrono::Utc::now(),
404        identity,
405    ))
406}
407
408/// Optional `providers` narrowing: ids OriginLM discovery knows, else an error.
409pub fn provider_filter(value: Option<&Value>) -> Result<Option<BTreeSet<String>>> {
410    let items = match value {
411        None | Some(Value::Null) => return Ok(None),
412        Some(Value::Array(items)) => items,
413        Some(_) => return Err(invalid("`providers` must be an array")),
414    };
415    let mut set = BTreeSet::new();
416    for item in items {
417        let id = item
418            .as_str()
419            .ok_or_else(|| invalid("`providers` must be strings"))?;
420        if !originlm_discovery::definitions()
421            .iter()
422            .any(|definition| definition.id == id)
423        {
424            return Err(invalid(&format!("Unknown provider `{id}`")));
425        }
426        set.insert(id.to_owned());
427    }
428    Ok(Some(set))
429}
430
431pub enum ProbeOutcome {
432    /// `true` when the service answered from its own short-lived probe cache.
433    Ok(bool),
434    /// Error code, plus the adapter's own diagnostic codes when the error
435    /// carried them (`message [CODE,...]`).
436    Failed(String, Vec<String>),
437}
438
439/// Diagnostic codes an adapter appended to an error message as `[A,B]`.
440pub fn detail_codes(message: &str) -> Vec<String> {
441    let Some(inner) = message
442        .trim_end()
443        .strip_suffix(']')
444        .and_then(|rest| rest.rsplit_once('[').map(|(_, inner)| inner))
445    else {
446        return vec![];
447    };
448    inner
449        .split(',')
450        .map(str::trim)
451        .filter(|code| {
452            !code.is_empty()
453                && code.len() <= 96
454                && code
455                    .chars()
456                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_' || c == '.')
457        })
458        .map(str::to_owned)
459        .take(16)
460        .collect()
461}
462
463fn allow(arguments: &Value, keys: &[&str]) -> Result<()> {
464    match arguments.as_object() {
465        Some(map) if map.keys().all(|k| keys.contains(&k.as_str())) => Ok(()),
466        _ => Err(invalid("Unexpected tool argument")),
467    }
468}
469
470fn invalid(message: &str) -> DomainError {
471    DomainError::new(ErrorCode::InvalidRequest, message)
472}
473
474fn provider_name(id: &str) -> String {
475    originlm_discovery::definitions()
476        .iter()
477        .find(|definition| definition.id == id)
478        .map(|definition| definition.name.to_string())
479        .unwrap_or_else(|| id.to_owned())
480}
481
482fn known(observation: &Value) -> Option<&Value> {
483    (observation["state"] == "known").then(|| &observation["value"])
484}
485
486fn parse_time(value: &Value) -> Option<chrono::DateTime<chrono::Utc>> {
487    value
488        .as_str()
489        .and_then(|text| chrono::DateTime::parse_from_rfc3339(text).ok())
490        .map(|time| time.with_timezone(&chrono::Utc))
491}
492
493fn decimal(value: &Value) -> Option<f64> {
494    value.as_str().and_then(|text| text.parse::<f64>().ok())
495}
496
497fn round1(value: f64) -> f64 {
498    (value * 10.0).round() / 10.0
499}
500
501fn account_label(snapshot: &Value, account_id: &Value, identity: bool) -> Value {
502    if !identity {
503        return Value::Null;
504    }
505    snapshot["accounts"]
506        .as_array()
507        .into_iter()
508        .flatten()
509        .find(|account| account["id"] == *account_id && !account_id.is_null())
510        .and_then(|account| known(&account["displayLabel"]).cloned())
511        .unwrap_or(Value::Null)
512}
513
514/// Providers whose adapters can report plan quota, and the grant that turns
515/// the read on. Claude Code and Codex are granted by default; the others are
516/// listed with the flags that enable them. Every other detected provider has
517/// no usage source in OriginLM today and is listed as such.
518pub const USAGE_SOURCES: [&str; 10] = crate::args::DEFAULT_USAGE_PROVIDERS;
519
520fn usage_source(provider: &str) -> Option<&'static str> {
521    USAGE_SOURCES.iter().find(|id| **id == provider).copied()
522}
523
524/// Why a detected provider has no usage source in OriginLM, checked per
525/// provider (see docs/integration/mcp-server.md).
526fn no_source_reason(provider: &str) -> &'static str {
527    match provider {
528        "ollama" => "Ollama's local API reports sign-in and plan, not cloud usage limits",
529        "lmstudio" => "local runtime; LM Studio has no plan quota",
530        "kiro" => "Kiro CLI does not report usage",
531        _ => "OriginLM has no usage source for it",
532    }
533}
534
535/// Plain reason for a probed connection that returned no reading, from the
536/// adapter's own diagnostics. Unknown codes fall back to a neutral line.
537fn reading_missing_reason(row: &Value) -> Option<String> {
538    let codes: Vec<&str> = row["diagnostics"]
539        .as_array()
540        .into_iter()
541        .flatten()
542        .filter_map(Value::as_str)
543        .collect();
544    let has = |code: &str| codes.iter().any(|c| c.starts_with(code));
545    let reason = if has("USAGE_NOT_YET_OBSERVED") {
546        "Muse reports usage only after this login has run a turn".to_owned()
547    } else if has("METADATA_RUNTIME_MISSING") {
548        "this installation's runtime is missing".to_owned()
549    } else if has("GEMINI_API_KEY_AUTH_NO_QUOTA") {
550        "Gemini CLI signs in with a Gemini API key here; that is metered and Google publishes no usage endpoint for a key".to_owned()
551    } else if has("GEMINI_VERTEX_AUTH_NO_QUOTA") {
552        "Gemini CLI uses Vertex AI here; usage is billed in Google Cloud, not as a plan quota"
553            .to_owned()
554    } else if has("GEMINI_LOGIN_EXPIRED") {
555        "Gemini CLI's saved login has expired; run gemini once to refresh it".to_owned()
556    } else if has("GEMINI_LOGIN_NOT_FOUND") {
557        "no saved Gemini CLI login".to_owned()
558    } else if has("METADATA_READ_TIMEOUT") || has("USAGE_READ_FAILED_Timeout") {
559        "the client did not answer in time; try olm usage --refresh".to_owned()
560    } else if has("COPILOT_GH_LOGIN_UNAVAILABLE") {
561        "sign in with `gh auth login` to read Copilot usage".to_owned()
562    } else if has("COPILOT_USAGE_REQUEST_FAILED") {
563        "GitHub did not return Copilot usage for the gh login".to_owned()
564    } else if has("PI_NO_SAVED_LOGINS") {
565        "Pi has no saved logins".to_owned()
566    } else if let Some(name) = codes.iter().find_map(|c| {
567        c.strip_prefix("PI_")
568            .and_then(|c| c.strip_suffix("_NO_USAGE_SOURCE"))
569    }) {
570        format!(
571            "Pi login `{}` has no usage source",
572            name.to_ascii_lowercase()
573        )
574    } else if has("ANTIGRAVITY_DIRECT_LOGIN_AVAILABLE") {
575        "skipped because a native Antigravity login is available".to_owned()
576    } else if has("ANTIGRAVITY_T3_LOGIN_EXPIRED") {
577        "the saved T3 Code login has expired; open T3 Code to renew it".to_owned()
578    } else if has("ANTIGRAVITY_IDE_LOGIN_EXPIRED") {
579        "the Antigravity app's saved login has expired; open Antigravity to renew it".to_owned()
580    } else if has("ANTIGRAVITY_LOGIN_EXPIRED") {
581        "Antigravity's saved login has expired; open the agy CLI to renew it".to_owned()
582    } else if has("ANTIGRAVITY_CREDENTIAL") {
583        "no saved Antigravity login for this profile".to_owned()
584    } else if has("GROK_BILLING_UNAVAILABLE") {
585        "Grok did not answer its billing request".to_owned()
586    } else if has("CURSOR_SESSION_TOKEN_UNAVAILABLE") || has("CURSOR_CLI_NOT_SIGNED_IN") {
587        "Cursor is not signed in".to_owned()
588    } else if row["auth"] == "unauthenticated" {
589        "not signed in".to_owned()
590    } else if row["auth"] != "authenticated" && has("PLAN_NOT_REPORTED_BY_PROVIDER") {
591        "the client reported no sign-in or plan for this profile".to_owned()
592    } else {
593        return None;
594    };
595    Some(reason)
596}
597
598/// Shape the projected snapshot into the `usage` result. Pure, for tests.
599///
600/// Every detected connection is listed (narrowed only by `filter`); only the
601/// `granted` providers were probed. A connection without a reading is still
602/// listed, with the reason: not granted, or no usage source at all.
603pub fn usage_report(
604    snapshot: &Value,
605    granted: &BTreeSet<String>,
606    filter: Option<&BTreeSet<String>>,
607    probes: &std::collections::BTreeMap<String, ProbeOutcome>,
608    started: chrono::DateTime<chrono::Utc>,
609    now: chrono::DateTime<chrono::Utc>,
610    identity: bool,
611) -> Value {
612    let empty = vec![];
613    let pools = snapshot["quotaPools"].as_array().unwrap_or(&empty);
614    let mut rows = vec![];
615    for connection in snapshot["connections"].as_array().unwrap_or(&empty) {
616        let provider = connection["providerId"].as_str().unwrap_or_default();
617        if filter.is_some_and(|filter| !filter.contains(provider)) {
618            continue;
619        }
620        let connection_id = connection["id"].as_str().unwrap_or_default();
621        let mut windows = vec![];
622        let mut oldest: Option<chrono::DateTime<chrono::Utc>> = None;
623        for pool in pools.iter().filter(|pool| {
624            pool["connectionIds"]
625                .as_array()
626                .is_some_and(|ids| ids.iter().any(|id| id == connection_id))
627        }) {
628            for window in pool["windows"].as_array().unwrap_or(&empty) {
629                let reading = &window["reading"];
630                let mut row = json!({
631                    "id": window["id"],
632                    "label": friendly_label(window["label"].as_str().unwrap_or("window")),
633                    "providerLabel": window["label"],
634                    "resetsAt": window["resetsAt"],
635                    "windowSeconds": window["durationSeconds"],
636                });
637                if let Some(value) = known(reading) {
638                    let observed = parse_time(&reading["observedAt"]);
639                    if let Some(observed) = observed {
640                        oldest = Some(oldest.map_or(observed, |o| o.min(observed)));
641                    }
642                    let used = decimal(&value["used"]);
643                    let limit = decimal(&value["limit"]);
644                    let percent = match (used, limit, value["unit"].as_str()) {
645                        (Some(used), Some(limit), _) if limit > 0.0 => Some(used / limit * 100.0),
646                        (Some(used), None, Some("percent")) => Some(used),
647                        _ => None,
648                    };
649                    row["usedPercent"] = percent.map(round1).map_or(Value::Null, |p| json!(p));
650                    row["remainingPercent"] = percent
651                        .map(|p| round1((100.0 - p).max(0.0)))
652                        .map_or(Value::Null, |p| json!(p));
653                    row["observedAt"] = reading["observedAt"].clone();
654                    row["freshness"] = reading["freshness"].clone();
655                    row["unit"] = value["unit"].clone();
656                    row["used"] = value["used"].clone();
657                    row["limit"] = value["limit"].clone();
658                } else {
659                    row["usedPercent"] = Value::Null;
660                    row["remainingPercent"] = Value::Null;
661                    row["unknownReason"] = reading["reason"].clone();
662                }
663                row["resetsInSeconds"] = parse_time(&window["resetsAt"])
664                    .map(|reset| json!((reset - now).num_seconds().max(0)))
665                    .unwrap_or(Value::Null);
666                windows.push(row);
667            }
668        }
669        let probe = probes.get(connection_id);
670        // The connection's own diagnostics, plus any the failed read carried.
671        let mut diagnostics: Vec<Value> = connection["diagnostics"]
672            .as_array()
673            .cloned()
674            .unwrap_or_default();
675        if let Some(ProbeOutcome::Failed(_, codes)) = probe {
676            diagnostics.extend(codes.iter().map(|code| json!(code)));
677        }
678        // A previous quota snapshot cannot stand in for a missing login or
679        // for a fallback that was intentionally skipped.
680        if provider == "antigravity"
681            && diagnostics.iter().any(|code| {
682                matches!(
683                    code.as_str(),
684                    Some(
685                        "ANTIGRAVITY_DIRECT_LOGIN_AVAILABLE"
686                            | "ANTIGRAVITY_CREDENTIAL_NOT_FOUND"
687                            | "ANTIGRAVITY_LOGIN_EXPIRED"
688                            | "ANTIGRAVITY_IDE_LOGIN_EXPIRED"
689                            | "ANTIGRAVITY_T3_LOGIN_EXPIRED"
690                    )
691                )
692            })
693        {
694            windows.clear();
695            oldest = None;
696        }
697        let age = oldest.map(|observed| (now - observed).num_seconds().max(0));
698        let probe_ok = matches!(probe, Some(ProbeOutcome::Ok(_)));
699        let source = if granted.contains(provider) {
700            "granted"
701        } else if usage_source(provider).is_some() {
702            "not_granted"
703        } else {
704            "none"
705        };
706        let state = if windows.is_empty() {
707            match source {
708                "granted" => "unavailable",
709                "not_granted" => "not_read",
710                _ => "no_source",
711            }
712        } else if probe_ok
713            && age.is_some_and(|age| age <= LIVE_AGE_SECONDS)
714            && oldest.is_some_and(|o| o >= started - chrono::Duration::seconds(LIVE_AGE_SECONDS))
715        {
716            "live"
717        } else {
718            "cached"
719        };
720        let mut data = json!({
721            "state": state,
722            "observedAt": oldest.map(|o| o.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
723            "ageSeconds": age,
724        });
725        match probe {
726            Some(ProbeOutcome::Failed(code, _)) => data["refreshError"] = json!(code),
727            Some(ProbeOutcome::Ok(true)) => data["servedFromProbeCache"] = json!(true),
728            _ => {}
729        }
730        rows.push(json!({
731            "providerId": provider,
732            "providerName": provider_name(provider),
733            "connectionId": connection_id,
734            "connectionName": connection["displayName"],
735            "auth": known(&connection["auth"]).cloned().unwrap_or(json!("unknown")),
736            "account": account_label(snapshot, &connection["accountId"], identity),
737            "identityHidden": !identity,
738            "plan": known(&connection["plan"]).map(|plan| plan["label"].clone()).unwrap_or(Value::Null),
739            "usageSource": source,
740            "diagnostics": diagnostics,
741            "noSourceReason": if source == "none" { json!(no_source_reason(provider)) } else { Value::Null },
742            "data": data,
743            "windows": windows,
744        }));
745    }
746    // Readings first, then granted connections without one, then providers
747    // whose usage was not read, then providers with no usage source.
748    rows.sort_by_key(|row| {
749        let rank = if row["windows"].as_array().is_some_and(|w| !w.is_empty()) {
750            0
751        } else {
752            match row["usageSource"].as_str() {
753                Some("granted") => 1,
754                Some("not_granted") => 2,
755                _ => 3,
756            }
757        };
758        // Claude Code and Codex lead their group; the rest are alphabetical.
759        let lead = match row["providerId"].as_str() {
760            Some("claude_code") => 0,
761            Some("codex") => 1,
762            _ => 2,
763        };
764        (
765            rank,
766            lead,
767            row["providerName"].as_str().unwrap_or_default().to_owned(),
768            row["connectionName"]
769                .as_str()
770                .unwrap_or_default()
771                .to_owned(),
772        )
773    });
774    let found: BTreeSet<&str> = rows
775        .iter()
776        .filter_map(|row| row["providerId"].as_str())
777        .collect();
778    let missing: Vec<&String> = filter
779        .unwrap_or(granted)
780        .iter()
781        .filter(|p| !found.contains(p.as_str()))
782        .collect();
783    json!({
784        "generatedAt": now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
785        "providers": rows,
786        "notFound": missing,
787        "notes": [
788            "Percentages are the provider's own plan-quota readings, not token estimates.",
789            "A missing window or null percent is unknown, not zero.",
790            "Every detected provider is listed. usageSource `none` means OriginLM has no usage source for it; `not_granted` means one exists but this run excluded it (--no-usage or an explicit --allow-metadata list).",
791            "data.state is `live` when this call read the provider within the last 90 s, otherwise `cached` with its age."
792        ]
793    })
794}
795
796/// Claude Code's `limits[]` rows carry a raw `kind` (`session`, `weekly_all`,
797/// `weekly_scoped · <model>`). Name the ones whose meaning is established —
798/// the session bucket is the same one the adapter's keyed path labels
799/// "5-hour session" — and keep any other provider label unchanged.
800pub fn friendly_label(label: &str) -> String {
801    let (kind, scope) = match label.split_once(" · ") {
802        Some((kind, scope)) => (kind, Some(scope)),
803        None => (label, None),
804    };
805    match (kind, scope) {
806        ("session", None) => "5-hour session".into(),
807        ("weekly_all", None) => "Weekly (all models)".into(),
808        ("weekly_scoped", Some(model)) => format!("Weekly ({model})"),
809        _ => label.to_owned(),
810    }
811}
812
813fn duration_text(seconds: i64) -> String {
814    let (d, h, m) = (
815        seconds / 86_400,
816        (seconds % 86_400) / 3_600,
817        (seconds % 3_600) / 60,
818    );
819    match (d, h) {
820        (0, 0) => format!("{m}m"),
821        (0, _) => format!("{h}h {m}m"),
822        _ => format!("{d}d {h}h"),
823    }
824}
825
826/// The human-readable side of the `usage` result.
827pub fn usage_text(report: &Value) -> String {
828    let mut text = String::new();
829    for row in report["providers"].as_array().into_iter().flatten() {
830        let data = &row["data"];
831        let mut who = vec![];
832        if let Some(account) = row["account"].as_str() {
833            who.push(account.to_owned());
834        }
835        if let Some(plan) = row["plan"].as_str() {
836            who.push(format!("plan {plan}"));
837        }
838        let freshness = match (data["state"].as_str(), data["ageSeconds"].as_i64()) {
839            (Some("live"), Some(age)) => format!("live, read {age}s ago"),
840            (Some("cached"), Some(age)) => format!("CACHED, {} old", duration_text(age)),
841            _ => status_without_reading(row),
842        };
843        text.push_str(&format!(
844            "{}{} — {}{}\n",
845            row["connectionName"]
846                .as_str()
847                .or(row["providerName"].as_str())
848                .unwrap_or("?"),
849            if who.is_empty() {
850                String::new()
851            } else {
852                format!(" ({})", who.join(", "))
853            },
854            freshness,
855            data["refreshError"]
856                .as_str()
857                .map(|e| format!(" — refresh failed: {e}"))
858                .unwrap_or_default(),
859        ));
860        for window in row["windows"].as_array().into_iter().flatten() {
861            let label = window["label"].as_str().unwrap_or("window");
862            let reset = match (
863                window["resetsAt"].as_str(),
864                window["resetsInSeconds"].as_i64(),
865            ) {
866                (Some(at), Some(secs)) => format!(
867                    ", resets {} (in {})",
868                    parse_time(&json!(at))
869                        .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
870                        .unwrap_or_else(|| at.to_owned()),
871                    duration_text(secs)
872                ),
873                _ => String::new(),
874            };
875            match (
876                window["usedPercent"].as_f64(),
877                window["remainingPercent"].as_f64(),
878            ) {
879                (Some(used), Some(left)) => {
880                    text.push_str(&format!("  {label}: {used}% used, {left}% left{reset}\n"))
881                }
882                _ => text.push_str(&format!(
883                    "  {label}: {}{reset}\n",
884                    amount_text(window).unwrap_or_else(|| "unknown".into())
885                )),
886            }
887        }
888    }
889    for missing in report["notFound"].as_array().into_iter().flatten() {
890        text.push_str(&format!(
891            "{}: not found on this machine.\n",
892            provider_name(missing.as_str().unwrap_or("?"))
893        ));
894    }
895    if text.is_empty() {
896        text.push_str("No AI provider was detected on this machine.\n");
897    }
898    text
899}
900
901/// A known non-percent reading, e.g. dollars spent with no limit.
902fn amount_text(window: &Value) -> Option<String> {
903    let used: f64 = window["used"].as_str()?.parse().ok()?;
904    let unit = window["unit"].as_str()?;
905    let money = |v: f64| {
906        if unit == "usd" {
907            format!("${v:.2}")
908        } else {
909            format!("{v} {unit}")
910        }
911    };
912    Some(
913        match window["limit"].as_str().and_then(|l| l.parse::<f64>().ok()) {
914            Some(limit) => format!("{} of {} used", money(used), money(limit)),
915            None => format!("{} used, no limit", money(used)),
916        },
917    )
918}
919
920fn percent(value: f64) -> String {
921    if value.fract() == 0.0 {
922        format!("{value:.0}%")
923    } else {
924        format!("{value:.1}%")
925    }
926}
927
928/// Terminal rendering for `originlm usage` / `olm usage`: one block per
929/// account with aligned window rows, then every detected provider that has no
930/// reading, each with its reason. Reset times are shown in `offset` (the
931/// caller's local zone).
932pub fn usage_terminal(report: &Value, offset: chrono::FixedOffset) -> String {
933    let rows: Vec<&Value> = report["providers"]
934        .as_array()
935        .into_iter()
936        .flatten()
937        .collect();
938    let with: Vec<&&Value> = rows
939        .iter()
940        .filter(|row| row["windows"].as_array().is_some_and(|w| !w.is_empty()))
941        .collect();
942    let without: Vec<&&Value> = rows
943        .iter()
944        .filter(|row| row["windows"].as_array().is_none_or(Vec::is_empty))
945        .collect();
946    let label_width = with
947        .iter()
948        .flat_map(|row| row["windows"].as_array().into_iter().flatten())
949        .map(|w| w["label"].as_str().unwrap_or("window").chars().count())
950        .max()
951        .unwrap_or(0);
952    let name = |row: &Value| {
953        row["connectionName"]
954            .as_str()
955            .or(row["providerName"].as_str())
956            .unwrap_or("?")
957            .to_owned()
958    };
959    let mut out = String::new();
960    for row in &with {
961        let data = &row["data"];
962        let mut header = name(row);
963        if let Some(plan) = row["plan"].as_str() {
964            header.push_str(&format!("  ·  {plan}"));
965        }
966        if let Some(account) = row["account"].as_str() {
967            header.push_str(&format!("  ·  {account}"));
968        }
969        let freshness = match (data["state"].as_str(), data["ageSeconds"].as_i64()) {
970            (Some("live"), Some(age)) => format!("live, read {age}s ago"),
971            (Some("cached"), Some(age)) => format!("CACHED, {} old", duration_text(age)),
972            _ => "age unknown".to_owned(),
973        };
974        out.push_str(&format!("{header}  ·  {freshness}"));
975        if let Some(error) = data["refreshError"].as_str() {
976            out.push_str(&format!("  (refresh failed: {error})"));
977        }
978        out.push('\n');
979        for window in row["windows"].as_array().into_iter().flatten() {
980            let label = window["label"].as_str().unwrap_or("window");
981            let reading = match (
982                window["usedPercent"].as_f64(),
983                window["remainingPercent"].as_f64(),
984            ) {
985                (Some(used), Some(left)) => {
986                    format!("{:>5} used  {:>5} left", percent(used), percent(left))
987                }
988                _ => amount_text(window).unwrap_or_else(|| format!("{:>9}", "unknown")),
989            };
990            let reset = match (
991                parse_time(&window["resetsAt"]),
992                window["resetsInSeconds"].as_i64(),
993            ) {
994                (Some(at), Some(secs)) => format!(
995                    "  resets {} (in {})",
996                    at.with_timezone(&offset).format("%a %b %-d %H:%M"),
997                    duration_text(secs)
998                ),
999                _ => String::new(),
1000            };
1001            out.push_str(format!("  {label:<label_width$}  {reading}{reset}").trim_end());
1002            out.push('\n');
1003        }
1004        out.push('\n');
1005    }
1006    if !without.is_empty() {
1007        out.push_str("Detected without a usage reading:\n");
1008        let width = without
1009            .iter()
1010            .map(|row| name(row).chars().count())
1011            .max()
1012            .unwrap_or(0);
1013        for row in &without {
1014            out.push_str(&format!(
1015                "  {:<width$}  {}\n",
1016                name(row),
1017                status_without_reading(row)
1018            ));
1019        }
1020        out.push('\n');
1021    }
1022    for missing in report["notFound"].as_array().into_iter().flatten() {
1023        out.push_str(&format!(
1024            "{}: not found on this machine.\n",
1025            provider_name(missing.as_str().unwrap_or("?"))
1026        ));
1027    }
1028    if rows.is_empty() && report["notFound"].as_array().is_none_or(Vec::is_empty) {
1029        out.push_str("No AI provider was detected on this machine.\n");
1030    }
1031    out.push_str(
1032        "Percentages are the providers' own plan-quota readings; unknown is not zero.\n\
1033         Local token totals: olm usage --history\n",
1034    );
1035    out
1036}
1037
1038/// Why a listed connection has no reading. Plain, and never a number.
1039fn status_without_reading(row: &Value) -> String {
1040    match row["data"]["state"].as_str() {
1041        Some("no_source") => format!(
1042            "detected; usage unavailable ({})",
1043            row["noSourceReason"]
1044                .as_str()
1045                .unwrap_or("OriginLM has no usage source for it")
1046        ),
1047        Some("not_read") => "detected; usage not read (excluded from this run)".to_owned(),
1048        _ => match (
1049            reading_missing_reason(row),
1050            row["data"]["refreshError"].as_str(),
1051        ) {
1052            (Some(reason), _) => format!("no usage: {reason}"),
1053            (None, Some(error)) => format!("no usage: read failed ({error})"),
1054            (None, None) => "detected; no usage reported".to_owned(),
1055        },
1056    }
1057}
1058
1059/// Shape the snapshot into the `providers` result. Pure, for tests.
1060pub fn providers_report(snapshot: &Value, granted: &BTreeSet<String>, identity: bool) -> Value {
1061    let empty = vec![];
1062    let pools = snapshot["quotaPools"].as_array().unwrap_or(&empty);
1063    let rows: Vec<Value> = snapshot["connections"]
1064        .as_array()
1065        .unwrap_or(&empty)
1066        .iter()
1067        .map(|connection| {
1068            let id = &connection["id"];
1069            let windows: usize = pools
1070                .iter()
1071                .filter(|pool| pool["connectionIds"].as_array().is_some_and(|ids| ids.contains(id)))
1072                .map(|pool| pool["windows"].as_array().map_or(0, Vec::len))
1073                .sum();
1074            let provider = connection["providerId"].as_str().unwrap_or_default();
1075            json!({
1076                "providerId": provider,
1077                "providerName": provider_name(provider),
1078                "connectionId": id,
1079                "connectionName": connection["displayName"],
1080                "status": connection["status"],
1081                "auth": known(&connection["auth"]).cloned().unwrap_or(json!("unchecked")),
1082                "account": account_label(snapshot, &connection["accountId"], identity),
1083                "plan": known(&connection["plan"]).map(|plan| plan["label"].clone()).unwrap_or(Value::Null),
1084                "usageGranted": granted.contains(provider),
1085                "usageWindows": windows,
1086            })
1087        })
1088        .collect();
1089    json!({"providers": rows})
1090}
1091
1092/// Serve MCP over a byte stream until EOF.
1093pub async fn serve<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
1094    reader: R,
1095    mut writer: W,
1096    mut server: McpServer,
1097) -> Result<()> {
1098    let mut lines = BufReader::new(reader);
1099    let mut line = String::new();
1100    let io = |_| DomainError::new(ErrorCode::ProviderUnavailable, "MCP stdio closed");
1101    loop {
1102        line.clear();
1103        let read = (&mut lines)
1104            .take(MAX_LINE_BYTES as u64 + 1)
1105            .read_line(&mut line)
1106            .await
1107            .map_err(io)?;
1108        if read == 0 {
1109            return Ok(());
1110        }
1111        let trimmed = line.trim();
1112        if trimmed.is_empty() {
1113            continue;
1114        }
1115        let reply = if line.len() > MAX_LINE_BYTES {
1116            // Drain the rest of the oversized line before answering.
1117            let mut rest = Vec::new();
1118            lines.read_until(b'\n', &mut rest).await.map_err(io)?;
1119            Some(
1120                json!({"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"MCP message too large"}}),
1121            )
1122        } else {
1123            match serde_json::from_str::<Value>(trimmed) {
1124                Ok(Value::Array(_)) => Some(
1125                    json!({"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Batches are not supported"}}),
1126                ),
1127                Ok(message) => server.handle(message).await,
1128                Err(_) => Some(
1129                    json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}}),
1130                ),
1131            }
1132        };
1133        if let Some(reply) = reply {
1134            let mut bytes = serde_json::to_vec(&reply).unwrap_or_default();
1135            bytes.push(b'\n');
1136            writer.write_all(&bytes).await.map_err(io)?;
1137            writer.flush().await.map_err(io)?;
1138        }
1139    }
1140}
1141
1142fn code(error: &DomainError) -> String {
1143    serde_json::to_value(&error.code)
1144        .ok()
1145        .and_then(|value| value.as_str().map(str::to_owned))
1146        .unwrap_or_else(|| "ERROR".into())
1147}
1148
1149#[cfg(test)]
1150mod tests {
1151    use super::*;
1152    use std::collections::BTreeMap;
1153
1154    fn time(text: &str) -> chrono::DateTime<chrono::Utc> {
1155        parse_time(&json!(text)).unwrap()
1156    }
1157
1158    fn known_value(value: Value, observed: &str) -> Value {
1159        json!({"state":"known","value":value,
1160            "source":{"kind":"official_protocol","adapterId":"x","adapterVersion":"1"},
1161            "observedAt":observed,"freshness":"fresh","verification":"reported"})
1162    }
1163
1164    fn reading(used: &str, observed: &str) -> Value {
1165        known_value(
1166            json!({"unit":"percent","used":used,"limit":"100","remaining":null,"usedFraction":null}),
1167            observed,
1168        )
1169    }
1170
1171    fn connection(
1172        id: &str,
1173        provider: &str,
1174        name: &str,
1175        account: Value,
1176        auth: Value,
1177        plan: Value,
1178    ) -> Value {
1179        json!({"id":id,"providerId":provider,"displayName":name,"accountId":account,
1180            "auth":auth,"plan":plan,"status":"ready"})
1181    }
1182
1183    fn snapshot() -> Value {
1184        let at = "2026-11-11T16:00:00Z";
1185        let unknown = json!({"state":"unknown","reason":"NOT_REPORTED"});
1186        json!({
1187            "accounts":[{"id":"acct-c","providerId":"claude_code",
1188                "displayLabel":known_value(json!("me@example.com"), at),"identitySource":unknown}],
1189            "connections":[
1190                connection("conn-claude","claude_code","Claude Code · Default profile",json!("acct-c"),
1191                    known_value(json!("authenticated"),at),known_value(json!({"nativeId":"max","label":"Claude Max"}),at)),
1192                connection("conn-codex","codex","Codex · Default profile",Value::Null,
1193                    known_value(json!("authenticated"),at),unknown.clone()),
1194                connection("conn-codex-2","codex","Codex · Additional profile 2",Value::Null,
1195                    known_value(json!("unauthenticated"),at),unknown.clone()),
1196                connection("conn-ollama","ollama","Ollama",Value::Null,unknown.clone(),unknown.clone()),
1197                connection("conn-cursor","cursor","Cursor",Value::Null,unknown.clone(),unknown.clone()),
1198            ],
1199            "quotaPools":[
1200                {"id":"pool-c","accountId":"acct-c","connectionIds":["conn-claude"],"routeIds":[],"sharing":"unknown","windows":[
1201                    {"id":"session-0","label":"session","reading":reading("16",at),
1202                     "resetsAt":"2026-11-11T20:10:00.080121+00:00","durationSeconds":null},
1203                    {"id":"weekly_scoped-2","label":"weekly_scoped · Fable","reading":reading("54",at),
1204                     "resetsAt":"2026-11-14T21:00:00Z","durationSeconds":null},
1205                    {"id":"spend","label":"Monthly spend","reading":{"state":"unavailable","reason":"USAGE_UNAVAILABLE"},
1206                     "resetsAt":null,"durationSeconds":null}
1207                ]},
1208                {"id":"pool-x","accountId":null,"connectionIds":["conn-codex"],"routeIds":[],"sharing":"unknown","windows":[
1209                    {"id":"w1","label":"5 hr","reading":reading("61","2026-11-11T15:00:00Z"),
1210                     "resetsAt":"2026-11-11T18:00:00+00:00","durationSeconds":18000}
1211                ]}
1212            ]
1213        })
1214    }
1215
1216    #[test]
1217    fn antigravity_auth_diagnostics_hide_cached_quota() {
1218        for diagnostic in [
1219            "ANTIGRAVITY_DIRECT_LOGIN_AVAILABLE",
1220            "ANTIGRAVITY_CREDENTIAL_NOT_FOUND",
1221        ] {
1222            let mut state = snapshot();
1223            state["connections"][1]["providerId"] = json!("antigravity");
1224            state["connections"][1]["diagnostics"] = json!([diagnostic]);
1225            let granted = BTreeSet::from(["antigravity".into()]);
1226            let now = "2026-11-11T16:00:00Z".parse().unwrap();
1227            let report = usage_report(
1228                &state,
1229                &granted,
1230                Some(&granted),
1231                &Default::default(),
1232                now,
1233                now,
1234                false,
1235            );
1236            assert_eq!(report["providers"][0]["data"]["state"], "unavailable");
1237            assert_eq!(report["providers"][0]["windows"], json!([]));
1238        }
1239    }
1240
1241    fn wanted() -> BTreeSet<String> {
1242        ["claude_code", "codex"].map(String::from).into()
1243    }
1244
1245    fn row<'a>(report: &'a Value, id: &str) -> &'a Value {
1246        report["providers"]
1247            .as_array()
1248            .unwrap()
1249            .iter()
1250            .find(|row| row["connectionId"] == id)
1251            .unwrap()
1252    }
1253
1254    #[test]
1255    fn live_and_cached_readings_are_labelled_with_their_age() {
1256        let mut probes = BTreeMap::new();
1257        probes.insert("conn-claude".to_owned(), ProbeOutcome::Ok(false));
1258        probes.insert(
1259            "conn-codex".to_owned(),
1260            ProbeOutcome::Failed("PROVIDER_UNAVAILABLE".into(), vec![]),
1261        );
1262        let report = usage_report(
1263            &snapshot(),
1264            &wanted(),
1265            None,
1266            &probes,
1267            time("2026-11-11T16:00:01Z"),
1268            time("2026-11-11T16:00:30Z"),
1269            true,
1270        );
1271        let rows = report["providers"].as_array().unwrap();
1272        // Every detected connection is listed: readings, then granted without
1273        // one, then a usage source not granted, then no usage source at all.
1274        let order: Vec<_> = rows
1275            .iter()
1276            .map(|r| r["connectionId"].as_str().unwrap())
1277            .collect();
1278        assert_eq!(
1279            order,
1280            [
1281                "conn-claude",
1282                "conn-codex",
1283                "conn-codex-2",
1284                "conn-cursor",
1285                "conn-ollama"
1286            ]
1287        );
1288        assert_eq!(rows[2]["data"]["state"], "unavailable");
1289        assert_eq!(rows[3]["data"]["state"], "not_read");
1290        assert_eq!(rows[3]["usageSource"], "not_granted");
1291        assert_eq!(rows[4]["data"]["state"], "no_source");
1292        assert_eq!(rows[4]["usageSource"], "none");
1293        // Detected without a reading never becomes a number.
1294        assert_eq!(rows[4]["windows"], json!([]));
1295        assert!(rows[4]["data"]["ageSeconds"].is_null());
1296
1297        let claude = row(&report, "conn-claude");
1298        assert_eq!(claude["data"]["state"], "live");
1299        assert_eq!(claude["data"]["ageSeconds"], 30);
1300        assert_eq!(claude["account"], "me@example.com");
1301        assert_eq!(claude["plan"], "Claude Max");
1302        let session = &claude["windows"][0];
1303        assert_eq!(session["label"], "5-hour session");
1304        assert_eq!(session["providerLabel"], "session");
1305        assert_eq!(session["usedPercent"], 16.0);
1306        assert_eq!(session["remainingPercent"], 84.0);
1307        assert_eq!(session["resetsInSeconds"], 4 * 3600 + 9 * 60 + 30);
1308        assert_eq!(claude["windows"][1]["label"], "Weekly (Fable)");
1309        // An unavailable reading is unknown, never zero.
1310        assert!(claude["windows"][2]["usedPercent"].is_null());
1311        assert_eq!(claude["windows"][2]["unknownReason"], "USAGE_UNAVAILABLE");
1312
1313        let codex = row(&report, "conn-codex");
1314        assert_eq!(codex["data"]["state"], "cached");
1315        assert_eq!(codex["data"]["ageSeconds"], 3630);
1316        assert_eq!(codex["data"]["refreshError"], "PROVIDER_UNAVAILABLE");
1317        assert!(codex["plan"].is_null());
1318
1319        let text = usage_text(&report);
1320        for expected in [
1321            "Claude Code · Default profile (me@example.com, plan Claude Max) — live, read 30s ago",
1322            "5-hour session: 16% used, 84% left, resets 2026-11-11T20:10:00Z (in 4h 9m)",
1323            "Codex · Default profile — CACHED, 1h 0m old — refresh failed: PROVIDER_UNAVAILABLE",
1324            "Monthly spend: unknown",
1325            "Additional profile 2 — no usage: not signed in",
1326            "Cursor — detected; usage not read (excluded from this run)",
1327            "Ollama — detected; usage unavailable (Ollama's local API reports sign-in and plan, not cloud usage limits)",
1328        ] {
1329            assert!(text.contains(expected), "missing {expected:?} in:\n{text}");
1330        }
1331
1332        let terminal = usage_terminal(&report, chrono::FixedOffset::west_opt(5 * 3600).unwrap());
1333        for expected in [
1334            "Claude Code · Default profile  ·  Claude Max  ·  me@example.com  ·  live, read 30s ago\n",
1335            "  5-hour session    16% used    84% left  resets Wed Nov 11 15:10 (in 4h 9m)\n",
1336            "  Monthly spend     unknown\n",
1337            "Codex · Default profile  ·  CACHED, 1h 0m old  (refresh failed: PROVIDER_UNAVAILABLE)\n",
1338            "Detected without a usage reading:\n",
1339            "  Codex · Additional profile 2  no usage: not signed in\n",
1340            "  Ollama                        detected; usage unavailable (Ollama's local API reports sign-in and plan, not cloud usage limits)\n",
1341            "Local token totals: olm usage --history\n",
1342        ] {
1343            assert!(
1344                terminal.contains(expected),
1345                "missing {expected:?} in:\n{terminal}"
1346            );
1347        }
1348        assert!(
1349            !terminal.contains('{'),
1350            "no JSON in terminal output:\n{terminal}"
1351        );
1352    }
1353
1354    #[test]
1355    fn a_provider_filter_narrows_the_listing_and_names_what_is_missing() {
1356        let filter: BTreeSet<String> = ["ollama", "kiro"].map(String::from).into();
1357        let now = time("2026-11-11T16:00:00Z");
1358        let report = usage_report(
1359            &snapshot(),
1360            &wanted(),
1361            Some(&filter),
1362            &BTreeMap::new(),
1363            now,
1364            now,
1365            true,
1366        );
1367        let rows = report["providers"].as_array().unwrap();
1368        assert_eq!(rows.len(), 1);
1369        assert_eq!(rows[0]["providerId"], "ollama");
1370        assert_eq!(report["notFound"], json!(["kiro"]));
1371    }
1372
1373    #[test]
1374    fn an_empty_machine_says_so() {
1375        let now = time("2026-11-11T16:00:00Z");
1376        let empty = json!({"connections":[],"quotaPools":[],"accounts":[]});
1377        let report = usage_report(
1378            &empty,
1379            &BTreeSet::new(),
1380            None,
1381            &BTreeMap::new(),
1382            now,
1383            now,
1384            false,
1385        );
1386        let offset = chrono::FixedOffset::east_opt(0).unwrap();
1387        assert!(
1388            usage_terminal(&report, offset)
1389                .contains("No AI provider was detected on this machine.")
1390        );
1391        assert!(usage_text(&report).contains("No AI provider was detected on this machine."));
1392    }
1393
1394    #[test]
1395    fn a_reading_older_than_this_call_is_cached_even_after_a_successful_probe() {
1396        let mut probes = BTreeMap::new();
1397        probes.insert("conn-claude".to_owned(), ProbeOutcome::Ok(true));
1398        let report = usage_report(
1399            &snapshot(),
1400            &wanted(),
1401            None,
1402            &probes,
1403            time("2026-11-11T16:05:00Z"),
1404            time("2026-11-11T16:05:01Z"),
1405            true,
1406        );
1407        let claude = row(&report, "conn-claude");
1408        assert_eq!(claude["data"]["state"], "cached");
1409        assert_eq!(claude["data"]["servedFromProbeCache"], true);
1410    }
1411
1412    #[test]
1413    fn identity_is_withheld_without_the_grant_and_missing_providers_are_named() {
1414        // A granted provider that is not installed is named, not dropped.
1415        let granted: BTreeSet<String> = ["claude_code", "kiro"].map(String::from).into();
1416        let now = time("2026-11-11T16:00:00Z");
1417        let report = usage_report(
1418            &snapshot(),
1419            &granted,
1420            None,
1421            &BTreeMap::new(),
1422            now,
1423            now,
1424            false,
1425        );
1426        let claude = row(&report, "conn-claude");
1427        assert!(claude["account"].is_null());
1428        assert_eq!(claude["identityHidden"], true);
1429        assert_eq!(report["notFound"], json!(["kiro"]));
1430        assert!(usage_text(&report).contains("Kiro: not found on this machine."));
1431    }
1432
1433    #[test]
1434    fn providers_report_counts_windows_and_marks_grants() {
1435        let report = providers_report(&snapshot(), &wanted(), true);
1436        let rows = report["providers"].as_array().unwrap();
1437        assert_eq!(rows.len(), 5);
1438        assert_eq!(rows[0]["usageWindows"], 3);
1439        assert_eq!(rows[0]["auth"], "authenticated");
1440        assert_eq!(rows[3]["usageGranted"], false);
1441        assert_eq!(rows[3]["auth"], "unchecked");
1442    }
1443
1444    #[test]
1445    fn unknown_claude_kinds_keep_the_provider_label() {
1446        assert_eq!(friendly_label("weekly_all"), "Weekly (all models)");
1447        assert_eq!(friendly_label("7-day Opus"), "7-day Opus");
1448        assert_eq!(friendly_label("burst · X"), "burst · X");
1449    }
1450
1451    #[test]
1452    fn rows_without_a_reading_say_why_from_the_adapter_diagnostics() {
1453        let row = |diagnostics: &[&str], auth: &str| json!({"data":{"state":"unavailable"},"auth":auth,"diagnostics":diagnostics});
1454        for (codes, expected) in [
1455            (&["GEMINI_API_KEY_AUTH_NO_QUOTA"][..], "Gemini API key"),
1456            (
1457                &["USAGE_NOT_YET_OBSERVED"],
1458                "only after this login has run a turn",
1459            ),
1460            (
1461                &[
1462                    "CONFIGURATION_DIRECTORY_PRESENT",
1463                    "METADATA_RUNTIME_MISSING",
1464                ],
1465                "runtime is missing",
1466            ),
1467            (&["COPILOT_GH_LOGIN_UNAVAILABLE"], "gh auth login"),
1468            (
1469                &["PI_RADIUS_NO_USAGE_SOURCE"],
1470                "Pi login `radius` has no usage source",
1471            ),
1472            (
1473                &["USAGE_UNAVAILABLE", "USAGE_READ_FAILED_Timeout"],
1474                "did not answer in time",
1475            ),
1476        ] {
1477            let text = status_without_reading(&row(codes, "authenticated"));
1478            assert!(text.contains(expected), "{codes:?} -> {text}");
1479        }
1480        // An unrecognised code is never turned into a guess.
1481        assert_eq!(
1482            status_without_reading(&row(&["SOMETHING_NEW"], "authenticated")),
1483            "detected; no usage reported"
1484        );
1485        assert_eq!(
1486            status_without_reading(
1487                &json!({"data":{"state":"no_source"},"noSourceReason":"local runtime; LM Studio has no plan quota"})
1488            ),
1489            "detected; usage unavailable (local runtime; LM Studio has no plan quota)"
1490        );
1491    }
1492
1493    #[test]
1494    fn a_failed_read_keeps_the_adapter_reason_codes() {
1495        assert_eq!(
1496            detail_codes(
1497                "Native client timed out [NATIVE_SESSION_METADATA_NO_INFERENCE,GEMINI_API_KEY_AUTH_NO_QUOTA]"
1498            ),
1499            [
1500                "NATIVE_SESSION_METADATA_NO_INFERENCE",
1501                "GEMINI_API_KEY_AUTH_NO_QUOTA"
1502            ]
1503        );
1504        // Only well-formed codes are taken; ordinary text is not.
1505        assert!(detail_codes("plain message").is_empty());
1506        assert!(detail_codes("see [this link]").is_empty());
1507        let now = time("2026-11-11T16:00:00Z");
1508        let mut probes = BTreeMap::new();
1509        probes.insert(
1510            "conn-codex-2".to_owned(),
1511            ProbeOutcome::Failed(
1512                "TIMEOUT".into(),
1513                vec!["GEMINI_API_KEY_AUTH_NO_QUOTA".into()],
1514            ),
1515        );
1516        let report = usage_report(&snapshot(), &wanted(), None, &probes, now, now, false);
1517        let text = status_without_reading(row(&report, "conn-codex-2"));
1518        assert!(text.contains("Gemini API key"), "{text}");
1519    }
1520
1521    #[test]
1522    fn tool_definitions_are_read_only_and_closed() {
1523        let tools = tool_definitions();
1524        for tool in tools.as_array().unwrap() {
1525            assert_eq!(tool["annotations"]["readOnlyHint"], true);
1526            assert_eq!(tool["annotations"]["destructiveHint"], false);
1527            assert_eq!(tool["inputSchema"]["additionalProperties"], false);
1528        }
1529    }
1530}