Cotton code
718 lines · 30.7 KB · RustRaw
//! The bodies of `voice.*` (the contract is [`super::voice`]'s header): the//! sessions this core holds, the catalogue joined with this phone's models,//! the settings row, the vocabulary and command mode. The rules themselves//! are `cotton_rules::voice`, the same the Mac and the Worker run.use std::collections::BTreeMap;use std::sync::Mutex;use std::time::{Duration, Instant};use cotton_core::rules::shell_lines::LineSet;use cotton_core::cotton_rules::voice::format::{self, Rules};use cotton_core::cotton_rules::voice::language;use cotton_core::cotton_rules::voice::session::{units_at, Answer, Heard, Pass, Refused, Session};use serde_json::{json, Map, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;/// The voice models catalogue.pub const CATALOGUE: &str = include_str!("../../../cotton-core/kits/shell/voice/models.json");/// The settings row's table and its one row.pub const SETTINGS_TABLE: &str = "voice_settings";pub const SETTINGS_ROW: &str = "voice";/// The most languages a person dictates in.pub const MOST_LANGUAGES: usize = 3;/// The most names handed to an engine.pub const MOST_VOCABULARY: usize = 100;/// How long the control stays "settling" for a second pass, at most.pub const SECOND_WAIT_MS: u64 = 1500;/// A session not heard from this long is dropped at the next plan.const SESSION_IDLE: Duration = Duration::from_secs(60 * 60);fn bad(message: impl Into<String>) -> MethodError {    MethodError::new("bad_request", message)}// ── Sessions ─────────────────────────────────────────────────────────────struct Held {    session: Session,    command: bool,    live_upper: bool,    second_upper: bool,    touched_at: Instant,}static SESSIONS: Mutex<BTreeMap<String, Held>> = Mutex::new(BTreeMap::new());fn with_session<T>(request: &Value, then: impl FnOnce(&mut Held) -> Result<T, MethodError>) -> Result<T, MethodError> {    let id = request        .get("session")        .and_then(Value::as_str)        .filter(|session| !session.is_empty())        .ok_or_else(|| bad("a voice call names its session"))?;    let mut sessions = SESSIONS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    let held = sessions.get_mut(id).ok_or_else(|| MethodError::new("not_found", format!("no voice session {id}: plan one first")))?;    held.touched_at = Instant::now();    then(held)}fn new_session_id() -> String {    use rand::Rng;    format!("v-{:016x}", rand::thread_rng().gen::<u64>())}// ── The catalogue and this phone's models ────────────────────────────────fn catalogue() -> &'static Value {    static PARSED: std::sync::OnceLock<Value> = std::sync::OnceLock::new();    PARSED.get_or_init(|| serde_json::from_str(CATALOGUE).unwrap_or(Value::Null))}fn model_entry(id: &str) -> Option<&'static Value> {    catalogue()["models"].get(id)}/// Where this phone keeps what it holds of the catalogue: a device's own/// state, never synced (a model is downloaded per phone).fn states_path(handle: &CottonHandle) -> std::path::PathBuf {    handle.data_dir().join("voice").join("models.json")}static STATES_LOCK: Mutex<()> = Mutex::new(());fn read_states(handle: &CottonHandle) -> Map<String, Value> {    std::fs::read(states_path(handle))        .ok()        .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())        .and_then(|value| value.as_object().cloned())        .unwrap_or_default()}fn model_row(id: &str, entry: &Value, state: Option<&Value>) -> Value {    let files: Vec<&Value> = entry["files"].as_array().map(|files| files.iter().collect()).unwrap_or_default();    let bytes = entry["bytes"].as_u64().or_else(|| files.iter().map(|file| file["bytes"].as_u64()).sum::<Option<u64>>());    let mut row = json!({        "id": id,        "family": entry["family"],        "kind": entry["kind"],        "engine": format!("sherpa:{id}"),        "languages": entry["languages"],        "role": entry["role"],        "bytes": bytes,        "licence": entry["licence"],        "files": entry["files"],        "fetchable": !files.is_empty() && files.iter().all(|file| file["url"].is_string() && file["sha256"].is_string()),        "state": state.and_then(|state| state["state"].as_str()).unwrap_or("absent"),    });    // How the engine is configured is the catalogue's to say (a NeMo    // transducer's `model_type`, a language's code), never the platform's to    // guess from a model's name.    for key in ["upper_case", "measured", "options", "stream_options", "language_codes", "longest_s"] {        if !entry[key].is_null() {            row[key] = entry[key].clone();        }    }    // A model that does not level its own input gets the microphone levelled first.    if entry["normalises_input"] == false {        row["level_input"] = catalogue()["levelling"].clone();    }    if let Some(state) = state {        for key in ["path", "bytes_done"] {            if !state[key].is_null() {                row[key] = state[key].clone();            }        }    }    row}fn ready(states: &Map<String, Value>, id: &str) -> bool {    states.get(id).is_some_and(|state| state["state"] == "ready")}pub fn models(handle: &CottonHandle) -> Result<Value, MethodError> {    let states = read_states(handle);    let mut rows = Vec::new();    let mut held_bytes = 0u64;    for (id, entry) in catalogue()["models"].as_object().into_iter().flatten() {        let row = model_row(id, entry, states.get(id));        if row["state"] == "ready" {            held_bytes += row["bytes"].as_u64().unwrap_or(0);        }        rows.push(row);    }    Ok(json!({        "models": rows,        "languages": catalogue()["languages"],        "vad": catalogue()["vad"],        "lid": catalogue()["lid"],        "held_bytes": held_bytes,        "status": catalogue()["status"],    }))}pub fn model(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let id = request.get("model").and_then(Value::as_str).ok_or_else(|| bad("voice.model names its model"))?;    let entry = model_entry(id).ok_or_else(|| MethodError::new("not_found", format!("the catalogue has no model {id}")))?;    let state = request.get("state").and_then(Value::as_str).ok_or_else(|| bad("voice.model says its state"))?;    if !matches!(state, "absent" | "downloading" | "ready" | "failed") {        return Err(bad("a model's state is absent, downloading, ready or failed"));    }    let path = request.get("path").and_then(Value::as_str);    if state == "ready" && path.is_none() {        return Err(bad("a ready model says where it is (path)"));    }    let _lock = STATES_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    let mut states = read_states(handle);    if state == "absent" {        states.remove(id);    } else {        let mut row = json!({ "state": state });        if let Some(path) = path {            row["path"] = json!(path);        }        if let Some(done) = request.get("bytes_done").and_then(Value::as_u64) {            row["bytes_done"] = json!(done);        }        states.insert(id.to_string(), row);    }    let file = states_path(handle);    let write = || -> std::io::Result<()> {        std::fs::create_dir_all(file.parent().expect("a folder"))?;        let temporary = file.with_extension("json.part");        // not a copy: voice notes.        std::fs::write(&temporary, serde_json::to_vec_pretty(&Value::Object(states.clone()))?)?;        // not a copy: voice notes.        std::fs::rename(&temporary, &file)    };    write().map_err(|error| MethodError::new("write_refused", format!("the voice models' state was not kept: {error}")))?;    Ok(model_row(id, entry, states.get(id)))}// ── Settings ─────────────────────────────────────────────────────────────/// The person's voice settings as they stand: the row's, or the defaults/// (their own language, two passes, ask before mobile data).#[derive(Debug, Clone, PartialEq)]pub struct Settings {    pub languages: Vec<(String, String)>,    pub passes: String,    pub mobile_data: String,}/// The script a language is written in by default (ISO 15924, lowercase).pub fn native_script(code: &str) -> &'static str {    match code {        "te" => "telu",        "hi" | "mr" | "ne" => "deva",        "ja" => "jpan",        "ta" => "taml",        "kn" => "knda",        "ml" => "mlym",        "bn" => "beng",        "gu" => "gujr",        "pa" => "guru",        "zh" => "hans",        "ko" => "kore",        "ar" | "ur" | "fa" => "arab",        "ru" | "uk" | "bg" | "sr" => "cyrl",        _ => "latn",    }}fn settings_of(row: Option<&Value>, own_language: &str) -> Settings {    let row = row.cloned().unwrap_or(Value::Null);    let languages: Vec<(String, String)> = row["languages"]        .as_str()        .and_then(|text| serde_json::from_str::<Value>(text).ok())        .or_else(|| row["languages"].as_array().map(|a| Value::Array(a.clone())))        .and_then(|value| value.as_array().cloned())        .unwrap_or_default()        .iter()        .filter_map(|entry| {            let code = entry["code"].as_str()?.to_string();            let script = entry["script"].as_str().map(str::to_string).unwrap_or_else(|| native_script(&code).to_string());            Some((code, script))        })        .take(MOST_LANGUAGES)        .collect();    let languages = if languages.is_empty() { vec![(own_language.to_string(), native_script(own_language).to_string())] } else { languages };    let pick = |key: &str, allowed: &[&str], default: &str| {        row[key].as_str().filter(|value| allowed.contains(value)).unwrap_or(default).to_string()    };    Settings {        languages,        passes: pick("passes", &["two", "live"], "two"),        mobile_data: pick("mobile_data", &["never", "ask", "always"], "ask"),    }}fn own_language(client: &ClientController) -> String {    super::voice_words::language(client).unwrap_or_else(|_| "en".to_string())}/// The settings row, read from the person's own database.fn read_settings(client: &ClientController) -> Settings {    let language = own_language(client);    let row = (|| {        let _personal = client.name_database(None).ok()?;        super::records::call(client, "records.get", &json!({ "table": SETTINGS_TABLE, "id": SETTINGS_ROW })).ok()    })();    let row = row.map(|answer| answer.get("data").cloned().or_else(|| answer.get("record").and_then(|r| r.get("data")).cloned()).unwrap_or(answer));    settings_of(row.as_ref(), &language)}fn settings_json(settings: &Settings, lines: &LineSet) -> Value {    json!({        "languages": settings.languages.iter().map(|(code, script)| json!({            "code": code,            "script": script,            "name": language::find(code).map(|l| l.name.clone()),            "native_script": native_script(code),        })).collect::<Vec<_>>(),        "passes": settings.passes,        "mobile_data": settings.mobile_data,        "known": language::all().iter().map(|l| json!({ "code": l.language, "name": l.name, "native_script": native_script(&l.language) })).collect::<Vec<_>>(),        "lines": settings_lines(lines),    })}pub fn settings(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let lines = voice_lines(&client);    let Some(set) = request.get("set").filter(|set| !set.is_null()) else {        return Ok(settings_json(&read_settings(&client), &lines));    };    let set = set.as_object().ok_or_else(|| bad("set holds the settings to change"))?;    let mut data = Map::new();    for (key, value) in set {        match key.as_str() {            "languages" => {                let list = value.as_array().ok_or_else(|| bad("languages is a list"))?;                if list.is_empty() || list.len() > MOST_LANGUAGES {                    return Err(bad("a person dictates in one to three languages"));                }                let mut seen = Vec::new();                let mut clean = Vec::new();                for entry in list {                    let code = entry["code"].as_str().or(entry.as_str()).ok_or_else(|| bad("a language names its code"))?;                    let base = code.split(['-', '_']).next().unwrap_or_default().to_ascii_lowercase();                    if base.is_empty() || seen.contains(&base) {                        return Err(bad("each language once"));                    }                    let script = entry["script"].as_str().unwrap_or(native_script(&base)).to_ascii_lowercase();                    if script != native_script(&base) && script != "latn" {                        return Err(bad(format!("{base} is written in its own script or in Latin letters")));                    }                    seen.push(base.clone());                    clean.push(json!({ "code": base, "script": script }));                }                data.insert("languages".into(), json!(Value::Array(clean).to_string()));            }            "passes" => {                let passes = value.as_str().filter(|v| matches!(*v, "two" | "live")).ok_or_else(|| bad("passes is two or live"))?;                data.insert("passes".into(), json!(passes));            }            "mobile_data" => {                let rule = value.as_str().filter(|v| matches!(*v, "never" | "ask" | "always")).ok_or_else(|| bad("mobile_data is never, ask or always"))?;                data.insert("mobile_data".into(), json!(rule));            }            other => return Err(bad(format!("voice has no setting {other}"))),        }    }    {        let _personal = client.name_database(None).map_err(|why| MethodError::new("unreadable", why))?;        data.insert("key".into(), json!(SETTINGS_ROW));        super::records::call(&client, "records.create", &json!({ "table": SETTINGS_TABLE, "data": data }))?;    }    Ok(settings_json(&read_settings(&client), &lines))}// ── Lines ────────────────────────────────────────────────────────────────fn voice_lines(client: &ClientController) -> LineSet {    let rows = super::records::line_rows_kept(client);    LineSet::of_rows("voice", &rows).or_else(|| LineSet::shipped("voice")).expect("the voice lines are in this build")}fn control_lines(lines: &LineSet, platform: &str) -> Value {    let say = |name: &str| lines.say(name, &[]).unwrap_or_default();    let mut out = json!({        "idle": say("control.idle"),        "listening": say("control.listening"),        "settling": say("control.settling"),        "stop": say("control.stop"),        "command_hint": say("control.command_hint"),        "not_heard": say("control.not_heard"),        "no_permission": say("control.no_permission"),        "open_settings": say("control.open_settings"),        "waiting_wifi": say("download.waiting_wifi"),        "failed": say("download.failed"),    });    if platform == "android" {        out["cotton_voice"] = json!(say("android.cotton_voice"));    }    out}fn settings_lines(lines: &LineSet) -> Value {    let say = |name: &str| lines.say(name, &[]).unwrap_or_default();    json!({        "title": say("settings.title"),        "languages": say("settings.languages"),        "add_language": say("settings.add_language"),        "most_languages": say("settings.most_languages"),        "script": say("settings.script"),        "script_latin": say("settings.script_latin"),        "passes": say("settings.passes"),        "two": say("settings.two"),        "live": say("settings.live"),        "mobile_data": say("settings.mobile_data"),        "never": say("settings.never"),        "ask": say("settings.ask"),        "always": say("settings.always"),    })}// ── Plan ─────────────────────────────────────────────────────────────────fn platform(request: &Value) -> &'static str {    match request.get("platform").and_then(Value::as_str) {        Some("ios") => "ios",        Some("android") => "android",        Some("mac") => "mac",        _ if cfg!(target_os = "ios") => "ios",        _ if cfg!(target_os = "android") => "android",        _ if cfg!(target_os = "macos") => "mac",        _ => "android",    }}/// The names handed to the engines: Story's characters and places first in/// a Story table, then the ranked kept vocabulary for the screen.fn vocabulary(client: &ClientController, request: &Value) -> Vec<String> {    let mut out: Vec<String> = Vec::new();    let mut push = |term: &str, out: &mut Vec<String>| {        let term = term.trim();        if !term.is_empty() && !out.iter().any(|known| known.eq_ignore_ascii_case(term)) && out.len() < MOST_VOCABULARY {            out.push(term.to_string());        }    };    let table = request.get("table").and_then(Value::as_str);    let record = request.get("record").and_then(Value::as_str);    if let Some(table) = table.filter(|table| table.starts_with("story_")) {        for name in story_names(client, table, record) {            push(&name, &mut out);        }    }    let mut screen = Map::new();    if let Some(database) = crate::shell::client::named_database() {        screen.insert("databaseId".into(), json!(database));    }    if let Some(table) = table {        screen.insert("table".into(), json!(table));    }    if let Some(record) = record {        screen.insert("recordId".into(), json!(record));    }    let mut args = Map::new();    if !screen.is_empty() {        args.insert("screen".into(), Value::Object(screen));    }    let context = super::voice_words::context_for(client, &args).or_else(|_| super::voice_words::context_for(client, &Map::new()));    if let Ok(context) = context {        for term in context["biasTerms"].as_array().into_iter().flatten().filter_map(Value::as_str) {            push(term, &mut out);        }    }    out}/// The story a Story record belongs to, and its characters (most lines/// first) then its places.fn story_names(client: &ClientController, table: &str, record: Option<&str>) -> Vec<String> {    let story = match (table, record) {        ("story_story", Some(id)) => Some(id.to_string()),        (_, Some(id)) => client            .read_tool("get_record_by_table", json!({ "table": table, "id": id }).as_object().unwrap())            .ok()            .and_then(|found| {                let data = found.get("data").unwrap_or(&found);                link_id(&data["story"])            }),        _ => None,    };    let mut names = Vec::new();    for (kind, rank) in [("story_character", "lines"), ("story_place", "scenes")] {        let mut filter = Map::new();        if let Some(story) = &story {            filter.insert("story".into(), json!(story));        }        let Ok(found) = client.read_tool("list_records", json!({ "table": kind, "where": filter, "limit": 200 }).as_object().unwrap()) else { continue };        let mut rows: Vec<(i64, String)> = found["records"]            .as_array()            .into_iter()            .flatten()            .filter_map(|record| {                let data = record.get("data").unwrap_or(record);                if !data["trashed_at"].is_null() || !data["archived_at"].is_null() {                    return None;                }                Some((data[rank].as_i64().unwrap_or(0), data["name"].as_str()?.to_string()))            })            .collect();        rows.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));        names.extend(rows.into_iter().map(|(_, name)| name));    }    names}fn link_id(value: &Value) -> Option<String> {    match value {        Value::String(id) => Some(id.clone()),        Value::Object(link) => link.get("id").and_then(Value::as_str).map(str::to_string),        Value::Array(links) => links.first().and_then(link_id),        _ => None,    }}fn size_words(bytes: u64) -> String {    if bytes >= 1_000_000_000 {        format!("{:.1} GB", bytes as f64 / 1e9)    } else {        format!("{} MB", (bytes as f64 / 1e6).ceil() as u64)    }}pub fn plan(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let mode = request.get("mode").and_then(Value::as_str).unwrap_or("dictate");    if !matches!(mode, "dictate" | "command") {        return Err(bad("mode is dictate or command"));    }    let client = handle.client();    let platform = platform(request);    let settings = read_settings(&client);    let lines = voice_lines(&client);    let codes: Vec<String> = settings.languages.iter().map(|(code, _)| code.clone()).collect();    let primary = codes.first().cloned().unwrap_or_else(|| "en".into());    let choice = &catalogue()["languages"][primary.as_str()];    let live_model = choice["live"].as_str().filter(|id| model_entry(id).is_some());    let second_model = choice["second"].as_str().filter(|id| model_entry(id).is_some());    let apple = platform != "android" && language::find(&primary).is_some_and(|l| l.apple_speech);    let live = match (apple, live_model) {        (true, _) => json!({ "engine": "apple.speech" }),        (false, Some(id)) => json!({ "engine": format!("sherpa:{id}"), "model": id }),        (false, None) if platform == "ios" => json!({ "engine": "apple.speech" }),        (false, None) => json!({ "engine": "android.speech" }),    };    let second = match (settings.passes.as_str(), second_model) {        ("two", Some(id)) if mode == "dictate" => json!({ "engine": format!("sherpa:{id}"), "model": id }),        _ => Value::Null,    };    // What this phone lacks of the chosen models, one entry per file, only    // files the catalogue can be trusted for (a url and a sha256).    let states = read_states(handle);    let name = language::find(&primary).map(|l| l.name.clone()).unwrap_or_else(|| primary.clone());    let mut wanted: Vec<(&str, &str)> = Vec::new();    if let Some(id) = live["model"].as_str() {        wanted.push((id, "download.live"));        let streaming = model_entry(id).and_then(|e| e["kind"].as_str()).is_some_and(|kind| kind.starts_with("online-"));        if !streaming {            if let Some(vad) = catalogue()["vad"].as_str() {                wanted.push((vad, "download.vad"));            }        }    }    if let Some(id) = second["model"].as_str() {        if !wanted.iter().any(|(known, _)| *known == id) {            wanted.push((id, "download.second"));        }    }    let mut downloads = Vec::new();    let mut missing_bytes = 0u64;    for (id, why_line) in wanted {        if ready(&states, id) {            continue;        }        let Some(entry) = model_entry(id) else { continue };        let why = lines.say(why_line, &[("language", &name)]).unwrap_or_default();        for file in entry["files"].as_array().into_iter().flatten() {            let (Some(url), Some(sha256)) = (file["url"].as_str(), file["sha256"].as_str()) else { continue };            missing_bytes += file["bytes"].as_u64().unwrap_or(0);            downloads.push(json!({ "model": id, "file": file["name"], "bytes": file["bytes"], "url": url, "sha256": sha256, "why": why }));        }    }    let mut control = control_lines(&lines, platform);    if missing_bytes > 0 {        control["download"] = json!(lines.say("download.prompt", &[("language", &name), ("size", &size_words(missing_bytes))]).unwrap_or_default());    }    let vocabulary = if mode == "command" { Vec::new() } else { vocabulary(&client, request) };    let code_refs: Vec<&str> = codes.iter().map(String::as_str).collect();    let rules = Rules::of(&code_refs, vocabulary.clone());    let upper = |engine: &Value| engine["model"].as_str().and_then(model_entry).is_some_and(|entry| entry["upper_case"] == true);    let id = new_session_id();    {        let mut sessions = SESSIONS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        sessions.retain(|_, held| held.touched_at.elapsed() < SESSION_IDLE);        sessions.insert(id.clone(), Held {            session: Session::new(rules, mode == "command", !second.is_null()),            command: mode == "command",            live_upper: upper(&live),            second_upper: upper(&second),            touched_at: Instant::now(),        });    }    Ok(json!({        "session": id,        "mode": mode,        "languages": codes,        "scripts": settings.languages.iter().map(|(code, script)| (code.clone(), json!(script))).collect::<Map<_, _>>(),        "live": live,        "second": second,        "vocabulary": vocabulary,        "downloads": downloads,        "mobile_data": settings.mobile_data,        "lines": control,    }))}// ── Heard, touched, end ──────────────────────────────────────────────────fn span_of(request: &Value) -> Option<(u64, u64)> {    let from = request.get("from_ms").and_then(Value::as_u64);    let to = request.get("to_ms").and_then(Value::as_u64);    if let (Some(from), Some(to)) = (from, to) {        return Some((from, to.max(from)));    }    let words = request.get("words")?.as_array()?;    let start = words.iter().filter_map(|w| w["start_ms"].as_u64()).min()?;    let end = words.iter().filter_map(|w| w["end_ms"].as_u64()).max()?;    Some((start, end.max(start)))}fn answer_json(answer: &Answer) -> Value {    let mut out = json!({        "settled": answer.settled,        "tentative": answer.tentative,        "edits": answer.edits.iter().map(|edit| json!({ "from": edit.from, "to": edit.to, "text": edit.text })).collect::<Vec<_>>(),    });    if !answer.later.is_empty() {        out["later"] = json!(answer.later);    }    if answer.awaiting_second > 0 {        out["wait_ms"] = json!(SECOND_WAIT_MS);    }    out}pub fn heard(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let pass = match request.get("pass").and_then(Value::as_str) {        Some("live") => Pass::Live,        Some("second") => Pass::Second,        _ => return Err(bad("pass is live or second")),    };    let is_final = request.get("final").and_then(Value::as_bool).unwrap_or(pass == Pass::Second);    let text = request.get("text").and_then(Value::as_str).unwrap_or_default();    let span = span_of(request);    let (answer, query) = with_session(request, |held| {        let upper_case = if pass == Pass::Live { held.live_upper } else { held.second_upper };        let answer = held.session.heard(&Heard { pass, is_final, text, span, upper_case });        let query = (held.command && is_final).then(|| format::command_query(&held.session.text(), held.session.rules()));        Ok((answer, query))    })?;    let mut out = answer_json(&answer);    if let Some(query) = query.filter(|query| !query.is_empty()) {        out["command"] = command(handle, &query);    }    Ok(out)}pub fn touched(_handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let from = request.get("from").and_then(Value::as_u64).ok_or_else(|| bad("touched says from"))? as usize;    let to = request.get("to").and_then(Value::as_u64).ok_or_else(|| bad("touched says to"))? as usize;    let text = request.get("text").and_then(Value::as_str);    let answer = with_session(request, |held| {        held.session.touched_range(from, to, text).map_err(|Refused::Range| bad("the range is not in the session's text"))    })?;    Ok(answer_json(&answer))}pub fn end(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let (answer, text, command_query) = with_session(request, |held| {        let answer = held.session.end();        let text = held.session.text();        let query = held.command.then(|| format::command_query(&text, held.session.rules()));        Ok((answer, text, query))    })?;    if let Some(id) = request.get("session").and_then(Value::as_str) {        SESSIONS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(id);    }    let words = text.split_whitespace().count();    let mut out = json!({        "text": text,        "edits": answer_json(&answer)["edits"],        "words": words,        "length": units_at(&text, text.len()),    });    if let Some(query) = command_query.filter(|query| !query.is_empty()) {        out["command"] = command(handle, &query);    }    Ok(out)}// ── Command mode ─────────────────────────────────────────────────────────/// The words through the universal search: the record they name, or Find.fn command(handle: &CottonHandle, query: &str) -> Value {    let found = crate::methods::dispatch(handle, "read.find", &json!({ "query": query, "limit": 5 })).unwrap_or(Value::Null);    let lines = voice_lines(&handle.client());    let hits: Vec<&Value> = found["hits"].as_array().map(|hits| hits.iter().collect()).unwrap_or_default();    let title_of = |hit: &Value| hit["words"]["title"].as_str().or(hit["title"].as_str()).unwrap_or_default().to_string();    let folded = |text: &str| text.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ");    let wanted = folded(query);    let exact = hits.iter().find(|hit| folded(&title_of(hit)) == wanted);    let every_word = || {        let words: Vec<&str> = wanted.split(' ').collect();        let matching: Vec<&&Value> = hits.iter().filter(|hit| {            let title = folded(&title_of(hit));            words.iter().all(|word| title.contains(word))        }).collect();        (matching.len() == 1).then(|| *matching[0])    };    let chosen = exact.copied().or_else(every_word).or_else(|| (hits.len() == 1).then(|| hits[0]));    match chosen {        Some(hit) => {            let title = title_of(hit);            let opens = &hit["words"]["opens"];            let mut command = json!({                "kind": "open",                "query": query,                "table": opens["table"].as_str().or(hit["kind"].as_str()),                "id": opens["id"].as_str().or(hit["id"].as_str()),                "title": title,                "says": lines.say("command.opening", &[("title", &title)]).unwrap_or_default(),            });            if let Some(path) = opens["path"].as_str() {                command["path"] = json!(path);            }            if let Some(database) = hit["database"].as_str().or(hit["databaseId"].as_str()) {                command["database"] = json!(database);            }            command        }        None => json!({            "kind": "search",            "query": query,            "says": lines.say("command.finding", &[("query", query)]).unwrap_or_default(),        }),    }}#[cfg(test)]#[path = "voice_tests.rs"]mod tests;