eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! Naming a session: a name derived from the opening message, and the one bounded model call that
//! may replace it.
//!
//! Two stages, and the order matters. The first is deterministic and cannot fail — the first line
//! of what the user typed, whitespace collapsed, capped — so a list of sessions is never a column
//! of `null`s waiting for a provider to answer. The second is a small-model call that only ever
//! replaces the first, and only if its answer survives [`clean_reply`]: a reply that reads like an
//! explanation rather than a name is thrown away whole, because a name is not a summary and a
//! truncated summary is worse than the first line the user wrote.
//!
//! Nothing here touches the store or a provider. Both stages are pure functions of text so that
//! the interesting part — what counts as a usable name — is testable without a model.

use crate::message::Message;

/// Longest derived name, in characters. The sidebar is narrow and the terminal's column is
/// narrower; past this a name is a paragraph with the ending cut off.
pub const MAX_NAME_CHARS: usize = 60;

/// How much of the opening message the small call reads. Enough for the ask and the reason for it,
/// which is what a name is made of; the rest of a long paste is the same request in more words.
pub const UPGRADE_INPUT_CHARS: usize = 1_000;

/// The name to show before any model has been asked: the first line of the opening message, with
/// runs of whitespace collapsed and the cap applied at a word boundary where there is one.
///
/// `None` when the message has nothing to name — an empty prompt, or one that is only whitespace
/// and punctuation. The caller keeps the preview then rather than inventing a placeholder.
pub fn derive(opening: &str) -> Option<String> {
    let line = opening
        .lines()
        .map(str::trim)
        .find(|l| !l.is_empty())?
        // Leading markdown noise is not part of anyone's name.
        .trim_start_matches(['#', '>', '-', '*', '`', ' ']);
    let one_line = line.split_whitespace().collect::<Vec<_>>().join(" ");
    let one_line = one_line.trim();
    if one_line.is_empty() {
        return None;
    }
    // A trailing full stop is punctuation on a sentence, not part of a name; a message that is
    // nothing but punctuation has no name in it at all.
    let trimmed = one_line.trim_end_matches(['.', ',', ';', ':', '-', '?', '!']);
    if trimmed.is_empty() {
        return None;
    }
    Some(cap(trimmed))
}

/// Cut to [`MAX_NAME_CHARS`], preferring the last space at or after the halfway point so a name
/// does not end mid-word when it does not have to. Never splits a character.
fn cap(text: &str) -> String {
    if text.chars().count() <= MAX_NAME_CHARS {
        return text.to_string();
    }
    let mut cut = text
        .char_indices()
        .nth(MAX_NAME_CHARS)
        .map(|(i, _)| i)
        .unwrap_or(text.len());
    let head = &text[..cut];
    let halfway = text.chars().count() / 2;
    if let Some(space) = head.rfind(' ') {
        if head[..space].chars().count() >= halfway {
            cut = space;
        }
    }
    text[..cut].trim_end().to_string()
}

/// The prompt the small call is given. It asks for one JSON object and nothing else, and says so
/// twice, because the shape is what [`clean_reply`] enforces and a model that ignores the second
/// half of a long instruction is the normal case.
pub fn upgrade_prompt(opening: &str) -> Vec<Message> {
    const SYSTEM: &str = "\
You name conversations. Given the opening message of one, answer with a JSON object of exactly \
one key: {\"title\": \"...\"}. The title is 3 to 7 words, lowercase unless a name needs capitals, \
and says what the work is about — not that it is a conversation, not a summary of the whole \
thing, no trailing full stop, no quotes inside. Answer with the JSON object and nothing else.";

    let excerpt: String = opening.chars().take(UPGRADE_INPUT_CHARS).collect();
    vec![
        Message::system(SYSTEM),
        Message::user(format!("OPENING MESSAGE:\n{excerpt}")),
    ]
}

/// What survives of the small call's answer, or why nothing does.
///
/// The answer is parsed as JSON rather than scanned for a name: a backend that ignored the shape
/// and wrote a sentence gets its sentence thrown away, and the derived name stays. Every rule here
/// is about the difference between a name and an explanation — a name is one short line that does
/// not end in a full stop.
pub fn clean_reply(reply: &str, opening: &str) -> std::result::Result<String, String> {
    let text = reply.trim();
    if text.is_empty() {
        return Err("the reply was empty".into());
    }
    let value: serde_json::Value = serde_json::from_str(text)
        .map_err(|_| format!("the reply was not a JSON object: {}", head(text)))?;
    let raw = match &value {
        // The asked-for shape, and the shape a stricter backend may wrap the string in.
        serde_json::Value::Object(map) => map
            .get("title")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "the reply had no `title` string".to_string())?,
        serde_json::Value::String(s) => s.as_str(),
        other => return Err(format!("the reply was a {}, not an object", kind(other))),
    };
    // Before tidying: the collapse below would turn a two-line answer into one line, and a name
    // that arrived as a paragraph is an explanation with the newline removed.
    if raw.chars().any(char::is_control) {
        return Err("the reply's title had control characters".into());
    }
    let name = tidy(raw);
    if name.is_empty() {
        return Err("the reply's title was empty".into());
    }
    let chars = name.chars().count();
    if chars > MAX_NAME_CHARS {
        return Err(format!("the reply's title was {chars} characters"));
    }
    let words = name.split_whitespace().count();
    if words > 8 {
        return Err(format!(
            "the reply's title was {words} words, which is a summary"
        ));
    }
    if name.ends_with('.') || name.ends_with(',') || name.ends_with(';') {
        return Err("the reply's title ended like a sentence".into());
    }
    // The opening message handed back with the edges trimmed is not a name: it is the derived one
    // in more characters, and spending a call to get it is the failure this check exists for.
    if let Some(derived) = derive(opening) {
        let same = name.to_lowercase();
        let derived_lower = derived.to_lowercase();
        if same == derived_lower || (words <= 2 && derived_lower.starts_with(&same)) {
            return Err("the reply's title was the opening message again".into());
        }
    }
    Ok(name)
}

