From b8dc61735bd159b9aa9b52d024f5de2bc5561fb5 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Fri, 4 Dec 2026 00:27:51 +0800 Subject: [PATCH] =?UTF-8?q?feat(agents):=20=E8=B5=84=E6=BA=90=E5=BA=93?= =?UTF-8?q?=E6=8A=80=E8=83=BD=E5=8F=AF=E6=96=B0=E5=BB=BA=E3=80=81=E8=AF=BB?= =?UTF-8?q?=E5=86=99=20SKILL.md=E3=80=81=E4=BB=8E=E6=9C=AC=E6=9C=BA?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9=E5=AE=89=E8=A3=85=E5=B9=B6=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E6=9D=A5=E6=BA=90=EF=BC=8C=E6=9D=A5=E6=BA=90=E6=9C=89?= =?UTF-8?q?=E5=8F=98=E5=8C=96=E6=97=B6=E5=8F=AF=E9=87=8D=E6=96=B0=E5=AE=89?= =?UTF-8?q?=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 11 +- rust/crates/agent-runtime/src/lib.rs | 5 + rust/crates/agent-runtime/src/library.rs | 515 +++---- .../agent-runtime/src/library/backups.rs | 122 +- .../crates/agent-runtime/src/library/found.rs | 22 +- .../agent-runtime/src/library/instructions.rs | 3 +- .../agent-runtime/src/library/providers.rs | 1 + .../agent-runtime/src/library/skills.rs | 1309 +++++++++++++++++ .../crates/agent-runtime/src/tests/library.rs | 1 + .../src/tests/library/backups.rs | 13 +- .../src/tests/library/servers.rs | 24 + .../agent-runtime/src/tests/library/skills.rs | 807 ++++++++++ rust/crates/core/src/protocol/command.rs | 28 + .../diagnostics/src/catalog_generated.rs | 70 +- rust/logging/events/agent.json | 117 +- shared/plugins/contract/v1/README.md | 226 ++- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 36 +- .../plugins/reference/protocol-changelog.md | 1 + 20 files changed, 2941 insertions(+), 378 deletions(-) create mode 100644 rust/crates/agent-runtime/src/library/skills.rs create mode 100644 rust/crates/agent-runtime/src/tests/library/skills.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 1d46e702..f762c9c9 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -504,12 +504,17 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.export` | Export a recorded session as Markdown of at most `maxBytes`: messages, replies, one line per tool call and their times, keeping the start or the end, in words the host passes in `labels` | | `agentSessions.subagents` | List a recorded session's subagents, as the plugin's scan reports them, with their calls and each one's usage; empty when the plugin reports none | | `agentLibrary.configure` | Open the agent library in the platform's application data | -| `agentLibrary.read` | Read the library `directory`, the library and what each configurable agent's instructions, skills, MCP servers and hooks hold, with the agent's `backup: {savedAtMs, modifiedSince}` while Core keeps one and its `mcpServerSupport` (the transports and server fields its plugin declares); MCP server variables and headers are `{name, valueSet}`, never a value; each server's state per agent compares what a put writes, and `stateDetails` gives the reason an item cannot be put and the server fields the agent does not keep; `found` groups the servers, hooks and skills agents hold outside the library, marking distinct copies, differences from the library and whether and from which agent each group can be imported; an agent's `instructions` is `{path, state, ownLines?}`, `state` comparing Lithe's block in the file with the library (`absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge`, `unreadable`) and `ownLines` counting the user's own lines outside it; a library saved with `active` reads as that set `on`; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | +| `agentLibrary.read` | Read the library `directory`, the library, its skills with the `source` of each one copied in from a folder (`{path, installedAtMs}`), and what each configurable agent's instructions, skills, MCP servers and hooks hold, with the agent's `backup: {savedAtMs, modifiedSince}` while Core keeps one and its `mcpServerSupport` (the transports and server fields its plugin declares); MCP server variables and headers are `{name, valueSet}`, never a value; each server's state per agent compares what a put writes, and `stateDetails` gives the reason an item cannot be put and the server fields the agent does not keep; `found` groups the servers, hooks and skills agents hold outside the library, marking distinct copies, differences from the library and whether and from which agent each group can be imported; an agent's `instructions` is `{path, state, ownLines?}`, `state` comparing Lithe's block in the file with the library (`absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge`, `unreadable`) and `ownLines` counting the user's own lines outside it; a library saved with `active` reads as that set `on`; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | | `agentLibrary.save` | Replace the library the user edited if it is still at the revision read (instruction sets each with `on` and `agents`; `active` is refused; a server variable without a value keeps the value the library has, a renamed server naming its old name in `renamedFrom`), writing `library.json` owner-only, then write Lithe's block in the instruction file of every agent that follows the library, never over a block edited outside Lithe, and answer each agent's `written`, `unchanged`, `skipped` or `failed` with its reason in `instructions` | | `agentLibrary.parseServers` | Read the MCP servers a pasted JSON text describes (common client shapes, comments and trailing commas allowed) into the shape `save` takes, values included, without saving; answer `{servers, problems}`, a syntax error with its line and character column and each unreadable entry with its JSON pointer and reason | | `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration, backing up the configuration or instruction file it replaces first; a server `put` writes only the fields the agent's plugin declares, values included, and is refused for a transport, variables or a switched-off server the agent cannot keep; a server `import` takes the agent's server with its values into the library at the revision read without changing the agent, answering `{changed, revision}`; an instruction `write` changes only Lithe's block and needs `replace` over an edited one, and `import` moves the user's own text outside the block into a new or existing set at the library revision read, leaving only the block, and answers `{changed, revision, instructions}` | -| `agentLibrary.importSkill` | Copy a skill from an agent or a directory the user chose into the library | -| `agentLibrary.removeSkill` | Remove a library skill and its links from agents | +| `agentLibrary.createSkill` | Make a library skill whose `SKILL.md` holds front matter with the `name` and one-line `description` given, then `body` or a heading of the name; refuses, ignoring case, a name a library skill holds (`skillExists`) or another entry of the skills folder holds (`skillNameTaken`), and a full library; answers `{name, revision}` | +| `agentLibrary.readSkill` | Read a library skill's `SKILL.md` whole (at most 64 KiB, UTF-8) with its `revision`, the SHA-256 of the file, and list the skill's other regular files by `path` and `size` without reading them | +| `agentLibrary.writeSkill` | Replace a library skill's `SKILL.md` with the whole text the user edited if the file is still at the `revision` read, after checking its front matter (`name` the skill's, nonblank `description` of at most 1024 characters), backing the file up first; answers `{changed, revision}` | +| `agentLibrary.importSkill` | Copy a skill from an agent or a folder the user chose into the library without following any link, leaving `.git` and `.DS_Store` behind and refusing special files, under the names `createSkill` takes; a folder is recorded as the skill's source with the time and the digest of what was copied | +| `agentLibrary.checkSkillSources` | For each library skill copied in from a folder, or those `names` lists, compare the folder with what was copied (`unchanged`, `changed`, or `unavailable` with the refusal a reinstall would give) and say whether the library's copy was `edited` since; reads every file of each folder, never the network | +| `agentLibrary.reinstallSkill` | Copy a library skill again from the folder it was installed from, keeping the version it replaces with the skill's backups and putting it back when the new one cannot take its place; a copy edited in the library since needs `discardEdits` | +| `agentLibrary.removeSkill` | Remove a library skill and its links from agents, with its source record and backups | | `agentProviders.read` | Read each agent's model, model providers, profiles and account label through its plugin, with a key reported only as `keySet` and other secrets as variable names; adds the providers Lithe saved (`listKeptBy: "lithe"`) and the agent's `backup: {savedAtMs, modifiedSince}`; always answers `models`, the models the plugin lists (none when it lists none), each with `shown`, beside the `efforts`, `speeds`, `effort` and `speed` it reports | | `agentProviders.apply` | Apply one model, provider or profile change the plugin declares, through a checked staged copy of the agent's file backed up first; `addProvider`/`updateProvider` may carry a write-only `key` (or `clearKey`), handed only to the plugin's `edit`; `setModel` (which may carry `effort` and `speed`), `setEffort` and `setSpeed` are refused with `unknownModel`, `unknownEffort`, `unknownSpeed` or `unsupportedCombination` when the listed models do not take them, and `setModelMenu` is Core's own | | `agentProviders.restore` | Put every file of any configurable agent, with or without providers, back as it was before Lithe's first change since the last restore, whether `agentProviders.apply` or `agentLibrary.apply` changed it, and forget what Core last wrote to a restored instruction file and stop the agent following the library's instructions (`unfollowed`); refused when a file changed after Lithe's last write unless `discardLaterChanges` | diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index f54d5d20..64bf4d65 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -134,7 +134,12 @@ impl Runtime { "agentLibrary.save" => self.library.save(self, payload), "agentLibrary.parseServers" => self.library.parse_servers(payload), "agentLibrary.apply" => self.library.apply(self, payload), + "agentLibrary.createSkill" => self.library.create_skill(payload), + "agentLibrary.readSkill" => self.library.read_skill(payload), + "agentLibrary.writeSkill" => self.library.write_skill(payload), "agentLibrary.importSkill" => self.library.import_skill(self, payload), + "agentLibrary.checkSkillSources" => self.library.check_skill_sources(payload), + "agentLibrary.reinstallSkill" => self.library.reinstall_skill(payload), "agentLibrary.removeSkill" => self.library.remove_skill(self, payload), "agentProviders.read" => self.library.read_providers(self, payload), "agentProviders.apply" => self.library.apply_providers(self, payload), diff --git a/rust/crates/agent-runtime/src/library.rs b/rust/crates/agent-runtime/src/library.rs index 09788e42..664e0b6a 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -6,10 +6,15 @@ //! `library.json`, owner-only, holds the servers with the values of their //! environment variables and headers (`servers` module), the hooks and the //! instruction sets, -//! `skills//` holds one directory per skill, `state.json` records what +//! `skills//` holds one directory per skill, `sources.json`, +//! owner-only, the folder each skill copied in from this machine came +//! from, when, and the digest of what was copied (`skills` module), written +//! when such a skill is installed or reinstalled and dropped with the skill, +//! `state.json` records what //! Core last wrote to each agent's instruction file, `staging/` holds the -//! copies plugins edit, `backups/` the agents' files as they were before -//! Lithe changed them (`backups` module), `saved-providers.json` the +//! copies plugins edit and the skills being copied in, `backups/` the +//! agents' files as they were before Lithe changed them and the versions of +//! a skill Lithe replaced (`backups` module), `saved-providers.json` the //! providers Lithe keeps for an agent whose CLI holds one endpoint, and //! `models.json` the models the user hid from Lithe's pickers //! (`providers` module). @@ -44,6 +49,10 @@ //! replaces nothing. A restore puts the agent's files back whichever kind of //! change wrote them. //! +//! The library's own skills are made, edited, copied in from a folder and +//! installed again from it by the `skills` module; Core changes no file of +//! a skill outside the library for that. +//! //! `agentLibrary.read` also answers, for the host to show without rules of //! its own, why a server cannot be put into an agent and which of its //! fields the agent does not keep, and the items agents hold that the @@ -60,6 +69,7 @@ mod paste; mod providers; mod saved; mod servers; +mod skills; #[cfg(test)] pub(crate) use providers::is_endpoint_for_test; @@ -774,12 +784,21 @@ enum Leftover { Temporary, /// A staged copy of an agent's configuration file. Staging, - /// A skill directory copied in part before its import failed. + /// A skill directory copied in part before its import failed, or one + /// made or copied whole that did not go into the library. SkillImport, /// A backup baseline or history entry. Backup, /// The backup record, not put back after a failure. BackupRecord, + /// The backups of a skill removed from the library, or the version a + /// reinstall replaced before the one before it. + SkillBackup, + /// The source record of a skill removed from the library. + SkillSource, + /// The version of a skill a reinstall replaced, not put back after the + /// new version could not go into the library. + SkillReplaced, } impl Leftover { @@ -790,8 +809,19 @@ impl Leftover { Leftover::SkillImport => "skillImport", Leftover::Backup => "backup", Leftover::BackupRecord => "backupRecord", + Leftover::SkillBackup => "skillBackup", + Leftover::SkillSource => "skillSource", + Leftover::SkillReplaced => "skillReplaced", } } + + /// Whether what stays behind is a directory. + fn directory(self) -> bool { + matches!( + self, + Leftover::SkillImport | Leftover::SkillBackup | Leftover::SkillReplaced + ) + } } /// Logs that `leftover` stays behind because of `error`. What stays may @@ -810,11 +840,11 @@ fn leftover_kept(leftover: Leftover, error: &io::Error) { } /// Removes `path`, a file the library no longer needs, or a directory for -/// a [`Leftover::SkillImport`]. Nothing at `path` is what removing wants; -/// any other failure leaves it there and is logged, since it is a fact no -/// other record holds. +/// a leftover that is one ([`Leftover::directory`]). Nothing at `path` is +/// what removing wants; any other failure leaves it there and is logged, +/// since it is a fact no other record holds. fn remove_leftover(path: &Path, leftover: Leftover) { - let removed = if leftover == Leftover::SkillImport { + let removed = if leftover.directory() { fs::remove_dir_all(path) } else { fs::remove_file(path) @@ -873,8 +903,37 @@ fn links_into(link: &Path, directory: &Path) -> bool { // Skills. /// A skill's `name` and `description` from the YAML front matter of its -/// `SKILL.md`. Only plain, quoted and block scalars are read. +/// `SKILL.md`, the description cut to [`MAX_DESCRIPTION_CHARS`]. Only plain, +/// quoted and block scalars are read, without the comments YAML leaves out +/// ([`scalar`]); front matter without its closing line is read to the end +/// of the text. fn front_matter(text: &str) -> (Option, Option) { + let fields = parse_front_matter(text); + let description = fields + .description + .map(|text| text.chars().take(MAX_DESCRIPTION_CHARS).collect()); + (fields.name, description) +} + +/// The fields of a `SKILL.md`'s front matter Core reads. +#[derive(Debug, Default)] +struct FrontMatter { + name: Option, + /// Whole, never cut. + description: Option, + /// Whether a `---` line closes the front matter. + closed: bool, +} + +/// The front matter of a `SKILL.md` as a write must give it: opened and +/// closed by `---` lines; `None` without both. +fn front_matter_fields(text: &str) -> Option { + let fields = parse_front_matter(text); + fields.closed.then_some(fields) +} + +/// Reads `name` and `description` from the front matter that opens `text`. +fn parse_front_matter(text: &str) -> FrontMatter { /// A block scalar being read: its key, whether it folds its lines, and /// the lines so far. type Block = (&'static str, bool, Vec); @@ -892,12 +951,14 @@ fn front_matter(text: &str) -> (Option, Option) { let mut lines = text.lines(); if lines.next().map(str::trim_end) != Some("---") { - return (None, None); + return FrontMatter::default(); } let mut values: BTreeMap<&'static str, String> = BTreeMap::new(); let mut block: Option = None; + let mut closed = false; for line in lines { if line.trim_end() == "---" { + closed = true; break; } let indented = line.starts_with(' ') || line.starts_with('\t'); @@ -923,33 +984,92 @@ fn front_matter(text: &str) -> (Option, Option) { if value.starts_with('|') || value.starts_with('>') { block = Some((key, value.starts_with('>'), Vec::new())); } else { - values.insert(key, unquote(value)); + values.insert(key, scalar(value)); } } finish(&mut values, block.take()); let mut take = |key| values.remove(key).filter(|value| !value.is_empty()); - let name = take("name"); - let description = - take("description").map(|text| text.chars().take(MAX_DESCRIPTION_CHARS).collect()); - (name, description) -} - -fn unquote(value: &str) -> String { - let bytes = value.as_bytes(); - if bytes.len() >= 2 { - let (first, last) = (bytes[0], bytes[bytes.len() - 1]); - if first == last && (first == b'"' || first == b'\'') { - let inner = &value[1..value.len() - 1]; - return if first == b'"' { - inner.replace("\\\"", "\"") - } else { - inner.replace("''", "'") - }; + FrontMatter { + name: take("name"), + description: take("description"), + closed, + } +} + +/// A one-line YAML scalar as YAML reads it. A quoted scalar is its text +/// between the quotes, `#` and all, and may be followed by a comment; a +/// plain scalar ends where a comment starts, at a `#` that opens the value +/// or follows a space or tab. Quotes that do not close the value leave it +/// as written. +fn scalar(value: &str) -> String { + let quoted = match value.chars().next() { + Some('\'') => single_quoted(&value[1..]), + Some('"') => double_quoted(&value[1..]), + _ => return plain_scalar(value), + }; + quoted.unwrap_or_else(|| value.to_string()) +} + +/// A plain scalar without the comment after it. +fn plain_scalar(value: &str) -> String { + let mut blank = true; + for (index, character) in value.char_indices() { + if character == '#' && blank { + return value[..index].trim_end().to_string(); } + blank = character == ' ' || character == '\t'; } value.to_string() } +/// Whether what follows a closing quote is nothing or a comment. +fn ends_scalar(rest: &str) -> bool { + let trimmed = rest.trim_start_matches([' ', '\t']); + trimmed.is_empty() || (trimmed.len() < rest.len() && trimmed.starts_with('#')) +} + +/// The text of a single-quoted scalar after its opening quote, where `''` +/// is one quote; `None` when it does not close or more than a comment +/// follows. +fn single_quoted(rest: &str) -> Option { + let mut text = String::new(); + let mut characters = rest.char_indices().peekable(); + while let Some((index, character)) = characters.next() { + if character != '\'' { + text.push(character); + } else if characters.next_if(|(_, next)| *next == '\'').is_some() { + text.push('\''); + } else { + return ends_scalar(&rest[index + 1..]).then_some(text); + } + } + None +} + +/// The text of a double-quoted scalar after its opening quote, with the +/// escapes `\\`, `\"`, `\/`, `\t` and `\n` read and any other kept as +/// written; `None` when it does not close or more than a comment follows. +fn double_quoted(rest: &str) -> Option { + let mut text = String::new(); + let mut characters = rest.char_indices(); + while let Some((index, character)) = characters.next() { + match character { + '"' => return ends_scalar(&rest[index + 1..]).then_some(text), + '\\' => match characters.next()?.1 { + escaped @ ('\\' | '"' | '/') => text.push(escaped), + 't' => text.push('\t'), + 'n' => text.push('\n'), + other => { + text.push('\\'); + text.push(other); + } + }, + _ => text.push(character), + } + } + None +} + /// What Core reads of a skill directory's `SKILL.md`. struct SkillFile { description: Option, @@ -977,12 +1097,6 @@ fn skill_file(directory: &Path) -> Option { }) } -/// The description in the `SKILL.md` of `directory`, if it has one; `None` -/// as the outer value when there is no readable `SKILL.md`. -fn skill_description(directory: &Path) -> Option> { - skill_file(directory).map(|file| file.description) -} - /// A skill of the library. struct LibrarySkill { name: String, @@ -991,20 +1105,27 @@ struct LibrarySkill { digest: Option, } -/// The skills of the library, by name. +/// The skills of the library, by name: each directory of `skills/`, not a +/// link, whose name is a skill name and whose `SKILL.md` Core can open. Of +/// more than [`MAX_SKILLS`], the first by name, so every read lists the +/// same ones. fn library_skills(directory: &Path) -> Vec { let Ok(entries) = fs::read_dir(directory.join(SKILLS_DIRECTORY)) else { return Vec::new(); }; - let mut skills: Vec = entries + let mut candidates: Vec<(String, PathBuf)> = entries .filter_map(Result::ok) .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) .filter_map(|entry| { let name = entry.file_name().into_string().ok()?; - if !is_skill_name(&name) { - return None; - } - let file = skill_file(&entry.path())?; + is_skill_name(&name).then(|| (name, entry.path())) + }) + .collect(); + candidates.sort_by(|left, right| left.0.cmp(&right.0)); + candidates + .into_iter() + .filter_map(|(name, path)| { + let file = skill_file(&path)?; Some(LibrarySkill { name, description: file.description, @@ -1012,9 +1133,19 @@ fn library_skills(directory: &Path) -> Vec { }) }) .take(MAX_SKILLS) - .collect(); - skills.sort_by(|left, right| left.name.cmp(&right.name)); - skills + .collect() +} + +/// The name of every entry of the library's `skills/` that is UTF-8, +/// whatever it is: the names a new skill must not take. +fn skill_entry_names(directory: &Path) -> Vec { + let Ok(entries) = fs::read_dir(directory.join(SKILLS_DIRECTORY)) else { + return Vec::new(); + }; + entries + .filter_map(Result::ok) + .filter_map(|entry| entry.file_name().into_string().ok()) + .collect() } /// What one entry of an agent's skills directory is. @@ -1054,18 +1185,21 @@ fn agent_skills(root: &Path, library: &Path) -> Result, ReadFail Err(_) => return Err(ReadFailure::Io), }; let library_skills = library.join(SKILLS_DIRECTORY); + let mut candidates: Vec<(String, PathBuf, fs::FileType)> = entries + .filter_map(Result::ok) + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + if name.starts_with('.') || check_name(&name, "").is_err() { + return None; + } + Some((name, entry.path(), entry.file_type().ok()?)) + }) + .collect(); + // Of more than MAX_SKILLS, the first by name, so every read lists the + // same ones. + candidates.sort_by(|left, right| left.0.cmp(&right.0)); let mut skills = Vec::new(); - for entry in entries.filter_map(Result::ok) { - let Ok(name) = entry.file_name().into_string() else { - continue; - }; - if name.starts_with('.') || check_name(&name, "").is_err() { - continue; - } - let path = entry.path(); - let Ok(kind) = entry.file_type() else { - continue; - }; + for (name, path, kind) in candidates { let kind = if kind.is_symlink() { if links_into(&path, &library_skills) { SkillKind::Library @@ -1090,50 +1224,9 @@ fn agent_skills(root: &Path, library: &Path) -> Result, ReadFail break; } } - skills.sort_by(|left, right| left.name.cmp(&right.name)); Ok(skills) } -/// Counts of a tree copy. -#[derive(Default)] -struct Copied { - files: usize, - bytes: u64, - skipped: usize, -} - -/// Copies the regular files and directories of `from` into the new directory -/// `to`, skipping links and other entries, within the import bounds. -fn copy_tree(from: &Path, to: &Path, depth: usize, copied: &mut Copied) -> Result<(), CoreError> { - if depth > MAX_IMPORT_DEPTH { - return Err(too_large_skill()); - } - fs::create_dir(to).map_err(|_| write_failed())?; - let entries = fs::read_dir(from).map_err(|_| unreadable_file())?; - for entry in entries { - let entry = entry.map_err(|_| unreadable_file())?; - let kind = entry.file_type().map_err(|_| unreadable_file())?; - let target = to.join(entry.file_name()); - if kind.is_dir() { - copy_tree(&entry.path(), &target, depth + 1, copied)?; - } else if kind.is_file() { - copied.files += 1; - if copied.files > MAX_IMPORT_FILES { - return Err(too_large_skill()); - } - let length = entry.metadata().map_err(|_| unreadable_file())?.len(); - copied.bytes += length; - if copied.bytes > MAX_IMPORT_BYTES { - return Err(too_large_skill()); - } - fs::copy(entry.path(), &target).map_err(|_| write_failed())?; - } else { - copied.skipped += 1; - } - } - Ok(()) -} - // --------------------------------------------------------------------------- // Refusals. @@ -1173,14 +1266,6 @@ fn too_large_file() -> CoreError { ) } -fn too_large_skill() -> CoreError { - refusal( - ErrorCode::InvalidRequest, - "agentLibrary.skillTooLarge", - "The skill has more files, bytes or levels than Lithe copies.", - ) -} - fn read_failure(failure: ReadFailure) -> CoreError { match failure { ReadFailure::TooLarge => too_large_file(), @@ -1188,6 +1273,14 @@ fn read_failure(failure: ReadFailure) -> CoreError { } } +fn no_skills() -> CoreError { + refusal( + ErrorCode::NotSupported, + "agentLibrary.noSkills", + "The agent keeps no skills directory.", + ) +} + fn backend_unavailable() -> CoreError { refusal( ErrorCode::InvalidRequest, @@ -1727,6 +1820,7 @@ impl Library { let (library, revision) = self.load(&config)?; let state = Self::load_state(&config); let skills = library_skills(&config.directory); + let sources = skills::source_answers(&config); let mut failed = 0u64; let views: Vec = runtime .catalog @@ -1812,6 +1906,9 @@ impl Library { if let Some(description) = &kept.description { row["description"] = json!(description); } + if let Some(source) = sources.get(&kept.name) { + row["source"] = source.clone(); + } row }) .collect(); @@ -1874,7 +1971,12 @@ impl Library { "skills": matching(&request, skills), }) }); - let found = found::found(&library, &skills, &views); + let found = found::found( + &library, + &skills, + &skill_entry_names(&config.directory), + &views, + ); let mut answer = json!({ "directory": path_text(&config.directory), "revision": revision, @@ -2428,6 +2530,7 @@ impl Library { config, &target_path, (&agent_key, &backup_id), + backups::BackupFailed::library, edit_file, shows_change, ) @@ -2440,12 +2543,14 @@ impl Library { /// The staged copy is removed whatever happens. Before the file is /// replaced its bytes are backed up under `backup` (the agent's record /// key and the file's backup ID), and the change fails, unwritten, if - /// they cannot be. Answers whether the file changed. + /// they cannot be, with the refusal `backup_failed` gives in the + /// command's own domain. Answers whether the file changed. fn edit_staged( &self, config: &Config, target: &Path, backup: (&str, &str), + backup_failed: fn(backups::BackupFailed) -> CoreError, edit: impl FnOnce(&Path, bool) -> Result, shows_change: impl FnOnce(&Path) -> Result<(), CoreError>, ) -> Result { @@ -2474,7 +2579,8 @@ impl Library { )); } let (agent, file) = backup; - let taken = backups::take(config, agent, file, now.as_deref(), &edited)?; + let taken = backups::take(config, agent, file, now.as_deref(), &edited) + .map_err(backup_failed)?; let written = real .parent() .map_or(Ok(()), ensure_directory) @@ -2531,11 +2637,7 @@ impl Library { name: &str, ) -> Result { let Some(root) = &paths.skills else { - return Err(refusal( - ErrorCode::NotSupported, - "agentLibrary.noSkills", - "The agent keeps no skills directory.", - )); + return Err(no_skills()); }; let library_skills = config.directory.join(SKILLS_DIRECTORY); let skill = library_skills.join(name); @@ -2588,192 +2690,6 @@ impl Library { }, } } - - /// `agentLibrary.importSkill`: copies a skill into the library, from an - /// agent's skills directory or from a directory the user chose. - pub fn import_skill(&self, runtime: &Runtime, payload: Value) -> Result { - #[derive(Deserialize)] - #[serde(rename_all = "camelCase", deny_unknown_fields)] - struct ImportRequest { - #[serde(default)] - agent: Option, - #[serde(default)] - name: Option, - #[serde(default)] - directory: Option, - } - require_user()?; - let request: ImportRequest = crate::decode(payload)?; - let config = self.config()?; - let source = match (&request.agent, &request.name, &request.directory) { - (Some(agent), Some(name), None) => { - let agent = configurable_agent(runtime, agent)?; - let configuration = agent - .agent - .configuration - .as_ref() - .expect("configurable agents declare configuration"); - let root = agent_paths(&config, configuration).skills.ok_or_else(|| { - refusal( - ErrorCode::NotSupported, - "agentLibrary.noSkills", - "The agent keeps no skills directory.", - ) - })?; - if !is_skill_name(name) { - return Err(invalid_skill_name()); - } - let source = root.join(name); - if fs::symlink_metadata(&source).is_ok_and(|m| m.file_type().is_symlink()) { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentLibrary.notOwnSkill", - "Only a skill directory of the agent's own is imported.", - )); - } - source - } - (None, None, Some(directory)) => { - let directory = PathBuf::from(directory); - if !directory.is_absolute() { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentLibrary.invalidSkillDirectory", - "The skill directory must be an absolute path.", - )); - } - directory - } - _ => { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentLibrary.invalidImport", - "A skill is imported from an agent and a name, or from a directory.", - )) - } - }; - if skill_description(&source).is_none() { - return Err(refusal( - ErrorCode::EntryNotFound, - "agentLibrary.notSkill", - "The directory has no readable SKILL.md.", - )); - } - let name = match request.name { - Some(name) => name, - None => { - let bytes = read_bounded(&source.join(SKILL_FILE), MAX_SKILL_FILE_BYTES) - .ok() - .flatten() - .unwrap_or_default(); - front_matter(&String::from_utf8_lossy(&bytes)) - .0 - .or_else(|| { - source - .file_name() - .and_then(|name| name.to_str()) - .map(str::to_string) - }) - .unwrap_or_default() - } - }; - if !is_skill_name(&name) { - return Err(invalid_skill_name()); - } - - let skills = config.directory.join(SKILLS_DIRECTORY); - let destination = skills.join(&name); - if fs::symlink_metadata(&destination).is_ok() { - return Err(refusal( - ErrorCode::EntryExists, - "agentLibrary.skillExists", - "The library already has a skill of this name.", - )); - } - ensure_private_directory(&config.directory)?; - ensure_private_directory(&config.directory.join(STAGING_DIRECTORY))?; - ensure_directory(&skills)?; - let partial = sibling_temporary( - &config.directory.join(STAGING_DIRECTORY).join(&name), - "import", - ) - .ok_or_else(write_failed)?; - let mut copied = Copied::default(); - let outcome = copy_tree(&source, &partial, 0, &mut copied).and_then(|()| { - let _writing = self.lock_writing(); - lithe_platform::entries::rename_no_replace(&partial, &destination).map_err(|error| { - if error.kind() == io::ErrorKind::AlreadyExists { - refusal( - ErrorCode::EntryExists, - "agentLibrary.skillExists", - "The library already has a skill of this name.", - ) - } else { - write_failed() - } - }) - }); - if outcome.is_err() { - remove_leftover(&partial, Leftover::SkillImport); - } - outcome?; - log( - "agent.library.skill_import_finished", - [ - ("files", json!(copied.files)), - ("skipped", json!(copied.skipped)), - ], - ); - Ok(json!({ "name": name, "files": copied.files, "skipped": copied.skipped })) - } - - /// `agentLibrary.removeSkill`: removes a library skill and every link to - /// it in the agents' skills directories. - pub fn remove_skill(&self, runtime: &Runtime, payload: Value) -> Result { - #[derive(Deserialize)] - #[serde(rename_all = "camelCase", deny_unknown_fields)] - struct RemoveRequest { - name: String, - } - require_user()?; - let request: RemoveRequest = crate::decode(payload)?; - let config = self.config()?; - if !is_skill_name(&request.name) { - return Err(invalid_skill_name()); - } - let skill = config.directory.join(SKILLS_DIRECTORY).join(&request.name); - if !skill.is_dir() { - return Err(unknown_item()); - } - let mut unlinked = 0u64; - let _writing = self.lock_writing(); - for agent in runtime.catalog.configurable() { - if !agent.may_configure { - continue; - } - let configuration = agent - .agent - .configuration - .as_ref() - .expect("configurable agents declare configuration"); - let Some(root) = agent_paths(&config, configuration).skills else { - continue; - }; - let link = root.join(&request.name); - if fs::symlink_metadata(&link).is_ok_and(|m| m.file_type().is_symlink()) - && links_into(&link, &skill) - { - remove_link(&link).map_err(|_| write_failed())?; - unlinked += 1; - } - } - fs::remove_dir_all(&skill).map_err(|_| write_failed())?; - log( - "agent.library.skill_removed", - [("unlinked", json!(unlinked))], - ); - Ok(json!({ "unlinked": unlinked })) - } } fn unknown_item() -> CoreError { @@ -2796,7 +2712,7 @@ fn invalid_skill_name() -> CoreError { refusal( ErrorCode::InvalidRequest, "agentLibrary.invalidSkillName", - "A skill name uses ASCII letters, digits, `.`, `_` and `-`.", + "A skill name is 1 to 64 ASCII letters, digits, `.`, `_` and `-`, not starting with `.`; a new one also does not end with `.` and is no Windows device name.", ) } @@ -2850,6 +2766,9 @@ pub(crate) fn front_matter_for_test(text: &str) -> (Option, Option/backups//record.json what Core keeps per file //! /backups//baseline/ the bytes before Lithe's first change //! /backups//history/ the bytes before each later change +//! /backups//... the same for a library skill's SKILL.md +//! /backups//replaced/ the skill directory the last reinstall replaced //! ``` //! //! `` and `` are digests of the agent's record key and the //! file's backup ID (`AgentPaths::backup_id`), so no name a plugin chose -//! becomes a path. +//! becomes a path. `` is the digest of [`skill_key`], which holds a +//! `:` that no agent key holds, so a skill and an agent never share one. +//! A skill's backups go with the skill when it is removed. //! //! - One file has one backup ID, whichever kind of change reaches it, so it //! has one baseline: the file as it was before Lithe's first change since @@ -38,8 +43,9 @@ use super::{ agent_paths, configurable_agent, digest, ensure_private_directory, leftover_kept, read_bounded, - real_file, refusal, remove_leftover, require_user, write_replacing, Config, Leftover, Library, - INSTRUCTIONS_BACKUP_ID, MAX_CONFIGURATION_FILE_BYTES, MAX_LIBRARY_FILE_BYTES, + real_file, refusal, remove_leftover, require_user, write_failed, write_replacing, Config, + Leftover, Library, INSTRUCTIONS_BACKUP_ID, MAX_CONFIGURATION_FILE_BYTES, + MAX_LIBRARY_FILE_BYTES, }; use crate::{log, Runtime}; use lithe_protocol::{CoreError, ErrorCode}; @@ -53,6 +59,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Instant; const BACKUPS_DIRECTORY: &str = "backups"; +/// The skill directory a reinstall replaced, in the skill's backups. +const REPLACED_DIRECTORY: &str = "replaced"; const RECORD_FILE: &str = "record.json"; const BASELINE_DIRECTORY: &str = "baseline"; const HISTORY_DIRECTORY: &str = "history"; @@ -114,13 +122,31 @@ pub(super) struct Taken { history: PathBuf, } -/// The refusal when a backup cannot be kept; the file is then not written. -pub(super) fn backup_failed() -> CoreError { - refusal( - ErrorCode::PermissionDenied, - "agentProviders.backupFailed", - "The configuration file could not be backed up, so it was not changed.", - ) +/// A backup that could not be kept; the file is then not written. The +/// command that wanted it refuses in its own domain. +#[derive(Debug)] +pub(super) struct BackupFailed; + +impl BackupFailed { + /// The refusal of an `agentLibrary.*` command: + /// `agentLibrary.backupFailed`. + pub(super) fn library(self) -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentLibrary.backupFailed", + "The file could not be backed up, so it was not changed.", + ) + } + + /// The refusal of an `agentProviders.*` command: + /// `agentProviders.backupFailed`. + pub(super) fn providers(self) -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentProviders.backupFailed", + "The configuration file could not be backed up, so it was not changed.", + ) + } } fn restore_failed() -> CoreError { @@ -180,8 +206,8 @@ fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> { } /// Creates the agent's backup directories owner-only. -fn prepare(config: &Config, directory: &Path) -> Result<(), CoreError> { - let map = |_| backup_failed(); +fn prepare(config: &Config, directory: &Path) -> Result<(), BackupFailed> { + let map = |_| BackupFailed; ensure_private_directory(&config.directory).map_err(map)?; ensure_private_directory(&config.directory.join(BACKUPS_DIRECTORY)).map_err(map)?; ensure_private_directory(directory).map_err(map)?; @@ -244,7 +270,7 @@ pub(super) fn take( file_id: &str, original: Option<&[u8]>, edited: &[u8], -) -> Result { +) -> Result { let directory = agent_directory(config, agent_key); prepare(config, &directory)?; let previous = load(&directory); @@ -256,7 +282,7 @@ pub(super) fn take( // stay, writing the new one fails, and the backup with it. remove_leftover(&path, Leftover::Backup); if let Some(bytes) = original { - write_private(&path, bytes).map_err(|_| backup_failed())?; + write_private(&path, bytes).map_err(|_| BackupFailed)?; baseline = Some(path); } record.files.insert( @@ -277,7 +303,7 @@ pub(super) fn take( Ok(path) => path, Err(_) => { undo_baseline(&baseline); - return Err(backup_failed()); + return Err(BackupFailed); } }; if let Some(file) = record.files.get_mut(file_id) { @@ -286,7 +312,7 @@ pub(super) fn take( if store(&directory, &record).is_err() { undo_baseline(&baseline); remove_leftover(&history, Leftover::Backup); - return Err(backup_failed()); + return Err(BackupFailed); } Ok(Taken { directory, @@ -439,6 +465,68 @@ pub(super) fn restore_error(refusal_kind: &RestoreRefusal) -> CoreError { } } +// --------------------------------------------------------------------------- +// Library skills. + +/// The key a library skill's backups are kept under, as an agent's are +/// under its record key. +pub(super) fn skill_key(name: &str) -> String { + format!("lithe:skill:{name}") +} + +/// Puts the new version `fresh` of the library skill `name` in place of the +/// directory `current`, which goes into the skill's backups as the version +/// replaced, over the one an earlier reinstall left there. When `current` +/// cannot go there nothing changes (`agentLibrary.backupFailed`); when +/// `fresh` cannot then take its place, `current` is put back +/// (`agentLibrary.writeFailed`). +pub(super) fn replace_skill( + config: &Config, + name: &str, + current: &Path, + fresh: &Path, +) -> Result<(), CoreError> { + let directory = agent_directory(config, &skill_key(name)); + let map = |_| BackupFailed.library(); + ensure_private_directory(&config.directory).map_err(map)?; + ensure_private_directory(&config.directory.join(BACKUPS_DIRECTORY)).map_err(map)?; + ensure_private_directory(&directory).map_err(map)?; + let replaced = directory.join(REPLACED_DIRECTORY); + // Should the older version stay, the rename below fails, and the + // reinstall with it. + remove_leftover(&replaced, Leftover::SkillBackup); + fs::rename(current, &replaced).map_err(|_| BackupFailed.library())?; + if lithe_platform::entries::rename_no_replace(fresh, current).is_err() { + if let Err(error) = fs::rename(&replaced, current) { + leftover_kept(Leftover::SkillReplaced, &error); + } + return Err(write_failed()); + } + Ok(()) +} + +/// Undoes a [`replace_skill`] whose record could not be written: the new +/// version goes back to `fresh` and the replaced one back to `current`. +pub(super) fn put_back_skill(config: &Config, name: &str, current: &Path, fresh: &Path) { + let replaced = agent_directory(config, &skill_key(name)).join(REPLACED_DIRECTORY); + if let Err(error) = fs::rename(current, fresh) { + leftover_kept(Leftover::SkillImport, &error); + return; + } + if let Err(error) = fs::rename(&replaced, current) { + leftover_kept(Leftover::SkillReplaced, &error); + } +} + +/// Removes every backup of the library skill `name`, once the skill is +/// gone. +pub(super) fn forget_skill(config: &Config, name: &str) { + remove_leftover( + &agent_directory(config, &skill_key(name)), + Leftover::SkillBackup, + ); +} + // --------------------------------------------------------------------------- // Command. diff --git a/rust/crates/agent-runtime/src/library/found.rs b/rust/crates/agent-runtime/src/library/found.rs index 3a2b113d..9df07916 100644 --- a/rust/crates/agent-runtime/src/library/found.rs +++ b/rust/crates/agent-runtime/src/library/found.rs @@ -25,6 +25,7 @@ //! that differ only in a value are two variants. use super::servers::{import_rank, in_library, AgentServer}; +use super::skills::{is_new_skill_name, no_room, NoRoom}; use super::{AgentView, LibraryData, LibrarySkill, SkillKind, MAX_HOOKS, MAX_SERVERS}; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -235,7 +236,9 @@ struct FoundSkill<'a> { own: bool, } -fn skills(library: &[LibrarySkill], views: &[AgentView]) -> Vec { +/// The skill groups; `entries` names everything in the library's +/// `skills/`, which a skill imported must not take the name of. +fn skills(library: &[LibrarySkill], entries: &[String], views: &[AgentView]) -> Vec { let mut found = Vec::new(); for view in views { for (index, skill) in view.skills.iter().flatten().enumerate() { @@ -293,10 +296,16 @@ fn skills(library: &[LibrarySkill], views: &[AgentView]) -> Vec { "variants": count, "inLibrary": kept.is_some(), }); - let from = match copies.iter().find(|found| found.own) { - _ if kept.is_some() => Err("agentLibrary.skillExists"), - Some(own) => Ok(Some(own.agent)), - None => Err("agentLibrary.notOwnSkill"), + // The refusals `importSkill` gives, as far as the groups tell. + let from = match ( + copies.iter().find(|found| found.own), + no_room(library, entries, &name), + ) { + (_, Some(held @ (NoRoom::SkillExists | NoRoom::NameTaken))) => Err(held.code()), + (None, _) => Err("agentLibrary.notOwnSkill"), + (Some(_), _) if !is_new_skill_name(&name) => Err("agentLibrary.invalidSkillName"), + (Some(_), Some(full)) => Err(full.code()), + (Some(own), None) => Ok(Some(own.agent)), }; import(&mut group, from); group @@ -309,11 +318,12 @@ fn skills(library: &[LibrarySkill], views: &[AgentView]) -> Vec { pub(super) fn found( library: &LibraryData, skills_kept: &[LibrarySkill], + skill_entries: &[String], views: &[AgentView], ) -> Value { json!({ "mcpServers": servers(library, views), "hooks": hooks(library, views), - "skills": skills(skills_kept, views), + "skills": skills(skills_kept, skill_entries, views), }) } diff --git a/rust/crates/agent-runtime/src/library/instructions.rs b/rust/crates/agent-runtime/src/library/instructions.rs index c2e688d2..8149708d 100644 --- a/rust/crates/agent-runtime/src/library/instructions.rs +++ b/rust/crates/agent-runtime/src/library/instructions.rs @@ -606,7 +606,8 @@ impl Library { backup_id, current.map(str::as_bytes), next.as_bytes(), - )?; + ) + .map_err(backups::BackupFailed::library)?; let written = real .parent() .map_or(Ok(()), ensure_directory) diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs index dca8a641..04679539 100644 --- a/rust/crates/agent-runtime/src/library/providers.rs +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -1959,6 +1959,7 @@ impl Library { config, &target_path, (&agent_key, &backup_id), + backups::BackupFailed::providers, edit_file, shows_change, ) diff --git a/rust/crates/agent-runtime/src/library/skills.rs b/rust/crates/agent-runtime/src/library/skills.rs new file mode 100644 index 00000000..425d3a39 --- /dev/null +++ b/rust/crates/agent-runtime/src/library/skills.rs @@ -0,0 +1,1309 @@ +//! The library's skills as the user makes and keeps them: a new skill, +//! its `SKILL.md` read and written whole, a skill copied in from a folder +//! of this machine or from an agent, where a copied folder came from and +//! whether it changed since, installing it again, and removing a skill. +//! +//! - A skill is a directory `skills//` of the library with a regular +//! file `SKILL.md` whose YAML front matter gives its `name` and +//! `description`. Agents get it as a link (`agentLibrary.apply`), so a +//! change here reaches every agent linked to it at once. +//! - A copy reads the source through directory handles that never follow a +//! link: links are left out, a device, socket or pipe refuses the copy, +//! and `.git` and `.DS_Store` stay behind. The copy is made in `staging/` +//! and moved into `skills/` whole, so a skill is never there in part. +//! - The digest of a skill directory covers each file a copy takes: its +//! path, whether it is executable, and its bytes. Two directories with the +//! same files have the same digest, which is how Core tells that a source +//! folder changed and that the library's copy was edited since. +//! - `sources.json` records, for each skill copied in from a folder, the +//! folder's absolute path, when the copy was made, and the digest of what +//! was copied. Core reads it for `agentLibrary.read`, writes it under the +//! writing lock, and drops a skill's entry with the skill. +//! - Before `SKILL.md` is replaced its bytes are backed up like an agent's +//! file (`backups` module), and a reinstall keeps the directory it +//! replaces with the skill's backups; a change that cannot be backed up is +//! not made, and one that cannot be written puts the old version back. +//! +//! Nothing here goes to the network. Logs carry counts, booleans and +//! refusal codes, never a skill's name, path or text. + +use super::{ + backups, digest, ensure_directory, ensure_private_directory, front_matter_fields, + invalid_skill_name, is_skill_name, library_skills, read_bounded, refusal, remove_leftover, + require_user, sibling_temporary, skill_entry_names, too_large_file, unknown_item, + unreadable_file, write_failed, write_owner_only, write_replacing, Config, Leftover, Library, + LibrarySkill, ReadFailure, MAX_DESCRIPTION_CHARS, MAX_IMPORT_BYTES, MAX_IMPORT_DEPTH, + MAX_IMPORT_FILES, MAX_LIBRARY_FILE_BYTES, MAX_SKILLS, MAX_SKILL_FILE_BYTES, SKILLS_DIRECTORY, + SKILL_FILE, STAGING_DIRECTORY, +}; +use crate::{log, Runtime}; +use lithe_platform::scoped_read::{Directory, Kind}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::ffi::{OsStr, OsString}; +use std::fs; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +/// Where each skill copied in from a folder came from. +const SOURCES_FILE: &str = "sources.json"; + +/// Entries a copy leaves behind, wherever they are in the skill: version +/// control's and Finder's, never part of a skill. +const LEFT_BEHIND: [&str; 2] = [".git", ".DS_Store"]; + +/// Most names `agentLibrary.checkSkillSources` takes. +const MAX_CHECKED: usize = MAX_SKILLS; + +// --------------------------------------------------------------------------- +// Refusals. + +fn invalid_skill_file() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidSkillFile", + "A SKILL.md is UTF-8 text without NUL that starts with YAML front matter between two --- lines.", + ) +} + +fn name_mismatch() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.skillNameMismatch", + "The front matter's name is not the skill's name.", + ) +} + +fn invalid_description() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidSkillDescription", + "A skill's description is 1 to 1024 characters without control characters.", + ) +} + +fn special_file() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.specialFile", + "The skill directory holds a device, socket, pipe or other entry that is not a file, directory or link.", + ) +} + +fn not_skill() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentLibrary.notSkill", + "The directory has no SKILL.md that is a regular file.", + ) +} + +fn too_large_skill() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.skillTooLarge", + "The skill has more files, bytes or levels than Lithe copies.", + ) +} + +fn skill_exists() -> CoreError { + refusal( + ErrorCode::EntryExists, + "agentLibrary.skillExists", + "The library already has a skill of this name.", + ) +} + +fn library_full() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.libraryFull", + "The library holds as many items of this kind as it can.", + ) +} + +fn source_missing() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentLibrary.sourceMissing", + "The folder the skill was installed from is no longer a directory.", + ) +} + +// --------------------------------------------------------------------------- +// Names and front matter. + +/// Whether `name` may name a skill that enters the library: a skill name +/// that Windows also stores under exactly that name, so a library holds +/// only names every host can keep. +pub(super) fn is_new_skill_name(name: &str) -> bool { + is_skill_name(name) && lithe_platform::names::is_portable_windows_component(name) +} + +/// The library's skill names, as the directory lists them. +fn skill_names(config: &Config) -> Vec { + let Ok(entries) = fs::read_dir(config.directory.join(SKILLS_DIRECTORY)) else { + return Vec::new(); + }; + entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| is_skill_name(name)) + .collect() +} + +/// The directory of the library skill `name`: a directory of exactly that +/// name, not a link, in `skills/` (`agentLibrary.unknownItem`). +fn skill_directory(config: &Config, name: &str) -> Result { + if !is_skill_name(name) { + return Err(invalid_skill_name()); + } + if !skill_names(config).iter().any(|known| known == name) { + return Err(unknown_item()); + } + Ok(config.directory.join(SKILLS_DIRECTORY).join(name)) +} + +/// Why a skill of a name cannot enter the library. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum NoRoom { + /// A skill `agentLibrary.read` lists has the name, ignoring ASCII case. + SkillExists, + /// Something else in `skills/` has it: a file, a link, a directory + /// without a `SKILL.md` Core can open, or a skill beyond the ones + /// `read` lists. + NameTaken, + /// The library lists [`MAX_SKILLS`] skills. + LibraryFull, +} + +impl NoRoom { + pub(super) fn code(self) -> &'static str { + match self { + NoRoom::SkillExists => "agentLibrary.skillExists", + NoRoom::NameTaken => "agentLibrary.skillNameTaken", + NoRoom::LibraryFull => "agentLibrary.libraryFull", + } + } + + fn refusal(self) -> CoreError { + match self { + NoRoom::SkillExists => skill_exists(), + NoRoom::NameTaken => refusal( + ErrorCode::EntryExists, + "agentLibrary.skillNameTaken", + "The library's skills folder holds an entry of this name that is not a skill.", + ), + NoRoom::LibraryFull => library_full(), + } + } +} + +/// Why a skill `name` cannot enter a library that lists the skills +/// `listed` and whose `skills/` holds entries named `entries`; `None` when +/// it can. Names are compared ignoring ASCII case, so every host can hold +/// both. +pub(super) fn no_room(listed: &[LibrarySkill], entries: &[String], name: &str) -> Option { + if listed + .iter() + .any(|skill| skill.name.eq_ignore_ascii_case(name)) + { + Some(NoRoom::SkillExists) + } else if entries.iter().any(|entry| entry.eq_ignore_ascii_case(name)) { + Some(NoRoom::NameTaken) + } else if listed.len() >= MAX_SKILLS { + Some(NoRoom::LibraryFull) + } else { + None + } +} + +/// Refuses a new skill `name` the library has no room for ([`no_room`]). +fn check_room(config: &Config, name: &str) -> Result<(), CoreError> { + let listed = library_skills(&config.directory); + match no_room(&listed, &skill_entry_names(&config.directory), name) { + Some(reason) => Err(reason.refusal()), + None => Ok(()), + } +} + +/// A description as a new skill keeps it: its lines and runs of +/// whitespace joined into single spaces. +fn normalized_description(description: &str) -> Result { + if description + .chars() + .any(|c| c.is_control() && !c.is_whitespace()) + { + return Err(invalid_description()); + } + let joined = description.split_whitespace().collect::>().join(" "); + if joined.is_empty() || joined.chars().count() > MAX_DESCRIPTION_CHARS { + return Err(invalid_description()); + } + Ok(joined) +} + +/// `text` as a YAML scalar of one line: plain when YAML reads it back as +/// the same string, otherwise single-quoted. +fn yaml_scalar(text: &str) -> String { + let plain = text.starts_with(|c: char| c.is_ascii_alphabetic()) + && !text.contains(": ") + && !text.contains(" #") + && !text.ends_with(':') + && !text.chars().any(char::is_control) + && !matches!( + text.to_ascii_lowercase().as_str(), + "y" | "n" | "yes" | "no" | "on" | "off" | "true" | "false" | "null" + ); + if plain { + text.to_string() + } else { + format!("'{}'", text.replace('\'', "''")) + } +} + +/// Checks a `SKILL.md` text for the skill `name`: at most 64 KiB +/// (`agentLibrary.fileTooLarge`), without NUL and with front matter +/// (`agentLibrary.invalidSkillFile`), whose `name` is the skill's or +/// `kept`, the name the file gives now (`agentLibrary.skillNameMismatch`), +/// and whose `description` has 1 to 1024 characters +/// (`agentLibrary.invalidSkillDescription`). +fn check_skill_text(name: &str, text: &str, kept: Option<&str>) -> Result<(), CoreError> { + if text.len() as u64 > MAX_SKILL_FILE_BYTES { + return Err(too_large_file()); + } + if text.contains('\0') { + return Err(invalid_skill_file()); + } + let fields = front_matter_fields(text).ok_or_else(invalid_skill_file)?; + match fields.name.as_deref() { + Some(given) if given == name || Some(given) == kept => {} + _ => return Err(name_mismatch()), + } + match fields.description.as_deref() { + Some(description) + if !description.trim().is_empty() + && description.chars().count() <= MAX_DESCRIPTION_CHARS + && !description + .chars() + .any(|c| c.is_control() && !c.is_whitespace()) => {} + _ => return Err(invalid_description()), + } + Ok(()) +} + +/// The `SKILL.md` of the library skill at `directory`: a regular file of +/// at most 64 KiB (`agentLibrary.fileTooLarge`) that is UTF-8 +/// (`agentLibrary.unreadable`). +fn read_skill_text(directory: &Path) -> Result { + let path = directory.join(SKILL_FILE); + match fs::symlink_metadata(&path) { + Ok(metadata) if metadata.is_file() => {} + Ok(_) => return Err(unreadable_file()), + Err(error) if error.kind() == io::ErrorKind::NotFound => return Err(unknown_item()), + Err(_) => return Err(unreadable_file()), + } + let bytes = match read_bounded(&path, MAX_SKILL_FILE_BYTES) { + Ok(Some(bytes)) => bytes, + Ok(None) => return Err(unknown_item()), + Err(ReadFailure::TooLarge) => return Err(too_large_file()), + Err(ReadFailure::Io) => return Err(unreadable_file()), + }; + String::from_utf8(bytes).map_err(|_| unreadable_file()) +} + +// --------------------------------------------------------------------------- +// Trees. + +/// Why reading a skill directory failed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TreeFailure { + /// The directory is not there, or is not a directory. + Missing, + /// It has no `SKILL.md` that is a regular file. + NotSkill, + /// More files, bytes or levels than a copy takes. + TooLarge, + /// A device, socket, pipe or other special entry. + Special, + /// Something could not be read. + Io, + /// The copy could not be written. + Write, +} + +impl TreeFailure { + fn refusal(self) -> CoreError { + match self { + TreeFailure::Missing => source_missing(), + TreeFailure::NotSkill => not_skill(), + TreeFailure::TooLarge => too_large_skill(), + TreeFailure::Special => special_file(), + TreeFailure::Io => unreadable_file(), + TreeFailure::Write => write_failed(), + } + } +} + +/// One file a copy takes. +struct TreeFile { + /// Its place in the skill, with `/`. + path: String, + executable: bool, + /// SHA-256 of its bytes. + digest: String, +} + +/// What a walk of a skill directory found. +#[derive(Default)] +struct Tree { + files: Vec, + bytes: u64, + /// Links and the entries a copy leaves behind. + skipped: usize, +} + +impl Tree { + /// SHA-256 of every file's path, executable bit and digest, in path + /// order: the same for two directories with the same files. + fn digest(&self) -> String { + let mut lines: Vec = self + .files + .iter() + .map(|file| { + format!( + "{}\0{}\0{}\n", + file.path, + if file.executable { "x" } else { "-" }, + file.digest + ) + }) + .collect(); + lines.sort(); + digest(lines.concat().as_bytes()) + } +} + +fn io_failure(error: &io::Error) -> TreeFailure { + match error.kind() { + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => TreeFailure::Missing, + _ => TreeFailure::Io, + } +} + +/// Reads the skill directory `root`, and with `copy_to` copies it into +/// that new directory, within the copy bounds. Links in `root`'s own path +/// are followed; none inside it is. +fn walk(root: &Path, copy_to: Option<&Path>) -> Result { + let directory = Directory::open_root(root).map_err(|error| io_failure(&error))?; + let skill_file = directory + .child_metadata(OsStr::new(SKILL_FILE)) + .map_err(|error| match io_failure(&error) { + TreeFailure::Missing => TreeFailure::NotSkill, + other => other, + })?; + if skill_file.kind != Kind::File { + return Err(TreeFailure::NotSkill); + } + let mut tree = Tree::default(); + if let Some(to) = copy_to { + fs::create_dir(to).map_err(|_| TreeFailure::Write)?; + } + walk_directory(&directory, root, copy_to, "", 0, &mut tree)?; + Ok(tree) +} + +fn walk_directory( + directory: &Directory, + path: &Path, + copy_to: Option<&Path>, + prefix: &str, + depth: usize, + tree: &mut Tree, +) -> Result<(), TreeFailure> { + if depth > MAX_IMPORT_DEPTH { + return Err(TreeFailure::TooLarge); + } + let mut entries: Vec<(OsString, Kind, u64)> = Vec::new(); + let mut crowded = false; + directory + .visit(|name, metadata| { + if entries.len() >= MAX_IMPORT_FILES { + crowded = true; + return Err(io::Error::other("crowded")); + } + entries.push((name.to_os_string(), metadata.kind, metadata.size)); + Ok(()) + }) + .or_else(|error| if crowded { Ok(()) } else { Err(error) }) + .map_err(|error| io_failure(&error))?; + if crowded { + return Err(TreeFailure::TooLarge); + } + entries.sort_by(|left, right| left.0.cmp(&right.0)); + for (name, kind, size) in entries { + let text = name.to_string_lossy(); + if LEFT_BEHIND.contains(&text.as_ref()) { + tree.skipped += 1; + continue; + } + let place = format!("{prefix}{text}"); + match kind { + Kind::Symlink => tree.skipped += 1, + Kind::Other => return Err(TreeFailure::Special), + Kind::Directory => { + let child = directory + .directory(&name) + .map_err(|error| io_failure(&error))?; + let child_to = copy_to.map(|to| to.join(&name)); + if let Some(to) = &child_to { + fs::create_dir(to).map_err(|_| TreeFailure::Write)?; + } + walk_directory( + &child, + &path.join(&name), + child_to.as_deref(), + &format!("{place}/"), + depth + 1, + tree, + )?; + } + Kind::File => { + if tree.files.len() >= MAX_IMPORT_FILES { + return Err(TreeFailure::TooLarge); + } + let budget = MAX_IMPORT_BYTES - tree.bytes; + if size > budget { + return Err(TreeFailure::TooLarge); + } + let mut bytes = Vec::new(); + directory + .file(&name) + .and_then(|file| file.take(budget + 1).read_to_end(&mut bytes)) + .map_err(|error| io_failure(&error))?; + if bytes.len() as u64 > budget { + return Err(TreeFailure::TooLarge); + } + tree.bytes += bytes.len() as u64; + // The mode is read by path; the bytes come from the handle, + // which never follows a link. + let executable = fs::symlink_metadata(path.join(&name)).is_ok_and(|metadata| { + metadata.is_file() && lithe_platform::fs::has_execute_bit(&metadata) + }); + if let Some(to) = copy_to { + write_copy(&to.join(&name), &bytes, executable) + .map_err(|_| TreeFailure::Write)?; + } + tree.files.push(TreeFile { + path: place, + executable, + digest: digest(&bytes), + }); + } + } + } + Ok(()) +} + +/// Writes one copied file, new, executable when the source was. +fn write_copy(target: &Path, bytes: &[u8], executable: bool) -> io::Result<()> { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(target)?; + file.write_all(bytes)?; + drop(file); + if executable { + lithe_platform::fs::add_execute_bits(target)?; + } + Ok(()) +} + +/// A file of a library skill other than its `SKILL.md`, as `readSkill` +/// lists it. +struct Listed { + path: String, + size: u64, +} + +/// The regular files of the skill directory `root` other than its +/// `SKILL.md`, in path order, at most [`MAX_IMPORT_FILES`] and +/// [`MAX_IMPORT_DEPTH`] levels deep; `true` when there were more. +fn list_files(root: &Path) -> Result<(Vec, bool), CoreError> { + fn visit( + directory: &Directory, + prefix: &str, + depth: usize, + listed: &mut Vec, + ) -> io::Result { + let mut entries: Vec<(OsString, Kind, u64)> = Vec::new(); + let mut more = false; + directory + .visit(|name, metadata| { + if entries.len() > MAX_IMPORT_FILES { + more = true; + return Err(io::Error::other("crowded")); + } + entries.push((name.to_os_string(), metadata.kind, metadata.size)); + Ok(()) + }) + .or_else(|error| if more { Ok(()) } else { Err(error) })?; + entries.sort_by(|left, right| left.0.cmp(&right.0)); + for (name, kind, size) in entries { + let text = name.to_string_lossy(); + let place = format!("{prefix}{text}"); + match kind { + Kind::File if place != SKILL_FILE => { + if listed.len() == MAX_IMPORT_FILES { + return Ok(true); + } + listed.push(Listed { path: place, size }); + } + Kind::Directory => { + if depth == MAX_IMPORT_DEPTH { + more = true; + continue; + } + let child = directory.directory(&name)?; + if visit(&child, &format!("{place}/"), depth + 1, listed)? { + return Ok(true); + } + } + _ => {} + } + } + Ok(more) + } + let directory = Directory::open_root(root).map_err(|_| unreadable_file())?; + let mut listed = Vec::new(); + let more = visit(&directory, "", 0, &mut listed).map_err(|_| unreadable_file())?; + listed.sort_by(|left, right| left.path.cmp(&right.path)); + Ok((listed, more)) +} + +// --------------------------------------------------------------------------- +// Sources. + +/// Where a skill copied in from a folder came from. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Source { + /// The folder's absolute path, as the user chose it. + path: String, + /// When the copy was made, in milliseconds since the epoch. + installed_at_ms: i64, + /// The digest ([`Tree::digest`]) of what was copied. + digest: String, +} + +impl Source { + fn valid(&self) -> bool { + Path::new(&self.path).is_absolute() + && self.digest.len() == 64 + && self.digest.chars().all(|c| c.is_ascii_hexdigit()) + } + + fn answer(&self) -> Value { + json!({ "path": self.path, "installedAtMs": self.installed_at_ms }) + } +} + +/// `sources.json`. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SourcesFile { + version: u32, + #[serde(default)] + skills: BTreeMap, +} + +/// The recorded sources by skill name. A file Core cannot read counts as +/// none, and the next write replaces it. +fn load_sources(config: &Config) -> BTreeMap { + read_bounded(&config.directory.join(SOURCES_FILE), MAX_LIBRARY_FILE_BYTES) + .ok() + .flatten() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|file| file.version == 0) + .map(|file| file.skills) + .unwrap_or_default() + .into_iter() + .filter(|(name, source)| is_skill_name(name) && source.valid()) + .collect() +} + +/// Replaces `sources.json`, owner-only. Callers hold the writing lock. +fn store_sources(config: &Config, skills: BTreeMap) -> Result<(), CoreError> { + ensure_private_directory(&config.directory)?; + write_sources(config, skills).map_err(|_| write_failed()) +} + +fn write_sources(config: &Config, skills: BTreeMap) -> io::Result<()> { + let bytes = + serde_json::to_vec_pretty(&SourcesFile { version: 0, skills }).map_err(io::Error::other)?; + write_owner_only(&config.directory.join(SOURCES_FILE), &bytes) +} + +/// Forgets the source of the removed skill `name`. One that cannot be +/// forgotten is logged and harms nothing: a source of no skill is never +/// read, and the next skill of the name replaces it. Callers hold the +/// writing lock. +fn forget_source(config: &Config, name: &str) { + let mut skills = load_sources(config); + if skills.remove(name).is_none() { + return; + } + if let Err(error) = write_sources(config, skills) { + super::leftover_kept(Leftover::SkillSource, &error); + } +} + +/// Sets or forgets the source of the skill `name`, writing only when that +/// changes the record. Callers hold the writing lock. +fn record_source(config: &Config, name: &str, source: Option) -> Result<(), CoreError> { + let mut skills = load_sources(config); + let changed = match source { + Some(source) => skills.insert(name.to_string(), source.clone()) != Some(source), + None => skills.remove(name).is_some(), + }; + if changed { + store_sources(config, skills)?; + } + Ok(()) +} + +/// The `source` of each library skill copied in from a folder, by name, +/// for `agentLibrary.read`. +pub(super) fn source_answers(config: &Config) -> BTreeMap { + load_sources(config) + .into_iter() + .map(|(name, source)| (name, source.answer())) + .collect() +} + +// --------------------------------------------------------------------------- +// Copies. + +/// A finished copy into `staging/`, waiting to be moved into place. +struct Staged { + path: PathBuf, + tree: Tree, +} + +impl Staged { + fn discard(self) { + remove_leftover(&self.path, Leftover::SkillImport); + } +} + +/// Copies the skill directory `source` into a new directory of `staging/`. +fn stage_copy(config: &Config, source: &Path, name: &str) -> Result { + let staging = config.directory.join(STAGING_DIRECTORY); + ensure_private_directory(&config.directory)?; + ensure_private_directory(&staging)?; + let path = sibling_temporary(&staging.join(name), "import").ok_or_else(write_failed)?; + match walk(source, Some(&path)) { + Ok(tree) => Ok(Staged { path, tree }), + Err(failure) => { + remove_leftover(&path, Leftover::SkillImport); + Err(failure.refusal()) + } + } +} + +/// The digest of the library skill at `directory`; `None` when it cannot +/// be read in full, which counts as edited. +fn library_digest(directory: &Path) -> Option { + walk(directory, None).ok().map(|tree| tree.digest()) +} + +// --------------------------------------------------------------------------- +// Commands. + +/// The `change` a failed skill command logs. +#[derive(Debug, Clone, Copy)] +enum SkillChange { + Create, + Write, + Import, + Reinstall, + Remove, +} + +impl SkillChange { + fn token(self) -> &'static str { + match self { + SkillChange::Create => "create", + SkillChange::Write => "write", + SkillChange::Import => "import", + SkillChange::Reinstall => "reinstall", + SkillChange::Remove => "remove", + } + } +} + +/// Logs a refused skill command with its code, and passes the outcome on. +fn logged(change: SkillChange, outcome: Result) -> Result { + if let Err(error) = &outcome { + log( + "agent.library.skill_change_failed", + [ + ("change", json!(change.token())), + ( + "reason", + json!(error + .details + .as_deref() + .unwrap_or("agentLibrary.writeFailed")), + ), + ], + ); + } + outcome +} + +/// Where `agentLibrary.importSkill` copies from. +enum ImportFrom { + /// An agent's own skill directory; no source is recorded. + Agent(PathBuf), + /// A folder the user chose, recorded as the skill's source. + Folder(PathBuf), +} + +impl Library { + /// `agentLibrary.createSkill`: a new library skill whose `SKILL.md` + /// holds front matter with `name` and `description`, then `body`, or a + /// heading of the name without one. + pub fn create_skill(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct CreateRequest { + name: String, + description: String, + #[serde(default)] + body: Option, + } + require_user()?; + let request: CreateRequest = crate::decode(payload)?; + let outcome = self.create_checked(request.name, &request.description, request.body); + logged(SkillChange::Create, outcome) + } + + fn create_checked( + &self, + name: String, + description: &str, + body: Option, + ) -> Result { + let config = self.config()?; + if !is_new_skill_name(&name) { + return Err(invalid_skill_name()); + } + let description = normalized_description(description)?; + let mut text = format!( + "---\nname: {}\ndescription: {}\n---\n\n", + yaml_scalar(&name), + yaml_scalar(&description) + ); + match body { + Some(body) => { + text.push_str(&body); + if !body.is_empty() && !body.ends_with('\n') { + text.push('\n'); + } + } + None => text.push_str(&format!("# {name}\n")), + } + check_skill_text(&name, &text, None)?; + + let skills = config.directory.join(SKILLS_DIRECTORY); + let staging = config.directory.join(STAGING_DIRECTORY); + ensure_private_directory(&config.directory)?; + ensure_private_directory(&staging)?; + ensure_directory(&skills)?; + let partial = sibling_temporary(&staging.join(&name), "create").ok_or_else(write_failed)?; + let made = fs::create_dir(&partial).and_then(|()| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(partial.join(SKILL_FILE))?; + file.write_all(text.as_bytes())?; + file.sync_all() + }); + if made.is_err() { + remove_leftover(&partial, Leftover::SkillImport); + return Err(write_failed()); + } + let placed = { + let _writing = self.lock_writing(); + // A source left by a skill of the name removed outside Lithe + // goes first, so the new skill never reads as installed. + check_room(&config, &name) + .and_then(|()| record_source(&config, &name, None)) + .and_then(|()| move_into_library(&config, &partial, &name)) + }; + if let Err(error) = placed { + remove_leftover(&partial, Leftover::SkillImport); + return Err(error); + } + log( + "agent.library.skill_create_finished", + [("bytes", json!(text.len()))], + ); + Ok(json!({ "name": name, "revision": digest(text.as_bytes()) })) + } + + /// `agentLibrary.readSkill`: the `SKILL.md` of a library skill, whole, + /// with its revision, and the skill's other files by path and size. + pub fn read_skill(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct ReadRequest { + name: String, + } + let request: ReadRequest = crate::decode(payload)?; + let config = self.config()?; + let directory = skill_directory(&config, &request.name)?; + let text = read_skill_text(&directory)?; + let (files, more) = list_files(&directory)?; + let mut answer = json!({ + "name": request.name, + "text": text, + "revision": digest(text.as_bytes()), + "files": files + .iter() + .map(|file| json!({ "path": file.path, "size": file.size })) + .collect::>(), + }); + if more { + answer["truncated"] = json!(true); + } + Ok(answer) + } + + /// `agentLibrary.writeSkill`: replaces the `SKILL.md` of a library skill + /// with `text` if it is still at `revision`, backing the file up first. + pub fn write_skill(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct WriteRequest { + name: String, + revision: String, + text: String, + } + require_user()?; + let request: WriteRequest = crate::decode(payload)?; + let outcome = (|| { + let config = self.config()?; + let directory = skill_directory(&config, &request.name)?; + let _writing = self.lock_writing(); + let current = read_skill_text(&directory)?; + if digest(current.as_bytes()) != request.revision { + return Err(super::revision_changed()); + } + let kept = super::front_matter(¤t).0; + check_skill_text(&request.name, &request.text, kept.as_deref())?; + if request.text == current { + return Ok((false, request.revision.clone())); + } + let taken = backups::take( + &config, + &backups::skill_key(&request.name), + SKILL_FILE, + Some(current.as_bytes()), + request.text.as_bytes(), + ) + .map_err(backups::BackupFailed::library)?; + if write_replacing(&directory.join(SKILL_FILE), request.text.as_bytes()).is_err() { + backups::undo(taken); + return Err(write_failed()); + } + Ok((true, digest(request.text.as_bytes()))) + })(); + let outcome = outcome.map(|(changed, revision)| { + log( + "agent.library.skill_write_finished", + [ + ("changed", json!(changed)), + ("bytes", json!(request.text.len())), + ], + ); + json!({ "changed": changed, "revision": revision }) + }); + logged(SkillChange::Write, outcome) + } + + /// `agentLibrary.importSkill`: copies a skill into the library, from an + /// agent's skills directory or from a folder the user chose, which is + /// then recorded as the skill's source. + pub fn import_skill(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ImportRequest { + #[serde(default)] + agent: Option, + #[serde(default)] + name: Option, + #[serde(default)] + directory: Option, + } + require_user()?; + let request: ImportRequest = crate::decode(payload)?; + let outcome = (|| { + let config = self.config()?; + let from = match (&request.agent, &request.name, &request.directory) { + (Some(agent), Some(name), None) => { + let agent = super::configurable_agent(runtime, agent)?; + let configuration = agent + .agent + .configuration + .as_ref() + .expect("configurable agents declare configuration"); + let root = super::agent_paths(&config, configuration) + .skills + .ok_or_else(super::no_skills)?; + if !is_skill_name(name) { + return Err(invalid_skill_name()); + } + let source = root.join(name); + if fs::symlink_metadata(&source).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.notOwnSkill", + "Only a skill directory of the agent's own is imported.", + )); + } + ImportFrom::Agent(source) + } + (None, None, Some(directory)) => { + let directory = PathBuf::from(directory); + if !directory.is_absolute() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidSkillDirectory", + "The skill directory must be an absolute path.", + )); + } + ImportFrom::Folder(directory) + } + _ => { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidImport", + "A skill is imported from an agent and a name, or from a directory.", + )) + } + }; + self.import_checked(&config, from, request.name.clone()) + })(); + logged(SkillChange::Import, outcome) + } + + fn import_checked( + &self, + config: &Config, + from: ImportFrom, + name: Option, + ) -> Result { + let source = match &from { + ImportFrom::Agent(path) | ImportFrom::Folder(path) => path.clone(), + }; + let skill_file = source.join(SKILL_FILE); + if !fs::metadata(&source).is_ok_and(|metadata| metadata.is_dir()) + || !fs::symlink_metadata(&skill_file).is_ok_and(|metadata| metadata.is_file()) + { + return Err(not_skill()); + } + let name = match name { + Some(name) => name, + None => { + let bytes = read_bounded(&skill_file, MAX_SKILL_FILE_BYTES) + .ok() + .flatten() + .unwrap_or_default(); + super::front_matter(&String::from_utf8_lossy(&bytes)) + .0 + .or_else(|| { + source + .file_name() + .and_then(|name| name.to_str()) + .map(str::to_string) + }) + .unwrap_or_default() + } + }; + if !is_new_skill_name(&name) { + return Err(invalid_skill_name()); + } + { + let _writing = self.lock_writing(); + check_room(config, &name)?; + } + ensure_directory(&config.directory.join(SKILLS_DIRECTORY))?; + let staged = stage_copy(config, &source, &name)?; + let recorded = match &from { + ImportFrom::Folder(path) => Some(Source { + path: path.to_string_lossy().into_owned(), + installed_at_ms: crate::now_ms(), + digest: staged.tree.digest(), + }), + ImportFrom::Agent(_) => None, + }; + let placed = { + let _writing = self.lock_writing(); + // The source is recorded first, so the skill is never there + // without it; a record whose skill did not arrive is never read, + // and the next skill of the name replaces it. + check_room(config, &name) + .and_then(|()| record_source(config, &name, recorded)) + .and_then(|()| move_into_library(config, &staged.path, &name)) + }; + let (files, skipped) = (staged.tree.files.len(), staged.tree.skipped); + if let Err(error) = placed { + staged.discard(); + return Err(error); + } + log( + "agent.library.skill_import_finished", + [("files", json!(files)), ("skipped", json!(skipped))], + ); + Ok(json!({ "name": name, "files": files, "skipped": skipped })) + } + + /// `agentLibrary.checkSkillSources`: for each library skill copied in + /// from a folder, whether that folder changed since, and whether the + /// library's copy was edited since. + pub fn check_skill_sources(&self, payload: Value) -> Result { + #[derive(Default, Deserialize)] + #[serde(deny_unknown_fields)] + struct CheckRequest { + #[serde(default)] + names: Option>, + } + let request: CheckRequest = crate::decode(payload)?; + if let Some(names) = &request.names { + if names.len() > MAX_CHECKED { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidFilter", + "At most 512 skills are checked at once.", + )); + } + if !names.iter().all(|name| is_skill_name(name)) { + return Err(invalid_skill_name()); + } + } + let started = Instant::now(); + let config = self.config()?; + let names = skill_names(&config); + let mut changed = 0u64; + let mut unavailable = 0u64; + let rows: Vec = load_sources(&config) + .into_iter() + .filter(|(name, _)| names.contains(name)) + .filter(|(name, _)| { + request + .names + .as_ref() + .is_none_or(|wanted| wanted.contains(name)) + }) + .map(|(name, source)| { + let directory = config.directory.join(SKILLS_DIRECTORY).join(&name); + let edited = library_digest(&directory).as_deref() != Some(source.digest.as_str()); + let mut row = json!({ + "name": name, + "path": source.path, + "installedAtMs": source.installed_at_ms, + "edited": edited, + }); + match walk(Path::new(&source.path), None) { + Ok(tree) if tree.digest() == source.digest => { + row["state"] = json!("unchanged"); + } + Ok(_) => { + changed += 1; + row["state"] = json!("changed"); + } + Err(failure) => { + unavailable += 1; + row["state"] = json!("unavailable"); + row["reason"] = json!(failure.refusal().details); + } + } + row + }) + .collect(); + log( + "agent.library.skill_sources_inspected", + [ + ("skills", json!(rows.len())), + ("changed", json!(changed)), + ("unavailable", json!(unavailable)), + ( + "duration_ms", + json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), + ), + ], + ); + Ok(json!({ "skills": rows })) + } + + /// `agentLibrary.reinstallSkill`: copies a library skill again from the + /// folder it was copied in from, in place of the library's copy, which + /// is kept with the skill's backups. A copy edited since it was + /// installed is replaced only with `discardEdits`. + pub fn reinstall_skill(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ReinstallRequest { + name: String, + #[serde(default)] + discard_edits: bool, + } + require_user()?; + let request: ReinstallRequest = crate::decode(payload)?; + let outcome = self.reinstall_checked(&request.name, request.discard_edits); + logged(SkillChange::Reinstall, outcome) + } + + fn reinstall_checked(&self, name: &str, discard_edits: bool) -> Result { + let no_source = || { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.noSource", + "The skill was not installed from a folder.", + ) + }; + let config = self.config()?; + let directory = skill_directory(&config, name)?; + let source = load_sources(&config).remove(name).ok_or_else(no_source)?; + let staged = stage_copy(&config, Path::new(&source.path), name)?; + let fresh = staged.tree.digest(); + let (files, skipped) = (staged.tree.files.len(), staged.tree.skipped); + let outcome = (|| { + let _writing = self.lock_writing(); + // What another change did while the folder was copied counts. + if !directory.is_dir() { + return Err(unknown_item()); + } + let installed = load_sources(&config).remove(name).ok_or_else(no_source)?; + let current = library_digest(&directory); + if current.as_deref() == Some(fresh.as_str()) { + // The library already holds what the folder holds. + record_source( + &config, + name, + Some(Source { + digest: fresh.clone(), + ..installed + }), + )?; + return Ok((false, false)); + } + let edited = current.as_deref() != Some(installed.digest.as_str()); + if edited && !discard_edits { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.skillEdited", + "The library's copy of the skill changed since it was installed.", + )); + } + backups::replace_skill(&config, name, &directory, &staged.path)?; + let record = Source { + path: installed.path, + installed_at_ms: crate::now_ms(), + digest: fresh.clone(), + }; + if let Err(error) = record_source(&config, name, Some(record)) { + backups::put_back_skill(&config, name, &directory, &staged.path); + return Err(error); + } + Ok((true, edited)) + })(); + staged.discard(); + let (changed, discarded) = outcome?; + log( + "agent.library.skill_reinstall_finished", + [ + ("files", json!(files)), + ("skipped", json!(skipped)), + ("changed", json!(changed)), + ("discarded", json!(discarded)), + ], + ); + Ok(json!({ "name": name, "files": files, "skipped": skipped, "changed": changed })) + } + + /// `agentLibrary.removeSkill`: removes a library skill and every link to + /// it in the agents' skills directories, with its source record and its + /// backups. + pub fn remove_skill(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct RemoveRequest { + name: String, + } + require_user()?; + let request: RemoveRequest = crate::decode(payload)?; + let outcome = (|| { + let config = self.config()?; + let skill = skill_directory(&config, &request.name)?; + let mut unlinked = 0u64; + let _writing = self.lock_writing(); + for agent in runtime.catalog.configurable() { + if !agent.may_configure { + continue; + } + let configuration = agent + .agent + .configuration + .as_ref() + .expect("configurable agents declare configuration"); + let Some(root) = super::agent_paths(&config, configuration).skills else { + continue; + }; + let link = root.join(&request.name); + if fs::symlink_metadata(&link).is_ok_and(|m| m.file_type().is_symlink()) + && super::links_into(&link, &skill) + { + super::remove_link(&link).map_err(|_| write_failed())?; + unlinked += 1; + } + } + fs::remove_dir_all(&skill).map_err(|_| write_failed())?; + forget_source(&config, &request.name); + backups::forget_skill(&config, &request.name); + log( + "agent.library.skill_removed", + [("unlinked", json!(unlinked))], + ); + Ok(json!({ "unlinked": unlinked })) + })(); + logged(SkillChange::Remove, outcome) + } +} + +/// Moves the finished copy `partial` into `skills/` as `name`, never over +/// anything already there, which refuses as [`check_room`] tells it. +fn move_into_library(config: &Config, partial: &Path, name: &str) -> Result<(), CoreError> { + let destination = config.directory.join(SKILLS_DIRECTORY).join(name); + lithe_platform::entries::rename_no_replace(partial, &destination).map_err(|error| { + if error.kind() != io::ErrorKind::AlreadyExists { + return write_failed(); + } + // Something came in its place after the check, outside Lithe. + match check_room(config, name) { + Err(refused) => refused, + Ok(()) => NoRoom::NameTaken.refusal(), + } + }) +} + +#[cfg(test)] +pub(crate) fn yaml_scalar_for_test(text: &str) -> String { + yaml_scalar(text) +} diff --git a/rust/crates/agent-runtime/src/tests/library.rs b/rust/crates/agent-runtime/src/tests/library.rs index b7c0d4f6..9da9241d 100644 --- a/rust/crates/agent-runtime/src/tests/library.rs +++ b/rust/crates/agent-runtime/src/tests/library.rs @@ -758,3 +758,4 @@ fn malformed_requests_and_a_damaged_library_file_are_refused_each_with_its_own_c mod backups; mod instructions; mod servers; +mod skills; diff --git a/rust/crates/agent-runtime/src/tests/library/backups.rs b/rust/crates/agent-runtime/src/tests/library/backups.rs index a7bfd334..c13b5845 100644 --- a/rust/crates/agent-runtime/src/tests/library/backups.rs +++ b/rust/crates/agent-runtime/src/tests/library/backups.rs @@ -378,7 +378,7 @@ fn a_library_change_whose_backup_fails_is_not_written() { let (refused, logs) = capture::run(false, || { test.refused_change(json!({ "category": "mcpServers", "op": "put", "name": "docs" })) }); - assert_eq!(refused, "agentProviders.backupFailed"); + assert_eq!(refused, "agentLibrary.backupFailed"); assert_eq!(fs::read(&config).unwrap(), ORIGINAL_CONFIG, "untouched"); assert_eq!(test.staged_files(), 0); let failed = logs @@ -386,10 +386,7 @@ fn a_library_change_whose_backup_fails_is_not_written() { .find(|log| log.event == "agent.library.change_failed") .expect("the refusal is logged"); assert_eq!(failed.fields["category"], json!("mcpServers")); - assert_eq!( - failed.fields["reason"], - json!("agentProviders.backupFailed") - ); + assert_eq!(failed.fields["reason"], json!("agentLibrary.backupFailed")); // The save itself succeeds; the agent it could not bring up to date is // reported with the reason, and its file is untouched. @@ -397,16 +394,16 @@ fn a_library_change_whose_backup_fails_is_not_written() { capture::run(false, || test.save_answer(full_library("Shared rule."))); assert_eq!( synced["instructions"], - json!([{ "agent": AGENT_KEY, "result": "failed", "reason": "agentProviders.backupFailed" }]) + json!([{ "agent": AGENT_KEY, "result": "failed", "reason": "agentLibrary.backupFailed" }]) ); assert!(sync_logs .iter() .any(|log| log.event == "agent.library.change_failed" && log.fields["category"] == json!("instructions") - && log.fields["reason"] == json!("agentProviders.backupFailed"))); + && log.fields["reason"] == json!("agentLibrary.backupFailed"))); assert_eq!( test.refused_change(json!({ "category": "instructions", "op": "write" })), - "agentProviders.backupFailed" + "agentLibrary.backupFailed" ); assert_eq!(fs::read(&instructions).unwrap(), b"My own notes\n"); assert!(test.written_instructions().is_none()); diff --git a/rust/crates/agent-runtime/src/tests/library/servers.rs b/rust/crates/agent-runtime/src/tests/library/servers.rs index 088f4aa2..6e96be3b 100644 --- a/rust/crates/agent-runtime/src/tests/library/servers.rs +++ b/rust/crates/agent-runtime/src/tests/library/servers.rs @@ -621,6 +621,17 @@ fn items_outside_the_library_are_grouped_with_their_differences() { ); write_skill(&sample_skills.join("review"), "---\nname: review\n---\nA\n"); write_skill(&other_skills.join("review"), "---\nname: review\n---\nB\n"); + // A library skill of the name in another case takes it as well. + let format = test.harness.dir.path().join("source").join("Format"); + write_skill(&format, "---\nname: Format\n---\nLibrary format\n"); + test.harness.run( + "agentLibrary.importSkill", + json!({ "directory": path_text(&format) }), + ); + write_skill( + &sample_skills.join("format"), + "---\nname: format\n---\nOwn\n", + ); // Agents come in the catalog's order, `other` before `sample`. let found = test.read()["found"].clone(); @@ -704,6 +715,19 @@ fn items_outside_the_library_are_grouped_with_their_differences() { ] ); assert_eq!(provided["reason"], "agentLibrary.notOwnSkill"); + let format = skill("format"); + assert_eq!( + ( + format["inLibrary"].clone(), + format["importable"].clone(), + format["reason"].clone() + ), + ( + json!(false), + json!(false), + json!("agentLibrary.skillExists") + ) + ); } #[test] diff --git a/rust/crates/agent-runtime/src/tests/library/skills.rs b/rust/crates/agent-runtime/src/tests/library/skills.rs new file mode 100644 index 00000000..8d52eb22 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/library/skills.rs @@ -0,0 +1,807 @@ +//! The library's own skills: creating one, reading and writing its +//! `SKILL.md` whole against a revision with a backup first, copying one in +//! from a folder with its source recorded, telling that the folder or the +//! library's copy changed since, installing it again, and removing it with +//! what Core keeps about it. + +use super::*; + +const SKILL_TEXT: &str = + "---\nname: folder-skill\ndescription: Checks the sample project.\n---\n\nBody\n"; + +fn create(test: &LibraryTest, payload: Value) -> Value { + test.harness.run("agentLibrary.createSkill", payload) +} + +fn read_skill(test: &LibraryTest, name: &str) -> Value { + test.harness + .run("agentLibrary.readSkill", json!({ "name": name })) +} + +fn write_skill(test: &LibraryTest, name: &str, revision: &Value, text: &str) -> Value { + test.harness.run( + "agentLibrary.writeSkill", + json!({ "name": name, "revision": revision, "text": text }), + ) +} + +fn refused_write(test: &LibraryTest, name: &str, revision: &Value, text: &str) -> String { + test.harness.refused( + "agentLibrary.writeSkill", + json!({ "name": name, "revision": revision, "text": text }), + ) +} + +fn check(test: &LibraryTest) -> Vec { + test.harness + .run("agentLibrary.checkSkillSources", json!({}))["skills"] + .as_array() + .unwrap() + .clone() +} + +/// The skill row `name` of `agentLibrary.read`. +fn skill_row(test: &LibraryTest, name: &str) -> Value { + test.read()["skills"] + .as_array() + .unwrap() + .iter() + .find(|row| row["name"] == name) + .cloned() + .unwrap_or_else(|| panic!("the library lists {name}")) +} + +/// The contents of every file under `root`, by path relative to it with +/// `/`, so a test can see what a directory holds. +fn contents(root: &Path) -> BTreeMap { + fn visit(root: &Path, directory: &Path, found: &mut BTreeMap) { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + visit(root, &path, found); + } else { + let relative = path.strip_prefix(root).unwrap(); + let key = relative + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"); + found.insert(key, fs::read_to_string(&path).unwrap_or_default()); + } + } + } + let mut found = BTreeMap::new(); + if root.exists() { + visit(root, root, &mut found); + } + found +} + +/// What the library keeps in `backups/`, by path relative to it. +fn backups(test: &LibraryTest) -> BTreeMap { + contents(&test.library.join("backups")) +} + +/// A folder with a skill in it, and what a copy leaves behind. +fn source_folder(test: &LibraryTest) -> PathBuf { + let source = test.harness.dir.path().join("source").join("folder-skill"); + fs::create_dir_all(source.join("scripts")).unwrap(); + fs::create_dir_all(source.join(".git")).unwrap(); + fs::write(source.join("SKILL.md"), SKILL_TEXT).unwrap(); + fs::write(source.join("scripts").join("run.sh"), "echo one\n").unwrap(); + fs::write(source.join(".DS_Store"), "finder").unwrap(); + fs::write(source.join(".git").join("HEAD"), "ref: main\n").unwrap(); + source +} + +#[test] +fn a_new_skill_gets_front_matter_and_refuses_bad_names_descriptions_and_duplicates() { + use crate::library::{front_matter_for_test, yaml_scalar_for_test}; + let test = LibraryTest::new("library skill create", CONFIGURATION_GRANTS); + let created = create( + &test, + json!({ "name": "pdf-tools", "description": "Use when: the user's PDF\n has #tags" }), + ); + assert_eq!(created["name"], "pdf-tools"); + let read = read_skill(&test, "pdf-tools"); + assert_eq!(read["revision"], created["revision"]); + let text = read["text"].as_str().unwrap(); + assert_eq!( + text, + "---\nname: pdf-tools\ndescription: 'Use when: the user''s PDF has #tags'\n---\n\n# pdf-tools\n" + ); + assert_eq!( + front_matter_for_test(text), + ( + Some("pdf-tools".into()), + Some("Use when: the user's PDF has #tags".into()) + ) + ); + assert_eq!( + skill_row(&test, "pdf-tools")["description"], + "Use when: the user's PDF has #tags" + ); + assert!(skill_row(&test, "pdf-tools").get("source").is_none()); + assert_eq!(read["files"], json!([])); + + let with_body = create( + &test, + json!({ "name": "notes", "description": "Takes notes.", "body": "Write notes." }), + ); + assert_eq!( + read_skill(&test, "notes")["text"], + "---\nname: notes\ndescription: Takes notes.\n---\n\nWrite notes.\n" + ); + assert_eq!(with_body["name"], "notes"); + assert_eq!(yaml_scalar_for_test("yes"), "'yes'"); + assert_eq!(yaml_scalar_for_test("1password"), "'1password'"); + assert_eq!(yaml_scalar_for_test("Plain text."), "Plain text."); + + let refused = |payload: Value| test.harness.refused("agentLibrary.createSkill", payload); + let description = "Checks."; + assert_eq!( + refused(json!({ "name": "pdf-tools", "description": description })), + "agentLibrary.skillExists" + ); + assert_eq!( + refused(json!({ "name": "PDF-Tools", "description": description })), + "agentLibrary.skillExists", + "a name differing only in case is the same skill on every host" + ); + for name in [".hidden", "con", "trail.", "two words", "", &"a".repeat(65)] { + assert_eq!( + refused(json!({ "name": name, "description": description })), + "agentLibrary.invalidSkillName", + "{name:?}" + ); + } + for description in [ + " \n ".to_string(), + "x".repeat(1025), + "bell\u{7}".to_string(), + ] { + assert_eq!( + refused(json!({ "name": "fresh", "description": description })), + "agentLibrary.invalidSkillDescription" + ); + } + assert_eq!( + refused( + json!({ "name": "fresh", "description": description, "body": "x".repeat(70 * 1024) }) + ), + "agentLibrary.fileTooLarge" + ); + assert_eq!( + refused(json!({ "name": "fresh", "description": description, "body": "nul\u{0}" })), + "agentLibrary.invalidSkillFile" + ); + assert_eq!( + refused(json!({ "name": "fresh", "description": description, "extra": true })), + "agents.invalidPayload" + ); + assert!(!test.library.join("skills").join("fresh").exists()); + assert_eq!( + fs::read_dir(test.library.join("staging")).unwrap().count(), + 0, + "a refused skill leaves nothing in staging" + ); + + // An entry of `skills/` that is not a skill keeps its name, in any case. + let skills = test.library.join("skills"); + fs::create_dir(skills.join("stray")).unwrap(); + fs::write(skills.join("loose.md"), "not a skill").unwrap(); + for name in ["stray", "STRAY", "loose.md"] { + assert_eq!( + refused(json!({ "name": name, "description": description })), + "agentLibrary.skillNameTaken", + "{name}" + ); + } + assert!( + test.read()["skills"] + .as_array() + .unwrap() + .iter() + .all(|row| row["name"] != "stray"), + "read lists skills only" + ); + let own = test.home.join(".sample").join("skills").join("stray"); + fs::create_dir_all(&own).unwrap(); + fs::write(own.join("SKILL.md"), "---\nname: stray\n---\n").unwrap(); + let found = test.read()["found"]["skills"].clone(); + let group = found + .as_array() + .unwrap() + .iter() + .find(|group| group["name"] == "stray") + .expect("the agent's own skill is found"); + assert_eq!( + (group["importable"].clone(), group["reason"].clone()), + (json!(false), json!("agentLibrary.skillNameTaken")) + ); + assert_eq!( + test.harness.refused( + "agentLibrary.importSkill", + json!({ "agent": AGENT_KEY, "name": "stray" }) + ), + "agentLibrary.skillNameTaken" + ); +} + +#[test] +fn front_matter_comments_are_read_as_yaml_reads_them() { + use crate::library::front_matter_for_test; + let read = |fields: &str| front_matter_for_test(&format!("---\n{fields}\n---\n")); + assert_eq!( + read("name: lint # the linter\ndescription: Checks code. # short"), + (Some("lint".into()), Some("Checks code.".into())) + ); + let description = |value: &str| read(&format!("name: lint\ndescription: {value}")).1; + assert_eq!( + description("Issue#12 stays\t# after a tab"), + Some("Issue#12 stays".into()), + "a # without a blank before it is text" + ); + assert_eq!(description("# only a comment"), None); + assert_eq!( + description("'Use # inside' # after"), + Some("Use # inside".into()) + ); + assert_eq!(description("'it''s # kept'"), Some("it's # kept".into())); + assert_eq!( + description(r##""Say \"#1\" \\ done" # after"##), + Some(r##"Say "#1" \ done"##.into()) + ); + assert_eq!( + description("'not closed # here"), + Some("'not closed # here".into()), + "quotes that do not close leave the value as written" + ); + assert_eq!( + description("|\n # a line, not a comment\n more"), + Some("# a line, not a comment\nmore".into()) + ); + + // A write reads the front matter the same way. + let test = LibraryTest::new("library skill comments", CONFIGURATION_GRANTS); + let created = create( + &test, + json!({ "name": "notes", "description": "Takes notes." }), + ); + let written = write_skill( + &test, + "notes", + &created["revision"], + "---\nname: notes # mine\ndescription: Takes notes. # short\n---\n\nBody\n", + ); + assert_eq!(written["changed"], true); + assert_eq!(skill_row(&test, "notes")["description"], "Takes notes."); +} + +#[test] +fn more_skills_than_a_read_lists_are_cut_by_name_every_time() { + let test = LibraryTest::new("library skill limit", CONFIGURATION_GRANTS); + let skills = test.library.join("skills"); + let own = test.home.join(".sample").join("skills"); + // Made last first, so the order they were made in is not the answer. + for index in (0..514).rev() { + let name = format!("skill-{index:03}"); + for root in [&skills, &own] { + fs::create_dir_all(root.join(&name)).unwrap(); + fs::write( + root.join(&name).join("SKILL.md"), + format!("---\nname: {name}\n---\n"), + ) + .unwrap(); + } + } + let expected: Vec = (0..512).map(|index| format!("skill-{index:03}")).collect(); + let listed = |read: &Value| -> (Vec, Vec) { + let names = |rows: &Value| { + rows.as_array() + .unwrap() + .iter() + .map(|row| row["name"].as_str().unwrap().to_string()) + .collect::>() + }; + ( + names(&read["skills"]), + names(&read["agents"][0]["skills"]["items"]), + ) + }; + let first = listed(&test.read()); + assert_eq!(first.0, expected, "the library's first 512 by name"); + assert_eq!(first.1, expected, "the agent's first 512 by name"); + assert_eq!(listed(&test.read()), first, "every read lists the same"); + + let refused = |name: &str| { + test.harness.refused( + "agentLibrary.createSkill", + json!({ "name": name, "description": "More." }), + ) + }; + assert_eq!(refused("skill-600"), "agentLibrary.libraryFull"); + assert_eq!( + refused("skill-513"), + "agentLibrary.skillNameTaken", + "a skill beyond the listed ones still has its name" + ); +} + +#[test] +fn a_skill_change_whose_backup_fails_is_refused_by_the_library() { + let test = LibraryTest::new("library skill backup fails", CONFIGURATION_GRANTS); + let created = create( + &test, + json!({ "name": "notes", "description": "Takes notes." }), + ); + let source = source_folder(&test); + test.harness.run( + "agentLibrary.importSkill", + json!({ "directory": path_text(&source) }), + ); + fs::write(source.join("scripts").join("run.sh"), "echo two\n").unwrap(); + // A file where the backups directory goes cannot hold one. + fs::write(test.library.join("backups"), "not a directory").unwrap(); + + let text = "---\nname: notes\ndescription: Takes more notes.\n---\n"; + assert_eq!( + refused_write(&test, "notes", &created["revision"], text), + "agentLibrary.backupFailed" + ); + assert_eq!(read_skill(&test, "notes")["revision"], created["revision"]); + assert_eq!( + test.harness.refused( + "agentLibrary.reinstallSkill", + json!({ "name": "folder-skill" }) + ), + "agentLibrary.backupFailed" + ); + assert_eq!( + fs::read_to_string( + test.library + .join("skills") + .join("folder-skill") + .join("scripts") + .join("run.sh") + ) + .unwrap(), + "echo one\n", + "the library's copy stays" + ); +} + +#[test] +fn a_skill_file_is_written_whole_only_at_its_revision_and_backed_up_first() { + let test = LibraryTest::new("library skill write", CONFIGURATION_GRANTS); + let created = create( + &test, + json!({ "name": "review", "description": "Reviews changes." }), + ); + let skill = test.library.join("skills").join("review"); + fs::create_dir_all(skill.join("references")).unwrap(); + fs::write(skill.join("references").join("guide.md"), "12345").unwrap(); + fs::write(skill.join("helper.py"), "print()\n").unwrap(); + let read = read_skill(&test, "review"); + assert_eq!( + read["files"], + json!([ + { "path": "helper.py", "size": 8 }, + { "path": "references/guide.md", "size": 5 } + ]), + "other files are listed by path and size, never read" + ); + let revision = read["revision"].clone(); + assert_eq!(revision, created["revision"]); + + let edited = "---\nname: review\ndescription: |\n Reviews changes\n before a merge.\n---\n\nRead the diff.\n"; + let written = write_skill(&test, "review", &revision, edited); + assert_eq!(written["changed"], true); + assert_ne!(written["revision"], revision); + assert_eq!(read_skill(&test, "review")["text"], edited); + assert_eq!( + skill_row(&test, "review")["description"], + "Reviews changes\nbefore a merge." + ); + let kept = backups(&test); + assert!( + kept.iter() + .any(|(path, text)| path.contains("/baseline/") && text.contains("# review")), + "the file as it was is backed up: {kept:?}" + ); + assert!(test.library.join("backups").read_dir().unwrap().count() == 1); + + assert_eq!( + refused_write(&test, "review", &revision, edited), + "agentLibrary.revisionChanged", + "a write over a file read before the last write is refused" + ); + let unchanged = write_skill(&test, "review", &written["revision"], edited); + assert_eq!( + unchanged, + json!({ "changed": false, "revision": written["revision"] }) + ); + + let current = written["revision"].clone(); + for (text, code) in [ + ("No front matter.\n", "agentLibrary.invalidSkillFile"), + ( + "---\nname: review\ndescription: Open\n", + "agentLibrary.invalidSkillFile", + ), + ( + "---\nname: review\ndescription: x\n---\nnul\u{0}", + "agentLibrary.invalidSkillFile", + ), + ( + "---\nname: other\ndescription: Renamed.\n---\n", + "agentLibrary.skillNameMismatch", + ), + ( + "---\ndescription: No name.\n---\n", + "agentLibrary.skillNameMismatch", + ), + ( + "---\nname: review\n---\n", + "agentLibrary.invalidSkillDescription", + ), + ( + "---\nname: review\ndescription: \"\"\n---\n", + "agentLibrary.invalidSkillDescription", + ), + ] { + assert_eq!( + refused_write(&test, "review", ¤t, text), + code, + "{text:?}" + ); + } + let long = format!( + "---\nname: review\ndescription: {}\n---\n", + "x".repeat(1025) + ); + assert_eq!( + refused_write(&test, "review", ¤t, &long), + "agentLibrary.invalidSkillDescription" + ); + let large = format!( + "---\nname: review\ndescription: Big.\n---\n{}", + "x".repeat(64 * 1024) + ); + assert_eq!( + refused_write(&test, "review", ¤t, &large), + "agentLibrary.fileTooLarge" + ); + assert_eq!(read_skill(&test, "review")["text"], edited); + + // A file whose name is not the directory's keeps it. + fs::write( + skill.join("SKILL.md"), + "---\nname: Code Review\ndescription: Old style.\n---\n", + ) + .unwrap(); + let renamed = read_skill(&test, "review")["revision"].clone(); + let kept_name = "---\nname: Code Review\ndescription: Still old style.\n---\n"; + assert_eq!( + write_skill(&test, "review", &renamed, kept_name)["changed"], + true + ); + + assert_eq!( + test.harness + .refused("agentLibrary.readSkill", json!({ "name": "absent" })), + "agentLibrary.unknownItem" + ); + assert_eq!( + refused_write(&test, "absent", ¤t, edited), + "agentLibrary.unknownItem" + ); + fs::write(skill.join("SKILL.md"), [0xff, 0xfe, b'\n']).unwrap(); + assert_eq!( + test.harness + .refused("agentLibrary.readSkill", json!({ "name": "review" })), + "agentLibrary.unreadable", + "a SKILL.md that is not UTF-8 is never read for editing" + ); + + let (refused, logs) = capture::run(false, || refused_write(&test, "absent", ¤t, edited)); + assert_eq!(refused, "agentLibrary.unknownItem"); + let failed = logs + .iter() + .find(|log| log.event == "agent.library.skill_change_failed") + .expect("a refused skill change is logged"); + assert_eq!(failed.fields["change"], "write"); + assert_eq!(failed.fields["reason"], "agentLibrary.unknownItem"); + + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let create = test.harness.refused( + "agentLibrary.createSkill", + json!({ "name": "late", "description": "Late." }), + ); + let write = refused_write(&test, "review", ¤t, edited); + let reinstall = test + .harness + .refused("agentLibrary.reinstallSkill", json!({ "name": "review" })); + trace::replace(previous); + assert_eq!(create, "agentLibrary.userActionRequired"); + assert_eq!(write, "agentLibrary.userActionRequired"); + assert_eq!(reinstall, "agentLibrary.userActionRequired"); +} + +#[test] +fn a_skill_from_a_folder_records_its_source_and_is_installed_again_from_it() { + let test = LibraryTest::new("library skill source", CONFIGURATION_GRANTS); + let source = source_folder(&test); + let imported = test.harness.run( + "agentLibrary.importSkill", + json!({ "directory": path_text(&source) }), + ); + assert_eq!( + imported, + json!({ "name": "folder-skill", "files": 2, "skipped": 2 }), + "`.git` and `.DS_Store` stay behind" + ); + let library_copy = test.library.join("skills").join("folder-skill"); + assert_eq!( + contents(&library_copy).keys().collect::>(), + ["SKILL.md", "scripts/run.sh"] + ); + let row = skill_row(&test, "folder-skill"); + assert_eq!(row["source"]["path"], path_text(&source)); + let installed_at = row["source"]["installedAtMs"].as_i64().unwrap(); + assert!(installed_at > 0); + assert_eq!( + check(&test), + vec![json!({ + "name": "folder-skill", + "path": path_text(&source), + "installedAtMs": installed_at, + "edited": false, + "state": "unchanged", + })] + ); + // What a copy leaves behind is no change. + fs::write(source.join(".DS_Store"), "finder moved a window").unwrap(); + assert_eq!(check(&test)[0]["state"], "unchanged"); + + fs::write(source.join("scripts").join("run.sh"), "echo two\n").unwrap(); + assert_eq!(check(&test)[0]["state"], "changed"); + let (reinstalled, logs) = capture::run(false, || { + test.harness.run( + "agentLibrary.reinstallSkill", + json!({ "name": "folder-skill" }), + ) + }); + let finished = logs + .iter() + .find(|log| log.event == "agent.library.skill_reinstall_finished") + .expect("a reinstall is logged"); + assert_eq!(finished.fields["changed"], true); + assert_eq!(finished.fields["discarded"], false); + for log in &logs { + let fields = serde_json::to_string(&log.fields).unwrap(); + assert!( + !fields.contains("folder-skill") && !fields.contains("echo"), + "logs carry no name, path or content: {fields}" + ); + } + assert_eq!( + reinstalled, + json!({ "name": "folder-skill", "files": 2, "skipped": 2, "changed": true }) + ); + assert_eq!( + fs::read_to_string(library_copy.join("scripts").join("run.sh")).unwrap(), + "echo two\n" + ); + assert!( + backups(&test) + .iter() + .any(|(path, text)| path.ends_with("/replaced/scripts/run.sh") && text == "echo one\n"), + "the version a reinstall replaced is kept with the skill's backups" + ); + assert_eq!(check(&test)[0]["state"], "unchanged"); + let again = test.harness.run( + "agentLibrary.reinstallSkill", + json!({ "name": "folder-skill" }), + ); + assert_eq!( + again["changed"], false, + "an unchanged source changes nothing" + ); + + // An edit in the library is replaced only when the user says so. + let revision = read_skill(&test, "folder-skill")["revision"].clone(); + let edited = SKILL_TEXT.replace("Body", "Edited body"); + write_skill(&test, "folder-skill", &revision, &edited); + let row = &check(&test)[0]; + assert_eq!(row["edited"], true); + assert_eq!(row["state"], "unchanged"); + assert_eq!( + test.harness.refused( + "agentLibrary.reinstallSkill", + json!({ "name": "folder-skill" }), + ), + "agentLibrary.skillEdited" + ); + assert_eq!(read_skill(&test, "folder-skill")["text"], edited); + let discarded = test.harness.run( + "agentLibrary.reinstallSkill", + json!({ "name": "folder-skill", "discardEdits": true }), + ); + assert_eq!(discarded["changed"], true); + assert_eq!(read_skill(&test, "folder-skill")["text"], SKILL_TEXT); + assert!( + backups(&test) + .iter() + .any(|(path, text)| path.ends_with("/replaced/SKILL.md") && *text == edited), + "the edited version is kept" + ); + assert_eq!(check(&test)[0]["edited"], false); + + // A source that is gone, or no longer a skill, cannot be installed from. + fs::remove_file(source.join("SKILL.md")).unwrap(); + let row = &check(&test)[0]; + assert_eq!(row["state"], "unavailable"); + assert_eq!(row["reason"], "agentLibrary.notSkill"); + fs::remove_dir_all(&source).unwrap(); + let row = &check(&test)[0]; + assert_eq!(row["reason"], "agentLibrary.sourceMissing"); + assert_eq!( + test.harness.refused( + "agentLibrary.reinstallSkill", + json!({ "name": "folder-skill" }), + ), + "agentLibrary.sourceMissing" + ); + assert!( + library_copy.join("SKILL.md").is_file(), + "the library's copy stays" + ); + + create(&test, json!({ "name": "own", "description": "Mine." })); + assert_eq!( + test.harness + .refused("agentLibrary.reinstallSkill", json!({ "name": "own" })), + "agentLibrary.noSource" + ); + assert_eq!( + test.harness.run( + "agentLibrary.checkSkillSources", + json!({ "names": ["own"] }) + )["skills"], + json!([]), + "only skills copied in from a folder have a source" + ); + assert_eq!( + test.harness.refused( + "agentLibrary.checkSkillSources", + json!({ "names": ["bad name"] }), + ), + "agentLibrary.invalidSkillName" + ); + + test.harness.run( + "agentLibrary.removeSkill", + json!({ "name": "folder-skill" }), + ); + assert!(!library_copy.exists()); + assert!(check(&test).is_empty()); + let sources = fs::read_to_string(test.library.join("sources.json")).unwrap(); + assert!(!sources.contains("folder-skill"), "{sources}"); + assert!( + !backups(&test) + .keys() + .any(|path| path.contains("/replaced/")), + "a removed skill's backups go with it" + ); +} + +#[test] +fn a_copy_refuses_too_deep_a_folder_and_leaves_nothing_behind() { + let test = LibraryTest::new("library skill bounds", CONFIGURATION_GRANTS); + let source = test.harness.dir.path().join("deep"); + let mut directory = source.clone(); + for level in 0..18 { + directory = directory.join(format!("level-{level}")); + } + fs::create_dir_all(&directory).unwrap(); + fs::write(source.join("SKILL.md"), SKILL_TEXT).unwrap(); + fs::write(directory.join("deepest.md"), "deep").unwrap(); + assert_eq!( + test.harness.refused( + "agentLibrary.importSkill", + json!({ "directory": path_text(&source) }), + ), + "agentLibrary.skillTooLarge" + ); + assert_eq!( + test.harness.refused( + "agentLibrary.importSkill", + json!({ "directory": path_text(&test.harness.dir.path().join("absent")) }), + ), + "agentLibrary.notSkill" + ); + assert!(!test.library.join("skills").join("folder-skill").exists()); + assert_eq!( + fs::read_dir(test.library.join("staging")).unwrap().count(), + 0 + ); +} + +#[cfg(unix)] +#[test] +fn a_copy_never_follows_links_refuses_special_files_and_keeps_executable_bits() { + use std::os::unix::fs::{symlink, PermissionsExt}; + // A short name: a socket's path has at most about 100 bytes. + let test = LibraryTest::new("sk", CONFIGURATION_GRANTS); + let source = source_folder(&test); + let outside = test.harness.dir.path().join("outside"); + fs::create_dir_all(&outside).unwrap(); + fs::write(outside.join("secret.txt"), "secret").unwrap(); + symlink(&outside, source.join("outside")).unwrap(); + symlink( + source.join("scripts").join("run.sh"), + source.join("run-link.sh"), + ) + .unwrap(); + let script = source.join("scripts").join("run.sh"); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + + let imported = test.harness.run( + "agentLibrary.importSkill", + json!({ "directory": path_text(&source) }), + ); + assert_eq!( + imported["skipped"], 4, + "both links and what a copy leaves behind" + ); + let library_copy = test.library.join("skills").join("folder-skill"); + assert!(!library_copy.join("outside").exists()); + assert!(fs::symlink_metadata(library_copy.join("run-link.sh")).is_err()); + let mode = fs::metadata(library_copy.join("scripts").join("run.sh")) + .unwrap() + .permissions() + .mode(); + assert_ne!(mode & 0o111, 0, "an executable script stays executable"); + let sources = fs::metadata(test.library.join("sources.json")) + .unwrap() + .permissions() + .mode(); + assert_eq!(sources & 0o077, 0, "the source record is the owner's only"); + + // The executable bit is part of what a source holds. + fs::set_permissions(&script, fs::Permissions::from_mode(0o644)).unwrap(); + assert_eq!(check(&test)[0]["state"], "changed"); + + let special = test.harness.dir.path().join("s"); + fs::create_dir_all(&special).unwrap(); + fs::write( + special.join("SKILL.md"), + SKILL_TEXT.replace("folder-skill", "special"), + ) + .unwrap(); + let _socket = std::os::unix::net::UnixListener::bind(special.join("a.sock")).unwrap(); + assert_eq!( + test.harness.refused( + "agentLibrary.importSkill", + json!({ "directory": path_text(&special) }), + ), + "agentLibrary.specialFile" + ); + assert!(!test.library.join("skills").join("special").exists()); + + let linked = test.harness.dir.path().join("linked-skill-file"); + fs::create_dir_all(&linked).unwrap(); + symlink(source.join("SKILL.md"), linked.join("SKILL.md")).unwrap(); + assert_eq!( + test.harness.refused( + "agentLibrary.importSkill", + json!({ "directory": path_text(&linked) }), + ), + "agentLibrary.notSkill", + "a SKILL.md that is a link is not copied" + ); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 1339aeac..ccbb2d83 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -285,8 +285,22 @@ pub enum AgentsCommand { LibraryParseServers, /// Applies one library change to one agent's configuration (`agentLibrary.apply`). LibraryApply, + /// Makes a library skill with front matter (`agentLibrary.createSkill`). + LibraryCreateSkill, + /// Reads a library skill's `SKILL.md` whole with its revision and lists + /// its other files (`agentLibrary.readSkill`). + LibraryReadSkill, + /// Replaces a library skill's `SKILL.md` if it is still at the revision + /// read (`agentLibrary.writeSkill`). + LibraryWriteSkill, /// Copies a skill into the library (`agentLibrary.importSkill`). LibraryImportSkill, + /// Compares library skills with the folders they were installed from + /// (`agentLibrary.checkSkillSources`). + LibraryCheckSkillSources, + /// Copies a library skill again from the folder it was installed from + /// (`agentLibrary.reinstallSkill`). + LibraryReinstallSkill, /// Removes a library skill and its links (`agentLibrary.removeSkill`). LibraryRemoveSkill, /// Reads each agent's model, providers and profiles (`agentProviders.read`). @@ -339,7 +353,12 @@ impl AgentsCommand { Self::LibrarySave => "agentLibrary.save", Self::LibraryParseServers => "agentLibrary.parseServers", Self::LibraryApply => "agentLibrary.apply", + Self::LibraryCreateSkill => "agentLibrary.createSkill", + Self::LibraryReadSkill => "agentLibrary.readSkill", + Self::LibraryWriteSkill => "agentLibrary.writeSkill", Self::LibraryImportSkill => "agentLibrary.importSkill", + Self::LibraryCheckSkillSources => "agentLibrary.checkSkillSources", + Self::LibraryReinstallSkill => "agentLibrary.reinstallSkill", Self::LibraryRemoveSkill => "agentLibrary.removeSkill", Self::ProvidersRead => "agentProviders.read", Self::ProvidersApply => "agentProviders.apply", @@ -1369,7 +1388,16 @@ impl CoreCommand { "agentLibrary.save" => Some(Self::Agents(AgentsCommand::LibrarySave)), "agentLibrary.parseServers" => Some(Self::Agents(AgentsCommand::LibraryParseServers)), "agentLibrary.apply" => Some(Self::Agents(AgentsCommand::LibraryApply)), + "agentLibrary.createSkill" => Some(Self::Agents(AgentsCommand::LibraryCreateSkill)), + "agentLibrary.readSkill" => Some(Self::Agents(AgentsCommand::LibraryReadSkill)), + "agentLibrary.writeSkill" => Some(Self::Agents(AgentsCommand::LibraryWriteSkill)), "agentLibrary.importSkill" => Some(Self::Agents(AgentsCommand::LibraryImportSkill)), + "agentLibrary.checkSkillSources" => { + Some(Self::Agents(AgentsCommand::LibraryCheckSkillSources)) + } + "agentLibrary.reinstallSkill" => { + Some(Self::Agents(AgentsCommand::LibraryReinstallSkill)) + } "agentLibrary.removeSkill" => Some(Self::Agents(AgentsCommand::LibraryRemoveSkill)), "agentProviders.read" => Some(Self::Agents(AgentsCommand::ProvidersRead)), "agentProviders.apply" => Some(Self::Agents(AgentsCommand::ProvidersApply)), diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 17195436..856632f1 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -61,7 +61,7 @@ pub static EVENTS: &[EventMetadata] = &[ message: "The agent library could not clean up after itself, and what it names stays behind", fields: &[ FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Filesystem error category raised by the removal or write, such as PermissionDenied; never a path or file content", reason: None }, - FieldMetadata { name: "target", field_type: FieldType::Token, required: true, description: "What stays behind: temporary (the new file a failed write left next to the file it replaces), staging (a staged copy of an agent's configuration file), skillImport (a partly copied skill), backup (a backup baseline or history entry) or backupRecord (the backup record, not put back after a failure)", reason: None }, + FieldMetadata { name: "target", field_type: FieldType::Token, required: true, description: "What stays behind: temporary (the new file a failed write left next to the file it replaces), staging (a staged copy of an agent's configuration file), skillImport (a skill copied or made in staging that did not go into the library), backup (a backup baseline or history entry), backupRecord (the backup record, not put back after a failure), skillBackup (the backups of a removed skill, or the version an earlier reinstall replaced), skillSource (the source record of a removed skill) or skillReplaced (the version a reinstall replaced, not put back after the new one could not take its place)", reason: None }, ], span: None, rate: 60, @@ -95,6 +95,31 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.library.skill_change_failed", + channel: "agent", + level: LogLevel::Warn, + message: "A change to the library's skills was refused", + fields: &[ + FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Skill command refused: create, write, import, reinstall or remove", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code such as agentLibrary.skillEdited; never names, paths or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.skill_create_finished", + channel: "agent", + level: LogLevel::Info, + message: "A skill was made in the agent library", + fields: &[ + FieldMetadata { name: "bytes", field_type: FieldType::Int, required: true, description: "Bytes of the SKILL.md written; never its text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.library.skill_import_finished", channel: "agent", @@ -108,6 +133,21 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.library.skill_reinstall_finished", + channel: "agent", + level: LogLevel::Info, + message: "A library skill was copied again from the folder it was installed from", + fields: &[ + FieldMetadata { name: "changed", field_type: FieldType::Bool, required: true, description: "False when the library's copy already held what the folder holds", reason: None }, + FieldMetadata { name: "discarded", field_type: FieldType::Bool, required: true, description: "True when the copy replaced edits made in the library since the install", reason: None }, + FieldMetadata { name: "files", field_type: FieldType::Int, required: true, description: "Regular files copied", reason: None }, + FieldMetadata { name: "skipped", field_type: FieldType::Int, required: true, description: "Links and left-behind entries not copied", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.library.skill_removed", channel: "agent", @@ -120,6 +160,34 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.library.skill_sources_inspected", + channel: "agent", + level: LogLevel::Debug, + message: "Library skills were compared with the folders they were installed from", + fields: &[ + FieldMetadata { name: "changed", field_type: FieldType::Int, required: true, description: "Skills whose source folder changed since it was copied", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the check took", reason: None }, + FieldMetadata { name: "skills", field_type: FieldType::Int, required: true, description: "Skills with a recorded source that were checked", reason: None }, + FieldMetadata { name: "unavailable", field_type: FieldType::Int, required: true, description: "Skills whose source folder could not be read as a skill", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.skill_write_finished", + channel: "agent", + level: LogLevel::Info, + message: "A library skill's SKILL.md was written", + fields: &[ + FieldMetadata { name: "bytes", field_type: FieldType::Int, required: true, description: "Bytes of the SKILL.md sent; never its text", reason: None }, + FieldMetadata { name: "changed", field_type: FieldType::Bool, required: true, description: "False when the text was what the file already held", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.library.updated", channel: "agent", diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index ad5027f1..b2675234 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -455,7 +455,7 @@ "target": { "type": "token", "required": true, - "description": "What stays behind: temporary (the new file a failed write left next to the file it replaces), staging (a staged copy of an agent's configuration file), skillImport (a partly copied skill), backup (a backup baseline or history entry) or backupRecord (the backup record, not put back after a failure)" + "description": "What stays behind: temporary (the new file a failed write left next to the file it replaces), staging (a staged copy of an agent's configuration file), skillImport (a skill copied or made in staging that did not go into the library), backup (a backup baseline or history entry), backupRecord (the backup record, not put back after a failure), skillBackup (the backups of a removed skill, or the version an earlier reinstall replaced), skillSource (the source record of a removed skill) or skillReplaced (the version a reinstall replaced, not put back after the new one could not take its place)" }, "error": { "type": "error", @@ -685,6 +685,121 @@ }, "rate": 60, "owner": "lithe-core" + }, + { + "id": "agent.library.skill_create_finished", + "channel": "agent", + "level": "info", + "message": "A skill was made in the agent library", + "fields": { + "bytes": { + "type": "int", + "required": true, + "description": "Bytes of the SKILL.md written; never its text" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.skill_write_finished", + "channel": "agent", + "level": "info", + "message": "A library skill's SKILL.md was written", + "fields": { + "changed": { + "type": "bool", + "required": true, + "description": "False when the text was what the file already held" + }, + "bytes": { + "type": "int", + "required": true, + "description": "Bytes of the SKILL.md sent; never its text" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.skill_sources_inspected", + "channel": "agent", + "level": "debug", + "message": "Library skills were compared with the folders they were installed from", + "fields": { + "skills": { + "type": "int", + "required": true, + "description": "Skills with a recorded source that were checked" + }, + "changed": { + "type": "int", + "required": true, + "description": "Skills whose source folder changed since it was copied" + }, + "unavailable": { + "type": "int", + "required": true, + "description": "Skills whose source folder could not be read as a skill" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the check took" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.skill_reinstall_finished", + "channel": "agent", + "level": "info", + "message": "A library skill was copied again from the folder it was installed from", + "fields": { + "files": { + "type": "int", + "required": true, + "description": "Regular files copied" + }, + "skipped": { + "type": "int", + "required": true, + "description": "Links and left-behind entries not copied" + }, + "changed": { + "type": "bool", + "required": true, + "description": "False when the library's copy already held what the folder holds" + }, + "discarded": { + "type": "bool", + "required": true, + "description": "True when the copy replaced edits made in the library since the install" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.skill_change_failed", + "channel": "agent", + "level": "warn", + "message": "A change to the library's skills was refused", + "fields": { + "change": { + "type": "token", + "required": true, + "description": "Skill command refused: create, write, import, reinstall or remove" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code such as agentLibrary.skillEdited; never names, paths or text" + } + }, + "rate": 60, + "owner": "lithe-core" } ] } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 343c4f60..1da4560f 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4694,10 +4694,13 @@ bytes and each value at most 32 KiB (`agentLibrary.invalidEnvironment`). In `directory`, created owner-only, Core keeps `library.json` (the servers with the values of their environment variables and headers, the hooks and the instruction sets; always written owner-only), `skills//` (one -directory per skill), +directory per skill), `sources.json` (the folder each skill copied in from +this machine came from; always written owner-only; see +[Library skills](#library-skills)), `state.json` (a digest of what Core last put in each agent's instruction -block), `staging/` (the copies plugins edit) and `backups/` (each agent's -files as they were before Lithe changed them; see +block), `staging/` (the copies plugins edit and the skills being made or +copied in) and `backups/` (each agent's files as they were before Lithe +changed them, and the versions of a library skill Lithe replaced; see [Backups and restore](#backups-and-restore)). The library is `{mcpServers, hooks, instructions}`: @@ -4752,13 +4755,20 @@ and its `agents` when not empty. | `agentLibrary.save` | `{revision, library}` | `{revision, instructions}` | | `agentLibrary.parseServers` | `{text}` | `{servers, problems}` | | `agentLibrary.apply` | `{agent, change}` | `{changed}`; `{changed, revision, instructions}` for an instructions `import`, `{changed, revision}` for a server `import` | +| `agentLibrary.createSkill` | `{name, description, body?}` | `{name, revision}` | +| `agentLibrary.readSkill` | `{name}` | `{name, text, revision, files, truncated?}` | +| `agentLibrary.writeSkill` | `{name, revision, text}` | `{changed, revision}` | | `agentLibrary.importSkill` | `{agent, name}` or `{directory}` | `{name, files, skipped}` | +| `agentLibrary.checkSkillSources` | `{names?}` | `{skills}` | +| `agentLibrary.reinstallSkill` | `{name, discardEdits?}` | `{name, files, skipped, changed}` | | `agentLibrary.removeSkill` | `{name}` | `{unlinked}` | -- `save`, `apply`, `importSkill` and `removeSkill` run only for a request - whose origin is the user (`agentLibrary.userActionRequired`): a plugin - never changes the library or an agent's configuration. `parseServers` - only reads the text it is given (see [Pasted servers](#pasted-servers)). +- `save`, `apply`, `createSkill`, `writeSkill`, `importSkill`, + `reinstallSkill` and `removeSkill` run only for a request whose origin is + the user (`agentLibrary.userActionRequired`): a plugin never changes the + library or an agent's configuration. `parseServers` only reads the text + it is given (see [Pasted servers](#pasted-servers)); `readSkill` and + `checkSkillSources` only read. - `revision` is the SHA-256 of `library.json` in lowercase hex, or `empty` before the first save. `save` replaces the library only while the file is still at `revision` (`agentLibrary.revisionChanged`) and never replaces a @@ -4777,10 +4787,11 @@ host can show where the library is; the library, as `save` takes it back, with each variable of a server given as `{name, valueSet}` in place of its value; and `skills`, `states`, `stateDetails`, `found` and `agents`: -- `skills`: the library's skills, `{name, description?, agents}`, sorted by - name. `agents` maps each agent key to `on` (the agent's skills directory - has a link of that name into the library), `conflict` (an entry of that - name that is not) or `off`. +- `skills`: the library's skills, `{name, description?, agents, source?}`, + sorted by name; of more than 512, the first 512 by name. `agents` maps each agent key to `on` (the agent's skills + directory has a link of that name into the library), `conflict` (an entry + of that name that is not) or `off`. `source` is `{path, installedAtMs}` + for a skill copied in from a folder (see [Library skills](#library-skills)). - `states.mcpServers` maps each library server's name, and `states.hooks` each library hook's `id`, to the same kind of map. A server's state is as [MCP servers](#mcp-servers) describes. A hook is `on` @@ -4820,7 +4831,8 @@ value; and `skills`, `states`, `stateDetails`, `found` and `agents`: `absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge` or `unreadable`. `ownLines`, given whenever the file could be read, counts the lines of the user's own text outside Lithe's block. - - `skills`: `{path, items}` with up to 512 `{name, kind, description?}`, + - `skills`: `{path, items}` with up to 512 `{name, kind, description?}` + sorted by name, the first 512 by name when the directory holds more, `kind` being `library` (a link into the library), `own` (a directory of the agent's own) or `link` (a link elsewhere); or `{path, error: "agentLibrary.unreadable"}`. Entries without a readable `SKILL.md`, @@ -4897,7 +4909,7 @@ A server or hook changes through the plugin, on a copy: it. The copy is removed either way. 5. Before replacing the file, Core backs it up ([Backups and restore](#backups-and-restore)); when it cannot, the file - is not changed (`agentProviders.backupFailed`). + is not changed (`agentLibrary.backupFailed`). A skill is linked as a symbolic link to `skills/` of the library. Unlinking removes only a link into the library @@ -4911,26 +4923,145 @@ as they are. Instructions are written and imported as [Instruction files](#instruction-files) describes. -`importSkill` copies a skill into the library: `{agent, name}` the agent's -own skill directory `name` (a link is `agentLibrary.notOwnSkill`), -`{directory}` an absolute directory the user chose -(`agentLibrary.invalidSkillDirectory`); any other shape is -`agentLibrary.invalidImport`. The directory needs a readable `SKILL.md` -(`agentLibrary.notSkill`). The skill's name is `name`, else the `name` of the -`SKILL.md` front matter, else the directory's name, and is 1–64 bytes of +The library's own skills are made, edited, copied in and installed again +as [Library skills](#library-skills) describes. + +#### Library skills + +A library skill is a directory `skills//`, not a link, holding a +regular file `SKILL.md` Core can open, whose YAML front matter gives the +skill's `name` and `description`. Of the front matter Core reads only these +two, as YAML reads them: a plain scalar ends where a comment starts, at a +`#` that opens the value or follows a space or tab; a single- or +double-quoted scalar is the text between its quotes, `#` included, and may +be followed by a comment; the lines of a block scalar (`|` or `>`) are its +text. `read` cuts a description to 1024 characters, and reads a `SKILL.md` +larger than 64 KiB as a skill without one. A skill's name is 1–64 bytes of ASCII letters, digits, `.`, `_` and `-`, not starting with `.` -(`agentLibrary.invalidSkillName`). Core copies the regular files and -directories, counting the links and other entries it skips in `skipped`, -within 1024 files, 16 MiB and 16 levels (`agentLibrary.skillTooLarge`), and -moves the copy into the library without replacing a skill -(`agentLibrary.skillExists`). Of the front matter Core reads only `name` and -`description`, as plain, quoted or block scalars; a description is cut to -1024 characters. - -`removeSkill` removes the skill's links from the skills directory of every -agent whose plugin is granted, then the skill, and answers how many links it -removed. A link in an agent whose plugin is not granted is left, and leads -nowhere. +(`agentLibrary.invalidSkillName`). `read` lists at most 512 skills, the +first 512 by name. + +A skill that enters the library, made or copied in, also has a name that +does not end with `.` and is no Windows device name such as `con`. Names +are compared ignoring ASCII case, so that every host can hold the library: + +- a skill `read` lists of that name is `agentLibrary.skillExists`; +- any other entry of `skills/` of that name is + `agentLibrary.skillNameTaken`: a file, a link, a directory without a + `SKILL.md` Core can open, or a skill beyond the 512 `read` lists. `read` + lists none of them; the user removes or renames the entry in the library + directory (`directory` in `read`); +- a library that lists 512 skills is `agentLibrary.libraryFull`. + +A skill is made or copied in `staging/` and moved into `skills/` whole, +never over anything there. + +`createSkill {name, description, body?}` makes a skill whose `SKILL.md` is +front matter with `name` and `description`, a blank line, then `body`, or a +heading `# ` without one. Core joins the description's lines and runs +of whitespace into single spaces; it is then 1–1024 characters without +other control characters (`agentLibrary.invalidSkillDescription`). Each +value is written as a plain YAML scalar when YAML reads it back as the same +string, otherwise single-quoted. The file is at most 64 KiB +(`agentLibrary.fileTooLarge`) without NUL (`agentLibrary.invalidSkillFile`). +It answers the skill's `name` and the `revision` of its `SKILL.md`. + +`readSkill {name}` answers the skill's `SKILL.md` whole as `text`, with its +`revision`, the SHA-256 of the file in lowercase hex. The file must be a +regular file of at most 64 KiB (`agentLibrary.fileTooLarge`) that is UTF-8 +(`agentLibrary.unreadable`). `files` lists the skill's other regular files, +`{path, size}` in path order, `path` relative to the skill with `/` and +`size` in bytes; Core never reads or writes them. It lists at most 1024 of +them, 16 levels deep, and adds `truncated: true` when there are more. A +name the library has no skill of is `agentLibrary.unknownItem`. + +`writeSkill {name, revision, text}` replaces the `SKILL.md` with `text` +while the file is still at `revision` (`agentLibrary.revisionChanged`). +`text` is at most 64 KiB (`agentLibrary.fileTooLarge`), has no NUL and +opens with front matter between two `---` lines +(`agentLibrary.invalidSkillFile`); its `name` is the skill's name, or the +`name` the file gives now (`agentLibrary.skillNameMismatch`), and its +`description` has 1–1024 characters, not all whitespace, without control +characters other than whitespace (`agentLibrary.invalidSkillDescription`). +Text the file already holds answers `changed: false` and writes nothing. +Before the file is replaced, Core backs it up +([Backups and restore](#backups-and-restore)); when it cannot, the file is +not changed (`agentLibrary.backupFailed`). The new file replaces the old +one with the old one's permissions. Every agent the skill is linked into +reads the new text at once. It answers `changed` and the new `revision`. + +`importSkill` copies a skill into the library: `{agent, name}` the agent's +own skill directory `name` (a link is `agentLibrary.notOwnSkill`; an agent +without `skills` is `agentLibrary.noSkills`), `{directory}` an absolute +folder the user chose (`agentLibrary.invalidSkillDirectory`); any other +shape is `agentLibrary.invalidImport`. The directory needs a `SKILL.md` +that is a regular file, not a link (`agentLibrary.notSkill`). The skill's +name is `name`, else the `name` of the `SKILL.md` front matter, else the +directory's name. The copy: + +- reads the directory through handles that never follow a link, so nothing + outside it is read; links inside it are left out; +- leaves behind entries named `.git` and `.DS_Store`, wherever they are; +- refuses a device, socket, pipe or other entry that is not a regular file, + directory or link (`agentLibrary.specialFile`); +- takes at most 1024 files, 16 MiB and 16 levels (`agentLibrary.skillTooLarge`); +- keeps a file's executable bit where the platform has one. + +It answers how many regular files it copied (`files`) and how many entries +it left out (`skipped`). A copy that fails leaves nothing behind. + +A skill copied in from `{directory}` has a source, which `sources.json` +records: the folder's path as given, when the copy was made +(`installedAtMs`, milliseconds since the epoch), and the digest of what was +copied. The digest is the SHA-256 over each copied file's path, whether it +is executable, and the SHA-256 of its bytes, so it changes when a file the +copy takes changes and not when a link or a left-behind entry does. A skill +made with `createSkill` or copied from an agent has no source. `read` gives +each skill's source as `{path, installedAtMs}`. + +`checkSkillSources {names?}` answers `skills`, one `{name, path, +installedAtMs, state, reason?, edited}` for each library skill with a +source, or each of `names` (at most 512 skill names; more is +`agentLibrary.invalidFilter`, an invalid one `agentLibrary.invalidSkillName`) +that has one: + +| `state` | Meaning | +| --- | --- | +| `unchanged` | The folder holds what was copied. | +| `changed` | The folder holds something else; `reinstallSkill` copies it. | +| `unavailable` | The folder cannot be copied now; `reason` is the refusal `reinstallSkill` would give: `agentLibrary.sourceMissing` (not a directory any more), `agentLibrary.notSkill`, `agentLibrary.specialFile`, `agentLibrary.skillTooLarge` or `agentLibrary.unreadable`. | + +`edited` says whether the library's copy differs from what was copied, as +the same digest of the library's directory tells, or cannot be read in +full. The check reads every file of each folder it compares; it changes +nothing and never uses the network. + +`reinstallSkill {name, discardEdits?}` copies the skill again from its +source, as `importSkill` copies, and puts the copy in place of the +library's. A skill without a source is `agentLibrary.noSource`, and the +refusals of the copy are those of `importSkill` with +`agentLibrary.sourceMissing` for a folder that is no longer a directory. +When the library's copy is `edited`, it is replaced only with +`discardEdits: true` (`agentLibrary.skillEdited`). When the library already +holds what the folder holds, nothing changes (`changed: false`). Otherwise +the library's directory moves into the skill's backups +([Backups and restore](#backups-and-restore)) and the copy takes its +place; when the directory cannot move there nothing changes +(`agentLibrary.backupFailed`), and when the copy cannot take its place +the directory is put back (`agentLibrary.writeFailed`). The source record +then holds the new time and digest. Links into the library keep pointing at +the skill, so agents read the new version at once. + +`removeSkill {name}` removes the skill's links from the skills directory of +every agent whose plugin is granted, then the skill with its source record +and its backups, and answers how many links it removed. A link in an agent +whose plugin is not granted is left, and leads nowhere. + +These commands, `sources.json`, the skill backups and `source` in `read` +were added within `agents` 0, as were the refusal of special files, the +entries left behind, the stricter names of skills entering the library, +`agentLibrary.skillNameTaken`, comments in front matter, the first 512 by +name, and `agentLibrary.backupFailed` for the library's commands. #### MCP servers @@ -5053,7 +5184,7 @@ and each agent's items in the order its entry lists them. | --- | --- | --- | | `mcpServers` | `apply` `import` from the agent `importFrom`, whose copy is the first by the order `import` takes copies in | `agentLibrary.serverExists`, `agentLibrary.libraryFull`, or `agentLibrary.invalidLibrary` when that copy breaks a rule of the library | | `hooks` | the host adds the hook to the library in a `save` | `agentLibrary.libraryFull` | - | `skills` | `importSkill {agent, name}` from `importFrom`, the first agent whose own directory holds it | `agentLibrary.skillExists`, or `agentLibrary.notOwnSkill` when no copy is an agent's own directory | + | `skills` | `importSkill {agent, name}` from `importFrom`, the first agent whose own directory holds it | `agentLibrary.skillExists` or `agentLibrary.skillNameTaken` (the library holds a skill, or another entry, of the name, ignoring ASCII case; see [Library skills](#library-skills)), `agentLibrary.notOwnSkill` when no copy is an agent's own directory, `agentLibrary.invalidSkillName` for a name a skill entering the library cannot have, or `agentLibrary.libraryFull` | `valuesMissing: true` says the server copy an import takes lacks a variable's value. @@ -5185,13 +5316,13 @@ Writing: first); `failed` is a write that failed, `reason` being its refusal code, such as `agentLibrary.unreadable`, `agentLibrary.fileTooLarge`, `agentLibrary.brokenLink`, `agentLibrary.writeFailed` or - `agentProviders.backupFailed`. One agent's outcome never stops the + `agentLibrary.backupFailed`. One agent's outcome never stops the others, and the library stays saved. An agent whose `enabled` is false is not written, so turning it off leaves its block as it is. - Each write follows links in the file's path to the file itself (`agentLibrary.brokenLink`), replaces the file the same way as a configuration file, and backs it up first like one - (`agentProviders.backupFailed`), the write over an `edited` block + (`agentLibrary.backupFailed`), the write over an `edited` block included. An agent without `instructions` is `agentLibrary.noInstructions`. @@ -5689,7 +5820,17 @@ command makes it: Linking or unlinking a skill replaces and removes nothing of the agent's own, so it keeps nothing. When the backup cannot be kept, the file is not -changed, and either command refuses with `agentProviders.backupFailed`. +changed, and the command refuses in its own domain: an `agentLibrary.*` +command with `agentLibrary.backupFailed`, an `agentProviders.*` command +with `agentProviders.backupFailed`. + +A library skill's `SKILL.md` that `agentLibrary.writeSkill` replaces is +backed up the same way, under the digest of the skill's own key, which no +agent key can have: one baseline and the newest 20 earlier contents. The +directory an `agentLibrary.reinstallSkill` replaces moves to `replaced/` +there, in place of the one an earlier reinstall left. No restore command +reads them; they stay in the library directory for the user, and go when +`agentLibrary.removeSkill` removes the skill. For each file Core keeps one baseline: the file as it was before Lithe's first change since the last restore, or that it did not exist. A file has @@ -5773,7 +5914,18 @@ in `agentLibrary.read` offers no restore there. a staged copy, a partly imported skill, a backup baseline or history entry), or a backup record it cannot put back after a failure, stays where it is and logs `agent.library.cleanup_failed` with what it is and - the filesystem error category, never its path. Models and providers log `agent.providers.read_finished`, + the filesystem error category, never its path; for skills that is a + skill copied or made in `staging/` that did not go into the library, a + removed skill's backups or source record, or the version a reinstall + replaced and could not put back. Skill commands log + `agent.library.skill_create_finished` and + `agent.library.skill_write_finished` with byte counts, + `agent.library.skill_import_finished` and + `agent.library.skill_reinstall_finished` with file counts, + `agent.library.skill_sources_inspected` with counts and the duration, + `agent.library.skill_removed`, and `agent.library.skill_change_failed` + with the command and the refusal code; none carries a skill's name, + path or text. Models and providers log `agent.providers.read_finished`, `agent.providers.read_failed`, `agent.providers.change_applied` and `agent.providers.change_failed` with the `op` only. A restore, of any agent, logs `agent.providers.restore_applied` (file count, whether diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 78a8be8f..5f89a2bd 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -61,7 +61,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-38 | 受管网络 | 部分完成 | `network/request`:可取消、有界 HTTP(S) | 下载文件、身份验证会话 | [工作流](../guides/plugin-workflows.md) | | API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | -| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充);插件可在 `providers` 快照里[列出模型](../contract/v1/README.md#listed-models)及其推理强度、速度档和上下文窗口,Core 检查选择在清单里、组合是插件允许的,用户在 Lithe 选择器里显示或隐藏模型的开关由 Core 记住(`agentProviders.showModels`),插件声明 `setModelMenu` 时 CLI 自己的模型菜单跟着变,开关和选择可整组读出、写回(`agentProviders.readModelSettings`、`agentProviders.applyModelSettings`)(`agents` 0 内的补充);插件用 `configuration.mcpServers` 声明 CLI 支持的 MCP 连接方式和能保存的字段,资源库的 [MCP 服务器](../contract/v1/README.md#mcp-servers)多了环境变量和请求头(值存在仅所有者可读写的 `library.json`,只写不读,不进回答、拒绝和日志)、备注、开关、禁用的工具、超时和图标,Core 只写 Agent 能保存的字段,放不进去时在 `stateDetails` 给出原因;`agentLibrary.apply` 的服务器 `import` 连同值从 Agent 导入,`agentLibrary.parseServers` 解析粘贴的 JSON,`agentLibrary.read` 带资源库目录和只在 Agent 里的条目分组 `found`(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区、模型方案的保存与切换;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充);插件可在 `providers` 快照里[列出模型](../contract/v1/README.md#listed-models)及其推理强度、速度档和上下文窗口,Core 检查选择在清单里、组合是插件允许的,用户在 Lithe 选择器里显示或隐藏模型的开关由 Core 记住(`agentProviders.showModels`),插件声明 `setModelMenu` 时 CLI 自己的模型菜单跟着变,开关和选择可整组读出、写回(`agentProviders.readModelSettings`、`agentProviders.applyModelSettings`)(`agents` 0 内的补充);插件用 `configuration.mcpServers` 声明 CLI 支持的 MCP 连接方式和能保存的字段,资源库的 [MCP 服务器](../contract/v1/README.md#mcp-servers)多了环境变量和请求头(值存在仅所有者可读写的 `library.json`,只写不读,不进回答、拒绝和日志)、备注、开关、禁用的工具、超时和图标,Core 只写 Agent 能保存的字段,放不进去时在 `stateDetails` 给出原因;`agentLibrary.apply` 的服务器 `import` 连同值从 Agent 导入,`agentLibrary.parseServers` 解析粘贴的 JSON,`agentLibrary.read` 带资源库目录和只在 Agent 里的条目分组 `found`(`agents` 0 内的补充);资源库的[技能](../contract/v1/README.md#library-skills)可以新建(`agentLibrary.createSkill`,生成带 `name`、`description` 的 front matter)、整份读写 `SKILL.md`(`agentLibrary.readSkill`、`agentLibrary.writeSkill`,带 `revision`、有大小上限、校验 front matter,写前备份,技能里其他文件只列名字和大小),从本机文件夹安装时用不跟随链接的句柄拷贝、拒绝特殊文件并在仅所有者可读写的 `sources.json` 记下来源,之后可检查来源是否变化(`agentLibrary.checkSkillSources`)并从来源重新安装(`agentLibrary.reinstallSkill`,换下的目录留作备份);技能的操作都不联网(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区、模型方案的保存与切换;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | ### 计划中的 API @@ -284,7 +284,7 @@ Status meanings: | API-38 | Managed network | Partial | `network/request`: bounded HTTP(S) with cancellation | File downloads and authentication sessions | [Workflows](../guides/plugin-workflows.md) | | API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | -| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0); the plugin may [list models](../contract/v1/README.md#listed-models) in the `providers` snapshot with their reasoning efforts, speeds, and context windows, Core checks that a pick is listed and a combination the plugin allows, Core keeps the switches with which the user shows or hides models in Lithe's pickers (`agentProviders.showModels`), the CLI's own model menu follows them when the plugin declares `setModelMenu`, and the switches and picks are read and written back as one group (`agentProviders.readModelSettings`, `agentProviders.applyModelSettings`) (an addition within `agents` 0); a plugin declares the MCP transports its CLI connects with and the server fields it keeps in `configuration.mcpServers`, the library's [MCP servers](../contract/v1/README.md#mcp-servers) gain environment variables and headers (values kept in the owner-only `library.json`, write-only, never in an answer, refusal or log), a note, a switch, tools left out, timeouts and an icon, Core writes only the fields the agent keeps and gives the reason in `stateDetails` when a server cannot be put, a server `import` of `agentLibrary.apply` takes an agent's server with its values, `agentLibrary.parseServers` reads pasted JSON, and `agentLibrary.read` gives the library directory and `found`, the groups of items only in agents (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces, saving and switching model plans; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | +| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0); the plugin may [list models](../contract/v1/README.md#listed-models) in the `providers` snapshot with their reasoning efforts, speeds, and context windows, Core checks that a pick is listed and a combination the plugin allows, Core keeps the switches with which the user shows or hides models in Lithe's pickers (`agentProviders.showModels`), the CLI's own model menu follows them when the plugin declares `setModelMenu`, and the switches and picks are read and written back as one group (`agentProviders.readModelSettings`, `agentProviders.applyModelSettings`) (an addition within `agents` 0); a plugin declares the MCP transports its CLI connects with and the server fields it keeps in `configuration.mcpServers`, the library's [MCP servers](../contract/v1/README.md#mcp-servers) gain environment variables and headers (values kept in the owner-only `library.json`, write-only, never in an answer, refusal or log), a note, a switch, tools left out, timeouts and an icon, Core writes only the fields the agent keeps and gives the reason in `stateDetails` when a server cannot be put, a server `import` of `agentLibrary.apply` takes an agent's server with its values, `agentLibrary.parseServers` reads pasted JSON, and `agentLibrary.read` gives the library directory and `found`, the groups of items only in agents (an addition within `agents` 0); library [skills](../contract/v1/README.md#library-skills) can be created (`agentLibrary.createSkill`, which writes front matter with `name` and `description`), their `SKILL.md` read and written whole (`agentLibrary.readSkill`, `agentLibrary.writeSkill`, with a `revision`, a size limit and checked front matter, backed up before a write, the skill's other files listed by name and size only), and a skill installed from a folder on this machine is copied through handles that never follow a link, refuses special files and has its source recorded in the owner-only `sources.json`, so the host can check whether the source changed (`agentLibrary.checkSkillSources`) and install it again from there (`agentLibrary.reinstallSkill`, which keeps the replaced directory as a backup); nothing about skills uses the network (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces, saving and switching model plans; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | ### Planned APIs diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 9062154d..e5bee94f 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -67,7 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令;插件在 `providers` 快照里列出的模型(`models`、`efforts`、`speeds`、`effort`、`speed`、`modelMenu`、`targets.modelMenu`)、操作 `setEffort`、`setSpeed`、`setModelMenu` 和 `setModel` 的 `effort`、`speed`,以及命令 `agentProviders.showModels`、`agentProviders.readModelSettings`、`agentProviders.applyModelSettings` 是其后的补充;`configuration.mcpServers`、资源库 MCP 服务器的环境变量与请求头(值只写不读)、备注、开关、`pausedAgents`、禁用的工具、超时和图标,`configuration.read` 报告的值、开关、禁用的工具和超时,`edit` 的服务器按声明带这些字段,`agentLibrary.apply` 的服务器 `import`、`agentLibrary.parseServers`,以及 `agentLibrary.read` 的 `directory`、`stateDetails`、`found` 和 `mcpServerSupport` 是最后的补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令;插件在 `providers` 快照里列出的模型(`models`、`efforts`、`speeds`、`effort`、`speed`、`modelMenu`、`targets.modelMenu`)、操作 `setEffort`、`setSpeed`、`setModelMenu` 和 `setModel` 的 `effort`、`speed`,以及命令 `agentProviders.showModels`、`agentProviders.readModelSettings`、`agentProviders.applyModelSettings` 是其后的补充;`configuration.mcpServers`、资源库 MCP 服务器的环境变量与请求头(值只写不读)、备注、开关、`pausedAgents`、禁用的工具、超时和图标,`configuration.read` 报告的值、开关、禁用的工具和超时,`edit` 的服务器按声明带这些字段,`agentLibrary.apply` 的服务器 `import`、`agentLibrary.parseServers`,以及 `agentLibrary.read` 的 `directory`、`stateDetails`、`found` 和 `mcpServerSupport` 是其后的补充;资源库技能的 `agentLibrary.createSkill`、`agentLibrary.readSkill`、`agentLibrary.writeSkill`、`agentLibrary.checkSkillSources`、`agentLibrary.reinstallSkill`,`agentLibrary.importSkill {directory}` 记下的来源(`sources.json`,`agentLibrary.read` 技能的 `source`)和技能的备份是最后的补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -188,7 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands; the models a plugin lists in the `providers` snapshot (`models`, `efforts`, `speeds`, `effort`, `speed`, `modelMenu`, `targets.modelMenu`), the operations `setEffort`, `setSpeed` and `setModelMenu` with the `effort` and `speed` of `setModel`, and the commands `agentProviders.showModels`, `agentProviders.readModelSettings` and `agentProviders.applyModelSettings` were added after that; `configuration.mcpServers`, the environment variables and headers (write-only values), note, switch, `pausedAgents`, tools left out, timeouts and icon of a library MCP server, the values, switch, tools left out and timeouts `configuration.read` reports, the declared fields of a server `edit` receives, the server `import` of `agentLibrary.apply`, `agentLibrary.parseServers`, and the `directory`, `stateDetails`, `found` and `mcpServerSupport` of `agentLibrary.read` were added last | ✅ | Pending host integration | [Agents](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands; the models a plugin lists in the `providers` snapshot (`models`, `efforts`, `speeds`, `effort`, `speed`, `modelMenu`, `targets.modelMenu`), the operations `setEffort`, `setSpeed` and `setModelMenu` with the `effort` and `speed` of `setModel`, and the commands `agentProviders.showModels`, `agentProviders.readModelSettings` and `agentProviders.applyModelSettings` were added after that; `configuration.mcpServers`, the environment variables and headers (write-only values), note, switch, `pausedAgents`, tools left out, timeouts and icon of a library MCP server, the values, switch, tools left out and timeouts `configuration.read` reports, the declared fields of a server `edit` receives, the server `import` of `agentLibrary.apply`, `agentLibrary.parseServers`, and the `directory`, `stateDetails`, `found` and `mcpServerSupport` of `agentLibrary.read` were added after that; the library skill commands `agentLibrary.createSkill`, `agentLibrary.readSkill`, `agentLibrary.writeSkill`, `agentLibrary.checkSkillSources` and `agentLibrary.reinstallSkill`, the source `agentLibrary.importSkill {directory}` records (`sources.json`, and `source` of a skill in `agentLibrary.read`) and the backups of skills were added last | ✅ | Pending host integration | [Agents](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | | `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | ✅ | [Toolchains](domains/toolchains.md) | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 27a0e0d4..70b980f0 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -77,6 +77,21 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 - **从 Agent 导入**:`apply` 的 `{category: "mcpServers", op: "import", name, revision}` 把 Agent 的服务器连同值一起放进资源库,不改 Agent 的文件;资源库已有同名是 `agentLibrary.serverExists`,满了是 `agentLibrary.libraryFull`。 - **粘贴解析**:`agentLibrary.parseServers {text}` 把用户粘贴的 JSON(可带注释和末尾逗号,也可以只是一个 `"名称": {…}` 成员)解析成 `save` 用的服务器,不保存。支持 `mcpServers`、`servers`、`context_servers`、`mcp` 下的服务器表、单个服务器对象、服务器数组和名称到服务器的对象;语法错误给出行和列(按字符计),条目问题给出 JSON 指针和原因。 +### 资源库里的技能 + +资源库的每个技能是 `skills//` 目录(不是链接),里面有 Core 能打开的普通文件 `SKILL.md`,用 YAML front matter 给出 `name` 和 `description`。Core 按 YAML 的规则读这两个值:不加引号的值遇到注释就结束(值开头的 `#`,或空格、制表符后面的 `#`);单引号、双引号里的 `#` 是正文,引号后面可以跟注释;`|`、`>` 块里的每一行都是正文。技能名是 1–64 字节的 ASCII 字母、数字、`.`、`_`、`-`,不以 `.` 开头。`read` 最多列出 512 个技能,超出时取按名字排序的前 512 个,每次都一样;Agent 技能目录也是如此。 + +新建或拷入的技能另外不以 `.` 结尾、不是 `con` 这类 Windows 设备名。名字比较忽略大小写:和 `read` 列出的技能同名是 `agentLibrary.skillExists`;和 `skills/` 里其他东西同名是 `agentLibrary.skillNameTaken`,包括文件、链接、没有能打开的 `SKILL.md` 的目录,以及排在 512 个之外的技能,它们都不在 `read` 里,要用户到资源库目录(`read` 的 `directory`)删掉或改名;`read` 已经列出 512 个时是 `agentLibrary.libraryFull`。技能先在 `staging/` 里做好,再整个移进 `skills/`,不会盖掉任何已有的东西。以下命令(`agents` 0 内的补充)里,改动资源库的只接受用户发起的请求,都不联网: + +- **新建**:`agentLibrary.createSkill {name, description, body?}` 写出带 `name`、`description` 的 front matter,后面是 `body`(不给就是标题 `# `)。描述的换行和连续空白合成一个空格,1–1024 个字符,不含其他控制字符(`agentLibrary.invalidSkillDescription`);文件不超过 64 KiB。回答 `{name, revision}`。 +- **读写 `SKILL.md`**:`agentLibrary.readSkill {name}` 整份回答 `text` 和 `revision`(文件的 SHA-256),以及技能里其他普通文件的清单 `files`(`{path, size}`,最多 1024 个,超出时 `truncated: true`);其他文件只列名字和大小,不读不写。`agentLibrary.writeSkill {name, revision, text}` 在文件仍是 `revision` 时整份替换(否则 `agentLibrary.revisionChanged`):文本要以两行 `---` 之间的 front matter 开头(`agentLibrary.invalidSkillFile`),`name` 等于技能名或文件现在写的名字(`agentLibrary.skillNameMismatch`),`description` 合规(`agentLibrary.invalidSkillDescription`)。替换前先备份,备份不成功就不改(`agentLibrary.backupFailed`);内容没变回答 `changed: false`,什么都不写。 +- **从本机文件夹安装**:`agentLibrary.importSkill {directory}` 把用户选的文件夹拷进资源库。`SKILL.md` 要是普通文件、不是链接(`agentLibrary.notSkill`);拷贝用不跟随链接的句柄读取,不会读到文件夹外面,文件夹里的链接和 `.git`、`.DS_Store` 都略过(计入 `skipped`),设备、套接字、管道等特殊文件整体拒绝(`agentLibrary.specialFile`),最多 1024 个文件、16 MiB、16 层(`agentLibrary.skillTooLarge`),保留可执行位。拷贝失败不留下任何东西。`sources.json`(仅所有者可读写)记下来源:路径、安装时间 `installedAtMs` 和拷入内容的摘要;`read` 的技能带 `source: {path, installedAtMs}`。从 Agent 导入的 `{agent, name}` 和新建的技能没有来源。 +- **检查来源**:`agentLibrary.checkSkillSources {names?}` 对每个有来源的技能回答 `{name, path, installedAtMs, state, reason?, edited}`:`state` 为 `unchanged`、`changed` 或 `unavailable`(`reason` 是重新安装会给的拒绝码,如 `agentLibrary.sourceMissing`);`edited` 表示资源库里的副本是否已和当初拷入的不同。它读来源文件夹的全部文件,只读不改。 +- **从来源重新安装**:`agentLibrary.reinstallSkill {name, discardEdits?}` 按 `importSkill` 的规则重新拷一份,换掉资源库里的那份。没有来源是 `agentLibrary.noSource`;资源库的副本被改过时要 `discardEdits: true`,否则 `agentLibrary.skillEdited`;内容相同回答 `changed: false`。被换下的目录移到该技能的备份里,移不过去就什么都不改(`agentLibrary.backupFailed`),新副本放不进去就把原目录放回(`agentLibrary.writeFailed`)。链接进 Agent 的技能立刻读到新内容。 +- **删除**:`agentLibrary.removeSkill {name}` 去掉已授权 Agent 里的链接,再删掉技能、它的来源记录和备份。 + +详见[契约的 Library skills](../../contract/v1/README.md#library-skills)。 + ### 只在 Agent 里的条目 `read` 的 `found` 把 Agent 里有、资源库里没有的条目按项归组,宿主不用自己再比:MCP 服务器按名称,Hooks 按事件、匹配器、命令和超时,技能按名称(先是技能目录里的,再是 CLI 自己装的)。每组列出各 Agent 的副本和它是第几种写法(`variant`),资源库有同名项时标出副本和资源库那份是否不同(`differsFromLibrary`),并说明能否导入、从哪个 Agent 导入(`importFrom`)或为什么不能(`reason`)。两个副本只差在值上也算两种写法,但组里不带值。 @@ -117,7 +132,7 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 ### 修改前备份与恢复 -Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库目录的 `backups/` 下(目录 `0700`、文件 `0600`),不管是哪条命令改的:`agentProviders.apply` 改的声明文件、`agentLibrary.apply` 为 MCP 服务器和 Hooks 改的声明文件、`agentLibrary.apply` 的写入和并入、`agentLibrary.save` 之后的同步改动的指令文件(包括用户确认 `replace: true` 覆盖被改过的块的那一次)。技能的符号链接不覆盖、不删除 Agent 自己的内容,不备份,恢复时也不动。备份不成功就不改文件,两条命令都以 `agentProviders.backupFailed` 拒绝。 +Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库目录的 `backups/` 下(目录 `0700`、文件 `0600`),不管是哪条命令改的:`agentProviders.apply` 改的声明文件、`agentLibrary.apply` 为 MCP 服务器和 Hooks 改的声明文件、`agentLibrary.apply` 的写入和并入、`agentLibrary.save` 之后的同步改动的指令文件(包括用户确认 `replace: true` 覆盖被改过的块的那一次)。技能的符号链接不覆盖、不删除 Agent 自己的内容,不备份,恢复时也不动。备份不成功就不改文件,命令按自己的领域拒绝:`agentLibrary.*` 命令是 `agentLibrary.backupFailed`,`agentProviders.*` 命令是 `agentProviders.backupFailed`。资源库技能的 `SKILL.md` 被 `agentLibrary.writeSkill` 替换前也按同样的方式备份(一份基线加最近 20 份),`agentLibrary.reinstallSkill` 换下的目录放在同一处的 `replaced/`;它们没有恢复命令,删除技能时一起删掉。 - **一个文件一份基线**:基线是“自上次恢复以来 Lithe 第一次修改前的原样”(或“原来不存在”),无论资源库还是供应商先改到这个文件,都只存这一次,之后的修改不会替换它;例如 CLI 把 MCP 服务器和模型供应商放在同一个文件里时也是如此。另外保留 Lithe 最后一次写入内容的 SHA-256 和最近 20 份历史。备份是逐字节副本,可能含密钥,只存在本机 Lithe 数据目录,不进日志、不发给插件或宿主。 - **状态**:有备份时,`agentLibrary.read` 的每个 Agent 和 `agentProviders.read`(只列声明了 `providers` 的 Agent)都带同一个 `backup: {savedAtMs, modifiedSince}`:最早基线的保存时间,以及备份过的文件现在是否和 Lithe 最后写入的不一样(文件不见了或读不出也算改过)。 @@ -137,6 +152,7 @@ Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库 | [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储、命令和筛选、`read` 与 `edit` 函数、限制和拒绝码 | | [MCP servers](../../contract/v1/README.md#mcp-servers) | 服务器的额外字段、值的只写规则、按声明写入、状态和从 Agent 导入 | +| [Library skills](../../contract/v1/README.md#library-skills) | 技能的新建、`SKILL.md` 读写、从文件夹安装、来源检查与重新安装、删除和拒绝码 | | [Found items](../../contract/v1/README.md#found-items) | 只在 Agent 里的条目怎么分组、比较和导入 | | [Pasted servers](../../contract/v1/README.md#pasted-servers) | `agentLibrary.parseServers` 支持的写法和问题原因 | | [Instruction files](../../contract/v1/README.md#instruction-files) | 指令文件里 Lithe 的块、状态、保存后同步、并入资源库和已有数据的迁移 | @@ -251,6 +267,21 @@ Beyond its name, transport, command, arguments and URL, a library server may hav - **Importing from an agent**: `apply` with `{category: "mcpServers", op: "import", name, revision}` takes the agent's server with its values into the library without changing the agent's files; a server of that name already in the library is `agentLibrary.serverExists`, a full library `agentLibrary.libraryFull`. - **Pasted text**: `agentLibrary.parseServers {text}` reads the JSON the user pasted (comments and trailing commas allowed, or just one `"name": {…}` member) into servers in the shape `save` takes, and saves nothing. It reads the server maps under `mcpServers`, `servers`, `context_servers` and `mcp`, one server object, an array of servers, and an object of servers by name; a syntax error gives its line and column (in characters), and a problem with an entry its JSON pointer and reason. +### Library skills + +Each library skill is a directory `skills//`, not a link, whose regular file `SKILL.md`, one Core can open, gives its `name` and `description` in YAML front matter. Core reads the two as YAML does: a plain value ends at a comment (a `#` that opens the value or follows a space or tab); a `#` between single or double quotes is text, and a comment may follow the closing quote; every line of a `|` or `>` block is text. A skill name is 1–64 bytes of ASCII letters, digits, `.`, `_` and `-`, not starting with `.`. `read` lists at most 512 skills, the first 512 by name, the same every time, and an agent's skills directory the same way. + +A skill made or copied in also does not end with `.` and is no Windows device name such as `con`. Names are compared ignoring case: a skill `read` lists of the name is `agentLibrary.skillExists`; anything else of the name in `skills/` is `agentLibrary.skillNameTaken`, be it a file, a link, a directory without a `SKILL.md` Core can open, or a skill beyond the 512 listed, none of which `read` lists, so the user removes or renames it in the library directory (`directory` in `read`); a library that lists 512 is `agentLibrary.libraryFull`. A skill is made in `staging/` and moved into `skills/` whole, never over anything there. Of these commands (added within `agents` 0), those that change the library accept only a request the user started, and none uses the network: + +- **Create**: `agentLibrary.createSkill {name, description, body?}` writes front matter with `name` and `description`, then `body`, or the heading `# ` without one. The description's line breaks and runs of whitespace become single spaces, and it has 1–1024 characters without other control characters (`agentLibrary.invalidSkillDescription`); the file is at most 64 KiB. It answers `{name, revision}`. +- **Read and write `SKILL.md`**: `agentLibrary.readSkill {name}` answers the file whole as `text` with its `revision` (its SHA-256), and the skill's other regular files as `files` (`{path, size}`, at most 1024, with `truncated: true` beyond); those are listed by name and size and never read or written. `agentLibrary.writeSkill {name, revision, text}` replaces the file whole while it is still at `revision` (else `agentLibrary.revisionChanged`): the text opens with front matter between two `---` lines (`agentLibrary.invalidSkillFile`), its `name` is the skill's or the one the file gives now (`agentLibrary.skillNameMismatch`), and its `description` is valid (`agentLibrary.invalidSkillDescription`). The file is backed up first and left as it is when that fails (`agentLibrary.backupFailed`); the same text answers `changed: false` and writes nothing. +- **Install from a folder on this machine**: `agentLibrary.importSkill {directory}` copies the folder the user chose into the library. Its `SKILL.md` is a regular file, not a link (`agentLibrary.notSkill`). The copy reads through handles that never follow a link, so it reads nothing outside the folder; it leaves out links, `.git` and `.DS_Store` (counted in `skipped`), refuses a device, socket, pipe or other special file (`agentLibrary.specialFile`), takes at most 1024 files, 16 MiB and 16 levels (`agentLibrary.skillTooLarge`), and keeps executable bits. A copy that fails leaves nothing behind. `sources.json` (owner-only) records the source: the path, the time `installedAtMs` and a digest of what was copied; skills in `read` carry `source: {path, installedAtMs}`. A skill imported from an agent with `{agent, name}` or made with `createSkill` has none. +- **Check the sources**: `agentLibrary.checkSkillSources {names?}` answers `{name, path, installedAtMs, state, reason?, edited}` for each skill with a source: `state` is `unchanged`, `changed` or `unavailable` (`reason` is the refusal a reinstall would give, such as `agentLibrary.sourceMissing`), and `edited` says whether the library's copy differs from what was copied. It reads every file of the source folders and changes nothing. +- **Reinstall from the source**: `agentLibrary.reinstallSkill {name, discardEdits?}` copies the folder again by the rules of `importSkill` and puts the copy in place of the library's. A skill without a source is `agentLibrary.noSource`; an edited library copy needs `discardEdits: true`, else `agentLibrary.skillEdited`; the same content answers `changed: false`. The replaced directory moves into the skill's backups, and nothing changes when it cannot (`agentLibrary.backupFailed`); when the copy cannot take its place the directory is put back (`agentLibrary.writeFailed`). Agents that link the skill read the new version at once. +- **Remove**: `agentLibrary.removeSkill {name}` removes the skill's links from the granted agents, then the skill, its source record and its backups. + +See [Library skills](../../contract/v1/README.md#library-skills) in the contract. + ### Items only in agents `found` in `read` groups what agents hold outside the library, so the host compares nothing itself: MCP servers by name, hooks by event, matcher, command and timeout, skills by name (the skills directories first, then what the CLIs installed). Each group lists each agent's copy and which distinct copy it is (`variant`), marks, when the library has an item of the name, whether the copy differs from it (`differsFromLibrary`), and says whether the library can import it and from which agent (`importFrom`) or why not (`reason`). Two copies that differ only in a value are two variants, and no group carries a value. @@ -291,7 +322,7 @@ The commands are `agentProviders.read {agent?}`, `agentProviders.apply {agent, c ### Backups before a change, and restore -Before Core replaces any of an agent's files, it backs the file up under `backups/` in the library directory (directories `0700`, files `0600`), whichever command replaces it: a declared file `agentProviders.apply` changes, a declared file `agentLibrary.apply` changes for an MCP server or hook, and the instruction file an `agentLibrary.apply` write or import or the sync after an `agentLibrary.save` changes, including the write over an edited block that the user confirmed with `replace: true`. A skill link replaces and removes nothing of the agent's own, so it is not backed up, and a restore leaves it as it is. When the backup cannot be kept, the file is not changed and either command refuses with `agentProviders.backupFailed`. +Before Core replaces any of an agent's files, it backs the file up under `backups/` in the library directory (directories `0700`, files `0600`), whichever command replaces it: a declared file `agentProviders.apply` changes, a declared file `agentLibrary.apply` changes for an MCP server or hook, and the instruction file an `agentLibrary.apply` write or import or the sync after an `agentLibrary.save` changes, including the write over an edited block that the user confirmed with `replace: true`. A skill link replaces and removes nothing of the agent's own, so it is not backed up, and a restore leaves it as it is. When the backup cannot be kept, the file is not changed and the command refuses in its own domain: an `agentLibrary.*` command with `agentLibrary.backupFailed`, an `agentProviders.*` command with `agentProviders.backupFailed`. A library skill's `SKILL.md` that `agentLibrary.writeSkill` replaces is backed up the same way (one baseline and the newest 20), and the directory an `agentLibrary.reinstallSkill` replaces is kept there as `replaced/`; no restore command reads them, and removing the skill removes them. - **One baseline per file**: the baseline is the file as it was before Lithe's first change since the last restore, or that it did not exist. Whether the library or a providers change reaches the file first, it is kept once and later changes never replace it, also when a CLI keeps its MCP servers and model providers in one file. Core also keeps the SHA-256 of what Lithe last wrote and the newest 20 earlier contents. A backup is a byte-for-byte copy and may hold keys; it stays in the local Lithe data directory and never goes into a log, a plugin or the host. - **Status**: while a backup exists, each agent of `agentLibrary.read`, and of `agentProviders.read` for an agent that declares `providers`, carries the same `backup: {savedAtMs, modifiedSince}`: when the oldest baseline was kept, and whether a backed-up file now differs from what Lithe last wrote (a file that is gone or cannot be read counts as changed). @@ -311,6 +342,7 @@ Before Core replaces any of an agent's files, it backs the file up under `backup | [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage, commands and filters, the `read` and `edit` functions, limits, and refusal codes | | [MCP servers](../../contract/v1/README.md#mcp-servers) | A server's further fields, write-only values, writing by declaration, states, and importing from an agent | +| [Library skills](../../contract/v1/README.md#library-skills) | Creating a skill, reading and writing `SKILL.md`, installing from a folder, checking sources and reinstalling, removing, and refusal codes | | [Found items](../../contract/v1/README.md#found-items) | How items only in agents are grouped, compared and imported | | [Pasted servers](../../contract/v1/README.md#pasted-servers) | The shapes `agentLibrary.parseServers` reads and its problem reasons | | [Instruction files](../../contract/v1/README.md#instruction-files) | Lithe's block in the instruction file, its states, the sync after a save, import, and how existing data is migrated | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index ddad4660..58134a51 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -19,6 +19,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | | [#264](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/264)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的 MCP 服务器补齐字段:清单新增 `agents[].configuration.mcpServers {transports?, fields?}`,插件声明 CLI 支持的连接方式(`stdio`、`http`、`sse`,不写为全部)和能保存的字段(`environment`、`headers`、`enabled`、`disabledTools`、`startupTimeout`、`callTimeout`,不写为都不保存),需要 `read`,安装审查和目录条目列出它。资源库服务器新增 `environment`、`headers`(`{name, value?}`)、`note`、`enabled`、`pausedAgents`、`disabledTools`、`startupTimeoutSeconds`、`callTimeoutSeconds`、`icon`(PNG/JPEG/GIF/WebP,解码后不超过 32 KiB,不联网取);值存在 `library.json`,Core 总以仅所有者可读写写入,`agentLibrary.read` 只回答 `{name, valueSet}`,`save` 不带值的变量沿用原值、改名用 `renamedFrom`,回答、拒绝和日志都不带值。插件函数参数:`configuration.read` 的服务器新增 `environment`、`headers`(带值)、`enabled`、`disabledTools`、`startupTimeoutSeconds`、`callTimeoutSeconds`,原来只报名字的 `environmentNames`、`headerNames` 仍可用、两者不能同时给;`configuration.edit` 的 `put` 服务器只带插件声明的字段,声明了 `environment`/`headers` 时带值,声明了 `enabled` 时总带开关。宿主命令:新增 `agentLibrary.parseServers {text}`(解析粘贴的 JSON,回答 `{servers, problems}`,不保存);`agentLibrary.apply` 新增 `{category: "mcpServers", op: "import", name, revision}`(连同值从 Agent 导入,不改 Agent,回答 `{changed, revision}`);`agentLibrary.read` 新增 `directory`、`stateDetails`(`reason`、`unsupportedFields`)、`found`(只在 Agent 里的服务器、Hooks、技能分组,标出不同写法、与资源库是否不同、能否导入及原因)、Agent 条目的 `mcpServerSupport`,服务器状态改为比较 `put` 实际写入的内容,`query` 也匹配服务器备注。新增错误码 `agentLibrary.transportUnsupported`、`agentLibrary.fieldUnsupported`、`agentLibrary.valueMissing`、`agentLibrary.serverOff`(放不进 Agent 的原因)、`agentLibrary.serverExists`、`agentLibrary.libraryFull`(导入)、`agentLibrary.textTooLarge`(粘贴超过 256 KiB)、`agentLibrary.libraryTooLarge`(保存后的 `library.json` 会超过 Core 能读回的 8 MiB)。没有新增插件可调用的宿主方法、通知、日志事件或能力版本;四语 SDK 的 API 不变,SDK 文档改为说明读取时报告值。 | +| [#265](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/265)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库技能的新建、编辑和从本机文件夹安装,全部不联网。宿主命令:新增 `agentLibrary.createSkill {name, description, body?}`(生成带 `name`、`description` front matter 的 `SKILL.md`,回答 `{name, revision}`)、`agentLibrary.readSkill {name}`(整份回答 `SKILL.md` 的 `text`、`revision`,其他普通文件只列 `{path, size}`,最多 1024 个,超出时带 `truncated`)、`agentLibrary.writeSkill {name, revision, text}`(按 `revision` 整份替换,64 KiB 上限,校验 front matter 的 `name` 与 `description`,替换前按 #260 的方式备份,回答 `{changed, revision}`)、`agentLibrary.checkSkillSources {names?}`(对有来源的技能回答 `state` 为 `unchanged`/`changed`/`unavailable`、`reason?` 和 `edited`)、`agentLibrary.reinstallSkill {name, discardEdits?}`(从来源重新拷贝,换下的目录移进该技能备份的 `replaced/`,回答 `{name, files, skipped, changed}`);`agentLibrary.importSkill {directory}` 改为用不跟随链接的句柄拷贝,略过链接、`.git`、`.DS_Store`,拒绝特殊文件,保留可执行位,并在资源库目录新的 `sources.json`(仅所有者可读写)记下来源的路径、安装时间和内容摘要;`agentLibrary.read` 的技能新增 `source {path, installedAtMs}`;新建和拷入的技能名还要能在 Windows 上使用、不能与已有技能忽略大小写同名,资源库最多 512 个技能;`removeSkill` 同时删掉来源记录和备份。新增错误码 `agentLibrary.invalidSkillFile`、`agentLibrary.skillNameMismatch`、`agentLibrary.invalidSkillDescription`、`agentLibrary.specialFile`、`agentLibrary.noSource`、`agentLibrary.sourceMissing`、`agentLibrary.skillEdited`、`agentLibrary.skillNameTaken`(`skills/` 里不是技能的条目占着这个名字,忽略大小写:文件、链接、没有能打开的 `SKILL.md` 的目录,或排在 512 个之外的技能;`found` 的技能导入原因也用它)。资源库命令的备份失败改用新错误码 `agentLibrary.backupFailed`:`agentLibrary.apply` 改声明文件和指令文件、`agentLibrary.save` 之后的同步(`instructions` 的 `reason`)、`writeSkill`、`reinstallSkill`;`agentProviders.apply` 仍是 `agentProviders.backupFailed`。front matter 按 YAML 规则读注释:不加引号的值在值开头的 `#` 或空格、制表符后的 `#` 处结束,引号里的 `#` 保留,引号后可跟注释,块标量不变;双引号值读出 `\\`、`\"`、`\/`、`\t`、`\n` 转义。`agentLibrary.read` 的资源库技能和 Agent 技能目录超过 512 个时,取按名字排序的前 512 个(原来按目录顺序先截断再排序)。新增日志事件 `agent.library.skill_create_finished`、`skill_write_finished`、`skill_sources_inspected`、`skill_reinstall_finished`、`skill_change_failed`。没有新增插件可调用的宿主方法、通知、插件函数参数或能力版本;清单、schema 和四语 SDK 不变。 | ## 按协议查首次出现