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_LOGIN_REFRESH_FAILED") {
575        "Antigravity's saved login could not be refreshed".to_owned()
576    } else if has("ANTIGRAVITY_CREDENTIAL") {
577        "no saved Antigravity login for this profile".to_owned()
578    } else if has("GROK_BILLING_UNAVAILABLE") {
579        "Grok did not answer its billing request".to_owned()
580    } else if has("CURSOR_SESSION_TOKEN_UNAVAILABLE") || has("CURSOR_CLI_NOT_SIGNED_IN") {
581        "Cursor is not signed in".to_owned()
582    } else if row["auth"] == "unauthenticated" {
583        "not signed in".to_owned()
584    } else if row["auth"] != "authenticated" && has("PLAN_NOT_REPORTED_BY_PROVIDER") {
585        "the client reported no sign-in or plan for this profile".to_owned()
586    } else {
587        return None;
588    };
589    Some(reason)
590}
591
592/// Shape the projected snapshot into the `usage` result. Pure, for tests.
593///
594/// Every detected connection is listed (narrowed only by `filter`); only the
595/// `granted` providers were probed. A connection without a reading is still
596/// listed, with the reason: not granted, or no usage source at all.
597pub fn usage_report(
598    snapshot: &Value,
599    granted: &BTreeSet<String>,
600    filter: Option<&BTreeSet<String>>,
601    probes: &std::collections::BTreeMap<String, ProbeOutcome>,
602    started: chrono::DateTime<chrono::Utc>,
603    now: chrono::DateTime<chrono::Utc>,
604    identity: bool,
605) -> Value {
606    let empty = vec![];
607    let pools = snapshot["quotaPools"].as_array().unwrap_or(&empty);
608    let mut rows = vec![];
609    for connection in snapshot["connections"].as_array().unwrap_or(&empty) {
610        let provider = connection["providerId"].as_str().unwrap_or_default();
611        if filter.is_some_and(|filter| !filter.contains(provider)) {
612            continue;
613        }
614        let connection_id = connection["id"].as_str().unwrap_or_default();
615        let mut windows = vec![];
616        let mut oldest: Option<chrono::DateTime<chrono::Utc>> = None;
617        for pool in pools.iter().filter(|pool| {
618            pool["connectionIds"]
619                .as_array()
620                .is_some_and(|ids| ids.iter().any(|id| id == connection_id))
621        }) {
622            for window in pool["windows"].as_array().unwrap_or(&empty) {
623                let reading = &window["reading"];
624                let mut row = json!({
625                    "id": window["id"],
626                    "label": friendly_label(window["label"].as_str().unwrap_or("window")),
627                    "providerLabel": window["label"],
628                    "resetsAt": window["resetsAt"],
629                    "windowSeconds": window["durationSeconds"],
630                });
631                if let Some(value) = known(reading) {
632                    let observed = parse_time(&reading["observedAt"]);
633                    if let Some(observed) = observed {
634                        oldest = Some(oldest.map_or(observed, |o| o.min(observed)));
635                    }
636                    let used = decimal(&value["used"]);
637                    let limit = decimal(&value["limit"]);
638                    let percent = match (used, limit, value["unit"].as_str()) {
639                        (Some(used), Some(limit), _) if limit > 0.0 => Some(used / limit * 100.0),
640                        (Some(used), None, Some("percent")) => Some(used),
641                        _ => None,
642                    };
643                    row["usedPercent"] = percent.map(round1).map_or(Value::Null, |p| json!(p));
644                    row["remainingPercent"] = percent
645                        .map(|p| round1((100.0 - p).max(0.0)))
646                        .map_or(Value::Null, |p| json!(p));
647                    row["observedAt"] = reading["observedAt"].clone();
648                    row["freshness"] = reading["freshness"].clone();
649                    row["unit"] = value["unit"].clone();
650                    row["used"] = value["used"].clone();
651                    row["limit"] = value["limit"].clone();
652                } else {
653                    row["usedPercent"] = Value::Null;
654                    row["remainingPercent"] = Value::Null;
655                    row["unknownReason"] = reading["reason"].clone();
656                }
657                row["resetsInSeconds"] = parse_time(&window["resetsAt"])
658                    .map(|reset| json!((reset - now).num_seconds().max(0)))
659                    .unwrap_or(Value::Null);
660                windows.push(row);
661            }
662        }
663        let probe = probes.get(connection_id);
664        let age = oldest.map(|observed| (now - observed).num_seconds().max(0));
665        let probe_ok = matches!(probe, Some(ProbeOutcome::Ok(_)));
666        let source = if granted.contains(provider) {
667            "granted"
668        } else if usage_source(provider).is_some() {
669            "not_granted"
670        } else {
671            "none"
672        };
673        let state = if windows.is_empty() {
674            match source {
675                "granted" => "unavailable",
676                "not_granted" => "not_read",
677                _ => "no_source",
678            }
679        } else if probe_ok
680            && age.is_some_and(|age| age <= LIVE_AGE_SECONDS)
681            && oldest.is_some_and(|o| o >= started - chrono::Duration::seconds(LIVE_AGE_SECONDS))
682        {
683            "live"
684        } else {
685            "cached"
686        };
687        let mut data = json!({
688            "state": state,
689            "observedAt": oldest.map(|o| o.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
690            "ageSeconds": age,
691        });
692        match probe {
693            Some(ProbeOutcome::Failed(code, _)) => data["refreshError"] = json!(code),
694            Some(ProbeOutcome::Ok(true)) => data["servedFromProbeCache"] = json!(true),
695            _ => {}
696        }
697        // The connection's own diagnostics, plus any the failed read carried.
698        let mut diagnostics: Vec<Value> = connection["diagnostics"]
699            .as_array()
700            .cloned()
701            .unwrap_or_default();
702        if let Some(ProbeOutcome::Failed(_, codes)) = probe {
703            diagnostics.extend(codes.iter().map(|code| json!(code)));
704        }
705        rows.push(json!({
706            "providerId": provider,
707            "providerName": provider_name(provider),
708            "connectionId": connection_id,
709            "connectionName": connection["displayName"],
710            "auth": known(&connection["auth"]).cloned().unwrap_or(json!("unknown")),
711            "account": account_label(snapshot, &connection["accountId"], identity),
712            "identityHidden": !identity,
713            "plan": known(&connection["plan"]).map(|plan| plan["label"].clone()).unwrap_or(Value::Null),
714            "usageSource": source,
715            "diagnostics": diagnostics,
716            "noSourceReason": if source == "none" { json!(no_source_reason(provider)) } else { Value::Null },
717            "data": data,
718            "windows": windows,
719        }));
720    }
721    // Readings first, then granted connections without one, then providers
722    // whose usage was not read, then providers with no usage source.
723    rows.sort_by_key(|row| {
724        let rank = if row["windows"].as_array().is_some_and(|w| !w.is_empty()) {
725            0
726        } else {
727            match row["usageSource"].as_str() {
728                Some("granted") => 1,
729                Some("not_granted") => 2,
730                _ => 3,
731            }
732        };
733        // Claude Code and Codex lead their group; the rest are alphabetical.
734        let lead = match row["providerId"].as_str() {
735            Some("claude_code") => 0,
736            Some("codex") => 1,
737            _ => 2,
738        };
739        (
740            rank,
741            lead,
742            row["providerName"].as_str().unwrap_or_default().to_owned(),
743            row["connectionName"]
744                .as_str()
745                .unwrap_or_default()
746                .to_owned(),
747        )
748    });
749    let found: BTreeSet<&str> = rows
750        .iter()
751        .filter_map(|row| row["providerId"].as_str())
752        .collect();
753    let missing: Vec<&String> = filter
754        .unwrap_or(granted)
755        .iter()
756        .filter(|p| !found.contains(p.as_str()))
757        .collect();
758    json!({
759        "generatedAt": now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
760        "providers": rows,
761        "notFound": missing,
762        "notes": [
763            "Percentages are the provider's own plan-quota readings, not token estimates.",
764            "A missing window or null percent is unknown, not zero.",
765            "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).",
766            "data.state is `live` when this call read the provider within the last 90 s, otherwise `cached` with its age."
767        ]
768    })
769}
770
771/// Claude Code's `limits[]` rows carry a raw `kind` (`session`, `weekly_all`,
772/// `weekly_scoped · <model>`). Name the ones whose meaning is established —
773/// the session bucket is the same one the adapter's keyed path labels
774/// "5-hour session" — and keep any other provider label unchanged.
775pub fn friendly_label(label: &str) -> String {
776    let (kind, scope) = match label.split_once(" · ") {
777        Some((kind, scope)) => (kind, Some(scope)),
778        None => (label, None),
779    };
780    match (kind, scope) {
781        ("session", None) => "5-hour session".into(),
782        ("weekly_all", None) => "Weekly (all models)".into(),
783        ("weekly_scoped", Some(model)) => format!("Weekly ({model})"),
784        _ => label.to_owned(),
785    }
786}
787
788fn duration_text(seconds: i64) -> String {
789    let (d, h, m) = (
790        seconds / 86_400,
791        (seconds % 86_400) / 3_600,
792        (seconds % 3_600) / 60,
793    );
794    match (d, h) {
795        (0, 0) => format!("{m}m"),
796        (0, _) => format!("{h}h {m}m"),
797        _ => format!("{d}d {h}h"),
798    }
799}
800
801/// The human-readable side of the `usage` result.
802pub fn usage_text(report: &Value) -> String {
803    let mut text = String::new();
804    for row in report["providers"].as_array().into_iter().flatten() {
805        let data = &row["data"];
806        let mut who = vec![];
807        if let Some(account) = row["account"].as_str() {
808            who.push(account.to_owned());
809        }
810        if let Some(plan) = row["plan"].as_str() {
811            who.push(format!("plan {plan}"));
812        }
813        let freshness = match (data["state"].as_str(), data["ageSeconds"].as_i64()) {
814            (Some("live"), Some(age)) => format!("live, read {age}s ago"),
815            (Some("cached"), Some(age)) => format!("CACHED, {} old", duration_text(age)),
816            _ => status_without_reading(row),
817        };
818        text.push_str(&format!(
819            "{}{} — {}{}\n",
820            row["connectionName"]
821                .as_str()
822                .or(row["providerName"].as_str())
823                .unwrap_or("?"),
824            if who.is_empty() {
825                String::new()
826            } else {
827                format!(" ({})", who.join(", "))
828            },
829            freshness,
830            data["refreshError"]
831                .as_str()
832                .map(|e| format!(" — refresh failed: {e}"))
833                .unwrap_or_default(),
834        ));
835        for window in row["windows"].as_array().into_iter().flatten() {
836            let label = window["label"].as_str().unwrap_or("window");
837            let reset = match (
838                window["resetsAt"].as_str(),
839                window["resetsInSeconds"].as_i64(),
840            ) {
841                (Some(at), Some(secs)) => format!(
842                    ", resets {} (in {})",
843                    parse_time(&json!(at))
844                        .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
845                        .unwrap_or_else(|| at.to_owned()),
846                    duration_text(secs)
847                ),
848                _ => String::new(),
849            };
850            match (
851                window["usedPercent"].as_f64(),
852                window["remainingPercent"].as_f64(),
853            ) {
854                (Some(used), Some(left)) => {
855                    text.push_str(&format!("  {label}: {used}% used, {left}% left{reset}\n"))
856                }
857                _ => text.push_str(&format!(
858                    "  {label}: {}{reset}\n",
859                    amount_text(window).unwrap_or_else(|| "unknown".into())
860                )),
861            }
862        }
863    }
864    for missing in report["notFound"].as_array().into_iter().flatten() {
865        text.push_str(&format!(
866            "{}: not found on this machine.\n",
867            provider_name(missing.as_str().unwrap_or("?"))
868        ));
869    }
870    if text.is_empty() {
871        text.push_str("No AI provider was detected on this machine.\n");
872    }
873    text
874}
875
876/// A known non-percent reading, e.g. dollars spent with no limit.
877fn amount_text(window: &Value) -> Option<String> {
878    let used: f64 = window["used"].as_str()?.parse().ok()?;
879    let unit = window["unit"].as_str()?;
880    let money = |v: f64| {
881        if unit == "usd" {
882            format!("${v:.2}")
883        } else {
884            format!("{v} {unit}")
885        }
886    };
887    Some(
888        match window["limit"].as_str().and_then(|l| l.parse::<f64>().ok()) {
889            Some(limit) => format!("{} of {} used", money(used), money(limit)),
890            None => format!("{} used, no limit", money(used)),
891        },
892    )
893}
894
895fn percent(value: f64) -> String {
896    if value.fract() == 0.0 {
897        format!("{value:.0}%")
898    } else {
899        format!("{value:.1}%")
900    }
901}
902
903/// Terminal rendering for `originlm usage` / `olm usage`: one block per
904/// account with aligned window rows, then every detected provider that has no
905/// reading, each with its reason. Reset times are shown in `offset` (the
906/// caller's local zone).
907pub fn usage_terminal(report: &Value, offset: chrono::FixedOffset) -> String {
908    let rows: Vec<&Value> = report["providers"]
909        .as_array()
910        .into_iter()
911        .flatten()
912        .collect();
913    let with: Vec<&&Value> = rows
914        .iter()
915        .filter(|row| row["windows"].as_array().is_some_and(|w| !w.is_empty()))
916        .collect();
917    let without: Vec<&&Value> = rows
918        .iter()
919        .filter(|row| row["windows"].as_array().is_none_or(Vec::is_empty))
920        .collect();
921    let label_width = with
922        .iter()
923        .flat_map(|row| row["windows"].as_array().into_iter().flatten())
924        .map(|w| w["label"].as_str().unwrap_or("window").chars().count())
925        .max()
926        .unwrap_or(0);
927    let name = |row: &Value| {
928        row["connectionName"]
929            .as_str()
930            .or(row["providerName"].as_str())
931            .unwrap_or("?")
932            .to_owned()
933    };
934    let mut out = String::new();
935    for row in &with {
936        let data = &row["data"];
937        let mut header = name(row);
938        if let Some(plan) = row["plan"].as_str() {
939            header.push_str(&format!("  ·  {plan}"));
940        }
941        if let Some(account) = row["account"].as_str() {
942            header.push_str(&format!("  ·  {account}"));
943        }
944        let freshness = match (data["state"].as_str(), data["ageSeconds"].as_i64()) {
945            (Some("live"), Some(age)) => format!("live, read {age}s ago"),
946            (Some("cached"), Some(age)) => format!("CACHED, {} old", duration_text(age)),
947            _ => "age unknown".to_owned(),
948        };
949        out.push_str(&format!("{header}  ·  {freshness}"));
950        if let Some(error) = data["refreshError"].as_str() {
951            out.push_str(&format!("  (refresh failed: {error})"));
952        }
953        out.push('\n');
954        for window in row["windows"].as_array().into_iter().flatten() {
955            let label = window["label"].as_str().unwrap_or("window");
956            let reading = match (
957                window["usedPercent"].as_f64(),
958                window["remainingPercent"].as_f64(),
959            ) {
960                (Some(used), Some(left)) => {
961                    format!("{:>5} used  {:>5} left", percent(used), percent(left))
962                }
963                _ => amount_text(window).unwrap_or_else(|| format!("{:>9}", "unknown")),
964            };
965            let reset = match (
966                parse_time(&window["resetsAt"]),
967                window["resetsInSeconds"].as_i64(),
968            ) {
969                (Some(at), Some(secs)) => format!(
970                    "  resets {} (in {})",
971                    at.with_timezone(&offset).format("%a %b %-d %H:%M"),
972                    duration_text(secs)
973                ),
974                _ => String::new(),
975            };
976            out.push_str(format!("  {label:<label_width$}  {reading}{reset}").trim_end());
977            out.push('\n');
978        }
979        out.push('\n');
980    }
981    if !without.is_empty() {
982        out.push_str("Detected without a usage reading:\n");
983        let width = without
984            .iter()
985            .map(|row| name(row).chars().count())
986            .max()
987            .unwrap_or(0);
988        for row in &without {
989            out.push_str(&format!(
990                "  {:<width$}  {}\n",
991                name(row),
992                status_without_reading(row)
993            ));
994        }
995        out.push('\n');
996    }
997    for missing in report["notFound"].as_array().into_iter().flatten() {
998        out.push_str(&format!(
999            "{}: not found on this machine.\n",
1000            provider_name(missing.as_str().unwrap_or("?"))
1001        ));
1002    }
1003    if rows.is_empty() && report["notFound"].as_array().is_none_or(Vec::is_empty) {
1004        out.push_str("No AI provider was detected on this machine.\n");
1005    }
1006    out.push_str(
1007        "Percentages are the providers' own plan-quota readings; unknown is not zero.\n\
1008         Local token totals: olm usage --history\n",
1009    );
1010    out
1011}
1012
1013/// Why a listed connection has no reading. Plain, and never a number.
1014fn status_without_reading(row: &Value) -> String {
1015    match row["data"]["state"].as_str() {
1016        Some("no_source") => format!(
1017            "detected; usage unavailable ({})",
1018            row["noSourceReason"]
1019                .as_str()
1020                .unwrap_or("OriginLM has no usage source for it")
1021        ),
1022        Some("not_read") => "detected; usage not read (excluded from this run)".to_owned(),
1023        _ => match (
1024            reading_missing_reason(row),
1025            row["data"]["refreshError"].as_str(),
1026        ) {
1027            (Some(reason), _) => format!("no usage: {reason}"),
1028            (None, Some(error)) => format!("no usage: read failed ({error})"),
1029            (None, None) => "detected; no usage reported".to_owned(),
1030        },
1031    }
1032}
1033
1034/// Shape the snapshot into the `providers` result. Pure, for tests.
1035pub fn providers_report(snapshot: &Value, granted: &BTreeSet<String>, identity: bool) -> Value {
1036    let empty = vec![];
1037    let pools = snapshot["quotaPools"].as_array().unwrap_or(&empty);
1038    let rows: Vec<Value> = snapshot["connections"]
1039        .as_array()
1040        .unwrap_or(&empty)
1041        .iter()
1042        .map(|connection| {
1043            let id = &connection["id"];
1044            let windows: usize = pools
1045                .iter()
1046                .filter(|pool| pool["connectionIds"].as_array().is_some_and(|ids| ids.contains(id)))
1047                .map(|pool| pool["windows"].as_array().map_or(0, Vec::len))
1048                .sum();
1049            let provider = connection["providerId"].as_str().unwrap_or_default();
1050            json!({
1051                "providerId": provider,
1052                "providerName": provider_name(provider),
1053                "connectionId": id,
1054                "connectionName": connection["displayName"],
1055                "status": connection["status"],
1056                "auth": known(&connection["auth"]).cloned().unwrap_or(json!("unchecked")),
1057                "account": account_label(snapshot, &connection["accountId"], identity),
1058                "plan": known(&connection["plan"]).map(|plan| plan["label"].clone()).unwrap_or(Value::Null),
1059                "usageGranted": granted.contains(provider),
1060                "usageWindows": windows,
1061            })
1062        })
1063        .collect();
1064    json!({"providers": rows})
1065}
1066
1067/// Serve MCP over a byte stream until EOF.
1068pub async fn serve<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
1069    reader: R,
1070    mut writer: W,
1071    mut server: McpServer,
1072) -> Result<()> {
1073    let mut lines = BufReader::new(reader);
1074    let mut line = String::new();
1075    let io = |_| DomainError::new(ErrorCode::ProviderUnavailable, "MCP stdio closed");
1076    loop {
1077        line.clear();
1078        let read = (&mut lines)
1079            .take(MAX_LINE_BYTES as u64 + 1)
1080            .read_line(&mut line)
1081            .await
1082            .map_err(io)?;
1083        if read == 0 {
1084            return Ok(());
1085        }
1086        let trimmed = line.trim();
1087        if trimmed.is_empty() {
1088            continue;
1089        }
1090        let reply = if line.len() > MAX_LINE_BYTES {
1091            // Drain the rest of the oversized line before answering.
1092            let mut rest = Vec::new();
1093            lines.read_until(b'\n', &mut rest).await.map_err(io)?;
1094            Some(
1095                json!({"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"MCP message too large"}}),
1096            )
1097        } else {
1098            match serde_json::from_str::<Value>(trimmed) {
1099                Ok(Value::Array(_)) => Some(
1100                    json!({"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Batches are not supported"}}),
1101                ),
1102                Ok(message) => server.handle(message).await,
1103                Err(_) => Some(
1104                    json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}}),
1105                ),
1106            }
1107        };
1108        if let Some(reply) = reply {
1109            let mut bytes = serde_json::to_vec(&reply).unwrap_or_default();
1110            bytes.push(b'\n');
1111            writer.write_all(&bytes).await.map_err(io)?;
1112            writer.flush().await.map_err(io)?;
1113        }
1114    }
1115}
1116
1117fn code(error: &DomainError) -> String {
1118    serde_json::to_value(&error.code)
1119        .ok()
1120        .and_then(|value| value.as_str().map(str::to_owned))
1121        .unwrap_or_else(|| "ERROR".into())
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126    use super::*;
1127    use std::collections::BTreeMap;
1128
1129    fn time(text: &str) -> chrono::DateTime<chrono::Utc> {
1130        parse_time(&json!(text)).unwrap()
1131    }
1132
1133    fn known_value(value: Value, observed: &str) -> Value {
1134        json!({"state":"known","value":value,
1135            "source":{"kind":"official_protocol","adapterId":"x","adapterVersion":"1"},
1136            "observedAt":observed,"freshness":"fresh","verification":"reported"})
1137    }
1138
1139    fn reading(used: &str, observed: &str) -> Value {
1140        known_value(
1141            json!({"unit":"percent","used":used,"limit":"100","remaining":null,"usedFraction":null}),
1142            observed,
1143        )
1144    }
1145
1146    fn connection(
1147        id: &str,
1148        provider: &str,
1149        name: &str,
1150        account: Value,
1151        auth: Value,
1152        plan: Value,
1153    ) -> Value {
1154        json!({"id":id,"providerId":provider,"displayName":name,"accountId":account,
1155            "auth":auth,"plan":plan,"status":"ready"})
1156    }
1157
1158    fn snapshot() -> Value {
1159        let at = "2026-11-11T16:00:00Z";
1160        let unknown = json!({"state":"unknown","reason":"NOT_REPORTED"});
1161        json!({
1162            "accounts":[{"id":"acct-c","providerId":"claude_code",
1163                "displayLabel":known_value(json!("me@example.com"), at),"identitySource":unknown}],
1164            "connections":[
1165                connection("conn-claude","claude_code","Claude Code · Default profile",json!("acct-c"),
1166                    known_value(json!("authenticated"),at),known_value(json!({"nativeId":"max","label":"Claude Max"}),at)),
1167                connection("conn-codex","codex","Codex · Default profile",Value::Null,
1168                    known_value(json!("authenticated"),at),unknown.clone()),
1169                connection("conn-codex-2","codex","Codex · Additional profile 2",Value::Null,
1170                    known_value(json!("unauthenticated"),at),unknown.clone()),
1171                connection("conn-ollama","ollama","Ollama",Value::Null,unknown.clone(),unknown.clone()),
1172                connection("conn-cursor","cursor","Cursor",Value::Null,unknown.clone(),unknown.clone()),
1173            ],
1174            "quotaPools":[
1175                {"id":"pool-c","accountId":"acct-c","connectionIds":["conn-claude"],"routeIds":[],"sharing":"unknown","windows":[
1176                    {"id":"session-0","label":"session","reading":reading("16",at),
1177                     "resetsAt":"2026-11-11T20:10:00.080121+00:00","durationSeconds":null},
1178                    {"id":"weekly_scoped-2","label":"weekly_scoped · Fable","reading":reading("54",at),
1179                     "resetsAt":"2026-11-14T21:00:00Z","durationSeconds":null},
1180                    {"id":"spend","label":"Monthly spend","reading":{"state":"unavailable","reason":"USAGE_UNAVAILABLE"},
1181                     "resetsAt":null,"durationSeconds":null}
1182                ]},
1183                {"id":"pool-x","accountId":null,"connectionIds":["conn-codex"],"routeIds":[],"sharing":"unknown","windows":[
1184                    {"id":"w1","label":"5 hr","reading":reading("61","2026-11-11T15:00:00Z"),
1185                     "resetsAt":"2026-11-11T18:00:00+00:00","durationSeconds":18000}
1186                ]}
1187            ]
1188        })
1189    }
1190
1191    fn wanted() -> BTreeSet<String> {
1192        ["claude_code", "codex"].map(String::from).into()
1193    }
1194
1195    fn row<'a>(report: &'a Value, id: &str) -> &'a Value {
1196        report["providers"]
1197            .as_array()
1198            .unwrap()
1199            .iter()
1200            .find(|row| row["connectionId"] == id)
1201            .unwrap()
1202    }
1203
1204    #[test]
1205    fn live_and_cached_readings_are_labelled_with_their_age() {
1206        let mut probes = BTreeMap::new();
1207        probes.insert("conn-claude".to_owned(), ProbeOutcome::Ok(false));
1208        probes.insert(
1209            "conn-codex".to_owned(),
1210            ProbeOutcome::Failed("PROVIDER_UNAVAILABLE".into(), vec![]),
1211        );
1212        let report = usage_report(
1213            &snapshot(),
1214            &wanted(),
1215            None,
1216            &probes,
1217            time("2026-11-11T16:00:01Z"),
1218            time("2026-11-11T16:00:30Z"),
1219            true,
1220        );
1221        let rows = report["providers"].as_array().unwrap();
1222        // Every detected connection is listed: readings, then granted without
1223        // one, then a usage source not granted, then no usage source at all.
1224        let order: Vec<_> = rows
1225            .iter()
1226            .map(|r| r["connectionId"].as_str().unwrap())
1227            .collect();
1228        assert_eq!(
1229            order,
1230            [
1231                "conn-claude",
1232                "conn-codex",
1233                "conn-codex-2",
1234                "conn-cursor",
1235                "conn-ollama"
1236            ]
1237        );
1238        assert_eq!(rows[2]["data"]["state"], "unavailable");
1239        assert_eq!(rows[3]["data"]["state"], "not_read");
1240        assert_eq!(rows[3]["usageSource"], "not_granted");
1241        assert_eq!(rows[4]["data"]["state"], "no_source");
1242        assert_eq!(rows[4]["usageSource"], "none");
1243        // Detected without a reading never becomes a number.
1244        assert_eq!(rows[4]["windows"], json!([]));
1245        assert!(rows[4]["data"]["ageSeconds"].is_null());
1246
1247        let claude = row(&report, "conn-claude");
1248        assert_eq!(claude["data"]["state"], "live");
1249        assert_eq!(claude["data"]["ageSeconds"], 30);
1250        assert_eq!(claude["account"], "me@example.com");
1251        assert_eq!(claude["plan"], "Claude Max");
1252        let session = &claude["windows"][0];
1253        assert_eq!(session["label"], "5-hour session");
1254        assert_eq!(session["providerLabel"], "session");
1255        assert_eq!(session["usedPercent"], 16.0);
1256        assert_eq!(session["remainingPercent"], 84.0);
1257        assert_eq!(session["resetsInSeconds"], 4 * 3600 + 9 * 60 + 30);
1258        assert_eq!(claude["windows"][1]["label"], "Weekly (Fable)");
1259        // An unavailable reading is unknown, never zero.
1260        assert!(claude["windows"][2]["usedPercent"].is_null());
1261        assert_eq!(claude["windows"][2]["unknownReason"], "USAGE_UNAVAILABLE");
1262
1263        let codex = row(&report, "conn-codex");
1264        assert_eq!(codex["data"]["state"], "cached");
1265        assert_eq!(codex["data"]["ageSeconds"], 3630);
1266        assert_eq!(codex["data"]["refreshError"], "PROVIDER_UNAVAILABLE");
1267        assert!(codex["plan"].is_null());
1268
1269        let text = usage_text(&report);
1270        for expected in [
1271            "Claude Code · Default profile (me@example.com, plan Claude Max) — live, read 30s ago",
1272            "5-hour session: 16% used, 84% left, resets 2026-11-11T20:10:00Z (in 4h 9m)",
1273            "Codex · Default profile — CACHED, 1h 0m old — refresh failed: PROVIDER_UNAVAILABLE",
1274            "Monthly spend: unknown",
1275            "Additional profile 2 — no usage: not signed in",
1276            "Cursor — detected; usage not read (excluded from this run)",
1277            "Ollama — detected; usage unavailable (Ollama's local API reports sign-in and plan, not cloud usage limits)",
1278        ] {
1279            assert!(text.contains(expected), "missing {expected:?} in:\n{text}");
1280        }
1281
1282        let terminal = usage_terminal(&report, chrono::FixedOffset::west_opt(5 * 3600).unwrap());
1283        for expected in [
1284            "Claude Code · Default profile  ·  Claude Max  ·  me@example.com  ·  live, read 30s ago\n",
1285            "  5-hour session    16% used    84% left  resets Wed Nov 11 15:10 (in 4h 9m)\n",
1286            "  Monthly spend     unknown\n",
1287            "Codex · Default profile  ·  CACHED, 1h 0m old  (refresh failed: PROVIDER_UNAVAILABLE)\n",
1288            "Detected without a usage reading:\n",
1289            "  Codex · Additional profile 2  no usage: not signed in\n",
1290            "  Ollama                        detected; usage unavailable (Ollama's local API reports sign-in and plan, not cloud usage limits)\n",
1291            "Local token totals: olm usage --history\n",
1292        ] {
1293            assert!(
1294                terminal.contains(expected),
1295                "missing {expected:?} in:\n{terminal}"
1296            );
1297        }
1298        assert!(
1299            !terminal.contains('{'),
1300            "no JSON in terminal output:\n{terminal}"
1301        );
1302    }
1303
1304    #[test]
1305    fn a_provider_filter_narrows_the_listing_and_names_what_is_missing() {
1306        let filter: BTreeSet<String> = ["ollama", "kiro"].map(String::from).into();
1307        let now = time("2026-11-11T16:00:00Z");
1308        let report = usage_report(
1309            &snapshot(),
1310            &wanted(),
1311            Some(&filter),
1312            &BTreeMap::new(),
1313            now,
1314            now,
1315            true,
1316        );
1317        let rows = report["providers"].as_array().unwrap();
1318        assert_eq!(rows.len(), 1);
1319        assert_eq!(rows[0]["providerId"], "ollama");
1320        assert_eq!(report["notFound"], json!(["kiro"]));
1321    }
1322
1323    #[test]
1324    fn an_empty_machine_says_so() {
1325        let now = time("2026-11-11T16:00:00Z");
1326        let empty = json!({"connections":[],"quotaPools":[],"accounts":[]});
1327        let report = usage_report(
1328            &empty,
1329            &BTreeSet::new(),
1330            None,
1331            &BTreeMap::new(),
1332            now,
1333            now,
1334            false,
1335        );
1336        let offset = chrono::FixedOffset::east_opt(0).unwrap();
1337        assert!(
1338            usage_terminal(&report, offset)
1339                .contains("No AI provider was detected on this machine.")
1340        );
1341        assert!(usage_text(&report).contains("No AI provider was detected on this machine."));
1342    }
1343
1344    #[test]
1345    fn a_reading_older_than_this_call_is_cached_even_after_a_successful_probe() {
1346        let mut probes = BTreeMap::new();
1347        probes.insert("conn-claude".to_owned(), ProbeOutcome::Ok(true));
1348        let report = usage_report(
1349            &snapshot(),
1350            &wanted(),
1351            None,
1352            &probes,
1353            time("2026-11-11T16:05:00Z"),
1354            time("2026-11-11T16:05:01Z"),
1355            true,
1356        );
1357        let claude = row(&report, "conn-claude");
1358        assert_eq!(claude["data"]["state"], "cached");
1359        assert_eq!(claude["data"]["servedFromProbeCache"], true);
1360    }
1361
1362    #[test]
1363    fn identity_is_withheld_without_the_grant_and_missing_providers_are_named() {
1364        // A granted provider that is not installed is named, not dropped.
1365        let granted: BTreeSet<String> = ["claude_code", "kiro"].map(String::from).into();
1366        let now = time("2026-11-11T16:00:00Z");
1367        let report = usage_report(
1368            &snapshot(),
1369            &granted,
1370            None,
1371            &BTreeMap::new(),
1372            now,
1373            now,
1374            false,
1375        );
1376        let claude = row(&report, "conn-claude");
1377        assert!(claude["account"].is_null());
1378        assert_eq!(claude["identityHidden"], true);
1379        assert_eq!(report["notFound"], json!(["kiro"]));
1380        assert!(usage_text(&report).contains("Kiro: not found on this machine."));
1381    }
1382
1383    #[test]
1384    fn providers_report_counts_windows_and_marks_grants() {
1385        let report = providers_report(&snapshot(), &wanted(), true);
1386        let rows = report["providers"].as_array().unwrap();
1387        assert_eq!(rows.len(), 5);
1388        assert_eq!(rows[0]["usageWindows"], 3);
1389        assert_eq!(rows[0]["auth"], "authenticated");
1390        assert_eq!(rows[3]["usageGranted"], false);
1391        assert_eq!(rows[3]["auth"], "unchecked");
1392    }
1393
1394    #[test]
1395    fn unknown_claude_kinds_keep_the_provider_label() {
1396        assert_eq!(friendly_label("weekly_all"), "Weekly (all models)");
1397        assert_eq!(friendly_label("7-day Opus"), "7-day Opus");
1398        assert_eq!(friendly_label("burst · X"), "burst · X");
1399    }
1400
1401    #[test]
1402    fn rows_without_a_reading_say_why_from_the_adapter_diagnostics() {
1403        let row = |diagnostics: &[&str], auth: &str| json!({"data":{"state":"unavailable"},"auth":auth,"diagnostics":diagnostics});
1404        for (codes, expected) in [
1405            (&["GEMINI_API_KEY_AUTH_NO_QUOTA"][..], "Gemini API key"),
1406            (
1407                &["USAGE_NOT_YET_OBSERVED"],
1408                "only after this login has run a turn",
1409            ),
1410            (
1411                &[
1412                    "CONFIGURATION_DIRECTORY_PRESENT",
1413                    "METADATA_RUNTIME_MISSING",
1414                ],
1415                "runtime is missing",
1416            ),
1417            (&["COPILOT_GH_LOGIN_UNAVAILABLE"], "gh auth login"),
1418            (
1419                &["PI_RADIUS_NO_USAGE_SOURCE"],
1420                "Pi login `radius` has no usage source",
1421            ),
1422            (
1423                &["USAGE_UNAVAILABLE", "USAGE_READ_FAILED_Timeout"],
1424                "did not answer in time",
1425            ),
1426        ] {
1427            let text = status_without_reading(&row(codes, "authenticated"));
1428            assert!(text.contains(expected), "{codes:?} -> {text}");
1429        }
1430        // An unrecognised code is never turned into a guess.
1431        assert_eq!(
1432            status_without_reading(&row(&["SOMETHING_NEW"], "authenticated")),
1433            "detected; no usage reported"
1434        );
1435        assert_eq!(
1436            status_without_reading(
1437                &json!({"data":{"state":"no_source"},"noSourceReason":"local runtime; LM Studio has no plan quota"})
1438            ),
1439            "detected; usage unavailable (local runtime; LM Studio has no plan quota)"
1440        );
1441    }
1442
1443    #[test]
1444    fn a_failed_read_keeps_the_adapter_reason_codes() {
1445        assert_eq!(
1446            detail_codes(
1447                "Native client timed out [NATIVE_SESSION_METADATA_NO_INFERENCE,GEMINI_API_KEY_AUTH_NO_QUOTA]"
1448            ),
1449            [
1450                "NATIVE_SESSION_METADATA_NO_INFERENCE",
1451                "GEMINI_API_KEY_AUTH_NO_QUOTA"
1452            ]
1453        );
1454        // Only well-formed codes are taken; ordinary text is not.
1455        assert!(detail_codes("plain message").is_empty());
1456        assert!(detail_codes("see [this link]").is_empty());
1457        let now = time("2026-11-11T16:00:00Z");
1458        let mut probes = BTreeMap::new();
1459        probes.insert(
1460            "conn-codex-2".to_owned(),
1461            ProbeOutcome::Failed(
1462                "TIMEOUT".into(),
1463                vec!["GEMINI_API_KEY_AUTH_NO_QUOTA".into()],
1464            ),
1465        );
1466        let report = usage_report(&snapshot(), &wanted(), None, &probes, now, now, false);
1467        let text = status_without_reading(row(&report, "conn-codex-2"));
1468        assert!(text.contains("Gemini API key"), "{text}");
1469    }
1470
1471    #[test]
1472    fn tool_definitions_are_read_only_and_closed() {
1473        let tools = tool_definitions();
1474        for tool in tools.as_array().unwrap() {
1475            assert_eq!(tool["annotations"]["readOnlyHint"], true);
1476            assert_eq!(tool["annotations"]["destructiveHint"], false);
1477            assert_eq!(tool["inputSchema"]["additionalProperties"], false);
1478        }
1479    }
1480}