/// Strip what a model wraps a name in when it is being helpful: quotes, backticks, bold asterisks,
/// and a `Title:` label.
fn tidy(raw: &str) -> String {
    let mut text = raw.trim();
    for prefix in ["title:", "name:", "session:", "title -", "title \u{2013}"] {
        // Compared in bytes because every prefix here is ASCII, and skipping `prefix.len()` bytes
        // only lands on a character boundary if the text's head is ASCII too — which the
        // comparison just proved it is.
        if text.len() > prefix.len()
            && text.is_char_boundary(prefix.len())
            && text[..prefix.len()].eq_ignore_ascii_case(prefix)
        {
            text = &text[prefix.len()..];
            break;
        }
    }
    let text = text
        .trim()
        .trim_matches([
            '"', '\'', '`', '*', '\u{201c}', '\u{201d}', '\u{2018}', '\u{2019}',
        ])
        .trim();
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn head(text: &str) -> String {
    let short: String = text.chars().take(40).collect();
    if text.chars().count() > 40 {
        format!("{short}…")
    } else {
        short
    }
}

fn kind(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "boolean",
        serde_json::Value::Number(_) => "number",
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The first line, not the first paragraph: a prompt opens with its ask, and the rest of the
    /// paste is why. Whitespace is collapsed because a name is displayed on one line.
    #[test]
    fn the_first_line_is_the_name() {
        assert_eq!(
            derive("fix the gateway   restart loop\nit happens on boot").as_deref(),
            Some("fix the gateway restart loop")
        );
        assert_eq!(
            derive("\n\n  ## rename sessions  \n").as_deref(),
            Some("rename sessions")
        );
        assert_eq!(derive("   "), None, "nothing to name");
        assert_eq!(derive("..."), None, "punctuation only is not a name");
    }

    /// A sentence's full stop is not part of a name, and a long opening is cut at a word so the
    /// last thing on the row is a word rather than half of one.
    #[test]
    fn a_name_loses_the_full_stop_and_cuts_at_a_word() {
        assert_eq!(
            derive("add a title column to the store.").as_deref(),
            Some("add a title column to the store")
        );
        let long = "word ".repeat(40);
        let name = derive(&long).unwrap();
        assert!(name.chars().count() <= MAX_NAME_CHARS, "{name}");
        assert!(!name.ends_with(' '), "{name:?}");
        assert!(name.ends_with("word"), "cut at a word boundary: {name:?}");
        // A single word longer than the cap has no space to cut at, and must not be split inside
        // a character.
        let huge = "é".repeat(200);
        assert_eq!(derive(&huge).unwrap().chars().count(), MAX_NAME_CHARS);
    }

    /// The reply is JSON, and what comes out of it is one short line. A model that answered with a
    /// sentence, a summary or an essay gets nothing: stage 1 has a name already, and a truncated
    /// explanation is worse than the user's own first line.
    #[test]
    fn only_a_short_object_becomes_a_name() {
        let opening = "the dashboard's session list is unreadable at a hundred sessions";
        let ok = |r: &str| clean_reply(r, opening);
        assert_eq!(
            ok("{\"title\": \"session names from the model\"}").as_deref(),
            Ok("session names from the model")
        );
        assert_eq!(
            ok("{\"title\": \"Title: session names\"}").as_deref(),
            Ok("session names"),
            "a label is noise, not a name"
        );
        assert_eq!(
            ok("  \"quoted name\"  ").as_deref(),
            Ok("quoted name"),
            "a bare string still works"
        );
        assert!(
            ok("Sure! Here is a title: session names").is_err(),
            "prose is not JSON"
        );
        assert!(
            ok("{\"name\": \"session names\"}").is_err(),
            "the wrong key"
        );
        assert!(ok("{\"title\": \"\"}").is_err(), "an empty name");
        assert!(ok("{\"title\": 42}").is_err(), "a number is not a name");
        assert!(
            ok("{\"title\": \"rename the sessions and add a title column to the store and then\"}")
                .is_err(),
            "eleven words is a summary"
        );
        assert!(
            ok("{\"title\": \"a name that ends like a sentence.\"}").is_err(),
            "a full stop"
        );
        assert!(
            ok("{\"title\": \"two\\nlines\"}").is_err(),
            "control characters"
        );
    }

    /// Handing the opening message back is not an upgrade: it is the derived name with different
    /// edges, and it must not count as the model having named anything.
    #[test]
    fn an_echo_of_the_opening_is_not_an_upgrade() {
        let opening = "fix the gateway restart loop";
        assert!(clean_reply("{\"title\": \"fix the gateway restart loop\"}", opening).is_err());
        assert_eq!(
            clean_reply("{\"title\": \"gateway restart loop\"}", opening).as_deref(),
            Ok("gateway restart loop"),
            "fewer words is a name, and not an echo"
        );
    }

    /// The prompt carries the opening message, capped, and asks for the one object the parser
    /// expects.
    #[test]
    fn the_prompt_asks_for_one_object_and_sends_a_bounded_excerpt() {
        let long = "x".repeat(5_000);
        let asked = upgrade_prompt(&long);
        assert_eq!(asked.len(), 2);
        assert!(asked[0].content.as_deref().unwrap().contains("{\"title\""));
        let sent = asked[1].content.as_deref().unwrap();
        assert_eq!(
            sent.chars().count(),
            "OPENING MESSAGE:\n".chars().count() + UPGRADE_INPUT_CHARS
        );
    }
}