Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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 |
Expand Down
106 changes: 106 additions & 0 deletions appd/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")?;
Expand Down Expand Up @@ -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!({})))
}
Expand All @@ -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!({})))
}
Expand All @@ -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!({})))
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -4700,6 +4777,35 @@ impl Core {
self.store.keep(owner, &copy).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<String, u64> = indexed.into_iter().collect();
let mut present = HashSet::with_capacity(disk.len());
for note in disk {
present.insert(note.name.clone());
if indexed.get(&note.name).copied() == Some(note.modified_ms) {
continue;
}
if let Ok(Some(text)) = memory::read(place, &note.name) {
let _ = self
.store
.upsert_memory(owner, &note.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 {
Expand Down
2 changes: 2 additions & 0 deletions appd/src/lan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,7 @@ const ALLOWED_OVER_LAN: &[&str] = &[
"order_bots",
"delete_bot",
"search",
"search_memory",
"get_update",
"check_update",
"list_models",
Expand Down Expand Up @@ -1040,6 +1041,7 @@ mod tests {
"add_roles",
"preview_skill",
"install_skill",
"discover_skills",
"preview_bot_file",
"import_bot",
"preview_workplace",
Expand Down
113 changes: 113 additions & 0 deletions appd/src/skills.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<String>,
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<Discovered> {
discover_in(&discover_roots())
}

fn discover_in(roots: &[(PathBuf, String)]) -> Vec<Discovered> {
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<Skill, String> {
let mut text = String::new();
Expand Down Expand Up @@ -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();
}
}
Loading
Loading