diff --git a/PROTOCOL.md b/PROTOCOL.md index 4846d5fa..3279c229 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -133,7 +133,8 @@ Quick Ask's `quick_shot` fails with `helper_failed` (the message is the helper's | `set_bot` | `bot`, `name?`, `instructions?` (at most 8000 characters), `stepLimit?` (a whole number, 1 to 1000), `avatar?` (at most 8 characters: the name of one of the window's icons, or an emoji or letters), `color?` (`#rrggbb` or empty) | `{}`; what is given changes; `bots_changed` follows. A `stepLimit` is sent to a running engine as `step_limit`. `webSearch?` (true or false) is kept and sent as `web_search`. `check?` is `off`, `own`, `model` (with `checkModel`, a model's name, validated as `set_model` does) or `bot` (with `checkBot`, the id of another bot of the same project, not an installed agent's, not the bot itself) and is kept: see Check before done; anything else, a model or bot that cannot be used, is `bad_request`; it is refused `no_check` for a bot on an installed agent (other than `off`), and from a device on the network `forbidden`, as is `checkModel` or `checkBot` alone. | | `order_bots` | `bots`: every bot's id once, in the new order | `{}`; `list_bots` lists them so from then on | | `delete_bot` | `bot` | `{}`: its engine and browser stop, it leaves its project, everything stored for it is forgotten, and its folder and browser profile move to the Trash, as Finder moves them (Put Back works). When its folder cannot be moved, nothing is deleted: `trash_failed` | -| `search` | `text` (1 to 200 bytes), `bot?`, `conversation?` (with `bot`), `limit?` (default 50, at most 200) | `{hits: [{bot, conversation, seq, atMs, kind, snippet}]}`: prompts (`kind` `user`) and replies (`reply`) holding `text` in any case, of one conversation, of `bot` or of all bots, newest first; `atMs` is when the entry was written. A reply is searched whole, as the chat joins its pieces; `seq` is its first piece's, the chat item's `id`. | +| `search` | `text` (1 to 200 bytes), `bot?`, `conversation?` (with `bot`), `limit?` (default 50, at most 200) | `{hits: [{bot, conversation, seq, atMs, kind, snippet}]}`: prompts (`kind` `user`) and replies (`reply`) holding `text` in any case, of one conversation, of `bot` or of all bots, newest first; `atMs` is when the entry was written. A reply is searched whole, as the chat joins its pieces; `seq` is its first piece's, the chat item's `id`. Backed by a SQLite FTS5 index kept in sync with the transcript. | +| `search_memory` | `text` (1 to 200 bytes), `bot?` or `projectId?`, `limit?` (default 50, at most 200) | `{hits: [{bot?, project?, name, modifiedMs, snippet}]}`: bot and project memory notes holding `text` in any case (in the note's text or file name), newest modified first. Backed by a SQLite FTS5 index synced with `memory/`. | | `open_bot` | `bot`, `conversation?`, `limit?`, `before?` | `{bot: Bot, conversation, history:[{seq, at, entry}], more, questions:[question event], queue:[{nonce, text}]}`: of the conversation named, else of the bot's current one (see Conversations), whose id comes back; the last `limit` entries (all without it) with `seq` below `before`, oldest first, each as the `transcript` event gives it (`at` is when it was written, in milliseconds); `more` is `true` when there are older ones; `queue` is the prompts waiting in that conversation (see Queue and steer) | | `prompt` | `bot`, `conversation?`, `nonce`, `text` | `{}` once the engine admitted it; `{queued:true}` when the bot is busy or has prompts waiting (see Queue and steer); `{duplicate:true}` or `{duplicate:true, uncertain:true}` for a known nonce (see Prompt ledger), `{duplicate:true, queued:true}` for one still waiting. `queue_full` when 20 prompts already wait. Without `conversation` it goes into the bot's current one. | | `answer` | `bot`, `conversation?`, `question`, `choice` | `{}` once the engine took it; `no_such_question` if that question is not open. `Always` and `Conversation` on a question about an action: see Permissions. Without `conversation`: the one the engine has open. The card of a hand-off's acceptance command (see Bots together) is answered by the service itself, with `Approve` or `Deny` only. | @@ -187,6 +188,7 @@ Quick Ask's `quick_shot` fails with `helper_failed` (the message is the helper's | `read_roles` | `paths?`, `shipped?` | `{roles:[{path, name, instructions, model, effort, skills, levels, raises, shipped?}]}`: what each role file (whole paths) and each role that ships with the app (`shipped`: names, now `lead`; its role has `shipped` and no `path`) would create, 1 to 20 in all; `raises` names the kinds whose level allows more than a new bot's. `invalid_role` with the file and the reason. Refused (`forbidden`) for a device on the network | | `add_roles` | `projectId`, `paths?`, `shipped?`, `raise` | `{bots:[id]}`: a bot for each role, in the project (the `lead` role makes its bot the project's `lead` when the project has none of its own, and leaves one that is set); levels in `raises` are applied only with `raise: true`. All or none: `invalid_role` or `no_such_project` and no bot is created. Refused (`forbidden`) for a device on the network | | `list_skills` | `bot` | `{skills:[{name, description, author?, enabled}]}`, by name; `enabled` is false while the skill is switched off (see Skills) | +| `discover_skills` | none | `{skills:[{name, description, author?, path, from}]}`: valid `SKILL.md` folders found in standard local skill directories on this Mac, deduplicated by real path and sorted by name; `path` can be passed to `preview_skill` and `install_skill`. Refused (`forbidden`) for a device on the network | | `set_skill_enabled` | `bot`, `name`, `enabled` | `{}`: switches the installed skill `name` on or off for this bot (`no_such_skill`; `bad_request` when `enabled` is not true or false). `skills_changed` follows, and a running engine is sent `skills_off` | | `install_skill` | `bot`, `path` or `fromBot` and `name` | `{skill}`; copies the skill folder at `path`, or the skill `name` of the bot `fromBot` (`no_such_bot`), or `invalid_skill`. Refused (`forbidden`) for a device on the network (it names a path on this Mac) | | `preview_skill` | `path` or `fromBot` and `name` | `{skill, entries, bytes}` of the folder at `path`: what `install_skill` would copy in (files and folders, bytes), checked as it checks, to show before it is installed. Nothing is kept. `invalid_skill`. Refused (`forbidden`) for a device on the network | diff --git a/appd/src/core.rs b/appd/src/core.rs index 4c7d48c4..6ce4fc11 100644 --- a/appd/src/core.rs +++ b/appd/src/core.rs @@ -2315,6 +2315,12 @@ impl Core { .collect(); Ok(Some(json!({"skills": listed}))) } + "discover_skills" => { + self.reply_later(client, id, "discover_skills", || { + Ok(json!({"skills": skills::discover()})) + }); + Ok(None) + } "set_skill_enabled" => { let bot = self.bot_of(f)?; let name = str_field(f, "name")?; @@ -2391,6 +2397,7 @@ impl Core { } self.keep_note(owner, &place, name)?; memory::write(&place, name, text.as_bytes()).map_err(failed)?; + let _ = self.store.upsert_memory(owner, name, text, now_ms()); self.broadcast(&changed); Ok(Some(json!({}))) } @@ -2399,6 +2406,7 @@ impl Core { if !memory::delete(&place, name).map_err(failed)? { return Err(missing()); } + let _ = self.store.delete_memory_entry(owner, name); self.broadcast(&changed); Ok(Some(json!({}))) } @@ -2423,6 +2431,8 @@ impl Core { .ok_or(("no_such_change", "that version is not kept".to_owned()))?; self.keep_note(owner, &place, name)?; memory::write(&place, name, &bytes).map_err(|e| ("internal", e.to_string()))?; + let restored = String::from_utf8_lossy(&bytes); + let _ = self.store.upsert_memory(owner, name, &restored, now_ms()); self.broadcast(&changed); Ok(Some(json!({}))) } @@ -3154,6 +3164,73 @@ impl Core { .map_err(internal)?; Ok(Some(json!({"hits": hits}))) } + "search_memory" => { + let text = str_field(f, "text")?.trim(); + if text.is_empty() || text.len() > 200 { + return Err(bad("`text` must be 1 to 200 bytes")); + } + let bot = match f.get("bot") { + Some(Value::Null) | None => None, + Some(_) => Some(self.bot_of(f)?), + }; + let project = match f.get("projectId") { + Some(Value::Null) | None => None, + Some(_) => { + let id = str_field(f, "projectId")?; + let proj = self + .store + .projects() + .map_err(internal)? + .into_iter() + .find(|p| p.id.as_deref() == Some(id)) + .ok_or(("no_such_project", format!("no project `{id}`")))?; + Some(proj) + } + }; + if bot.is_some() && project.is_some() { + return Err(bad("give either `bot` or `projectId`, not both")); + } + let limit = f + .get("limit") + .and_then(Value::as_u64) + .unwrap_or(50) + .min(200); + if let Some(ref bot_id) = bot { + self.sync_memory_place(store::Owner::Bot(bot_id), &memory::Place::bot(bot_id)); + } else if let Some(ref proj) = project { + if let Some(id) = proj.id.as_deref() { + self.sync_memory_place( + store::Owner::Project(id), + &memory::Place::project(&proj.folder), + ); + } + } else { + if let Ok(bots) = self.store.bots() { + for b in bots { + self.sync_memory_place( + store::Owner::Bot(&b.id), + &memory::Place::bot(&b.id), + ); + } + } + if let Ok(projects) = self.store.projects() { + for p in projects { + if let Some(id) = p.id.as_deref() { + self.sync_memory_place( + store::Owner::Project(id), + &memory::Place::project(&p.folder), + ); + } + } + } + } + let project_id = project.as_ref().and_then(|p| p.id.as_deref()); + let hits = self + .store + .search_memory(bot.as_deref(), project_id, text, limit as usize) + .map_err(internal)?; + Ok(Some(json!({"hits": hits}))) + } "lan_status" => Ok(Some(self.lan.status())), "set_lan" => { let on = f @@ -4700,6 +4777,35 @@ impl Core { self.store.keep(owner, ©).map_err(internal) } + /// Syncs `memory_index` with the plain `.md` files in `place`, reading only notes whose + /// `modified_ms` changed and removing entries whose files were deleted. + fn sync_memory_place(&self, owner: Owner, place: &memory::Place) { + let Ok(disk) = memory::list(place) else { + return; + }; + let Ok(indexed) = self.store.indexed_memory(owner) else { + return; + }; + let indexed: HashMap = indexed.into_iter().collect(); + let mut present = HashSet::with_capacity(disk.len()); + for note in disk { + present.insert(note.name.clone()); + if indexed.get(¬e.name).copied() == Some(note.modified_ms) { + continue; + } + if let Ok(Some(text)) = memory::read(place, ¬e.name) { + let _ = self + .store + .upsert_memory(owner, ¬e.name, &text, note.modified_ms); + } + } + for name in indexed.keys() { + if !present.contains(name) { + let _ = self.store.delete_memory_entry(owner, name); + } + } + } + /// Whether a path in the bot's own folder must be full because relative paths start in a /// project. A store failure is logged; the action can still return its old relative path. fn full_attachment_paths(&self, bot: &str) -> bool { diff --git a/appd/src/lan.rs b/appd/src/lan.rs index 8330759e..23629c84 100644 --- a/appd/src/lan.rs +++ b/appd/src/lan.rs @@ -558,6 +558,7 @@ const ALLOWED_OVER_LAN: &[&str] = &[ "order_bots", "delete_bot", "search", + "search_memory", "get_update", "check_update", "list_models", @@ -1040,6 +1041,7 @@ mod tests { "add_roles", "preview_skill", "install_skill", + "discover_skills", "preview_bot_file", "import_bot", "preview_workplace", diff --git a/appd/src/skills.rs b/appd/src/skills.rs index 633750c5..14f7544f 100644 --- a/appd/src/skills.rs +++ b/appd/src/skills.rs @@ -8,6 +8,8 @@ use crate::sys::Dir; use crate::sys::log; use crate::{paths, sys}; use proto::skills::{self, DIR, FILE, Skill}; +use serde::Serialize; +use std::collections::HashSet; use std::fs; use std::io::{self, Read}; use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; @@ -30,6 +32,87 @@ const SKILL: Limits = Limits { }; /// Most bytes read of a `SKILL.md`. const MAX_FILE: u64 = 64 * 1024; +/// Most local skills returned by `discover`. +const MAX_DISCOVERED: usize = 200; + +/// One skill folder found on this Mac outside Bate's own bots. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Discovered { + pub name: String, + pub description: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub author: Option, + pub path: String, + /// Human-readable parent folder where the skill was found (e.g. `~/.agents/skills`). + pub from: String, +} + +/// Standard local folders where `SKILL.md` skills live on a Mac. +const DISCOVER_SUBDIRS: &[&str] = &[ + ".agents/skills", + ".claude/skills", + ".codex/skills", + ".cursor/skills", + ".gemini/skills", +]; + +fn discover_roots() -> Vec<(PathBuf, String)> { + if let Ok(custom) = std::env::var("BATE_DISCOVER_SKILLS_DIRS") { + return custom + .split(':') + .filter(|s| !s.is_empty()) + .map(|p| (PathBuf::from(p), p.to_owned())) + .collect(); + } + let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) else { + return Vec::new(); + }; + let home = PathBuf::from(home); + DISCOVER_SUBDIRS + .iter() + .map(|sub| (home.join(sub), format!("~/{sub}"))) + .collect() +} + +/// Scans standard local skill folders on this Mac for valid `SKILL.md` folders that can be +/// previewed and installed into a bot. Read-only, bounded, and deduplicated by real path. +pub fn discover() -> Vec { + discover_in(&discover_roots()) +} + +fn discover_in(roots: &[(PathBuf, String)]) -> Vec { + let mut found = Vec::new(); + let mut seen = HashSet::new(); + for (root, label) in roots { + let Ok(entries) = fs::read_dir(root) else { + continue; + }; + for entry in entries.flatten() { + if found.len() >= MAX_DISCOVERED { + break; + } + let Ok(real) = fs::canonicalize(entry.path()) else { + continue; + }; + if !seen.insert(real.clone()) { + continue; + } + let Ok((_, skill)) = open(&real) else { + continue; + }; + found.push(Discovered { + name: skill.name, + description: skill.description, + author: skill.author, + path: real.to_string_lossy().into_owned(), + from: label.clone(), + }); + } + } + found.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.from.cmp(&b.from))); + found +} fn parse(file: fs::File) -> Result { let mut text = String::new(); @@ -293,4 +376,34 @@ mod tests { assert_eq!(fs::read_to_string(out.join("SKILL.md")).unwrap(), "old"); fs::remove_dir_all(&root).unwrap(); } + + #[test] + fn discover_finds_valid_skills_and_deduplicates_symlinks() { + let root = std::env::temp_dir().join(format!("appd-{}-skill-discover", std::process::id())); + let _ = fs::remove_dir_all(&root); + let dir_a = root.join("a/skills"); + let dir_b = root.join("b/skills"); + fs::create_dir_all(dir_a.join("alpha")).unwrap(); + fs::create_dir_all(dir_a.join("broken")).unwrap(); + fs::create_dir_all(&dir_b).unwrap(); + fs::write( + dir_a.join("alpha/SKILL.md"), + "---\nname: alpha\ndescription: Does alpha things\nauthor: Ada\n---\nBody\n", + ) + .unwrap(); + fs::write(dir_a.join("broken/SKILL.md"), "not front matter").unwrap(); + // A symlink in the second root pointing to the same real folder is deduplicated. + std::os::unix::fs::symlink(dir_a.join("alpha"), dir_b.join("alpha")).unwrap(); + + let found = discover_in(&[ + (dir_a.clone(), "~/.a/skills".into()), + (dir_b.clone(), "~/.b/skills".into()), + ]); + assert_eq!(found.len(), 1); + assert_eq!(found[0].name, "alpha"); + assert_eq!(found[0].description, "Does alpha things"); + assert_eq!(found[0].author.as_deref(), Some("Ada")); + assert_eq!(found[0].from, "~/.a/skills"); + fs::remove_dir_all(&root).unwrap(); + } } diff --git a/appd/src/store.rs b/appd/src/store.rs index 0e6ff468..ee8c1356 100644 --- a/appd/src/store.rs +++ b/appd/src/store.rs @@ -337,6 +337,19 @@ CREATE INDEX IF NOT EXISTS mail_from ON mail(from_bot); CREATE TABLE IF NOT EXISTS file_copies(n INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, bot TEXT REFERENCES bots(id) ON DELETE CASCADE, project TEXT REFERENCES projects(id) ON DELETE CASCADE, conversation TEXT NOT NULL, path TEXT NOT NULL, earlier BLOB, after_sum TEXT, who TEXT NOT NULL, at INTEGER NOT NULL, undone_at INTEGER, told INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS file_copies_path ON file_copies(path); CREATE TABLE IF NOT EXISTS seen(conversation TEXT PRIMARY KEY REFERENCES conversations(id) ON DELETE CASCADE, seq INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS search_items(seq INTEGER PRIMARY KEY, conversation TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE, at INTEGER NOT NULL, kind TEXT NOT NULL, text TEXT NOT NULL); +CREATE INDEX IF NOT EXISTS search_items_conversation ON search_items(conversation, seq); +CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(text, content='search_items', content_rowid='seq', tokenize='trigram'); +CREATE TRIGGER IF NOT EXISTS search_items_ai AFTER INSERT ON search_items BEGIN INSERT INTO search_fts(rowid, text) VALUES (new.seq, new.text); END; +CREATE TRIGGER IF NOT EXISTS search_items_ad AFTER DELETE ON search_items BEGIN INSERT INTO search_fts(search_fts, rowid, text) VALUES('delete', old.seq, old.text); END; +CREATE TRIGGER IF NOT EXISTS search_items_au AFTER UPDATE ON search_items BEGIN INSERT INTO search_fts(search_fts, rowid, text) VALUES('delete', old.seq, old.text); INSERT INTO search_fts(rowid, text) VALUES (new.seq, new.text); END; +CREATE TABLE IF NOT EXISTS memory_index(id INTEGER PRIMARY KEY AUTOINCREMENT, owner_key TEXT NOT NULL, bot TEXT REFERENCES bots(id) ON DELETE CASCADE, project TEXT REFERENCES projects(id) ON DELETE CASCADE, name TEXT NOT NULL, text TEXT NOT NULL, modified_ms INTEGER NOT NULL, UNIQUE(owner_key, name)); +CREATE INDEX IF NOT EXISTS memory_index_bot ON memory_index(bot); +CREATE INDEX IF NOT EXISTS memory_index_project ON memory_index(project); +CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(name, text, content='memory_index', content_rowid='id', tokenize='trigram'); +CREATE TRIGGER IF NOT EXISTS memory_index_ai AFTER INSERT ON memory_index BEGIN INSERT INTO memory_fts(rowid, name, text) VALUES (new.id, new.name, new.text); END; +CREATE TRIGGER IF NOT EXISTS memory_index_ad AFTER DELETE ON memory_index BEGIN INSERT INTO memory_fts(memory_fts, rowid, name, text) VALUES('delete', old.id, old.name, old.text); END; +CREATE TRIGGER IF NOT EXISTS memory_index_au AFTER UPDATE ON memory_index BEGIN INSERT INTO memory_fts(memory_fts, rowid, name, text) VALUES('delete', old.id, old.name, old.text); INSERT INTO memory_fts(rowid, name, text) VALUES (new.id, new.name, new.text); END; "; /// What `PRAGMA user_version` holds: 0 before relations were foreign keys, 1 for those, 2 once @@ -469,6 +482,7 @@ fn migrate(conn: &Connection) -> Result<()> { } } let first_seen = !has_table(&tx, "seen")?; + let first_search = !has_table(&tx, "search_items")?; tx.execute_batch(SCHEMA)?; // A database of version 2 made before a message kept the one its sender was working on. if !has_column(&tx, "mail", "parent")? { @@ -546,10 +560,64 @@ fn migrate(conn: &Connection) -> Result<()> { [], )?; } + if first_search { + rebuild_search_index(&tx)?; + } tx.pragma_update(None, "user_version", SCHEMA_VERSION)?; tx.commit() } +/// Populates `search_items` (and via its trigger, `search_fts`) from existing `transcript` rows. +/// Uses the same reply-coalescing rules as `append` so upgraded databases search identically. +fn rebuild_search_index(conn: &Connection) -> Result<()> { + conn.execute("DELETE FROM search_items", [])?; + let mut read = conn.prepare( + "SELECT seq, conversation, at, entry FROM transcript ORDER BY conversation, seq", + )?; + let mut insert = conn.prepare( + "INSERT INTO search_items(seq, conversation, at, kind, text) VALUES (?1, ?2, ?3, ?4, ?5)", + )?; + let mut rows = read.query([])?; + let mut item: Option<(i64, String, u64, &'static str, String)> = None; + let mut flush = |item: Option<(i64, String, u64, &'static str, String)>| -> Result<()> { + if let Some((seq, conversation, at, kind, text)) = item + && matches!(kind, "user" | "reply") + { + insert.execute(params![seq, conversation, at, kind, text])?; + } + Ok(()) + }; + while let Some(row) = rows.next()? { + let (seq, row_conversation, at): (i64, String, u64) = + (row.get(0)?, row.get(1)?, row.get(2)?); + let entry: Value = parse(row.get(3)?)?; + let same = item + .as_ref() + .is_some_and(|(_, c, ..)| *c == row_conversation); + let text = |key: &str| entry[key].as_str().unwrap_or("").to_owned(); + let next = match entry["type"].as_str() { + Some("prompt") => Some(("user", text("text"))), + Some("text") => { + if let Some((_, _, _, "reply", so_far)) = item.as_mut().filter(|_| same) { + so_far.push_str(entry["delta"].as_str().unwrap_or("")); + continue; + } + Some(("reply", text("delta"))) + } + Some("thinking" | "tool_start") => Some(("other", String::new())), + Some("turn_end") if entry["reason"] != "done" => Some(("other", String::new())), + _ => None, + }; + if !same { + flush(item.take())?; + } + if let Some((kind, text)) = next { + flush(item.replace((seq, row_conversation, at, kind, text)))?; + } + } + flush(item) +} + fn has_table(conn: &Connection, name: &str) -> Result { conn.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1")? .exists([name]) @@ -711,6 +779,43 @@ pub struct Hit { pub snippet: String, } +/// A memory note where `search_memory` found the words. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MemoryHit { + #[serde(skip_serializing_if = "Option::is_none")] + pub bot: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub project: Option, + pub name: String, + pub modified_ms: u64, + pub snippet: String, +} + +/// Whether `needle` can be answered directly by SQLite FTS5's `trigram` tokenizer without +/// missing Unicode case-folded matches. +fn can_use_trigram(needle: &str) -> bool { + if needle.chars().count() < 3 || needle.contains('\0') { + return false; + } + // FTS5 trigram folds ASCII case by default; caseless Unicode (e.g. CJK, digits, symbols) + // matches verbatim, while cased non-ASCII letters fall back to scanning `search_items`. + needle + .chars() + .all(|c| c.is_ascii() || (!c.is_uppercase() && !c.is_lowercase())) +} + +fn fts_phrase(needle: &str) -> String { + format!("\"{}\"", needle.replace('"', "\"\"")) +} + +fn owner_parts(owner: Owner<'_>) -> (String, Option<&str>, Option<&str>) { + match owner { + Owner::Bot(id) => (format!("bot:{id}"), Some(id), None), + Owner::Project(id) => (format!("project:{id}"), None, Some(id)), + } +} + /// Up to 40 characters either side of the first `needle` (lower case) in `text`, if there is one. fn snippet(text: &str, needle: &str) -> Option { // Lower case can change lengths ('İ' is two characters): each lower-case byte keeps the @@ -1558,13 +1663,58 @@ impl Store { "INSERT INTO transcript(conversation, at, entry) VALUES (?1, ?2, ?3)", params![conversation, at, json(entry)], )?; - Ok(self.0.last_insert_rowid()) + let seq = self.0.last_insert_rowid(); + match entry["type"].as_str() { + Some("prompt") => { + let text = entry["text"].as_str().unwrap_or(""); + self.0.execute( + "INSERT INTO search_items(seq, conversation, at, kind, text) VALUES (?1, ?2, ?3, 'user', ?4)", + params![seq, conversation, at, text], + )?; + } + Some("text") => { + let delta = entry["delta"].as_str().unwrap_or(""); + let prev_type: Option = self + .0 + .prepare_cached( + "SELECT json_extract(entry, '$.type') FROM transcript \ + WHERE conversation = ?1 AND seq < ?2 \ + AND (json_extract(entry, '$.type') IN ('prompt', 'text', 'thinking', 'tool_start') \ + OR (json_extract(entry, '$.type') = 'turn_end' AND json_extract(entry, '$.reason') != 'done')) \ + ORDER BY seq DESC LIMIT 1", + )? + .query_row(params![conversation, seq], |r| r.get(0)) + .optional()?; + let open_reply: Option = if prev_type.as_deref() == Some("text") { + self.0 + .prepare_cached( + "SELECT seq FROM search_items WHERE conversation = ?1 AND kind = 'reply' ORDER BY seq DESC LIMIT 1", + )? + .query_row([conversation], |r| r.get(0)) + .optional()? + } else { + None + }; + if let Some(reply_seq) = open_reply { + self.0.execute( + "UPDATE search_items SET text = text || ?1 WHERE seq = ?2", + params![delta, reply_seq], + )?; + } else { + self.0.execute( + "INSERT INTO search_items(seq, conversation, at, kind, text) VALUES (?1, ?2, ?3, 'reply', ?4)", + params![seq, conversation, at, delta], + )?; + } + } + _ => {} + } + Ok(seq) } /// The newest `limit` prompts and replies holding `needle` (any case), of one conversation, /// of the conversations of `bot`, or of all. A reply is searched whole, as the chat shows /// it: a run of text pieces, found at the `seq` of its first. - // shortcut: reads every transcript entry per search; add an index (FTS5) when that gets slow. pub fn search( &self, bot: Option<&str>, @@ -1572,79 +1722,227 @@ impl Store { needle: &str, limit: usize, ) -> Result> { - let mut stmt = self.0.prepare_cached( - "SELECT t.seq, t.conversation, c.bot, t.at, t.entry FROM transcript t \ - JOIN conversations c ON c.id = t.conversation \ - WHERE (?1 IS NULL OR c.bot = ?1) AND (?2 IS NULL OR t.conversation = ?2) \ - ORDER BY t.conversation, t.seq", - )?; - let mut rows = stmt.query(params![bot, conversation])?; - let needle = needle.to_lowercase(); + if limit == 0 { + return Ok(Vec::new()); + } + let needle_lower = needle.to_lowercase(); let mut hits = Vec::new(); - // The item being read, as `chat.ts` makes them: where it begins, and its words. - let mut item: Option<(Hit, String)> = None; - let done = |item: Option<(Hit, String)>, hits: &mut Vec| { - if let Some((mut hit, text)) = item - && let Some(snippet) = snippet(&text, &needle) - { - hit.snippet = snippet; - hits.push(hit); - } + let make_hit = |seq: i64, + conv: String, + bot_id: String, + at_ms: u64, + kind: String, + text: String| + -> Option { + let kind = match kind.as_str() { + "user" => "user", + "reply" => "reply", + _ => return None, + }; + let shown = snippet(&text, &needle_lower)?; + Some(Hit { + bot: bot_id, + conversation: conv, + seq, + at_ms, + kind, + snippet: shown, + }) }; - while let Some(row) = rows.next()? { - let (seq, row_conversation): (i64, String) = (row.get(0)?, row.get(1)?); - let entry: Value = parse(row.get(4)?)?; - let same = item - .as_ref() - .is_some_and(|(h, _)| h.conversation == row_conversation); - let text = |key: &str| entry[key].as_str().unwrap_or("").to_owned(); - let next = match entry["type"].as_str() { - Some("prompt") => Some(("user", text("text"))), - Some("text") => { - if let Some((Hit { kind: "reply", .. }, so_far)) = - item.as_mut().filter(|_| same) - { - so_far.push_str(entry["delta"].as_str().unwrap_or("")); - continue; + if can_use_trigram(needle) { + let query = fts_phrase(needle); + let mut stmt = self.0.prepare_cached( + "SELECT s.seq, s.conversation, c.bot, s.at, s.kind, s.text \ + FROM search_fts f \ + JOIN search_items s ON s.seq = f.rowid \ + JOIN conversations c ON c.id = s.conversation \ + WHERE search_fts MATCH ?1 \ + AND (?2 IS NULL OR c.bot = ?2) \ + AND (?3 IS NULL OR s.conversation = ?3) \ + ORDER BY s.seq DESC \ + LIMIT ?4", + )?; + let mut rows = stmt.query(params![query, bot, conversation, limit as i64])?; + while let Some(row) = rows.next()? { + if let Some(hit) = make_hit( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + row.get(5)?, + ) { + hits.push(hit); + } + } + } else { + let mut stmt = self.0.prepare_cached( + "SELECT s.seq, s.conversation, c.bot, s.at, s.kind, s.text \ + FROM search_items s \ + JOIN conversations c ON c.id = s.conversation \ + WHERE (?1 IS NULL OR c.bot = ?1) AND (?2 IS NULL OR s.conversation = ?2) \ + ORDER BY s.seq DESC", + )?; + let mut rows = stmt.query(params![bot, conversation])?; + while let Some(row) = rows.next()? { + if let Some(hit) = make_hit( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + row.get(5)?, + ) { + hits.push(hit); + if hits.len() >= limit { + break; } - Some(("reply", text("delta"))) } - // Items the chat shows that are not searched; they end a reply. - Some("thinking" | "tool_start") => Some(("other", String::new())), - Some("turn_end") if entry["reason"] != "done" => Some(("other", String::new())), - _ => None, - }; - if !same { - done(item.take(), &mut hits); } - if let Some((kind, text)) = next { - let hit = Hit { - bot: row.get(2)?, - conversation: row_conversation, - seq, - at_ms: row.get(3)?, - kind, - snippet: String::new(), - }; - done(item.replace((hit, text)), &mut hits); + } + Ok(hits) + } + + /// Indexes or updates one memory note in `memory_index` (and `memory_fts`). + pub fn upsert_memory( + &self, + owner: Owner<'_>, + name: &str, + text: &str, + modified_ms: u64, + ) -> Result<()> { + let (owner_key, bot, project) = owner_parts(owner); + self.0.execute( + "INSERT INTO memory_index(owner_key, bot, project, name, text, modified_ms) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6) \ + ON CONFLICT(owner_key, name) DO UPDATE SET text = excluded.text, modified_ms = excluded.modified_ms", + params![owner_key, bot, project, name, text, modified_ms], + )?; + Ok(()) + } + + /// Removes one memory note from `memory_index` (and `memory_fts`). + pub fn delete_memory_entry(&self, owner: Owner<'_>, name: &str) -> Result<()> { + let (owner_key, ..) = owner_parts(owner); + self.0.execute( + "DELETE FROM memory_index WHERE owner_key = ?1 AND name = ?2", + params![owner_key, name], + )?; + Ok(()) + } + + /// Indexed `(name, modified_ms)` pairs for one bot or project, for incremental sync. + pub fn indexed_memory(&self, owner: Owner<'_>) -> Result> { + let (owner_key, ..) = owner_parts(owner); + let mut stmt = self + .0 + .prepare_cached("SELECT name, modified_ms FROM memory_index WHERE owner_key = ?1")?; + let rows = stmt.query_map([owner_key], |r| Ok((r.get(0)?, r.get(1)?)))?; + rows.collect() + } + + /// Searches indexed memory notes across bots and projects, newest modified first. + pub fn search_memory( + &self, + bot: Option<&str>, + project: Option<&str>, + needle: &str, + limit: usize, + ) -> Result> { + if limit == 0 { + return Ok(Vec::new()); + } + let needle_lower = needle.to_lowercase(); + let mut hits = Vec::new(); + let make_hit = |bot_id: Option, + project_id: Option, + name: String, + text: String, + modified_ms: u64| + -> Option { + let shown = snippet(&text, &needle_lower).or_else(|| snippet(&name, &needle_lower))?; + Some(MemoryHit { + bot: bot_id, + project: project_id, + name, + modified_ms, + snippet: shown, + }) + }; + if can_use_trigram(needle) { + let query = fts_phrase(needle); + let mut stmt = self.0.prepare_cached( + "SELECT m.bot, m.project, m.name, m.text, m.modified_ms \ + FROM memory_fts f \ + JOIN memory_index m ON m.id = f.rowid \ + WHERE memory_fts MATCH ?1 \ + AND (?2 IS NULL OR m.bot = ?2) \ + AND (?3 IS NULL OR m.project = ?3) \ + ORDER BY m.modified_ms DESC, m.id DESC \ + LIMIT ?4", + )?; + let mut rows = stmt.query(params![query, bot, project, limit as i64])?; + while let Some(row) = rows.next()? { + if let Some(hit) = make_hit( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + ) { + hits.push(hit); + } + } + } else { + let mut stmt = self.0.prepare_cached( + "SELECT bot, project, name, text, modified_ms \ + FROM memory_index \ + WHERE (?1 IS NULL OR bot = ?1) AND (?2 IS NULL OR project = ?2) \ + ORDER BY modified_ms DESC, id DESC", + )?; + let mut rows = stmt.query(params![bot, project])?; + while let Some(row) = rows.next()? { + if let Some(hit) = make_hit( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + ) { + hits.push(hit); + if hits.len() >= limit { + break; + } + } } } - done(item, &mut hits); - hits.sort_by_key(|h| std::cmp::Reverse(h.seq)); - hits.truncate(limit); Ok(hits) } /// Removes the prompt entry with `nonce` and everything after it. Does nothing if there is none. /// The ledger keeps the removed prompts: a late retry of one must not undo the rewind. pub fn rewind_transcript(&self, conversation: &str, nonce: &str) -> Result<()> { - self.0 - .execute( - "DELETE FROM transcript WHERE conversation = ?1 AND seq >= (SELECT min(seq) FROM transcript - WHERE conversation = ?1 AND json_extract(entry, '$.type') = 'prompt' AND json_extract(entry, '$.nonce') = ?2)", + let cut: Option = self + .0 + .query_row( + "SELECT min(seq) FROM transcript \ + WHERE conversation = ?1 AND json_extract(entry, '$.type') = 'prompt' AND json_extract(entry, '$.nonce') = ?2", [conversation, nonce], + |r| r.get(0), ) - .map(drop) + .optional()? + .flatten(); + if let Some(cut) = cut { + self.0.execute( + "DELETE FROM transcript WHERE conversation = ?1 AND seq >= ?2", + params![conversation, cut], + )?; + self.0.execute( + "DELETE FROM search_items WHERE conversation = ?1 AND seq >= ?2", + params![conversation, cut], + )?; + } + Ok(()) } /// The last `limit` entries of a conversation before `before`, oldest first, and whether @@ -3126,16 +3424,27 @@ mod tests { .put_project(&project("p1", &["a", "b"], Some("a"))) .unwrap(); store.put_room("p1", "a", "", "hello", 1).unwrap(); + store + .upsert_memory(Owner::Bot("a"), "notes.md", "bot a memory", 1) + .unwrap(); + store + .upsert_memory(Owner::Bot("b"), "notes.md", "bot b memory", 1) + .unwrap(); + store + .upsert_memory(Owner::Project("p1"), "shared.md", "project memory", 1) + .unwrap(); store.delete_bot("a").unwrap(); for &table in BOT_TABLES { assert_eq!(count(&store, table, "bot", "a"), 0, "{table}"); } assert_eq!(count(&store, "conversations", "bot", "a"), 0); + assert_eq!(count(&store, "memory_index", "bot", "a"), 0); + assert_eq!(count(&store, "memory_index", "bot", "b"), 1); // Made after version 1, so not among the tables a version 1 database moves. for table in CONVERSATION_TABLES .into_iter() - .chain(["conversation_grants"]) + .chain(["conversation_grants", "search_items"]) { assert_eq!( count(&store, table, "conversation", &conversation["a"]), @@ -3163,7 +3472,23 @@ mod tests { store.delete_project("p1").unwrap(); assert_eq!(count(&store, "projects", "id", "p1"), 0); assert_eq!(count(&store, "room", "project", "p1"), 0); + assert_eq!(count(&store, "memory_index", "project", "p1"), 0); assert_eq!(count(&store, "bots", "project", "p1"), 0); + // FTS5 shadow indexes stay consistent across CASCADE deletes. + store + .0 + .execute( + "INSERT INTO search_fts(search_fts) VALUES('integrity-check')", + [], + ) + .unwrap(); + store + .0 + .execute( + "INSERT INTO memory_fts(memory_fts) VALUES('integrity-check')", + [], + ) + .unwrap(); assert_eq!(store.bot("b").unwrap().unwrap().id, "b"); assert_eq!(store.project_of("b").unwrap(), None); std::fs::remove_dir_all(&dir).unwrap(); @@ -3380,13 +3705,159 @@ mod tests { .unwrap() .collect::>() .unwrap(); - // Three are handled by name where a bot is deleted; `file_copies` holds a project's rows - // too (its `bot` may be empty) and came after the last rebuild of the tables. - let apart = ["bots", "mail", "conversations", "file_copies"]; + // Three are handled by name where a bot is deleted; `file_copies` and `memory_index` hold + // a project's rows too (their `bot` may be NULL) and came after the last rebuild of the tables. + let apart = [ + "bots", + "mail", + "conversations", + "file_copies", + "memory_index", + ]; with_bot.retain(|t| !apart.contains(&t.as_str())); let mut listed: Vec = BOT_TABLES.iter().map(|t| (*t).to_owned()).collect(); listed.sort(); assert_eq!(with_bot, listed); std::fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn fts5_indexes_transcript_backfill_rewind_cjk_and_memory() { + let dir = std::env::temp_dir().join(format!("appd-store-fts5-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db_path = dir.join("app.db"); + + let store = Store::open(&db_path).unwrap(); + store.create_bot("a", "Ada", 1).unwrap(); + let conv = store.current_conversation("a").unwrap(); + let p1 = store + .append( + &conv, + 10, + &serde_json::json!({"type": "prompt", "nonce": "n1", "text": "Check the 日本語ログ and café"}), + ) + .unwrap(); + let r1 = store + .append( + &conv, + 11, + &serde_json::json!({"type": "text", "delta": "hel"}), + ) + .unwrap(); + store + .append( + &conv, + 12, + &serde_json::json!({"type": "text", "delta": "lo world"}), + ) + .unwrap(); + store + .append( + &conv, + 13, + &serde_json::json!({"type": "tool_start", "call": "c1"}), + ) + .unwrap(); + let r2 = store + .append( + &conv, + 14, + &serde_json::json!({"type": "text", "delta": "after tool call"}), + ) + .unwrap(); + store + .append( + &conv, + 15, + &serde_json::json!({"type": "prompt", "nonce": "n2", "text": "rewindable prompt"}), + ) + .unwrap(); + + // Coalesced reply, CJK, short query (<3 chars), and cased non-ASCII all work. + let hits = store.search(None, None, "HELLO", 10).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!((hits[0].seq, hits[0].kind), (r1, "reply")); + assert_eq!(store.search(None, None, "日本語", 10).unwrap()[0].seq, p1); + assert_eq!(store.search(None, None, "CAFÉ", 10).unwrap()[0].seq, p1); + assert_eq!(store.search(None, None, "he", 10).unwrap()[0].seq, r1); + assert_eq!( + store.search(None, None, "after tool", 10).unwrap()[0].seq, + r2 + ); + assert_eq!(store.search(None, None, "rewindable", 10).unwrap().len(), 1); + + // Rewind drops transcript + FTS5 rows cleanly. + store.rewind_transcript(&conv, "n2").unwrap(); + assert!( + store + .search(None, None, "rewindable", 10) + .unwrap() + .is_empty() + ); + + // Simulate an existing DB from before FTS5 by dropping search_items/search_fts and reopening. + drop(store); + let raw = Connection::open(&db_path).unwrap(); + raw.execute_batch("DROP TABLE search_fts; DROP TABLE search_items;") + .unwrap(); + drop(raw); + + let reopened = Store::open(&db_path).unwrap(); + let hits = reopened.search(None, None, "hello world", 10).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].seq, r1); + assert_eq!( + reopened.search(None, None, "日本語", 10).unwrap()[0].seq, + p1 + ); + + // Memory FTS5 upsert, search, update, delete, and integrity check. + reopened + .upsert_memory(Owner::Bot("a"), "plan.md", "Ship FTS5 search quickly", 100) + .unwrap(); + let mem_hits = reopened.search_memory(Some("a"), None, "FTS5", 10).unwrap(); + assert_eq!(mem_hits.len(), 1); + assert_eq!(mem_hits[0].name, "plan.md"); + reopened + .upsert_memory(Owner::Bot("a"), "plan.md", "Updated memory note", 200) + .unwrap(); + assert!( + reopened + .search_memory(Some("a"), None, "FTS5", 10) + .unwrap() + .is_empty() + ); + assert_eq!( + reopened + .search_memory(Some("a"), None, "updated", 10) + .unwrap() + .len(), + 1 + ); + reopened + .delete_memory_entry(Owner::Bot("a"), "plan.md") + .unwrap(); + assert!( + reopened + .search_memory(Some("a"), None, "updated", 10) + .unwrap() + .is_empty() + ); + reopened + .0 + .execute( + "INSERT INTO search_fts(search_fts) VALUES('integrity-check')", + [], + ) + .unwrap(); + reopened + .0 + .execute( + "INSERT INTO memory_fts(memory_fts) VALUES('integrity-check')", + [], + ) + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/appd/tests/service.rs b/appd/tests/service.rs index f112dc2f..8b9b4bfc 100644 --- a/appd/tests/service.rs +++ b/appd/tests/service.rs @@ -13433,8 +13433,10 @@ fn dump(db: &rusqlite::Connection) -> Vec { .collect(); let mut rows = Vec::new(); for table in tables { + // FTS5 `*_config` shadow tables are `WITHOUT ROWID`; fall back to scanning without rowid. let mut stmt = db .prepare(&format!("SELECT * FROM {table} ORDER BY rowid")) + .or_else(|_| db.prepare(&format!("SELECT * FROM {table}"))) .unwrap(); let columns = stmt.column_count(); let mut found = stmt.query([]).unwrap(); @@ -18353,6 +18355,7 @@ const ANSWERS_LATER: &[&str] = &[ "run_routine", "install_workplace", "list_catalog", + "discover_skills", "preview_skill_catalog", "install_skill_catalog", "preview_catalog", @@ -19415,3 +19418,118 @@ fn a_limit_or_an_agent_is_not_changed_while_the_workers_acceptance_command_runs( assert!(d.waits_for_reply(0).contains("passed")); w.ok("set_disk_access", json!({"bot": d.bo, "wholeDisk": true})); } + +#[test] +fn search_memory_finds_bot_and_project_notes_and_stays_in_sync_on_update_delete_and_disk_writes() { + let home = home("search-memory"); + let _service = Service::start(&home); + let mut w = Window::connect(&home); + let bot = w.create_bot(); + let folder = std::env::temp_dir().join(format!("appd-{}-search-mem-proj", std::process::id())); + let _ = fs::remove_dir_all(&folder); + fs::create_dir_all(folder.join(".bate/memory")).unwrap(); + let project = w.ok( + "set_project", + json!({"project": {"name": "Field", "folder": folder, "bots": [bot]}}), + )["project"]["id"] + .as_str() + .unwrap() + .to_owned(); + + // Window write to bot memory and direct disk write to project memory (as a bot's tool does). + w.ok( + "write_memory", + json!({"bot": bot, "name": "plan.md", "text": "Keep the quarterly roadmap concise."}), + ); + fs::write( + folder.join(".bate/memory/shared.md"), + "Quarterly milestones live in this shared note.", + ) + .unwrap(); + + let all = w.ok("search_memory", json!({"text": "quarterly"}))["hits"].clone(); + assert_eq!(all.as_array().unwrap().len(), 2, "{all}"); + let only_bot = w.ok("search_memory", json!({"bot": bot, "text": "quarterly"}))["hits"].clone(); + assert_eq!(only_bot.as_array().unwrap().len(), 1, "{only_bot}"); + assert_eq!(only_bot[0]["name"], "plan.md"); + assert_eq!(only_bot[0]["bot"], bot); + + let only_project = w.ok( + "search_memory", + json!({"projectId": project, "text": "milestones"}), + )["hits"] + .clone(); + assert_eq!(only_project.as_array().unwrap().len(), 1, "{only_project}"); + assert_eq!(only_project[0]["name"], "shared.md"); + assert_eq!(only_project[0]["project"], project); + + // Updating and deleting removes stale FTS5 hits. + w.ok( + "write_memory", + json!({"bot": bot, "name": "plan.md", "text": "Annual targets only."}), + ); + assert!( + w.ok("search_memory", json!({"bot": bot, "text": "quarterly"}))["hits"] + .as_array() + .unwrap() + .is_empty() + ); + assert_eq!( + w.ok("search_memory", json!({"bot": bot, "text": "annual"}))["hits"] + .as_array() + .unwrap() + .len(), + 1 + ); + w.ok("delete_memory", json!({"bot": bot, "name": "plan.md"})); + assert!( + w.ok("search_memory", json!({"bot": bot, "text": "annual"}))["hits"] + .as_array() + .unwrap() + .is_empty() + ); + assert_eq!( + refusal( + &mut w, + "search_memory", + json!({"bot": bot, "projectId": project, "text": "quarterly"}), + ), + "bad_request" + ); + let _ = fs::remove_dir_all(&folder); +} + +#[test] +fn discover_skills_lists_local_skills_for_preview_and_install() { + let home = home("discover-skills"); + let local_root = home.join("local-skills"); + let skill_dir = local_root.join("local-demo"); + fs::create_dir_all(&skill_dir).unwrap(); + fs::create_dir_all(local_root.join("not-a-skill")).unwrap(); + fs::write( + skill_dir.join("SKILL.md"), + "---\nname: local-demo\ndescription: Helps verify local discovery.\nauthor: Ada\n---\nSteps.\n", + ) + .unwrap(); + let _service = Service::start_with(&home, |c| { + c.env("APPD_ENGINE", home.join("fake-engine")) + .env("BATE_DISCOVER_SKILLS_DIRS", &local_root); + }); + let mut w = Window::connect(&home); + let bot = w.create_bot(); + + let found = w.ok("discover_skills", json!({}))["skills"].clone(); + assert_eq!(found.as_array().unwrap().len(), 1, "{found}"); + assert_eq!(found[0]["name"], "local-demo"); + assert_eq!(found[0]["author"], "Ada"); + let path = found[0]["path"].as_str().unwrap().to_owned(); + + let preview = w.ok("preview_skill", json!({"path": path}))["skill"].clone(); + assert_eq!(preview["name"], "local-demo"); + w.ok("install_skill", json!({"bot": bot, "path": path})); + + let installed = w.ok("list_skills", json!({"bot": bot}))["skills"].clone(); + assert_eq!(installed.as_array().unwrap().len(), 1, "{installed}"); + assert_eq!(installed[0]["name"], "local-demo"); + assert_eq!(installed[0]["enabled"], true); +} diff --git a/native/src/addons.rs b/native/src/addons.rs index 72ccde29..546ea167 100644 --- a/native/src/addons.rs +++ b/native/src/addons.rs @@ -194,6 +194,7 @@ pub fn bot_names(app: &App, ids: &[String]) -> String { pub mod made_by { pub const CATALOG: &str = "Bate's catalog, a list in Bate's own repository on GitHub (d41sys/bate). Each entry pins the exact archive by its hash."; pub const FOLDER: &str = "A folder you chose on this Mac. Bate cannot tell who made it."; + pub const FOUND: &str = "A skill folder found on this Mac. Bate cannot tell who made it."; pub const TYPED: &str = "You, here. Bate cannot tell who runs the server or the program."; pub const CONNECTOR_LIST: &str = "Bate's list of connectors, a file in Bate's own repository on GitHub (d41sys/bate). An entry is a pointer, not a recommendation: Bate has not checked the server or the program it names."; pub const SKILL_LIST: &str = "Bate's list of skills, a file in Bate's own repository on GitHub (d41sys/bate). Each entry pins the exact archive by its hash, but is not a recommendation: Bate has not checked what the skill says."; diff --git a/native/src/addons_fixture.rs b/native/src/addons_fixture.rs index 78567dc3..0a5cfbb4 100644 --- a/native/src/addons_fixture.rs +++ b/native/src/addons_fixture.rs @@ -18,6 +18,8 @@ pub struct Addons { pub connectors: BTreeMap>, /// Each bot's skills, as `list_skills` says them. pub skills: BTreeMap>, + /// Local skill folders found on this Mac (`discover_skills`). + pub discovered: Vec, /// The installed workplaces; who has each on is read from the projects. pub workplaces: Vec, /// The catalog's lists by kind: `connectors`, `skills`, `workplaces`. @@ -301,6 +303,7 @@ pub fn answer( json!({}) } "list_skills" => json!({"skills": a.skills.get(&bot).cloned().unwrap_or_default()}), + "discover_skills" => json!({"skills": a.discovered.clone()}), "set_skill_enabled" => { match named(a.skills.entry(bot.clone()).or_default(), &name) { Some(s) => s["enabled"] = request["enabled"].clone(), diff --git a/native/src/skills.rs b/native/src/skills.rs index 06ecd8bc..62845506 100644 --- a/native/src/skills.rs +++ b/native/src/skills.rs @@ -5,6 +5,7 @@ use crate::addons::{self, Flow, by_line, made_by, size_text, summary_text}; use crate::app::App; use crate::catalog::{self, Action}; use crate::forms::{self, Kind}; +use crate::resource::Resource; use crate::sheet::{self, Content, Item, Step, Who}; use crate::tokens::*; use serde_json::{Value, json}; @@ -14,6 +15,8 @@ type V = El; /// Where the outcome of what a row does is kept. const ACT: &str = "addons:skills:act"; +/// Where `discover_skills` results are watched. +const DISCOVER: &str = "addons:skills:discover"; /// What the panel that picks a folder with a skill in it is asked for (`App::file_chosen`). pub const FOLDER_PANEL: &str = "skills-folder"; @@ -106,10 +109,42 @@ pub enum Ask { }, } +/// A local skill folder found on this Mac (`discover_skills`). +#[derive(Debug, Clone, PartialEq)] +pub struct Discovered { + pub name: String, + pub description: String, + pub author: Option, + pub path: String, + pub from: String, +} + +impl Discovered { + fn from_value(v: &Value) -> Option { + Some(Discovered { + name: v["name"].as_str()?.to_owned(), + description: v["description"].as_str().unwrap_or_default().to_owned(), + author: v["author"].as_str().map(str::to_owned), + path: v["path"].as_str()?.to_owned(), + from: v["from"].as_str().unwrap_or_default().to_owned(), + }) + } +} + /// The page is shown: what it needs is asked for (`State::watch`, keys start `addons:list:`). pub fn enter(app: &mut App) -> Vec { addons::watch_lists(app, "skills", "list_skills", &["skills_changed"]); - Vec::new() + app.state + .watch(Resource::new(DISCOVER, "discover_skills", json!({}), &[])) +} + +fn discovered(app: &App) -> Vec { + app.state + .pages + .get(DISCOVER) + .and_then(|v| v["skills"].as_array()) + .map(|items| items.iter().filter_map(Discovered::from_value).collect()) + .unwrap_or_default() } fn lists(app: &App) -> (Vec<(String, Vec)>, addons::Lists) { @@ -456,6 +491,38 @@ pub fn body(app: &App, cx: &Cx, k: &Tokens) -> V { )); } flow.push(SPACE_2, SPACE_2, addons::rows(tiles)); + let found = discovered(app); + if !found.is_empty() { + addons::head(&mut flow, k, "On this Mac", Vec::new()); + let mut local_tiles = Vec::new(); + for d in found { + let mut lines = vec![addons::small(k, &d.description)]; + if let Some(author) = &d.author { + lines.push(addons::small(k, &by_line(author))); + } + if !d.from.is_empty() { + lines.push(addons::small(k, &d.from)); + } + let path = d.path.clone(); + let key = format!("discovered-skill-{}", d.name); + let btn = forms::action( + k, + format!("install-discovered-{}", d.name), + "Install…", + Kind::Fill, + true, + true, + ) + .on_press(move |app: &mut App| look(app, Source::Path(path.clone()), made_by::FOUND)); + local_tiles.push(addons::tile( + k, + key, + addons::tile_line(addons::what(k, &d.name, lines), vec![btn]), + Vec::new(), + )); + } + flow.push(SPACE_2, SPACE_2, addons::rows(local_tiles)); + } catalog::add( &mut flow, app, diff --git a/native/tests/addons.rs b/native/tests/addons.rs index 2e982e07..9ffdd825 100644 --- a/native/tests/addons.rs +++ b/native/tests/addons.rs @@ -649,6 +649,37 @@ fn a_skill_is_removed_from_each_bot_ticked_and_a_failure_keeps_that_bot_ticked() assert!(!sheet_is_open(&mut w)); } +#[test] +fn discovered_local_skills_appear_under_on_this_mac_and_open_the_install_sheet() { + let mut w = world(); + w.service.change(|d| { + d.addons.discovered.push(json!({ + "name": "local-helper", + "description": "Found in a local skills folder.", + "author": "Ada", + "path": "/Users/demo/.agents/skills/local-helper", + "from": "~/.agents/skills", + })); + }); + press(&mut w, "addons"); + go_addons_page(&mut w, "Skills"); + quiet(&mut w); + assert!(shows(&mut w.rt, "On this Mac")); + assert!(shows(&mut w.rt, "local-helper")); + assert!(shows(&mut w.rt, "~/.agents/skills")); + press(&mut w, "install-discovered-local-helper"); + let r = sent(&w, |r| r["type"] == "preview_skill"); + assert_eq!(r["path"], "/Users/demo/.agents/skills/local-helper"); + quiet(&mut w); + assert!(shows(&mut w.rt, "Install local-helper")); + assert!(shows(&mut w.rt, "A skill folder found on this Mac.")); + press(&mut w, "sheet-who-b1"); + confirm(&mut w); + let i = requests_of(&w.service, "install_skill").remove(0); + assert_eq!(i["bot"], "b1"); + assert_eq!(i["path"], "/Users/demo/.agents/skills/local-helper"); +} + // ---- Workplaces ------------------------------------------------------------------------- #[test] diff --git a/window/ui/src/Skills.tsx b/window/ui/src/Skills.tsx index cdb2dace..9a43bf9e 100644 --- a/window/ui/src/Skills.tsx +++ b/window/ui/src/Skills.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useEffect, useState } from "react"; import { byLine, each, madeBy, onFor, placed } from "./addons.ts"; import { Catalog } from "./Catalog.tsx"; import { Choose } from "./ProjectDialog.tsx"; @@ -6,7 +6,7 @@ import { RowMenu } from "./RowMenu.tsx"; import { Sheet } from "./Sheet.tsx"; import { usePerBot } from "./usePerBot.ts"; import { inShell, request } from "./service.ts"; -import type { Bot, InstalledSkill, SkillListed, SkillPreview } from "./types.ts"; +import type { Bot, DiscoveredSkill, InstalledSkill, SkillListed, SkillPreview } from "./types.ts"; import { sizeText } from "./workplaces.ts"; /** Where a skill is copied from: a folder, the same skill on a bot that has it, or an entry of Bate's list (`sha256`: the archive that was shown). */ @@ -19,6 +19,18 @@ export function Skills({ bots }: { bots: Bot[] }) { const rows = placed(lists); const [ask, setAsk] = useState(); const [error, setError] = useState(""); + const [discovered, setDiscovered] = useState([]); + useEffect(() => { + if (!inShell) return; + let gone = false; + request<{ skills: DiscoveredSkill[] }>("discover_skills", {}).then( + (d) => gone || setDiscovered(d.skills), + () => {}, + ); + return () => { + gone = true; + }; + }, []); const names = (ids: string[]) => ids.map((id) => bots.find((b) => b.id === id)?.name ?? id).join(", "); const has = (name: string) => rows.find((r) => r.name === name)?.users.map((u) => u.bot) ?? []; @@ -75,6 +87,28 @@ export function Skills({ bots }: { bots: Bot[] }) { ))} {!inShell &&

Skills are added in Bate's own window on the Mac.

} + {inShell && discovered.length > 0 && ( + <> +
+

On this Mac

+
+
    + {discovered.map((d) => ( +
  • +
    + {d.name} + {d.description} + {d.author && {byLine(d.author)}} + {d.from} +
    +
    + +
    +
  • + ))} +
+ + )} {inShell && ( kind="skills" diff --git a/window/ui/src/addons.ts b/window/ui/src/addons.ts index 13897fc1..83e90701 100644 --- a/window/ui/src/addons.ts +++ b/window/ui/src/addons.ts @@ -4,6 +4,7 @@ import type { Connector, ConnectorListed } from "./types.ts"; export const madeBy = { catalog: "Bate's catalog, a list in Bate's own repository on GitHub (d41sys/bate). Each entry pins the exact archive by its hash.", folder: "A folder you chose on this Mac. Bate cannot tell who made it.", + found: "A skill folder found on this Mac. Bate cannot tell who made it.", file: "A file you chose on this Mac. Bate cannot tell who made it.", typed: "You, here. Bate cannot tell who runs the server or the program.", copy: (bot: string) => `${bot}'s copy. Bate cannot tell who made it.`, diff --git a/window/ui/src/types.ts b/window/ui/src/types.ts index 89002ed0..63860c91 100644 --- a/window/ui/src/types.ts +++ b/window/ui/src/types.ts @@ -204,6 +204,9 @@ export type ConnectorListed = { /** An entry of the list of skills (`list_catalog` with `kind: "skills"`). */ export type SkillListed = { name: string; description: string; author?: string; size: number; sha256: string }; +/** A local `SKILL.md` folder found on this Mac (`discover_skills`). */ +export type DiscoveredSkill = Skill & { path: string; from: string }; + /** What `preview_bot_file` says a bot file holds. `sha256` is given back to `import_bot`. */ export type BotFilePreview = { name: string; diff --git a/window/ui/standin/answers.mjs b/window/ui/standin/answers.mjs index 2425e801..89dc004f 100644 --- a/window/ui/standin/answers.mjs +++ b/window/ui/standin/answers.mjs @@ -328,6 +328,8 @@ export const answers = (now) => { block_tool: {}, confirm_read_tools: {}, list_skills: ({ bot: id }) => ({ skills: skills[id] ?? [] }), + discover_skills: { skills: [] }, + search_memory: { hits: [] }, set_skill_enabled: {}, preview_skill: { skill: { name: "log-reading", description: "Read a log and say what failed first." }, entries: 3, bytes: 2400 }, preview_skill_catalog: { skill: { name: "log-reading", description: "Read a log and say what failed first.", author: "Example Lab" }, entries: 3, bytes: 2400, entry: { sha256: "1".repeat(8), author: "Example Lab" } },