//! The words an `assistant` row is read in, answered by the generic read//! from the stored `cotton_mcp_tokens` row: what the key may do, whether it//! can change records, the expiry it was made with, when it was last used,//! the day a key rotation signed it out, and its status word (Connected,//! Needs sign-in, Expired, Disconnected). The address and the recent uses//! are the reader's (`cotton-ffi` `phone::settings_assistants`).//! `token_hash` is never selected: no read carries a key's secret.use cotton_core::definitions::TableDefinition;use cotton_core::rules::connector_sign_in::{needs_sign_in_since, ConnectorFacts};use rusqlite::types::ValueasSqlValue;use serde_json::Value;usesuper::{sql_err, Stored};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::Valid;/// A key's status, one word each.pubconst CONNECTED: &str = "Connected";pubconst NEEDS_SIGN_IN: &str = "Needs sign-in";pubconst DISCONNECTED: &str = "Disconnected";pubconst EXPIRED: &str = "Expired";/// The expiries a key is minted with (`AssistantFacts.expiryChoices`).const EXPIRY_CHOICES: [(Option<i64>, &str); 3] = [(Some(30), "30 days"), (Some(90), "90 days"), (None, "Never")];/// Answer the words of every `assistant` record read.pub(super) fn assistant_words(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> {if !definition.has_engine() || definition.id != "assistant" || records.is_empty() {returnOk(()); }let driver = ctx.read.driver();let workspace = SqlValue::Text(ctx.workspace_id.to_string());let vault = driver .get("SELECT vmk_version, rotated_at FROM cotton_vault_state WHERE workspace_id = ?", std::slice::from_ref(&workspace)) .map_err(sql_err)?;let vmk_version = vault.as_ref().and_then(|row| row.int("vmk_version"));let rotated_at = vault.as_ref().and_then(|row| row.text("rotated_at"));for record in records.iter_mut() {let row = driver .get("SELECT t.scopes, t.expires_at, t.revoked_at, t.created_at, t.last_used_at, g.created_at AS grant_created_at, g.refresh_rotated_at AS grant_refreshed_at, (g.refresh_digest IS NOT NULL AND g.minted_by IS NOT NULL) AS grant_outlives_rotation FROM cotton_mcp_tokens t LEFT JOIN cotton_oauth_grants g ON g.token_id = t.id AND g.workspace_id = t.workspace_id AND g.revoked_at IS NULL WHERE t.workspace_id = ? AND t.id = ?", &[workspace.clone(), SqlValue::Text(record.id.clone())], ) .map_err(sql_err)?;letSome(row) = row else { continue };let said = |text: Option<&str>| text.filter(|text| !text.is_empty()).map_or(Value::Null, Value::from);let writes = can_change(row.text("scopes")); record.data.insert("kept".into(), Value::Bool(true)); record.data.insert("account".into(), Value::from(if writes { "Can read and change" } else { "Read-only" })); record.data.insert("can_change".into(), Value::Bool(writes)); record.data.insert("expires".into(), said(expiry_label(row.text("expires_at"), row.text("created_at"))), ); record.data.insert("last_synced_at".into(), said(row.text("last_used_at")));let since = needs_sign_in_since(&ConnectorFacts { vmk_version, rotated_at, grant_created_at: row.text("grant_created_at"), grant_refreshed_at: row.text("grant_refreshed_at"), token_revoked: row.text("revoked_at").is_some_and(|text| !text.is_empty()), token_last_used_at: row.text("last_used_at"), grant_outlives_rotation: row.int("grant_outlives_rotation") == Some(1), }); record.data.insert("needs_sign_in_since".into(), since.map_or(Value::Null, |day| Value::from(day.format("%Y-%m-%d").to_string())), ); record.data.insert("status".into(),Value::from(status_word(row.text("revoked_at"), row.text("expires_at"), since.is_some(), ctx.now)), ); }Ok(())}/// Whether the stored scopes grant `write` (an unreadable list grants none).fn can_change(scopes: Option<&str>) -> bool { scopes .and_then(|text| serde_json::from_str::<Vec<String>>(text).ok()) .is_some_and(|scopes| scopes.iter().any(|scope| scope == "write"))}fn instant(text: Option<&str>) -> Option<chrono::DateTime<chrono::Utc>> { text.filter(|text| !text.is_empty()) .and_then(|text| chrono::DateTime::parse_from_rfc3339(text).ok()) .map(|at| at.with_timezone(&chrono::Utc))}/// A key's status word: revoked reads Disconnected, past its expiry Expired,/// a live key signed out by a key rotation Needs sign-in, any other live key/// Connected (an expiry that will not parse reads live).// RULE: An assistant's status is one word the core says — Disconnected when revoked, Expired past its expiry, Needs sign-in when a rotation signed it out, else Connected — so Disconnect and Remove are offered on the right keys.pubfn status_word( revoked_at: Option<&str>, expires_at: Option<&str>, signed_out: bool, now: chrono::DateTime<chrono::Utc>,) -> &'static str {if revoked_at.is_some_and(|text| !text.is_empty()) {return DISCONNECTED; }if instant(expires_at).is_some_and(|at| at <= now) {return EXPIRED; }if signed_out { NEEDS_SIGN_IN } else { CONNECTED }}/// The expiry a key was made with when its two stamps say one of the choices/// exactly; Never with no expiry; nothing otherwise (`expiryLabel`).pubfn expiry_label(expires_at: Option<&str>, created_at: Option<&str>) -> Option<&'static str> {if expires_at.is_none_or(str::is_empty) {return EXPIRY_CHOICES.iter().find(|(days, _)| days.is_none()).map(|(_, label)| *label); }let (end, made) = (instant(expires_at)?, instant(created_at)?);let days = ((end - made).num_milliseconds() as f64 / 86_400_000.0).round() as i64; EXPIRY_CHOICES.iter().find(|(choice, _)| *choice == Some(days)).map(|(_, label)| *label)}