diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c7126667..d9464657 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -501,14 +501,14 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.stats` | Sum recorded agent usage with the latest rate limits. Optional `overview` returns totals, breakdown and time series in one snapshot; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs` | | `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | | `agentLibrary.configure` | Open the agent library in the platform's application data | -| `agentLibrary.read` | Read 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; 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 | -| `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration, backing up the configuration or instruction file it replaces first | +| `agentLibrary.read` | Read 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; 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), 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.apply` | Apply one library change the user chose to one agent's configuration, backing up the configuration or instruction file it replaces first; 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 | | `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}` | | `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` | -| `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; refused when a file changed after Lithe's last write unless `discardLaterChanges` | +| `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` | | `plugins.declarative.validate` | Validate and normalize a declarative plugin manifest | | `plugins.ui.applyResult` | Check a backend result for a plugin view and return the whole view to draw | | `plugins.web.open` | Register a plugin page for a web tool window | diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 6044731d..719857a1 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -128,7 +128,7 @@ impl Runtime { "agentSessions.calls" => self.records.calls(self, payload), "agentLibrary.configure" => self.library.configure(payload), "agentLibrary.read" => self.library.read(self, payload), - "agentLibrary.save" => self.library.save(payload), + "agentLibrary.save" => self.library.save(self, payload), "agentLibrary.apply" => self.library.apply(self, payload), "agentLibrary.importSkill" => self.library.import_skill(self, payload), "agentLibrary.removeSkill" => self.library.remove_skill(self, payload), diff --git a/rust/crates/agent-runtime/src/library.rs b/rust/crates/agent-runtime/src/library.rs index 4da51532..b1748d7a 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -26,9 +26,11 @@ //! old file's permissions, renamed over it. //! - Skills: a library skill is turned on as a symbolic link in the agent's //! skills directory; turning it off removes only a link into the library. -//! - Instructions: Core writes the active instruction set and the agent's -//! extra text, and refuses to replace text it did not write unless the user -//! confirms. +//! - Instructions (`instructions` module): Core writes only its own block of +//! the instruction file, the sets on for the agent and the agent's extra +//! text, never the user's text around it, and refuses to replace a block +//! edited outside Lithe unless the user confirms. Saving the library brings +//! every agent that follows it up to date. //! - Model, providers and profiles (`providers` module): the same staged //! copy, for the operations the manifest declares. //! @@ -41,6 +43,7 @@ //! names, commands, paths or text. mod backups; +mod instructions; mod providers; mod saved; @@ -194,6 +197,7 @@ impl LibraryHook { } } +/// A named instruction text, and which agents get it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct InstructionSet { @@ -201,10 +205,24 @@ struct InstructionSet { name: String, #[serde(default)] text: String, + /// Whether the set is switched on; off when a save leaves it out. + #[serde(default)] + on: bool, + /// The agent keys the set gives its text to while it is on; empty is + /// every agent. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + agents: Vec, +} + +impl InstructionSet { + /// Whether the set gives its text to the agent `key`. + fn gives(&self, key: &str) -> bool { + self.on && (self.agents.is_empty() || self.agents.iter().any(|agent| agent == key)) + } } /// Whether an agent's instruction file follows the library, and the text -/// only that agent gets after the shared set. +/// only that agent gets after the sets. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct AgentInstructions { @@ -219,13 +237,40 @@ struct AgentInstructions { struct Instructions { #[serde(default)] sets: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] + /// The one set a library saved before each set had its own switch gave + /// every agent. Only `library.json` may hold it: `load` turns it into + /// the sets' `on` and drops it, `check` refuses it, and it is never + /// written. + #[serde(default, skip_serializing)] active: Option, /// By agent key, `/`. #[serde(default)] agents: BTreeMap, } +impl Instructions { + /// Whether the agent `key`'s instruction file follows the library. + fn follows(&self, key: &str) -> bool { + self.agents.get(key).is_some_and(|agent| agent.enabled) + } + + /// Turns the `active` set of a library saved before each set had its own + /// switch into the switches: that set on, every other set off. Each + /// agent's instructions then compose byte for byte as before. + fn migrate_active(&mut self) -> Check { + let Some(active) = self.active.take() else { + return Ok(()); + }; + if !self.sets.iter().any(|set| set.id == active) { + return Err("instructions.active".into()); + } + for set in &mut self.sets { + set.on = set.id == active; + } + Ok(()) + } +} + /// What the user keeps in the library, as the host reads and saves it. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -238,20 +283,29 @@ struct LibraryData { instructions: Instructions, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct LibraryFile { version: u32, library: LibraryData, } +/// `library.json` as Core writes it. +#[derive(Serialize)] +struct LibraryFileOut<'a> { + version: u32, + library: &'a LibraryData, +} + /// What Core wrote, kept apart from the library so writing an agent's file /// never changes the library's revision. #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct StateFile { version: u32, - /// SHA-256 of the text Core last wrote to each agent's instruction file. + /// SHA-256 of the text Core last put in each agent's instruction block, + /// by agent key. A Core that predates blocks kept the whole file it + /// wrote, so a file without a block that matches is Lithe's throughout. /// A restore that puts the file back forgets it, so the restored text /// reads as text Lithe did not write. #[serde(default)] @@ -555,6 +609,12 @@ impl LibraryData { if instructions.sets.len() > MAX_SETS { return Err("instructions.sets".into()); } + // Only a `library.json` from before the switches names an active + // set, and `load` has already turned it into them; a save that + // names one is refused. + if instructions.active.is_some() { + return Err("instructions.active".into()); + } let mut set_ids = BTreeSet::new(); for (index, set) in instructions.sets.iter().enumerate() { let field = format!("instructions.sets[{index}]"); @@ -565,20 +625,22 @@ impl LibraryData { if set.text.len() > MAX_SET_TEXT_BYTES || set.text.contains('\0') { return Err(format!("{field}.text")); } - } - if instructions - .active - .as_deref() - .is_some_and(|active| !set_ids.contains(active)) - { - return Err("instructions.active".into()); + let mut agents = BTreeSet::new(); + if set.agents.len() > MAX_AGENT_ENTRIES + || !set + .agents + .iter() + .all(|key| is_agent_key(key) && agents.insert(key.as_str())) + { + return Err(format!("{field}.agents")); + } } if instructions.agents.len() > MAX_AGENT_ENTRIES { return Err("instructions.agents".into()); } for (key, agent) in &instructions.agents { let field = format!("instructions.agents[{key}]"); - if key.len() > 512 || !key.contains('/') { + if !is_agent_key(key) { return Err(field); } if agent.extra.len() > MAX_EXTRA_BYTES || agent.extra.contains('\0') { @@ -588,27 +650,28 @@ impl LibraryData { Ok(()) } - /// The instruction text of the agent `key`: the active set, then the - /// agent's extra text, ending with one line break. Empty when neither has - /// text. + /// The instruction text of the agent `key`: the text of each set on for + /// it, in the library's order, then the agent's extra text, a blank line + /// apart and ending with one line break. Empty when none has text. With + /// one set on for every agent this is, byte for byte, what a library of + /// a single active set composed. fn compose(&self, key: &str) -> String { let instructions = &self.instructions; - let shared = instructions - .active - .as_deref() - .and_then(|active| instructions.sets.iter().find(|set| set.id == active)) - .map_or("", |set| set.text.trim_end()); + let mut parts: Vec<&str> = instructions + .sets + .iter() + .filter(|set| set.gives(key)) + .map(|set| set.text.trim_end()) + .filter(|text| !text.is_empty()) + .collect(); let extra = instructions .agents .get(key) .map_or("", |agent| agent.extra.trim()); - let mut text = shared.to_string(); if !extra.is_empty() { - if !text.is_empty() { - text.push_str("\n\n"); - } - text.push_str(extra); + parts.push(extra); } + let mut text = parts.join("\n\n"); if !text.is_empty() { text.push('\n'); } @@ -616,6 +679,11 @@ impl LibraryData { } } +/// An agent key, `/`, as the library keeps it. +fn is_agent_key(key: &str) -> bool { + key.len() <= 512 && key.contains('/') +} + impl Snapshot { fn check(&self, file_ids: &BTreeSet<&str>) -> Check { if self.format != READ_FORMAT || self.version != 0 { @@ -777,11 +845,71 @@ fn write_replacing(target: &Path, bytes: &[u8]) -> io::Result<()> { fs::rename(&temporary, target) })(); if result.is_err() { - let _ = fs::remove_file(&temporary); + remove_leftover(&temporary, Leftover::Temporary); } result } +/// What the library leaves behind when it cannot clean up after itself, +/// as `agent.library.cleanup_failed` names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Leftover { + /// The new file a failed [`write_replacing`] left next to its target. + Temporary, + /// A staged copy of an agent's configuration file. + Staging, + /// A skill directory copied in part before its import failed. + SkillImport, + /// A backup baseline or history entry. + Backup, + /// The backup record, not put back after a failure. + BackupRecord, +} + +impl Leftover { + fn token(self) -> &'static str { + match self { + Leftover::Temporary => "temporary", + Leftover::Staging => "staging", + Leftover::SkillImport => "skillImport", + Leftover::Backup => "backup", + Leftover::BackupRecord => "backupRecord", + } + } +} + +/// Logs that `leftover` stays behind because of `error`. What stays may +/// be a copy of the user's configuration, keys included, so the event +/// carries the error's category alone, never a path or the message. +fn leftover_kept(leftover: Leftover, error: &io::Error) { + log( + "agent.library.cleanup_failed", + [ + ("target", json!(leftover.token())), + ("error", json!("The agent library could not clean up")), + ("error_code", json!(format!("{:?}", error.kind()))), + ("error_domain", json!("io")), + ], + ); +} + +/// 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. +fn remove_leftover(path: &Path, leftover: Leftover) { + let removed = if leftover == Leftover::SkillImport { + fs::remove_dir_all(path) + } else { + fs::remove_file(path) + }; + if let Err(error) = removed { + if error.kind() != io::ErrorKind::NotFound { + leftover_kept(leftover, &error); + } + } +} + /// The file a path names, through any links. A path whose link leads /// nowhere is refused, since replacing the link would lose where it pointed. fn real_file(path: &Path) -> Result { @@ -1275,23 +1403,6 @@ fn read_snapshot( Ok(snapshot) } -/// What an agent's instruction file holds, compared with the library. -fn instructions_state( - current: &Result>, ReadFailure>, - composed: &str, - written: Option<&String>, -) -> &'static str { - match current { - Err(ReadFailure::TooLarge) => "tooLarge", - Err(ReadFailure::Io) => "unreadable", - Ok(None) => "absent", - Ok(Some(bytes)) if bytes == composed.as_bytes() => "current", - Ok(Some(bytes)) if String::from_utf8_lossy(bytes).trim().is_empty() => "empty", - Ok(Some(bytes)) if written.is_some_and(|written| *written == digest(bytes)) => "written", - Ok(Some(_)) => "other", - } -} - /// An agent as `agentLibrary.read` reports it, with what Core needs to /// derive the library's states. struct AgentView { @@ -1452,6 +1563,9 @@ enum Operation { Link, Unlink, Write, + /// Moves the user's own instructions out of the agent's file into the + /// library. + Import, } impl Operation { @@ -1462,6 +1576,7 @@ impl Operation { Operation::Link => "link", Operation::Unlink => "unlink", Operation::Write => "write", + Operation::Import => "import", } } } @@ -1472,18 +1587,23 @@ impl Operation { struct Change { category: Category, op: Operation, - /// The MCP server or skill. + /// The MCP server or skill; for an instructions import, the name of the + /// new set. #[serde(default)] name: Option, - /// The library hook to put. + /// The library hook to put; for an instructions import, the set. #[serde(default)] id: Option, /// The agent's hook to remove. #[serde(default)] hook: Option, - /// Write instructions over text Lithe did not write. + /// Write over a block of the instruction file that holds text Lithe did + /// not write there. #[serde(default)] replace: bool, + /// The library revision an instructions import was chosen at. + #[serde(default)] + revision: Option, } #[derive(Deserialize)] @@ -1562,13 +1682,30 @@ impl Library { "The agent library file is not a library Lithe reads.", ) }; - let file: LibraryFile = serde_json::from_slice(&bytes).map_err(|_| invalid())?; - if file.version != 0 || file.library.check().is_err() { + let mut file: LibraryFile = serde_json::from_slice(&bytes).map_err(|_| invalid())?; + if file.version != 0 + || file.library.instructions.migrate_active().is_err() + || file.library.check().is_err() + { return Err(invalid()); } Ok((file.library, digest(&bytes))) } + /// Replaces `library.json` with `library` and answers its new revision. + /// Callers hold the writing lock. + fn store_library(config: &Config, library: &LibraryData) -> Result { + ensure_private_directory(&config.directory)?; + let file = LibraryFileOut { + version: 0, + library, + }; + let bytes = serde_json::to_vec_pretty(&file).map_err(|_| write_failed())?; + write_replacing(&config.directory.join(LIBRARY_FILE), &bytes) + .map_err(|_| write_failed())?; + Ok(digest(&bytes)) + } + fn load_state(config: &Config) -> StateFile { read_bounded(&config.directory.join(STATE_FILE), MAX_LIBRARY_FILE_BYTES) .ok() @@ -1794,12 +1931,11 @@ impl Library { view.entry["backup"] = backup.answer(); } if let Some(path) = &paths.instructions { - let current = read_bounded(path, MAX_INSTRUCTIONS_FILE_BYTES); - let composed = library.compose(&key); - view.entry["instructions"] = json!({ - "path": path_text(path), - "state": instructions_state(¤t, &composed, state.instructions.get(&key)), - }); + view.entry["instructions"] = instructions::entry( + path, + &instructions::block_text(&library.compose(&key)), + state.instructions.get(&key).map(String::as_str), + ); } if let Some(root) = &paths.skills { let mut skills = json!({ "path": path_text(root) }); @@ -1876,8 +2012,9 @@ impl Library { } /// `agentLibrary.save`: replaces the library if it is still at - /// `revision`. - pub fn save(&self, payload: Value) -> Result { + /// `revision`, then brings the instruction block of every agent that + /// follows the library up to date (`instructions` module). + pub fn save(&self, runtime: &Runtime, payload: Value) -> Result { #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SaveRequest { @@ -1888,43 +2025,34 @@ impl Library { let request: SaveRequest = crate::decode(payload)?; let config = self.config()?; if let Err(field) = request.library.check() { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentLibrary.invalidLibrary", - &format!("The library is invalid at {field}."), - )); + return Err(invalid_library(&field)); } let path = config.directory.join(LIBRARY_FILE); - let _writing = self.lock_writing(); - let current = match read_bounded(&path, MAX_LIBRARY_FILE_BYTES) { - Ok(Some(bytes)) => digest(&bytes), - Ok(None) => EMPTY_REVISION.to_string(), - // An unreadable library is replaced only by a save that read it. - Err(_) => return Err(unreadable_file()), - }; - if current != request.revision { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentLibrary.revisionChanged", - "The agent library changed since it was read.", - )); - } - ensure_private_directory(&config.directory)?; - let file = LibraryFile { - version: 0, - library: request.library, + let revision = { + let _writing = self.lock_writing(); + let current = match read_bounded(&path, MAX_LIBRARY_FILE_BYTES) { + Ok(Some(bytes)) => digest(&bytes), + Ok(None) => EMPTY_REVISION.to_string(), + // An unreadable library is replaced only by a save that read it. + Err(_) => return Err(unreadable_file()), + }; + if current != request.revision { + return Err(revision_changed()); + } + Self::store_library(&config, &request.library)? }; - let bytes = serde_json::to_vec_pretty(&file).map_err(|_| write_failed())?; - write_replacing(&path, &bytes).map_err(|_| write_failed())?; log( "agent.library.updated", [ - ("servers", json!(file.library.mcp_servers.len())), - ("hooks", json!(file.library.hooks.len())), - ("sets", json!(file.library.instructions.sets.len())), + ("servers", json!(request.library.mcp_servers.len())), + ("hooks", json!(request.library.hooks.len())), + ("sets", json!(request.library.instructions.sets.len())), ], ); - Ok(json!({ "revision": digest(&bytes) })) + // Each agent is written under the writing lock of its own, so a + // change elsewhere never waits for every agent's file. + let instructions = self.sync_instructions(runtime, &config, &request.library, None); + Ok(json!({ "revision": revision, "instructions": instructions })) } /// `agentLibrary.apply`: one change to one agent's configuration. @@ -1937,14 +2065,14 @@ impl Library { let op = request.change.op; let outcome = self.apply_checked(runtime, &agent, &request.change); match &outcome { - Ok(changed) => log( + Ok(answer) => log( "agent.library.change_applied", [ ("plugin", json!(agent.plugin_id)), ("agent", json!(agent.agent.id)), ("category", json!(category.token())), ("change", json!(op.token())), - ("changed", json!(changed)), + ("changed", answer["changed"].clone()), ( "duration_ms", json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), @@ -1968,15 +2096,17 @@ impl Library { ], ), } - outcome.map(|changed| json!({ "changed": changed })) + outcome } + /// One change, answered as `apply` answers it: `{changed}`, and for an + /// instructions import also the library's `revision` and `instructions`. fn apply_checked( &self, runtime: &Runtime, agent: &CatalogAgent, change: &Change, - ) -> Result { + ) -> Result { let config = self.config()?; let configuration = agent .agent @@ -1984,10 +2114,11 @@ impl Library { .as_ref() .expect("configurable agents declare configuration"); let paths = agent_paths(&config, configuration); + let changed = |changed: bool| json!({ "changed": changed }); match (change.category, change.op) { - (Category::McpServers | Category::Hooks, Operation::Put | Operation::Remove) => { - self.apply_file(runtime, &config, agent, configuration, &paths, change) - } + (Category::McpServers | Category::Hooks, Operation::Put | Operation::Remove) => self + .apply_file(runtime, &config, agent, configuration, &paths, change) + .map(changed), (Category::Skills, Operation::Link | Operation::Unlink) => { let name = change .name @@ -1995,12 +2126,16 @@ impl Library { .filter(|name| is_skill_name(name)) .ok_or_else(|| invalid_change("A skill change names a library skill."))?; self.apply_skill(&config, &paths, change.op, name) + .map(changed) } - (Category::Instructions, Operation::Write) => { - self.apply_instructions(&config, &agent.record_key(), &paths, change.replace) + (Category::Instructions, Operation::Write) => self + .apply_instructions(&config, &agent.record_key(), &paths, change.replace) + .map(changed), + (Category::Instructions, Operation::Import) => { + self.import_instructions(runtime, &config, agent, &paths, change) } _ => Err(invalid_change( - "MCP servers and hooks take put and remove, skills link and unlink, instructions write.", + "MCP servers and hooks take put and remove, skills link and unlink, instructions write and import.", )), } } @@ -2238,7 +2373,7 @@ impl Library { } Ok(true) })(); - let _ = fs::remove_file(&staging); + remove_leftover(&staging, Leftover::Staging); outcome } @@ -2270,7 +2405,7 @@ impl Library { lithe_platform::fs::owner_only_file(&mut options); let mut file = options.open(&path).map_err(|_| write_failed())?; if let Err(_error) = file.write_all(original.unwrap_or_default()) { - let _ = fs::remove_file(&path); + remove_leftover(&path, Leftover::Staging); return Err(write_failed()); } Ok(path) @@ -2342,80 +2477,6 @@ impl Library { } } - fn apply_instructions( - &self, - config: &Config, - key: &str, - paths: &AgentPaths, - replace: bool, - ) -> Result { - let Some(path) = &paths.instructions else { - return Err(refusal( - ErrorCode::NotSupported, - "agentLibrary.noInstructions", - "The agent keeps no instruction file.", - )); - }; - let (library, _) = self.load(config)?; - if !library - .instructions - .agents - .get(key) - .is_some_and(|agent| agent.enabled) - { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentLibrary.instructionsOff", - "The library's instructions are off for this agent.", - )); - } - let text = library.compose(key); - let _writing = self.lock_writing(); - let real = real_file(path)?; - let current = read_bounded(&real, MAX_INSTRUCTIONS_FILE_BYTES).map_err(read_failure)?; - let mut state = Self::load_state(config); - if current.as_deref() == Some(text.as_bytes()) { - return Ok(false); - } - if let Some(current) = ¤t { - let empty = String::from_utf8_lossy(current).trim().is_empty(); - let written = state - .instructions - .get(key) - .is_some_and(|written| *written == digest(current)); - if !empty && !written && !replace { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentLibrary.otherInstructions", - "The instruction file holds text Lithe did not write.", - )); - } - } - // Backed up like any file Core replaces, the write over text Lithe - // did not write that the user confirmed with `replace` included. - let taken = backups::take( - config, - key, - &paths.backup_id(path, INSTRUCTIONS_BACKUP_ID), - current.as_deref(), - text.as_bytes(), - )?; - let written = real - .parent() - .map_or(Ok(()), ensure_directory) - .and_then(|()| write_replacing(&real, text.as_bytes()).map_err(|_| write_failed())); - if let Err(error) = written { - backups::undo(taken); - return Err(error); - } - state.version = 0; - state - .instructions - .insert(key.to_string(), digest(text.as_bytes())); - Self::store_state(config, &state)?; - Ok(true) - } - /// `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 { @@ -2541,7 +2602,7 @@ impl Library { }) }); if outcome.is_err() { - let _ = fs::remove_dir_all(&partial); + remove_leftover(&partial, Leftover::SkillImport); } outcome?; log( @@ -2627,6 +2688,31 @@ fn invalid_skill_name() -> CoreError { ) } +/// A library that breaks a rule at `field`, saved or made by an import. +fn invalid_library(field: &str) -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidLibrary", + &format!("The library is invalid at {field}."), + ) +} + +fn revision_changed() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.revisionChanged", + "The agent library changed since it was read.", + ) +} + +fn not_granted() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentLibrary.notGranted", + "The user has not allowed the plugin to change this agent's configuration.", + ) +} + /// The agent `key` names, if it declares configuration and its plugin is /// granted `agents.configuration`. fn configurable_agent(runtime: &Runtime, key: &str) -> Result { @@ -2642,11 +2728,7 @@ fn configurable_agent(runtime: &Runtime, key: &str) -> Result (Option, Option String { - let library: LibraryData = serde_json::from_value(library).expect("library decodes"); + let mut library: LibraryData = serde_json::from_value(library).expect("library decodes"); + library + .instructions + .migrate_active() + .expect("active names a set"); + library.check().expect("the library is valid"); library.compose(key) } + +#[cfg(test)] +pub(crate) use instructions::{rewrite_for_test, state_tokens, sync_result_tokens}; + +/// Removes a backup file the way the library removes what it no longer +/// needs, logging a failure. +#[cfg(test)] +pub(crate) fn remove_backup_leftover_for_test(path: &Path) { + remove_leftover(path, Leftover::Backup); +} diff --git a/rust/crates/agent-runtime/src/library/backups.rs b/rust/crates/agent-runtime/src/library/backups.rs index a9c84ace..766eaba0 100644 --- a/rust/crates/agent-runtime/src/library/backups.rs +++ b/rust/crates/agent-runtime/src/library/backups.rs @@ -37,9 +37,9 @@ //! happen. use super::{ - agent_paths, configurable_agent, digest, ensure_private_directory, read_bounded, real_file, - refusal, require_user, write_replacing, Config, Library, INSTRUCTIONS_BACKUP_ID, - MAX_CONFIGURATION_FILE_BYTES, MAX_LIBRARY_FILE_BYTES, + 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, }; use crate::{log, Runtime}; use lithe_protocol::{CoreError, ErrorCode}; @@ -174,7 +174,7 @@ fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> { file.sync_all() }); if result.is_err() { - let _ = fs::remove_file(path); + remove_leftover(path, Leftover::Backup); } result } @@ -209,8 +209,15 @@ fn keep_history(directory: &Path, file_id: &str, bytes: Option<&[u8]>) -> io::Re } fn prune_history(history: &Path) { - let Ok(entries) = fs::read_dir(history) else { - return; + let entries = match fs::read_dir(history) { + Ok(entries) => entries, + Err(error) => { + // The oldest entries stay until a later change prunes them. + if error.kind() != io::ErrorKind::NotFound { + leftover_kept(Leftover::Backup, &error); + } + return; + } }; let mut names: Vec<_> = entries .filter_map(Result::ok) @@ -222,7 +229,7 @@ fn prune_history(history: &Path) { } names.sort(); for name in &names[..names.len() - MAX_HISTORY] { - let _ = fs::remove_file(history.join(name)); + remove_leftover(&history.join(name), Leftover::Backup); } } @@ -245,7 +252,9 @@ pub(super) fn take( let mut baseline = None; if !record.files.contains_key(file_id) { let path = directory.join(BASELINE_DIRECTORY).join(file_key(file_id)); - let _ = fs::remove_file(&path); + // A baseline an earlier undo could not remove goes first; should it + // 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())?; baseline = Some(path); @@ -261,7 +270,7 @@ pub(super) fn take( } let undo_baseline = |baseline: &Option| { if let Some(path) = baseline { - let _ = fs::remove_file(path); + remove_leftover(path, Leftover::Backup); } }; let history = match keep_history(&directory, file_id, original) { @@ -276,7 +285,7 @@ pub(super) fn take( } if store(&directory, &record).is_err() { undo_baseline(&baseline); - let _ = fs::remove_file(&history); + remove_leftover(&history, Leftover::Backup); return Err(backup_failed()); } Ok(Taken { @@ -289,11 +298,13 @@ pub(super) fn take( /// Takes back a backup whose file could not be written. pub(super) fn undo(taken: Taken) { - let _ = store(&taken.directory, &taken.previous.unwrap_or_default()); + if let Err(error) = store(&taken.directory, &taken.previous.unwrap_or_default()) { + leftover_kept(Leftover::BackupRecord, &error); + } if let Some(path) = taken.baseline { - let _ = fs::remove_file(path); + remove_leftover(&path, Leftover::Backup); } - let _ = fs::remove_file(taken.history); + remove_leftover(&taken.history, Leftover::Backup); } /// Whether the file at `path` differs from what Lithe last wrote. @@ -395,11 +406,17 @@ pub(super) fn restore( }; if put_back.is_err() { // Files already put back are no longer backed up; the rest are. - let _ = store(&directory, &remaining); + if let Err(error) = store(&directory, &remaining) { + leftover_kept(Leftover::BackupRecord, &error); + } return Err(RestoreRefusal::Failed); } remaining.files.remove(id); - let _ = fs::remove_file(directory.join(BASELINE_DIRECTORY).join(file_key(id))); + // A file that did not exist has no baseline to remove. + remove_leftover( + &directory.join(BASELINE_DIRECTORY).join(file_key(id)), + Leftover::Backup, + ); } store(&directory, &remaining).map_err(|_| RestoreRefusal::Failed)?; Ok(targets.len()) @@ -440,13 +457,15 @@ impl Library { /// since the last restore, whichever command changed it. Any agent that /// declares configuration takes it, with or without providers. Refuses /// when a file changed after Lithe's last write, unless - /// `discardLaterChanges`. + /// `discardLaterChanges`. Putting the instruction file back stops the + /// agent following the library, answered as `unfollowed`. pub fn restore_backup(&self, runtime: &Runtime, payload: Value) -> Result { require_user()?; let request: RestoreRequest = crate::decode(payload)?; let started = Instant::now(); let agent = configurable_agent(runtime, &request.agent)?; let key = agent.record_key(); + let mut unfollowed = false; let outcome = (|| { let config = self.config()?; let configuration = agent @@ -467,12 +486,15 @@ impl Library { request.discard_later_changes, |restoring| { // Lithe's text leaves the instruction file, so Core stops - // claiming what the file holds before it is put back; - // the restored text then needs `replace` to be written - // over, like any text Lithe did not write. + // claiming what the file holds before it is put back, + // and the agent stops following the library: the next + // save would otherwise write the block into the restored + // file again and undo the restore. match &instructions { Some(id) if restoring.contains(&id.as_str()) => { - Self::forget_written_instructions(&config, &key) + Self::forget_written_instructions(&config, &key)?; + unfollowed = self.stop_following(&config, &key)?; + Ok(()) } _ => Ok(()), } @@ -489,6 +511,7 @@ impl Library { ("agent", json!(agent.agent.id)), ("files", json!(files)), ("discarded", json!(request.discard_later_changes)), + ("unfollowed", json!(unfollowed)), ("duration_ms", json!(duration_ms)), ], ), @@ -508,6 +531,6 @@ impl Library { ], ), } - outcome.map(|_| json!({ "restored": true })) + outcome.map(|_| json!({ "restored": true, "unfollowed": unfollowed })) } } diff --git a/rust/crates/agent-runtime/src/library/instructions.rs b/rust/crates/agent-runtime/src/library/instructions.rs new file mode 100644 index 00000000..c2e688d2 --- /dev/null +++ b/rust/crates/agent-runtime/src/library/instructions.rs @@ -0,0 +1,827 @@ +//! The part of an agent's instruction file Lithe writes (plan API-45), and +//! the commands that write it, keep it in step with the library and move the +//! user's own text into the library. +//! +//! Lithe writes only its block: the lines between a begin line and an end +//! line. Every other line of the file is the user's and is kept byte for +//! byte; a new block goes after the user's text, and the block is taken out +//! when the library gives the agent nothing. The only text outside the block +//! Core touches is blank lines next to it, which it reduces to one. A file +//! that is not UTF-8 is read as unreadable and never written. +//! +//! `state.json` keeps, per agent, the SHA-256 of the text Core last put in +//! the block. A block that holds neither that text nor what the library gives +//! now was edited outside Lithe, and is replaced only when the user confirms +//! (`replace`). A Core that predates blocks kept the digest of the whole file +//! it wrote, so a file without a block that matches it is Lithe's text +//! throughout, and becomes a block of its own. + +use super::{ + agent_paths, backups, check_name, digest, ensure_directory, invalid_change, invalid_library, + is_item_id, not_granted, read_bounded, read_failure, real_file, refusal, revision_changed, + too_large_file, unknown_item, write_failed, write_replacing, AgentPaths, Change, Config, + InstructionSet, Instructions, Library, LibraryData, ReadFailure, StateFile, + INSTRUCTIONS_BACKUP_ID, MAX_INSTRUCTIONS_FILE_BYTES, +}; +use crate::catalog::CatalogAgent; +use crate::{log, Runtime}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde_json::{json, Value}; +use std::path::Path; +use std::time::Instant; + +/// The line Core writes before its block. +const BLOCK_BEGIN: &str = ""; +/// The line Core writes after its block. +const BLOCK_END: &str = ""; +/// A line that, trimmed, starts with this and ends with `-->` begins a +/// block, whatever words follow, so a begin line the user edited still +/// begins the block. +const BEGIN_PREFIX: &str = "") { + return None; + } + if line.starts_with(BEGIN_PREFIX) { + Some(Marker::Begin) + } else if line.starts_with(END_PREFIX) { + Some(Marker::End) + } else { + None + } +} + +/// An instruction file taken apart. +#[derive(Debug, Default)] +struct Layout { + /// The user's text before the first block, byte for byte. + before: String, + /// The user's text after the first block, byte for byte, without later + /// blocks and stray marker lines. + after: String, + /// The text inside each complete block, in file order, line breaks as + /// `\n`. + blocks: Vec, + /// Marker lines in no complete block: an end line no begin line opened, + /// or a begin line no end line follows. + strays: usize, +} + +/// Takes an instruction file apart. A block runs from a begin line to the +/// first end line after it, so a begin line inside a block is part of that +/// block's text, and an end line after it is a stray. +fn layout(file: &str) -> Layout { + let lines: Vec<&str> = file.split_inclusive('\n').collect(); + let markers: Vec> = lines.iter().map(|line| marker(line)).collect(); + // The first end line at or after each line, found in one pass from the + // end, so a file of many begin lines without an end stays linear. + let mut next_end = vec![None; lines.len() + 1]; + for index in (0..lines.len()).rev() { + next_end[index] = if markers[index] == Some(Marker::End) { + Some(index) + } else { + next_end[index + 1] + }; + } + let mut layout = Layout::default(); + let mut index = 0; + while index < lines.len() { + match markers[index] { + Some(Marker::Begin) => { + if let Some(end) = next_end[index + 1] { + let inner = lines[index + 1..end].concat().replace("\r\n", "\n"); + layout.blocks.push(inner); + index = end + 1; + continue; + } + layout.strays += 1; + } + Some(Marker::End) => layout.strays += 1, + None if layout.blocks.is_empty() => layout.before.push_str(lines[index]), + None => layout.after.push_str(lines[index]), + } + index += 1; + } + layout +} + +/// `text` without the blank lines it ends with; its last line keeps its +/// line break. +fn without_trailing_blank_lines(text: &str) -> &str { + let Some(last) = text.rfind(|c: char| !c.is_whitespace()) else { + return ""; + }; + match text[last..].find('\n') { + Some(offset) => &text[..=last + offset], + None => text, + } +} + +/// `text` without the blank lines it starts with; its first line keeps its +/// indentation. +fn without_leading_blank_lines(text: &str) -> &str { + let Some(first) = text.find(|c: char| !c.is_whitespace()) else { + return ""; + }; + match text[..first].rfind('\n') { + Some(newline) => &text[newline + 1..], + None => text, + } +} + +/// The user's own text: what is outside the blocks, without the blank +/// lines around it, line breaks as `\n` and no final line break. This is +/// what an import moves into the library, and its lines are `ownLines`. +fn own_text(layout: &Layout) -> String { + [&layout.before, &layout.after] + .into_iter() + .map(|part| without_trailing_blank_lines(without_leading_blank_lines(part))) + .filter(|part| !part.is_empty()) + .map(|part| { + part.replace("\r\n", "\n") + .trim_end_matches('\n') + .to_string() + }) + .collect::>() + .join("\n\n") +} + +/// The file with its block holding `text` (from [`block_text`]), or without +/// a block when `text` is empty; without the user's text too unless +/// `keep_own`. Every other block and stray marker line goes. The block +/// stays where the first one was, a new one goes after the user's text, and +/// the parts are one blank line apart. Line breaks in the block follow the +/// file's: `\r\n` when the file has any. +fn rewrite(file: &str, text: &str, keep_own: bool) -> String { + let layout = layout(file); + let newline = if file.contains("\r\n") { "\r\n" } else { "\n" }; + let mut block = String::new(); + if !text.is_empty() { + block.push_str(BLOCK_BEGIN); + block.push_str(newline); + block.push_str(&text.replace('\n', newline)); + if !text.ends_with('\n') { + block.push_str(newline); + } + block.push_str(BLOCK_END); + block.push_str(newline); + } + let (before, after) = if keep_own { + ( + without_trailing_blank_lines(&layout.before), + without_leading_blank_lines(&layout.after), + ) + } else { + ("", "") + }; + let mut out = String::with_capacity(before.len() + block.len() + after.len() + 4); + for part in [before, block.as_str(), after] { + if part.trim().is_empty() { + continue; + } + if !out.is_empty() { + if !out.ends_with('\n') { + out.push_str(newline); + } + out.push_str(newline); + } + out.push_str(part); + } + out +} + +#[cfg(test)] +pub(crate) fn rewrite_for_test(file: &str, composed: &str, keep_own: bool) -> String { + rewrite(file, &block_text(composed), keep_own) +} + +// --------------------------------------------------------------------------- +// States. + +/// What an agent's instruction file holds, compared with the library. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + /// Nothing is at the path. + Absent, + /// The file has no block and the library gives the agent text, or it + /// holds stray marker lines. + NoBlock, + /// The file holds one block with what the library gives the agent and + /// no other marker line, or no block and no marker line while the + /// library gives it nothing. + Current, + /// Lithe's text is out of date: each block holds what Core last wrote + /// or what the library gives now, but the file is not current; or the + /// whole file is the text a Core that predates blocks wrote. + Stale, + /// A block holds text Lithe did not write there. + Edited, + /// The file is larger than Core reads. + TooLarge, + /// The file cannot be read, or is not UTF-8. + Unreadable, +} + +impl State { + /// Every state, in the order the contract lists them. + #[cfg(test)] + const ALL: [State; 7] = [ + State::Absent, + State::NoBlock, + State::Current, + State::Stale, + State::Edited, + State::TooLarge, + State::Unreadable, + ]; + + fn token(self) -> &'static str { + match self { + State::Absent => "absent", + State::NoBlock => "noBlock", + State::Current => "current", + State::Stale => "stale", + State::Edited => "edited", + State::TooLarge => "tooLarge", + State::Unreadable => "unreadable", + } + } +} + +/// What a sync did to one agent's file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Synced { + /// The block was written. + Written, + /// The file already held what the library gives the agent. + Unchanged, + /// The file was left alone on purpose; `reason` says why. + Skipped, + /// Writing the file failed; `reason` is the refusal code. + Failed, +} + +impl Synced { + #[cfg(test)] + const ALL: [Synced; 4] = [ + Synced::Written, + Synced::Unchanged, + Synced::Skipped, + Synced::Failed, + ]; + + fn token(self) -> &'static str { + match self { + Synced::Written => "written", + Synced::Unchanged => "unchanged", + Synced::Skipped => "skipped", + Synced::Failed => "failed", + } + } +} + +/// The tokens of `instructions.state` in `agentLibrary.read`. +#[cfg(test)] +pub(crate) fn state_tokens() -> Vec<&'static str> { + State::ALL.iter().map(|state| state.token()).collect() +} + +/// The tokens of `result` in a sync's answer. +#[cfg(test)] +pub(crate) fn sync_result_tokens() -> Vec<&'static str> { + Synced::ALL.iter().map(|result| result.token()).collect() +} + +/// A file read and compared with the library. +struct Assessment { + state: State, + /// Lines of the user's own text. + own_lines: usize, + /// Whether the whole file is the text a Core that predates blocks + /// wrote; none of it is the user's. + legacy: bool, +} + +/// Compares the file (none when nothing is there) with `wanted`, the block +/// text the library gives the agent, given `written`, the digest of what +/// Core last put there. +fn assess(file: Option<&str>, wanted: &str, written: Option<&str>) -> Assessment { + let Some(file) = file else { + return Assessment { + state: State::Absent, + own_lines: 0, + legacy: false, + }; + }; + let layout = layout(file); + let written_here = + |text: &str| written.is_some_and(|written| written == digest(text.as_bytes())); + if layout.blocks.is_empty() + && layout.strays == 0 + && !file.trim().is_empty() + && written_here(file) + { + return Assessment { + state: State::Stale, + own_lines: 0, + legacy: true, + }; + } + let state = if layout.blocks.is_empty() { + if wanted.is_empty() && layout.strays == 0 { + State::Current + } else { + State::NoBlock + } + } else if layout.blocks.len() == 1 && layout.strays == 0 && layout.blocks[0] == wanted { + State::Current + } else if layout + .blocks + .iter() + .all(|block| block == wanted || written_here(block)) + { + State::Stale + } else { + State::Edited + }; + Assessment { + state, + own_lines: own_text(&layout).lines().count(), + legacy: false, + } +} + +/// The instruction file's text; a file that is not UTF-8 cannot be read. +fn read_text(path: &Path) -> Result, ReadFailure> { + read_bounded(path, MAX_INSTRUCTIONS_FILE_BYTES)? + .map(|bytes| String::from_utf8(bytes).map_err(|_| ReadFailure::Io)) + .transpose() +} + +/// An agent's `instructions` in `agentLibrary.read`: `{path, state, +/// ownLines?}`, `ownLines` whenever the file could be read. +pub(super) fn entry(path: &Path, wanted: &str, written: Option<&str>) -> Value { + let mut entry = json!({ "path": path.to_string_lossy() }); + match read_text(path) { + Ok(file) => { + let assessed = assess(file.as_deref(), wanted, written); + entry["state"] = json!(assessed.state.token()); + entry["ownLines"] = json!(assessed.own_lines); + } + Err(ReadFailure::TooLarge) => entry["state"] = json!(State::TooLarge.token()), + Err(ReadFailure::Io) => entry["state"] = json!(State::Unreadable.token()), + } + entry +} + +// --------------------------------------------------------------------------- +// Refusals. + +fn no_instructions() -> CoreError { + refusal( + ErrorCode::NotSupported, + "agentLibrary.noInstructions", + "The agent keeps no instruction file.", + ) +} + +fn instructions_off() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.instructionsOff", + "The library's instructions are off for this agent.", + ) +} + +/// The block holds text Lithe did not write there; writing over it needs +/// `replace`. +fn other_instructions() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.otherInstructions", + "Lithe's part of the instruction file holds text Lithe did not write.", + ) +} + +fn set_exists() -> CoreError { + refusal( + ErrorCode::EntryExists, + "agentLibrary.setExists", + "The library already has an instruction set with this id.", + ) +} + +/// Codes of a sync that left an agent alone on purpose, rather than failed. +const SKIPPED: [&str; 4] = [ + "agentLibrary.otherInstructions", + "agentLibrary.notGranted", + "agentLibrary.noInstructions", + "agentLibrary.instructionsOff", +]; + +// --------------------------------------------------------------------------- +// Writing. + +/// Records `wanted` as what Core last put in the agent's block; no block, +/// no record. +fn record_written(state: &mut StateFile, key: &str, wanted: &str) { + state.version = 0; + if wanted.is_empty() { + state.instructions.remove(key); + } else { + state + .instructions + .insert(key.to_string(), digest(wanted.as_bytes())); + } +} + +impl Instructions { + /// Puts `own` into the set `id`: a new set named `name`, on for the + /// agent `key` alone, or the end of the existing set, unless it holds + /// the text already. An existing set is switched on and, when it lists + /// agents, lists `key` too. The agent then follows the library, so it + /// still reads the text. + fn import( + &mut self, + key: &str, + id: &str, + name: Option<&str>, + own: &str, + ) -> Result<(), CoreError> { + match name { + Some(name) => { + if self.sets.iter().any(|set| set.id == id) { + return Err(set_exists()); + } + self.sets.push(InstructionSet { + id: id.to_string(), + name: name.to_string(), + text: own.to_string(), + on: true, + agents: vec![key.to_string()], + }); + } + None => { + let set = self + .sets + .iter_mut() + .find(|set| set.id == id) + .ok_or_else(unknown_item)?; + if !set.text.contains(own) { + let kept = set.text.trim_end(); + set.text = if kept.is_empty() { + own.to_string() + } else { + format!("{kept}\n\n{own}") + }; + } + set.on = true; + if !set.agents.is_empty() && !set.agents.iter().any(|agent| agent == key) { + set.agents.push(key.to_string()); + } + } + } + self.agents.entry(key.to_string()).or_default().enabled = true; + Ok(()) + } +} + +/// The instruction file's path, or the refusal for an agent without one. +fn instruction_path(paths: &AgentPaths) -> Result<&Path, CoreError> { + paths.instructions.as_deref().ok_or_else(no_instructions) +} + +/// Refuses a file larger than Core reads back. +fn check_size(next: &str) -> Result<(), CoreError> { + if next.len() as u64 > MAX_INSTRUCTIONS_FILE_BYTES { + return Err(too_large_file()); + } + Ok(()) +} + +impl Library { + /// `apply` of `{category: "instructions", op: "write", replace?}`: + /// brings the agent's block up to date. Answers whether the file + /// changed. + pub(super) fn apply_instructions( + &self, + config: &Config, + key: &str, + paths: &AgentPaths, + replace: bool, + ) -> Result { + let path = instruction_path(paths)?; + // The library is read under the lock, so a save that lands meanwhile + // is never overwritten by the text before it. + let _writing = self.lock_writing(); + let (library, _) = self.load(config)?; + if !library.instructions.follows(key) { + return Err(instructions_off()); + } + let wanted = block_text(&library.compose(key)); + self.write_block(config, key, paths, path, &wanted, replace) + } + + /// Puts `wanted` in the block of the agent `key`'s instruction file at + /// `path`, keeping the user's text, and records it. Refuses a block + /// edited outside Lithe unless `replace`. The caller holds the writing + /// lock. Answers whether the file changed. + fn write_block( + &self, + config: &Config, + key: &str, + paths: &AgentPaths, + path: &Path, + wanted: &str, + replace: bool, + ) -> Result { + let real = real_file(path)?; + let current = read_text(&real).map_err(read_failure)?; + let mut state = Self::load_state(config); + let assessed = assess( + current.as_deref(), + wanted, + state.instructions.get(key).map(String::as_str), + ); + match assessed.state { + State::Current => return Ok(false), + State::Edited if !replace => return Err(other_instructions()), + _ => {} + } + let next = rewrite( + current.as_deref().unwrap_or_default(), + wanted, + !assessed.legacy, + ); + if current.as_deref() == Some(next.as_str()) || (current.is_none() && next.is_empty()) { + return Ok(false); + } + check_size(&next)?; + let backup_id = paths.backup_id(path, INSTRUCTIONS_BACKUP_ID); + Self::replace_file(config, key, &backup_id, &real, current.as_deref(), &next)?; + record_written(&mut state, key, wanted); + Self::store_state(config, &state)?; + Ok(true) + } + + /// Backs the instruction file `real` up, then replaces it with `next`. + /// Answers the backup, which a later step of the same change that fails + /// takes back. + fn replace_file( + config: &Config, + key: &str, + backup_id: &str, + real: &Path, + current: Option<&str>, + next: &str, + ) -> Result { + let taken = backups::take( + config, + key, + backup_id, + current.map(str::as_bytes), + next.as_bytes(), + )?; + let written = real + .parent() + .map_or(Ok(()), ensure_directory) + .and_then(|()| write_replacing(real, next.as_bytes()).map_err(|_| write_failed())); + if let Err(error) = written { + backups::undo(taken); + return Err(error); + } + Ok(taken) + } + + /// Brings the block of every agent `library` says follows it up to date, + /// in catalog order, except the agent `except`; a block edited outside + /// Lithe is left as it is. Each agent's outcome is one entry, `{agent, + /// result, reason?}`; one agent's failure never stops the others. + pub(super) fn sync_instructions( + &self, + runtime: &Runtime, + config: &Config, + library: &LibraryData, + except: Option<&str>, + ) -> Vec { + runtime + .catalog + .configurable() + .into_iter() + .filter(|agent| { + let key = agent.record_key(); + except != Some(key.as_str()) && library.instructions.follows(&key) + }) + .map(|agent| self.sync_agent(config, &agent)) + .collect() + } + + fn sync_agent(&self, config: &Config, agent: &CatalogAgent) -> Value { + let started = Instant::now(); + let key = agent.record_key(); + let outcome = if agent.may_configure { + let configuration = agent + .agent + .configuration + .as_ref() + .expect("configurable agents declare configuration"); + // The library is read again under the lock: a save after the one + // that started this sync may have changed what the agent gets. + self.apply_instructions(config, &key, &agent_paths(config, configuration), false) + } else { + Err(not_granted()) + }; + let mut entry = json!({ "agent": key }); + match outcome { + Ok(changed) => { + let result = if changed { + Synced::Written + } else { + Synced::Unchanged + }; + entry["result"] = json!(result.token()); + // An agent already up to date changed nothing to record. + if changed { + log( + "agent.library.change_applied", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("category", json!("instructions")), + ("change", json!("write")), + ("changed", json!(true)), + ( + "duration_ms", + json!(u64::try_from(started.elapsed().as_millis()) + .unwrap_or(u64::MAX)), + ), + ], + ); + } + } + Err(error) => { + let reason = error + .details + .unwrap_or_else(|| "agentLibrary.writeFailed".to_string()); + let result = if SKIPPED.contains(&reason.as_str()) { + Synced::Skipped + } else { + Synced::Failed + }; + entry["result"] = json!(result.token()); + log( + "agent.library.change_failed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("category", json!("instructions")), + ("change", json!("write")), + ("reason", json!(reason)), + ], + ); + entry["reason"] = json!(reason); + } + } + entry + } + + /// `apply` of `{category: "instructions", op: "import", id, name?, + /// revision, replace?}`: moves the user's own text out of the agent's + /// instruction file into the set `id` (a new set when `name` is given), + /// leaves the file holding only the block, then brings every other + /// following agent up to date, since the set may give them the text + /// too. Answers `{changed, revision, instructions}`. + pub(super) fn import_instructions( + &self, + runtime: &Runtime, + config: &Config, + agent: &CatalogAgent, + paths: &AgentPaths, + change: &Change, + ) -> Result { + let key = agent.record_key(); + let path = instruction_path(paths)?; + let (Some(id), Some(revision)) = ( + change.id.as_deref().filter(|id| is_item_id(id)), + change.revision.as_deref(), + ) else { + return Err(invalid_change( + "Importing instructions names a set by its id, and the library revision.", + )); + }; + if let Some(name) = change.name.as_deref() { + check_name(name, "name").map_err(|_| { + invalid_change("A new set's name is 1–128 characters without leading or trailing spaces or control characters.") + })?; + } + let writing = self.lock_writing(); + let (library, current_revision) = self.load(config)?; + if current_revision != revision { + return Err(revision_changed()); + } + let unchanged = |revision: String| json!({ "changed": false, "revision": revision, "instructions": [] }); + let real = real_file(path)?; + let Some(file) = read_text(&real).map_err(read_failure)? else { + return Ok(unchanged(current_revision)); + }; + let mut state = Self::load_state(config); + let written = state.instructions.get(&key).map(String::as_str); + let assessed = assess(Some(&file), &block_text(&library.compose(&key)), written); + let own = if assessed.legacy { + String::new() + } else { + own_text(&layout(&file)) + }; + if own.is_empty() { + return Ok(unchanged(current_revision)); + } + if assessed.state == State::Edited && !change.replace { + return Err(other_instructions()); + } + + let mut imported = library.clone(); + imported + .instructions + .import(&key, id, change.name.as_deref(), &own)?; + if let Err(field) = imported.check() { + return Err(invalid_library(&field)); + } + let wanted = block_text(&imported.compose(&key)); + let next = rewrite(&file, &wanted, false); + check_size(&next)?; + // The file goes first: should the library then fail to save, the + // file is put back, and were that to fail too, the user's text is + // still what the agent reads, inside a block Core holds no record + // of, which reads as edited and is never written over unasked. + let backup_id = paths.backup_id(path, INSTRUCTIONS_BACKUP_ID); + let taken = Self::replace_file(config, &key, &backup_id, &real, Some(&file), &next)?; + let revision = if imported == library { + current_revision + } else { + match Self::store_library(config, &imported) { + Ok(revision) => revision, + Err(error) => { + // log-exempt: Same failure already recorded: this put-back follows the library write failure returned below, which `apply` logs as agent.library.change_failed; were it to fail, the file holds the user's text in a block that reads as edited. + let _ = write_replacing(&real, file.as_bytes()); + backups::undo(taken); + return Err(error); + } + } + }; + record_written(&mut state, &key, &wanted); + Self::store_state(config, &state)?; + drop(writing); + + let mut instructions = vec![json!({ "agent": key, "result": Synced::Written.token() })]; + instructions.extend(self.sync_instructions(runtime, config, &imported, Some(&key))); + Ok(json!({ "changed": true, "revision": revision, "instructions": instructions })) + } + + /// Stops the agent `key` following the library's instructions, for a + /// restore that puts its instruction file back: otherwise the next save + /// would write the block into the restored file again. Answers whether + /// the agent was following. The caller holds the writing lock. + pub(super) fn stop_following(&self, config: &Config, key: &str) -> Result { + let mut library = match self.load(config) { + Ok((library, _)) => library, + // No save can replace a library file Core cannot read as one: + // the host has no revision of it to save over, so nothing would + // write the block back. + Err(error) if error.details.as_deref() == Some("agentLibrary.invalidLibraryFile") => { + return Ok(false) + } + Err(error) => return Err(error), + }; + match library.instructions.agents.get_mut(key) { + Some(agent) if agent.enabled => agent.enabled = false, + _ => return Ok(false), + } + Self::store_library(config, &library)?; + Ok(true) + } +} diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs index b03925c4..8a446ec6 100644 --- a/rust/crates/agent-runtime/src/library/providers.rs +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -1355,6 +1355,7 @@ impl Library { let _writing = self.lock_writing(); // The plugin's refusal is what the user needs to see; a list // that cannot be put back reads as it was written. + // log-exempt: Same failure already recorded: this put-back follows the plugin edit failure returned below, which `apply` logs as agent.providers.change_failed and the request trace records; a list it cannot put back keeps the provider the user just saved, shown as saved. let _ = saved::store(&config, &agent_key, saved_before); } edited.map(|changed| changed || listed) diff --git a/rust/crates/agent-runtime/src/tests/library.rs b/rust/crates/agent-runtime/src/tests/library.rs index 4a318c47..89ed48d2 100644 --- a/rust/crates/agent-runtime/src/tests/library.rs +++ b/rust/crates/agent-runtime/src/tests/library.rs @@ -200,12 +200,20 @@ impl LibraryTest { } fn save(&self, library: Value) -> String { + self.save_answer(library)["revision"] + .as_str() + .unwrap() + .to_string() + } + + /// The whole answer of a save over the library as last read, with what + /// the save did to each agent that follows the library. + fn save_answer(&self, library: Value) -> Value { let revision = self.read()["revision"].clone(); - let saved = self.harness.run( + self.harness.run( "agentLibrary.save", json!({ "revision": revision, "library": library }), - ); - saved["revision"].as_str().unwrap().to_string() + ) } fn apply(&self, change: Value) -> bool { @@ -440,54 +448,6 @@ fn a_linked_configuration_file_is_replaced_where_it_points() { ); } -#[test] -fn instructions_follow_the_library_and_keep_text_lithe_did_not_write() { - let test = LibraryTest::new("library instructions", CONFIGURATION_GRANTS); - let file = test.home.join(".sample").join("INSTRUCTIONS.md"); - fs::write(&file, b"My own notes\n").unwrap(); - let library = |text: &str, enabled: bool| { - json!({ - "instructions": { - "sets": [{ "id": "default", "name": "Default", "text": text }], - "active": "default", - "agents": { AGENT_KEY: { "enabled": enabled, "extra": "Only for the sample agent." } } - } - }) - }; - test.save(library("Shared rule.\n", true)); - assert_eq!(test.read()["agents"][0]["instructions"]["state"], "other"); - assert_eq!( - test.refused_change(json!({ "category": "instructions", "op": "write" })), - "agentLibrary.otherInstructions" - ); - assert_eq!(fs::read(&file).unwrap(), b"My own notes\n"); - - assert!(test.apply(json!({ "category": "instructions", "op": "write", "replace": true }))); - assert_eq!( - fs::read_to_string(&file).unwrap(), - "Shared rule.\n\nOnly for the sample agent.\n" - ); - assert_eq!(test.read()["agents"][0]["instructions"]["state"], "current"); - - test.save(library("Shared rule, revised.", true)); - assert_eq!(test.read()["agents"][0]["instructions"]["state"], "written"); - assert!( - test.apply(json!({ "category": "instructions", "op": "write" })), - "Lithe rewrites what it wrote" - ); - assert_eq!( - fs::read_to_string(&file).unwrap(), - "Shared rule, revised.\n\nOnly for the sample agent.\n" - ); - assert!(!test.apply(json!({ "category": "instructions", "op": "write" }))); - - test.save(library("Shared rule, revised.", false)); - assert_eq!( - test.refused_change(json!({ "category": "instructions", "op": "write" })), - "agentLibrary.instructionsOff" - ); -} - #[cfg(unix)] #[test] fn skills_are_imported_without_links_and_linked_into_agents() { @@ -772,3 +732,4 @@ fn malformed_requests_and_a_damaged_library_file_are_refused_each_with_its_own_c } mod backups; +mod instructions; diff --git a/rust/crates/agent-runtime/src/tests/library/backups.rs b/rust/crates/agent-runtime/src/tests/library/backups.rs index 9ea5df75..a7bfd334 100644 --- a/rust/crates/agent-runtime/src/tests/library/backups.rs +++ b/rust/crates/agent-runtime/src/tests/library/backups.rs @@ -55,33 +55,54 @@ pub(super) fn model_edit(params: &Value) -> Result { Ok(json!({ "format": "litheAgentProvidersEdit", "version": 0, "changed": changed })) } -/// A library with one server, one hook and instructions on for the agent. +/// A library with one server, one hook and one instruction set on, which +/// the agent follows. fn full_library(rule: &str) -> Value { + library_following(rule, true) +} + +/// [`full_library`], with the agent following the instructions or not. A +/// save brings an agent that follows them up to date, so a test that must +/// see no instruction write yet saves with `following` false. +fn library_following(rule: &str, following: bool) -> Value { json!({ "mcpServers": [{ "name": "docs", "transport": "stdio", "command": "docs-mcp", "args": ["--stdio"] }], "hooks": [{ "id": "check-on-stop", "event": "Stop", "command": "sample-check" }], "instructions": { - "sets": [{ "id": "default", "name": "Default", "text": rule }], - "active": "default", - "agents": { AGENT_KEY: { "enabled": true } } + "sets": [{ "id": "default", "name": "Default", "text": rule, "on": true }], + "agents": { AGENT_KEY: { "enabled": following } } } }) } +/// The instruction file holding `user` and then Lithe's block of `text`. +pub(super) fn with_block(user: &str, text: &str) -> String { + let block = format!("{BEGIN}\n{text}{END}\n"); + if user.is_empty() { + block + } else { + format!("{user}\n{block}") + } +} + +/// The lines Core writes around its block. +pub(super) const BEGIN: &str = ""; +pub(super) const END: &str = ""; + /// The original configuration file, formatted so only a byte-for-byte /// restore gives it back. const ORIGINAL_CONFIG: &[u8] = b"{\"keep\": 1}\n"; impl LibraryTest { - fn instructions_file(&self) -> PathBuf { + pub(super) fn instructions_file(&self) -> PathBuf { self.home.join(".sample").join("INSTRUCTIONS.md") } - fn agent(&self) -> Value { + pub(super) fn agent(&self) -> Value { self.read()["agents"][0].clone() } - fn backup(&self) -> Option { + pub(super) fn backup(&self) -> Option { self.agent().get("backup").cloned() } @@ -96,7 +117,7 @@ impl LibraryTest { } /// The baselines kept, sorted by content. - fn baselines(&self) -> Vec> { + pub(super) fn baselines(&self) -> Vec> { let mut baselines: Vec> = fs::read_dir(self.backup_directory().join("baseline")) .unwrap() .map(|entry| fs::read(entry.unwrap().path()).unwrap()) @@ -105,9 +126,9 @@ impl LibraryTest { baselines } - /// The digest `state.json` keeps of what Core last wrote to the agent's - /// instruction file, if any. - fn written_instructions(&self) -> Option { + /// The digest `state.json` keeps of what Core last put in the agent's + /// instruction block, if any. + pub(super) fn written_instructions(&self) -> Option { let bytes = fs::read(self.library.join("state.json")).ok()?; let state: Value = serde_json::from_slice(&bytes).unwrap(); state["instructions"].get(AGENT_KEY).cloned() @@ -121,7 +142,7 @@ impl LibraryTest { payload } - fn restore(&self, discard: Option) -> Value { + pub(super) fn restore(&self, discard: Option) -> Value { self.harness .run("agentProviders.restore", Self::restore_payload(discard)) } @@ -148,7 +169,7 @@ fn library_changes_back_up_each_file_once_and_restore_puts_them_back() { fs::write(&config, ORIGINAL_CONFIG).unwrap(); let instructions = test.instructions_file(); fs::write(&instructions, b"My own notes\n").unwrap(); - test.save(full_library("Shared rule.")); + test.save(library_following("Shared rule.", false)); assert!(test.backup().is_none(), "no backup before a change"); let before = crate::now_ms(); @@ -173,12 +194,18 @@ fn library_changes_back_up_each_file_once_and_restore_puts_them_back() { "two changes to one file keep the first baseline only" ); - // The write the user confirmed over text Lithe did not write is the one - // that most needs a backup. - let (_, write_logs) = capture::run(false, || { - assert!(test.apply(json!({ "category": "instructions", "op": "write", "replace": true }))); - }); - assert_eq!(fs::read_to_string(&instructions).unwrap(), "Shared rule.\n"); + // Following the library puts the block after the user's text, and the + // file is backed up before that first write like any other. + let (synced, write_logs) = + capture::run(false, || test.save_answer(full_library("Shared rule."))); + assert_eq!( + synced["instructions"], + json!([{ "agent": AGENT_KEY, "result": "written" }]) + ); + assert_eq!( + fs::read_to_string(&instructions).unwrap(), + with_block("My own notes\n", "Shared rule.\n") + ); assert_eq!(test.agent()["instructions"]["state"], "current"); assert!(test.written_instructions().is_some()); assert_eq!( @@ -198,7 +225,7 @@ fn library_changes_back_up_each_file_once_and_restore_puts_them_back() { json!([]) ); let (restored, restore_logs) = capture::run(false, || test.restore(None)); - assert_eq!(restored, json!({ "restored": true })); + assert_eq!(restored, json!({ "restored": true, "unfollowed": true })); assert_eq!(fs::read(&config).unwrap(), ORIGINAL_CONFIG, "byte for byte"); assert_eq!( fs::read(&instructions).unwrap(), @@ -212,8 +239,12 @@ fn library_changes_back_up_each_file_once_and_restore_puts_them_back() { "a restore forgets the backup" ); assert_eq!( - agent["instructions"]["state"], "other", - "the restored text is not the library's, so it never reads as current" + agent["instructions"]["state"], "noBlock", + "the restored file has no block of Lithe's" + ); + assert_eq!( + read["library"]["instructions"]["agents"][AGENT_KEY]["enabled"], false, + "the agent stops following the library, or the next save would undo the restore" ); assert_eq!(read["states"]["mcpServers"]["docs"][AGENT_KEY], "off"); assert_eq!(read["states"]["hooks"]["check-on-stop"][AGENT_KEY], "off"); @@ -223,15 +254,23 @@ fn library_changes_back_up_each_file_once_and_restore_puts_them_back() { ); assert_eq!( test.refused_change(json!({ "category": "instructions", "op": "write" })), - "agentLibrary.otherInstructions", - "writing over the restored text needs the user's consent again" + "agentLibrary.instructionsOff", + "Lithe writes the restored file again only once the user follows the library again" ); + let revision = read["revision"].clone(); + let saved = test.harness.run( + "agentLibrary.save", + json!({ "revision": revision, "library": read["library"] }), + ); + assert_eq!(saved["instructions"], json!([])); + assert_eq!(fs::read(&instructions).unwrap(), b"My own notes\n"); let applied = restore_logs .iter() .find(|log| log.event == "agent.providers.restore_applied") .expect("the restore is logged"); assert_eq!(applied.fields["files"], json!(2)); + assert_eq!(applied.fields["unfollowed"], json!(true)); let home = path_text(&test.home); for log in logs.iter().chain(&write_logs).chain(&restore_logs) { let text = format!("{:?}", log.fields); @@ -253,7 +292,10 @@ fn a_restored_instruction_file_is_no_longer_claimed_as_lithe_text() { let test = LibraryTest::new("library backup absent", CONFIGURATION_GRANTS); let file = test.instructions_file(); test.save(full_library("First rule.")); - assert!(test.apply(json!({ "category": "instructions", "op": "write" }))); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("", "First rule.\n") + ); assert_eq!(test.backup().unwrap()["modifiedSince"], false); test.restore(None); @@ -261,17 +303,20 @@ fn a_restored_instruction_file_is_no_longer_claimed_as_lithe_text() { assert_eq!(test.agent()["instructions"]["state"], "absent"); assert_eq!(test.restore_refused(None), "agentProviders.noBackup"); - // The same text by hand after the restore is the user's: a claim left - // from before the restore would read it as written by Lithe and let a - // later write replace it without asking. + // The text Lithe last wrote, put there by hand after the restore, is the + // user's: a claim left from before the restore would read the file as + // Lithe's throughout and replace it with the block. fs::write(&file, "First rule.\n").unwrap(); - test.save(full_library("Second rule.")); - assert_eq!(test.agent()["instructions"]["state"], "other"); + let synced = test.save_answer(full_library("Second rule.")); assert_eq!( - test.refused_change(json!({ "category": "instructions", "op": "write" })), - "agentLibrary.otherInstructions" + synced["instructions"], + json!([{ "agent": AGENT_KEY, "result": "written" }]) + ); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("First rule.\n", "Second rule.\n"), + "the user's text stays, the block goes after it" ); - assert_eq!(fs::read_to_string(&file).unwrap(), "First rule.\n"); } #[test] @@ -282,7 +327,7 @@ fn restore_discards_later_changes_to_library_files_only_when_asked() { let instructions = test.instructions_file(); test.save(full_library("Shared rule.")); assert!(test.apply(json!({ "category": "mcpServers", "op": "put", "name": "docs" }))); - assert!(test.apply(json!({ "category": "instructions", "op": "write" }))); + assert!(instructions.exists(), "the save wrote the block"); assert_eq!(test.backup().unwrap()["modifiedSince"], false); fs::write(&instructions, "Shared rule.\nEdited by hand.\n").unwrap(); @@ -309,7 +354,11 @@ fn restore_discards_later_changes_to_library_files_only_when_asked() { "a refused restore keeps Core's record" ); - assert_eq!(test.restore(Some(true)), json!({ "restored": true })); + assert_eq!( + test.restore(Some(true)), + json!({ "restored": true, "unfollowed": true }), + "taking out the file Lithe created puts it back too" + ); assert_eq!(fs::read(&config).unwrap(), ORIGINAL_CONFIG); assert!(!instructions.exists()); assert!(test.backup().is_none()); @@ -322,7 +371,7 @@ fn a_library_change_whose_backup_fails_is_not_written() { fs::write(&config, ORIGINAL_CONFIG).unwrap(); let instructions = test.instructions_file(); fs::write(&instructions, b"My own notes\n").unwrap(); - test.save(full_library("Shared rule.")); + test.save(library_following("Shared rule.", false)); // A file where the backups directory goes cannot hold one. fs::write(test.library.join("backups"), b"not a directory").unwrap(); @@ -342,8 +391,21 @@ fn a_library_change_whose_backup_fails_is_not_written() { json!("agentProviders.backupFailed") ); + // The save itself succeeds; the agent it could not bring up to date is + // reported with the reason, and its file is untouched. + let (synced, sync_logs) = + capture::run(false, || test.save_answer(full_library("Shared rule."))); assert_eq!( - test.refused_change(json!({ "category": "instructions", "op": "write", "replace": true })), + synced["instructions"], + json!([{ "agent": AGENT_KEY, "result": "failed", "reason": "agentProviders.backupFailed" }]) + ); + assert!(sync_logs + .iter() + .any(|log| log.event == "agent.library.change_failed" + && log.fields["category"] == json!("instructions") + && log.fields["reason"] == json!("agentProviders.backupFailed"))); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), "agentProviders.backupFailed" ); assert_eq!(fs::read(&instructions).unwrap(), b"My own notes\n"); @@ -392,9 +454,16 @@ fn a_file_the_library_and_providers_both_change_keeps_one_baseline() { // The providers page sees the whole agent: a hand edit to the // instruction file Lithe wrote shows there too, and its restore puts - // the instruction file back with the configuration. + // the instruction file back with the configuration. The first restore + // stopped the agent following the library, so it follows again first. let instructions = test.instructions_file(); - assert!(test.apply(json!({ "category": "instructions", "op": "write" }))); + assert!( + !test.read()["library"]["instructions"]["agents"][AGENT_KEY]["enabled"] + .as_bool() + .unwrap() + ); + test.save(full_library("Shared rule.")); + assert!(instructions.exists()); assert_eq!(providers_backup()["modifiedSince"], false); fs::write(&instructions, "Shared rule.\nEdited by hand.\n").unwrap(); assert_eq!(providers_backup()["modifiedSince"], true); @@ -405,3 +474,29 @@ fn a_file_the_library_and_providers_both_change_keeps_one_baseline() { assert_eq!(test.agent()["instructions"]["state"], "absent"); assert!(providers_backup().is_null()); } + +#[test] +fn a_file_the_library_cannot_remove_is_logged_by_its_kind_alone() { + use crate::library::remove_backup_leftover_for_test; + let dir = TempDir::new("library leftovers"); + // Removing a file fails for a directory on every platform. + let directory = dir.path().join("secret-name"); + fs::create_dir_all(directory.join("inside")).unwrap(); + let ((), logs) = capture::run(false, || { + remove_backup_leftover_for_test(&directory); + remove_backup_leftover_for_test(&dir.path().join("absent")); + }); + let failed: Vec<_> = logs + .iter() + .filter(|log| log.event == "agent.library.cleanup_failed") + .collect(); + assert_eq!(failed.len(), 1, "nothing to remove is not a failure"); + assert_eq!(failed[0].fields["target"], json!("backup")); + assert_eq!(failed[0].fields["error_domain"], json!("io")); + assert!(failed[0].fields["error_code"] + .as_str() + .is_some_and(|code| !code.is_empty())); + let logged = serde_json::to_string(&failed[0].fields).unwrap(); + assert!(!logged.contains("secret-name"), "no path is logged"); + assert!(directory.exists(), "what Core cannot remove stays"); +} diff --git a/rust/crates/agent-runtime/src/tests/library/instructions.rs b/rust/crates/agent-runtime/src/tests/library/instructions.rs new file mode 100644 index 00000000..7e617b1f --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/library/instructions.rs @@ -0,0 +1,681 @@ +//! The library's instructions in an agent's instruction file: only Lithe's +//! block is written, sets compose by their switches and agent lists, a save +//! brings every following agent up to date, the user's own text moves into +//! the library on import, and a library or file from before blocks reads on. + +use super::backups::{with_block, BEGIN, END}; +use super::*; +use crate::library::{compose_for_test, rewrite_for_test, state_tokens, sync_result_tokens}; +use sha2::{Digest, Sha256}; + +/// A library whose sets are `sets`, followed by the agent or not. +fn instructions_library(sets: Value, following: bool) -> Value { + json!({ + "instructions": { + "sets": sets, + "agents": { AGENT_KEY: { "enabled": following } } + } + }) +} + +/// One set on for every agent, with `text`. +fn shared(text: &str) -> Value { + json!([{ "id": "shared", "name": "Shared", "text": text, "on": true }]) +} + +fn sha256(text: &str) -> String { + Sha256::digest(text.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +impl LibraryTest { + fn instructions_state(&self) -> Value { + self.agent()["instructions"].clone() + } + + /// `agentLibrary.apply` of an import, with the library's revision unless + /// `change` names one. + fn import(&self, mut change: Value) -> Result { + change["category"] = json!("instructions"); + change["op"] = json!("import"); + if change.get("revision").is_none() { + change["revision"] = self.read()["revision"].clone(); + } + self.harness + .runtime + .execute( + "agentLibrary.apply", + json!({ "agent": AGENT_KEY, "change": change }), + ) + .map_err(|error| error.details.unwrap_or_default()) + } +} + +#[test] +fn block_layouts_follow_the_shared_fixture() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../../fixtures/agents/library-instructions-v1.json" + )) + .unwrap(); + assert_eq!(fixture["markers"], json!({ "begin": BEGIN, "end": END })); + for case in fixture["layouts"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let file = case["file"].as_str().unwrap(); + let text = case["text"].as_str().unwrap(); + let keep_own = case["keepOwn"].as_bool().unwrap_or(true); + let expected = case["expected"].as_str().unwrap(); + let written = rewrite_for_test(file, text, keep_own); + assert_eq!(written, expected, "{name}"); + assert_eq!( + rewrite_for_test(&written, text, true), + written, + "{name}: writing the same text again changes nothing and never grows the file" + ); + } + assert_eq!(fixture["states"], json!(state_tokens())); + assert_eq!(fixture["syncResults"], json!(sync_result_tokens())); +} + +#[test] +fn sets_compose_in_list_order_for_the_agents_they_name() { + let library = json!({ + "instructions": { + "sets": [ + { "id": "a", "name": "A", "text": "For everyone.\n\n", "on": true }, + { "id": "b", "name": "B", "text": "Switched off.", "on": false }, + { "id": "c", "name": "C", "text": "Only for a/b.", "on": true, "agents": ["a/b"] }, + { "id": "d", "name": "D", "text": "Only for x/y.", "on": true, "agents": ["x/y"] }, + { "id": "e", "name": "E", "text": " ", "on": true } + ], + "agents": { "a/b": { "enabled": true, "extra": " Extra for a/b. " } } + } + }); + assert_eq!( + compose_for_test(library.clone(), "a/b"), + "For everyone.\n\nOnly for a/b.\n\nExtra for a/b.\n" + ); + assert_eq!(compose_for_test(library.clone(), "a/c"), "For everyone.\n"); + assert_eq!( + compose_for_test(library, "x/y"), + "For everyone.\n\nOnly for x/y.\n" + ); + + let test = LibraryTest::new("instruction sets", CONFIGURATION_GRANTS); + let refused = |instructions: Value| { + let revision = test.read()["revision"].clone(); + test.harness.refused( + "agentLibrary.save", + json!({ "revision": revision, "library": { "instructions": instructions } }), + ) + }; + let set = |agents: Value| json!({ "sets": [{ "id": "a", "name": "A", "text": "x", "on": true, "agents": agents }] }); + assert_eq!( + refused(set(json!(["no-plugin"]))), + "agentLibrary.invalidLibrary" + ); + assert_eq!( + refused(set(json!(["a/b", "a/b"]))), + "agentLibrary.invalidLibrary", + "an agent is listed once" + ); + assert_eq!( + refused(json!({ "sets": [{ "id": "a", "name": "A", "text": "x" }], "active": "a" })), + "agentLibrary.invalidLibrary", + "a save switches sets on one by one" + ); + assert_eq!( + refused(json!({ "sets": [{ "id": "a", "name": "A", "text": "x", "default": true }] })), + "agents.invalidPayload", + "a field Core does not know is refused" + ); +} + +#[test] +fn a_library_with_one_active_set_reads_on_and_composes_byte_for_byte() { + // What a library saved before each set had its own switch composed: the + // active set's text without its trailing space, one blank line, the + // agent's extra text trimmed, one final line break. + let old_sets = json!([ + { "id": "other", "name": "Other", "text": "Not active." }, + { "id": "default", "name": "Default", "text": "Shared rule.\n\n " } + ]); + let old = json!({ + "instructions": { + "sets": old_sets, + "active": "default", + "agents": { AGENT_KEY: { "enabled": true, "extra": "\nOnly here.\n" } } + } + }); + let composed = "Shared rule.\n\nOnly here.\n"; + assert_eq!(compose_for_test(old.clone(), AGENT_KEY), composed); + + // A Core that predates blocks wrote the composed text as the whole file + // and kept its digest. + let test = LibraryTest::new("instructions from before blocks", CONFIGURATION_GRANTS); + fs::create_dir_all(&test.library).unwrap(); + fs::write( + test.library.join("library.json"), + serde_json::to_vec(&json!({ "version": 0, "library": old })).unwrap(), + ) + .unwrap(); + fs::write( + test.library.join("state.json"), + serde_json::to_vec( + &json!({ "version": 0, "instructions": { AGENT_KEY: sha256(composed) } }), + ) + .unwrap(), + ) + .unwrap(); + let file = test.instructions_file(); + fs::write(&file, composed).unwrap(); + + let read = test.read(); + assert_eq!( + read["library"]["instructions"], + json!({ + "sets": [ + { "id": "other", "name": "Other", "text": "Not active.", "on": false }, + { "id": "default", "name": "Default", "text": "Shared rule.\n\n ", "on": true } + ], + "agents": { AGENT_KEY: { "enabled": true, "extra": "\nOnly here.\n" } } + }), + "the active set is on, every other set off, and `active` is gone" + ); + assert_eq!( + test.instructions_state(), + json!({ "path": path_text(&file), "state": "stale", "ownLines": 0 }), + "the whole file is Lithe's" + ); + assert!(test.apply(json!({ "category": "instructions", "op": "write" }))); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("", composed), + "the old file becomes a block of the same text" + ); + assert_eq!(test.written_instructions(), Some(json!(sha256(composed)))); + assert_eq!(test.instructions_state()["state"], "current"); + + // Saving the library as read keeps the text the agent gets. + let saved = test.save_answer(read["library"].clone()); + assert_eq!( + saved["instructions"], + json!([{ "agent": AGENT_KEY, "result": "unchanged" }]) + ); + let stored = fs::read_to_string(test.library.join("library.json")).unwrap(); + assert!(!stored.contains("\"active\""), "a save writes the switches"); + + // An `active` that names no set is a damaged library. + fs::write( + test.library.join("library.json"), + br#"{"version":0,"library":{"instructions":{"sets":[],"active":"gone"}}}"#, + ) + .unwrap(); + assert_eq!( + test.harness.refused("agentLibrary.read", json!({})), + "agentLibrary.invalidLibraryFile" + ); +} + +#[test] +fn a_file_from_before_blocks_that_the_user_changed_keeps_the_users_text() { + let test = LibraryTest::new("changed file from before blocks", CONFIGURATION_GRANTS); + test.save(instructions_library(shared("Shared rule."), false)); + // The digest of what an old Core wrote, but the user changed the file + // since: none of it is Lithe's any more. + fs::write( + test.library.join("state.json"), + serde_json::to_vec( + &json!({ "version": 0, "instructions": { AGENT_KEY: sha256("Shared rule.\n") } }), + ) + .unwrap(), + ) + .unwrap(); + let file = test.instructions_file(); + fs::write(&file, "Shared rule.\nAnd mine.\n").unwrap(); + assert_eq!(test.instructions_state()["state"], "noBlock"); + assert_eq!(test.instructions_state()["ownLines"], 2); + + let saved = test.save_answer(instructions_library(shared("Shared rule."), true)); + assert_eq!( + saved["instructions"], + json!([{ "agent": AGENT_KEY, "result": "written" }]), + "no confirmation: the user's text is kept" + ); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("Shared rule.\nAnd mine.\n", "Shared rule.\n") + ); +} + +#[test] +fn a_save_writes_only_the_block_and_keeps_the_users_text_byte_for_byte() { + let test = LibraryTest::new("instruction block", CONFIGURATION_GRANTS); + let file = test.instructions_file(); + fs::write(&file, "# Mine\r\n\r\n keep \r\n").unwrap(); + let sets = |first: &str| { + json!([ + { "id": "one", "name": "One", "text": first, "on": true }, + { "id": "two", "name": "Two", "text": "Second set.", "on": true } + ]) + }; + + let saved = test.save_answer(instructions_library(sets("First set."), true)); + assert_eq!( + saved["instructions"], + json!([{ "agent": AGENT_KEY, "result": "written" }]) + ); + assert_eq!( + fs::read_to_string(&file).unwrap(), + format!( + "# Mine\r\n\r\n keep \r\n\r\n{BEGIN}\r\nFirst set.\r\n\r\nSecond set.\r\n{END}\r\n" + ), + "the block goes after the user's text, with the file's line breaks" + ); + assert_eq!( + test.instructions_state(), + json!({ "path": path_text(&file), "state": "current", "ownLines": 3 }) + ); + + // Text the user adds after the block stays where it is. + let mut text = fs::read_to_string(&file).unwrap(); + text.push_str("\r\nAdded later.\r\n"); + fs::write(&file, &text).unwrap(); + assert_eq!(test.instructions_state()["state"], "current"); + assert_eq!(test.instructions_state()["ownLines"], 5); + let saved = test.save_answer(instructions_library(sets("First, changed."), true)); + assert_eq!(saved["instructions"][0]["result"], "written"); + assert_eq!( + fs::read_to_string(&file).unwrap(), + format!( + "# Mine\r\n\r\n keep \r\n\r\n{BEGIN}\r\nFirst, changed.\r\n\r\nSecond set.\r\n{END}\r\n\r\nAdded later.\r\n" + ) + ); + let saved = test.save_answer(instructions_library(sets("First, changed."), true)); + assert_eq!( + saved["instructions"], + json!([{ "agent": AGENT_KEY, "result": "unchanged" }]) + ); + + // A library that gives the agent nothing takes the block out. + let off = json!([{ "id": "one", "name": "One", "text": "First.", "on": false }]); + let saved = test.save_answer(instructions_library(off, true)); + assert_eq!(saved["instructions"][0]["result"], "written"); + assert_eq!( + fs::read_to_string(&file).unwrap(), + "# Mine\r\n\r\n keep \r\n\r\nAdded later.\r\n" + ); + assert_eq!(test.written_instructions(), None); + assert_eq!(test.instructions_state()["state"], "current"); + + // An agent that does not follow is not written, and its block reads as + // out of date once the library changes. + test.save(instructions_library(shared("Shared."), true)); + let saved = test.save_answer(instructions_library(shared("Shared, changed."), false)); + assert_eq!(saved["instructions"], json!([])); + assert_eq!(test.instructions_state()["state"], "stale"); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.instructionsOff" + ); +} + +#[test] +fn an_edited_block_is_written_only_when_the_user_replaces_it() { + let test = LibraryTest::new("edited block", CONFIGURATION_GRANTS); + let file = test.instructions_file(); + fs::write(&file, "Mine.\n").unwrap(); + test.save(instructions_library(shared("Shared rule."), true)); + let edited = with_block("Mine.\n", "Edited by hand.\n"); + fs::write(&file, &edited).unwrap(); + assert_eq!(test.instructions_state()["state"], "edited"); + + let saved = test.save_answer(instructions_library(shared("New rule."), true)); + assert_eq!( + saved["instructions"], + json!([{ "agent": AGENT_KEY, "result": "skipped", "reason": "agentLibrary.otherInstructions" }]) + ); + assert_eq!(fs::read_to_string(&file).unwrap(), edited); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.otherInstructions" + ); + assert!(test.apply(json!({ "category": "instructions", "op": "write", "replace": true }))); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("Mine.\n", "New rule.\n") + ); + assert_eq!(test.instructions_state()["state"], "current"); +} + +#[test] +fn extra_blocks_and_stray_marker_lines_are_cleaned_up_without_growth() { + let test = LibraryTest::new("extra blocks", CONFIGURATION_GRANTS); + let file = test.instructions_file(); + fs::write(&file, "Mine.\n").unwrap(); + test.save(instructions_library(shared("Shared rule."), true)); + // A copy of Lithe's block and a stray end line, as a merge might leave. + let mut text = fs::read_to_string(&file).unwrap(); + text.push_str(&format!("\nTheirs.\n{END}\n{BEGIN}\nShared rule.\n{END}\n")); + fs::write(&file, &text).unwrap(); + assert_eq!( + test.instructions_state()["state"], + "stale", + "every block holds Lithe's text, but there is more than one" + ); + + assert!(test.apply(json!({ "category": "instructions", "op": "write" }))); + let cleaned = format!("Mine.\n\n{BEGIN}\nShared rule.\n{END}\n\nTheirs.\n"); + assert_eq!(fs::read_to_string(&file).unwrap(), cleaned); + assert!(!test.apply(json!({ "category": "instructions", "op": "write" }))); + assert_eq!(fs::read_to_string(&file).unwrap(), cleaned); + + // A begin line without an end line is a stray: the file reads as + // having no block, and a write keeps the user's text and adds one. + fs::write(&file, format!("Mine.\n{BEGIN}\nUnfinished.\n")).unwrap(); + assert_eq!(test.instructions_state()["state"], "noBlock"); + assert!(test.apply(json!({ "category": "instructions", "op": "write" }))); + assert_eq!( + fs::read_to_string(&file).unwrap(), + format!("Mine.\nUnfinished.\n\n{BEGIN}\nShared rule.\n{END}\n") + ); +} + +#[test] +fn marker_lines_in_the_library_text_cannot_end_the_block() { + let test = LibraryTest::new("inert markers", CONFIGURATION_GRANTS); + let file = test.instructions_file(); + let text = format!("Before.\n{END}\n{BEGIN}\nAfter."); + let saved = test.save_answer(instructions_library(shared(&text), true)); + assert_eq!(saved["instructions"][0]["result"], "written"); + assert_eq!( + fs::read_to_string(&file).unwrap(), + format!( + "{BEGIN}\nBefore.\n\n\nAfter.\n{END}\n" + ) + ); + assert_eq!(test.instructions_state()["state"], "current"); + assert_eq!(test.instructions_state()["ownLines"], 0); + let saved = test.save_answer(instructions_library(shared(&text), true)); + assert_eq!(saved["instructions"][0]["result"], "unchanged"); +} + +#[test] +fn a_file_lithe_cannot_read_reads_as_such_and_is_never_written() { + let test = LibraryTest::new("unreadable instructions", CONFIGURATION_GRANTS); + let file = test.instructions_file(); + let bytes = b"Not UTF-8: \xff\xfe\n"; + fs::write(&file, bytes).unwrap(); + assert_eq!( + test.instructions_state(), + json!({ "path": path_text(&file), "state": "unreadable" }) + ); + let saved = test.save_answer(instructions_library(shared("Shared rule."), true)); + assert_eq!( + saved["instructions"], + json!([{ "agent": AGENT_KEY, "result": "failed", "reason": "agentLibrary.unreadable" }]) + ); + assert_eq!(fs::read(&file).unwrap(), bytes); + + let large = "x".repeat(1024 * 1024 + 1); + fs::write(&file, &large).unwrap(); + assert_eq!(test.instructions_state()["state"], "tooLarge"); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.fileTooLarge" + ); +} + +#[test] +fn a_save_reports_each_following_agent() { + let test = LibraryTest::new("instruction sync", CONFIGURATION_GRANTS); + // The configuration plugin's agent, an agent whose block the user + // edited, one whose file Lithe cannot read and one that does not + // follow; and another plugin's agent without the configuration grant. + let mut granted = configuration_manifest(); + let sample = granted["agents"][0].clone(); + granted["activationEvents"] = json!([ + "onAgent:sample", + "onAgent:edited", + "onAgent:unreadable", + "onAgent:apart" + ]); + let agents = granted["agents"].as_array_mut().unwrap(); + for name in ["edited", "unreadable", "apart"] { + let mut agent = sample.clone(); + agent["id"] = json!(name); + agent.as_object_mut().unwrap().remove("sessionSources"); + agent["configuration"]["instructions"]["roots"] = + json!([format!("${{userHome}}/.{name}/INSTRUCTIONS.md")]); + agents.push(agent); + } + let mut ungranted = configuration_manifest(); + ungranted["id"] = json!("dev.lithe.test.ungranted"); + ungranted["agents"][0]["configuration"]["instructions"]["roots"] = + json!(["${userHome}/.ungranted/INSTRUCTIONS.md"]); + let configured = test.harness.run( + "agents.configure", + json!({ "plugins": [ + { "manifest": granted, "grantedPermissions": CONFIGURATION_GRANTS }, + { "manifest": ungranted, "grantedPermissions": ALL_GRANTS } + ] }), + ); + assert_eq!(configured["rejected"], json!([])); + let key = |name: &str| format!("{PLUGIN}/{name}"); + let ungranted_key = "dev.lithe.test.ungranted/sample"; + let file_of = |name: &str| test.home.join(format!(".{name}")).join("INSTRUCTIONS.md"); + for name in ["edited", "unreadable", "apart", "ungranted"] { + fs::create_dir_all(test.home.join(format!(".{name}"))).unwrap(); + } + let edited = with_block("", "Mine, by hand.\n"); + fs::write(file_of("edited"), &edited).unwrap(); + fs::write(file_of("unreadable"), b"\xff\n").unwrap(); + + let following = json!({ "enabled": true }); + let library = json!({ + "instructions": { + "sets": shared("Shared rule."), + "agents": { + AGENT_KEY: following, + key("edited"): following, + key("unreadable"): following, + key("apart"): { "enabled": false }, + ungranted_key: following + } + } + }); + let (saved, logs) = capture::run(false, || test.save_answer(library)); + assert_eq!( + saved["instructions"], + json!([ + { "agent": key("edited"), "result": "skipped", "reason": "agentLibrary.otherInstructions" }, + { "agent": AGENT_KEY, "result": "written" }, + { "agent": key("unreadable"), "result": "failed", "reason": "agentLibrary.unreadable" }, + { "agent": ungranted_key, "result": "skipped", "reason": "agentLibrary.notGranted" } + ]), + "in the order `agents.list` gives; an agent that does not follow is not listed" + ); + assert_eq!( + fs::read_to_string(test.instructions_file()).unwrap(), + with_block("", "Shared rule.\n") + ); + assert_eq!(fs::read_to_string(file_of("edited")).unwrap(), edited); + assert!(!file_of("apart").exists()); + assert!(!file_of("ungranted").exists()); + let applied: Vec<_> = logs + .iter() + .filter(|log| log.event == "agent.library.change_applied") + .map(|log| log.fields["agent"].clone()) + .collect(); + assert_eq!( + applied, + vec![json!(AGENT)], + "only a write is logged as applied" + ); + let failed: Vec<_> = logs + .iter() + .filter(|log| log.event == "agent.library.change_failed") + .map(|log| (log.fields["agent"].clone(), log.fields["reason"].clone())) + .collect(); + assert_eq!( + failed, + vec![ + (json!("edited"), json!("agentLibrary.otherInstructions")), + (json!("unreadable"), json!("agentLibrary.unreadable")), + (json!("sample"), json!("agentLibrary.notGranted")), + ] + ); +} + +#[test] +fn import_moves_the_users_text_into_the_library_and_leaves_only_the_block() { + let test = LibraryTest::new("instruction import", CONFIGURATION_GRANTS); + let file = test.instructions_file(); + let original = "Own rule.\n\n\nMore of mine. \n"; + fs::write(&file, original).unwrap(); + test.save(instructions_library(shared("Shared rule."), false)); + assert!(test.backup().is_none()); + + // Refusals leave the file and the library as they are. + assert_eq!( + test.import(json!({ "id": "mine", "name": "Mine", "revision": "stale" })), + Err("agentLibrary.revisionChanged".into()) + ); + assert_eq!( + test.import(json!({ "id": "shared", "name": "Mine" })), + Err("agentLibrary.setExists".into()) + ); + assert_eq!( + test.import(json!({ "id": "absent" })), + Err("agentLibrary.unknownItem".into()) + ); + assert_eq!( + test.import(json!({ "name": "Mine" })), + Err("agentLibrary.invalidChange".into()) + ); + let unrevised = test.harness.refused( + "agentLibrary.apply", + json!({ "agent": AGENT_KEY, "change": { "category": "instructions", "op": "import", "id": "mine" } }), + ); + assert_eq!(unrevised, "agentLibrary.invalidChange"); + assert_eq!(fs::read_to_string(&file).unwrap(), original); + + let (imported, logs) = capture::run(false, || { + test.import(json!({ "id": "mine", "name": "Mine" })) + }); + let imported = imported.unwrap(); + assert_eq!(imported["changed"], true); + assert_eq!( + imported["instructions"], + json!([{ "agent": AGENT_KEY, "result": "written" }]) + ); + let read = test.read(); + assert_eq!(imported["revision"], read["revision"]); + assert_eq!( + read["library"]["instructions"], + json!({ + "sets": [ + { "id": "shared", "name": "Shared", "text": "Shared rule.", "on": true }, + { "id": "mine", "name": "Mine", "text": "Own rule.\n\n\nMore of mine. ", "on": true, "agents": [AGENT_KEY] } + ], + "agents": { AGENT_KEY: { "enabled": true } } + }), + "a new set for this agent alone, which the agent now follows; the text keeps its lines as written" + ); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("", "Shared rule.\n\nOwn rule.\n\n\nMore of mine.\n"), + "the agent still reads every line it read, now in Lithe's block" + ); + assert_eq!( + test.instructions_state(), + json!({ "path": path_text(&file), "state": "current", "ownLines": 0 }) + ); + assert_eq!( + test.baselines(), + vec![original.as_bytes().to_vec()], + "the file before the import is backed up" + ); + assert!(logs + .iter() + .any(|log| log.event == "agent.library.change_applied" + && log.fields["change"] == json!("import"))); + + // Nothing of the user's is left to import. + let again = test.import(json!({ "id": "shared" })).unwrap(); + assert_eq!(again["changed"], false); + assert_eq!(again["revision"], read["revision"]); + + // A restore puts the file back and stops the agent following, so no + // save writes the block into it again. + assert_eq!( + test.restore(None), + json!({ "restored": true, "unfollowed": true }) + ); + assert_eq!(fs::read_to_string(&file).unwrap(), original); + let read = test.read(); + assert_eq!( + read["library"]["instructions"]["agents"][AGENT_KEY]["enabled"], + false + ); + let saved = test.save_answer(read["library"].clone()); + assert_eq!(saved["instructions"], json!([])); + assert_eq!(fs::read_to_string(&file).unwrap(), original); +} + +#[test] +fn import_into_an_existing_set_appends_once_and_refuses_an_edited_block() { + let test = LibraryTest::new("instruction import into a set", CONFIGURATION_GRANTS); + let file = test.instructions_file(); + let sets = json!([ + { "id": "shared", "name": "Shared", "text": "Shared rule.", "on": true }, + { "id": "team", "name": "Team", "text": "Team rule.\n", "on": false, "agents": ["dev.lithe.test.other/agent"] } + ]); + test.save(instructions_library(sets, true)); + fs::write( + &file, + format!("Mine.\n\n{}", fs::read_to_string(&file).unwrap()), + ) + .unwrap(); + + let imported = test.import(json!({ "id": "team" })).unwrap(); + assert_eq!(imported["changed"], true); + let team = test.read()["library"]["instructions"]["sets"][1].clone(); + assert_eq!( + team, + json!({ "id": "team", "name": "Team", "text": "Team rule.\n\nMine.", "on": true, "agents": ["dev.lithe.test.other/agent", AGENT_KEY] }), + "the set is switched on and lists the agent too" + ); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("", "Shared rule.\n\nTeam rule.\n\nMine.\n") + ); + + // Text the set holds already is not added twice. + let block = fs::read_to_string(&file).unwrap(); + fs::write(&file, format!("Mine.\n\n{block}")).unwrap(); + let revision = test.read()["revision"].clone(); + let imported = test.import(json!({ "id": "team" })).unwrap(); + assert_eq!(imported["changed"], true); + assert_eq!(imported["revision"], revision, "the library did not change"); + assert_eq!(fs::read_to_string(&file).unwrap(), block); + + // The user's text next to a block edited by hand moves only once the + // user lets the edit go. + let edited = format!("Mine, again.\n\n{}", with_block("", "Edited.\n")); + fs::write(&file, &edited).unwrap(); + assert_eq!( + test.import(json!({ "id": "shared" })), + Err("agentLibrary.otherInstructions".into()) + ); + assert_eq!(fs::read_to_string(&file).unwrap(), edited); + let imported = test + .import(json!({ "id": "shared", "replace": true })) + .unwrap(); + assert_eq!(imported["changed"], true); + assert_eq!( + fs::read_to_string(&file).unwrap(), + with_block("", "Shared rule.\n\nMine, again.\n\nTeam rule.\n\nMine.\n") + ); +} diff --git a/rust/crates/agent-runtime/src/tests/providers/backups.rs b/rust/crates/agent-runtime/src/tests/providers/backups.rs index 87d5d0ec..f6ea5669 100644 --- a/rust/crates/agent-runtime/src/tests/providers/backups.rs +++ b/rust/crates/agent-runtime/src/tests/providers/backups.rs @@ -100,7 +100,7 @@ fn apply_keeps_the_original_once_and_restore_puts_it_back() { ); let (restored, restore_logs) = capture::run(false, || test.restore(None)); - assert_eq!(restored, json!({ "restored": true })); + assert_eq!(restored, json!({ "restored": true, "unfollowed": false })); assert_eq!(fs::read(&file).unwrap(), original, "byte for byte"); assert!( test.read().get("backup").is_none(), @@ -177,7 +177,10 @@ fn restore_refuses_to_discard_later_changes_unless_asked() { "agentProviders.changedSinceApply" ); - assert_eq!(test.restore(Some(true)), json!({ "restored": true })); + assert_eq!( + test.restore(Some(true)), + json!({ "restored": true, "unfollowed": false }) + ); assert_eq!(fs::read(&file).unwrap(), original); assert!( test.history().contains(&external), diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index a651fd81..f035c673 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -29,7 +29,7 @@ pub static EVENTS: &[EventMetadata] = &[ fields: &[ FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, FieldMetadata { name: "category", field_type: FieldType::Token, required: true, description: "Library category changed: mcpServers, hooks, skills or instructions", reason: None }, - FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Change applied: put, remove, link, unlink or write", reason: None }, + FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Change applied: put, remove, link, unlink, write (also each agent a library save brings up to date) or import", reason: None }, FieldMetadata { name: "changed", field_type: FieldType::Bool, required: true, description: "False when the agent's configuration already matched", reason: None }, FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took, including plugin calls", reason: None }, FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, @@ -46,7 +46,7 @@ pub static EVENTS: &[EventMetadata] = &[ fields: &[ FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, FieldMetadata { name: "category", field_type: FieldType::Token, required: true, description: "Library category changed: mcpServers, hooks, skills or instructions", reason: None }, - FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Change applied: put, remove, link, unlink or write", reason: None }, + FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Change applied: put, remove, link, unlink, write (also each agent a library save brings up to date) or import", reason: None }, FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code such as agentLibrary.fileChanged; never names, commands, paths or text", reason: None }, ], @@ -54,6 +54,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.library.cleanup_failed", + channel: "agent", + level: LogLevel::Warn, + 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 }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.library.read_failed", channel: "agent", @@ -191,6 +204,7 @@ pub static EVENTS: &[EventMetadata] = &[ FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took", reason: None }, FieldMetadata { name: "files", field_type: FieldType::Int, required: true, description: "Configuration files put back", reason: None }, FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "unfollowed", field_type: FieldType::Bool, required: true, description: "Whether putting the instruction file back stopped the agent following the library's instructions", reason: None }, ], span: None, rate: 60, diff --git a/rust/fixtures/agents/library-instructions-v1.json b/rust/fixtures/agents/library-instructions-v1.json new file mode 100644 index 00000000..7db3691f --- /dev/null +++ b/rust/fixtures/agents/library-instructions-v1.json @@ -0,0 +1,97 @@ +{ + "description": "Where Core puts its block in an agent's instruction file (agentLibrary, plan API-45). `text` is the instruction text the library gives the agent; `file` is the file before a write and `expected` after it. Lines outside the block are kept byte for byte; only blank lines next to the block become one. `keepOwn: false` is an import, which leaves only the block. Writing the same `text` into `expected` gives `expected` again. `states` and `syncResults` are every value of `instructions.state` in `agentLibrary.read` and of `result` in a sync's answer.", + "markers": { + "begin": "", + "end": "" + }, + "layouts": [ + { + "name": "appendsAfterTheUserText", + "file": "My own notes\n", + "text": "Shared rule.\n", + "expected": "My own notes\n\n\nShared rule.\n\n" + }, + { + "name": "createsAFileOfTheBlockAlone", + "file": "", + "text": "Shared rule.\n", + "expected": "\nShared rule.\n\n" + }, + { + "name": "replacesTheBlockWhereItIs", + "file": "Top\n\n\nOld\n\n\nBottom\n", + "text": "New\n", + "expected": "Top\n\n\nNew\n\n\nBottom\n" + }, + { + "name": "takesTheBlockOutWhenTheLibraryGivesNothing", + "file": "My own notes\n\n\nOld\n\n", + "text": "", + "expected": "My own notes\n" + }, + { + "name": "endsTheUserTextsLastLine", + "file": "Notes", + "text": "Rule\n", + "expected": "Notes\n\n\nRule\n\n" + }, + { + "name": "makesMarkerLinesInTheTextInert", + "file": "", + "text": "Rule\n\n\nMore\n", + "expected": "\nRule\n\n\nMore\n\n" + }, + { + "name": "dropsLaterBlocksAndStrayMarkerLines", + "file": "A\n\nOld\n\nB\n\n\nOld\n\n\nC\n", + "text": "New\n", + "expected": "A\n\n\nNew\n\n\nB\nC\n" + }, + { + "name": "readsAnEditedBeginLineAsTheBegin", + "file": "Notes\n\n\nOld\n\n", + "text": "New\n", + "expected": "Notes\n\n\nNew\n\n" + }, + { + "name": "keepsWindowsLineBreaks", + "file": "Notes\r\n", + "text": "Rule\n", + "expected": "Notes\r\n\r\n\r\nRule\r\n\r\n" + }, + { + "name": "reducesBlankLinesNextToTheBlockToOne", + "file": "A\n\n\n\n\nOld\n\n\n\n\nB\n", + "text": "New\n", + "expected": "A\n\n\nNew\n\n\nB\n" + }, + { + "name": "keepsIndentationAndTrailingSpaces", + "file": " indented \n\n\nOld\n\n\n - item\n", + "text": "New\n", + "expected": " indented \n\n\nNew\n\n\n - item\n" + }, + { + "name": "importLeavesOnlyTheBlock", + "file": "Own rule\n\n\nOld\n\n\nMore of my own\n", + "text": "Shared\n\nOwn rule\n\nMore of my own\n", + "keepOwn": false, + "expected": "\nShared\n\nOwn rule\n\nMore of my own\n\n" + } + ], + "states": [ + "absent", + "noBlock", + "current", + "stale", + "edited", + "tooLarge", + "unreadable" + ], + "syncResults": [ + "written", + "unchanged", + "skipped", + "failed" + ] +} diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 69f5929f..6185a234 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -345,7 +345,7 @@ "change": { "type": "token", "required": true, - "description": "Change applied: put, remove, link, unlink or write" + "description": "Change applied: put, remove, link, unlink, write (also each agent a library save brings up to date) or import" }, "changed": { "type": "bool", @@ -385,7 +385,7 @@ "change": { "type": "token", "required": true, - "description": "Change applied: put, remove, link, unlink or write" + "description": "Change applied: put, remove, link, unlink, write (also each agent a library save brings up to date) or import" }, "reason": { "type": "token", @@ -396,6 +396,26 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "agent.library.cleanup_failed", + "channel": "agent", + "level": "warn", + "message": "The agent library could not clean up after itself, and what it names stays behind", + "fields": { + "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)" + }, + "error": { + "type": "error", + "required": true, + "description": "Filesystem error category raised by the removal or write, such as PermissionDenied; never a path or file content" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "agent.providers.read_finished", "channel": "agent", @@ -537,6 +557,11 @@ "required": true, "description": "Whether the user chose to discard changes made after Lithe's last write" }, + "unfollowed": { + "type": "bool", + "required": true, + "description": "Whether putting the instruction file back stopped the agent following the library's instructions" + }, "duration": { "type": "duration", "required": true, diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 7b9d8e43..ed3cf484 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4420,7 +4420,7 @@ and keeps no name or icon of its own for any agent. | Field | Meaning | | --- | --- | -| `instructions` | `{roots}`: the Markdown file the CLI reads as the user's own instructions. Core reads and writes it. | +| `instructions` | `{roots}`: the Markdown file the CLI reads as the user's own instructions. Core reads it and writes only its own block in it (see [Instruction files](#instruction-files)). | | `skills` | `{roots}`: the directory of the CLI's user skills, one directory with a `SKILL.md` per skill. Core reads it and links library skills into it. | | `files` | At most 8 `{id, roots}`: the files in the CLI's own format that hold its MCP servers, hooks, model and model providers. `id` is 1–64 bytes of lowercase ASCII letters, digits and `-`, not starting or ending with `-`, unique in the agent. Only the backend reads their format. | | `read` | Backend function that reports the MCP servers and hooks `files` hold. Required with `files`, unless `providers` is declared, and refused without them. | @@ -4461,8 +4461,8 @@ values of the catalog's `sessionRootVariables`: at most 256, each name 1–256 bytes and each value at most 32 KiB (`agentLibrary.invalidEnvironment`). In `directory`, created owner-only, Core keeps `library.json` (the servers, hooks and instruction sets), `skills//` (one directory per skill), -`state.json` (a digest of what Core last wrote to each agent's instruction -file), `staging/` (the copies plugins edit) and `backups/` (each agent's +`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 [Backups and restore](#backups-and-restore)). @@ -4478,19 +4478,34 @@ The library is `{mcpServers, hooks, instructions}`: `-`, unique); `event` is 1–64 ASCII letters, digits and `_`, as the CLIs name their hook events; `command` is nonblank; `timeoutSeconds` is 1–86400. -- `instructions`: `{sets, active?, agents}`. `sets` holds at most 64 `{id, - name, text}`, `id` like a hook's and `text` at most 256 KiB; `active` - names one set. `agents` maps at most 256 agent keys `/` - to `{enabled, extra?}`: whether the agent's instruction file follows the - library, and at most 64 KiB of text only that agent gets. +- `instructions`: `{sets, agents}`. `sets` holds at most 64 `{id, name, + text, on?, agents?}`, `id` like a hook's and `text` at most 256 KiB + without NUL. `on` (default `false`) switches the set on; `agents` lists at + most 256 distinct agent keys `/` the set gives its text + to, and an empty or absent list is every agent. `agents` of + `instructions` maps at most 256 agent keys to `{enabled, extra?}`: whether + the agent's instruction file follows the library, and at most 64 KiB of + text only that agent gets. An agent key is at most 512 bytes and holds a + `/`; it need not name an agent the catalog has now. A name is 1–128 characters without leading or trailing spaces or control characters. A command, URL, matcher or argument is at most 4 KiB without NUL. -An agent's instructions are the active set's text, then, after a blank -line, the agent's `extra`, ending with one line break; they are empty when -neither has text. +An agent's instructions are the text of each set that is on and gives the +agent its text, in `sets` order, without trailing whitespace, then the +agent's `extra` without leading or trailing whitespace; the parts that have +text are joined by a blank line and end with one line break, and the +instructions are empty when none has text. + +Each set had no switch of its own before, and `instructions` named the one +set every agent got in `active`. Core still reads such a `library.json`: the +set `active` names is on for every agent and every other set off, so each +agent's instructions are byte for byte what they were (an `active` that +names no set is `agentLibrary.invalidLibraryFile`). `read` never answers +`active`, Core writes the switches at the next save, and a `save` that gives +`active` is `agentLibrary.invalidLibrary`. `read` answers every set's `on`, +and its `agents` when not empty. #### Library commands @@ -4498,8 +4513,8 @@ neither has text. | --- | --- | --- | | `agentLibrary.configure` | `{directory, userHome, environment?}` | `{}` | | `agentLibrary.read` | `{query?, agent?, presence?, sort?}` | `{revision, library, skills, states, agents, matches?}` | -| `agentLibrary.save` | `{revision, library}` | `{revision}` | -| `agentLibrary.apply` | `{agent, change}` | `{changed}` | +| `agentLibrary.save` | `{revision, library}` | `{revision, instructions}` | +| `agentLibrary.apply` | `{agent, change}` | `{changed}`; `{changed, revision, instructions}` for an `import` | | `agentLibrary.importSkill` | `{agent, name}` or `{directory}` | `{name, files, skipped}` | | `agentLibrary.removeSkill` | `{name}` | `{unlinked}` | @@ -4514,6 +4529,10 @@ neither has text. - `agent` is `/` of an agent that declares `configuration` (`agentLibrary.unknownAgent`) and whose plugin is granted `agents.configuration` (`agentLibrary.notGranted`). +- After the library is saved, Core brings the instruction block of every + agent the library says follows it up to date and answers what it did in + `instructions`, as [Instruction files](#instruction-files) describes. The + library is saved whatever happens to an agent's file. `read` answers the library, `skills`, `states` and `agents`: @@ -4542,10 +4561,12 @@ neither has text. agent's files, whichever command changed them, as [Backups and restore](#backups-and-restore) describes; the same that `agentProviders.read` gives an agent that declares `providers`. - - `instructions`: `{path, state}`, `state` being `absent`, `empty` (only - whitespace), `current` (exactly the agent's instructions), `written` - (what Lithe last wrote, since changed in the library), `other` (text - Lithe did not write), `tooLarge` or `unreadable`. + - `instructions`: `{path, state, ownLines?}`, for an agent that declares + `instructions`. `state` compares the file with the agent's + instructions, as [Instruction files](#instruction-files) describes: + `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?}`, `kind` being `library` (a link into the library), `own` (a directory of the agent's own) or `link` (a link elsewhere); or `{path, error: @@ -4589,7 +4610,8 @@ already had what it asks for: | `{category: "hooks", op: "remove", hook: {event, matcher?, command, timeoutSeconds?}}` | removes the agent's own hook that is this hook | | `{category: "skills", op: "link", name}` | links the library skill `name` into the agent's skills directory | | `{category: "skills", op: "unlink", name}` | removes the agent's link of that name into the library | -| `{category: "instructions", op: "write", replace?}` | writes the agent's instructions to its instruction file | +| `{category: "instructions", op: "write", replace?}` | brings Lithe's block in the agent's instruction file up to date | +| `{category: "instructions", op: "import", id, name?, revision, replace?}` | moves the user's own text in the agent's instruction file into the set `id` of the library | Any other combination is `agentLibrary.invalidChange`; a library item that does not exist is `agentLibrary.unknownItem`. @@ -4626,14 +4648,8 @@ an elevated process, otherwise `agentLibrary.linkFailed`. An agent without the agent's own, so Core keeps no backup for it, and a restore leaves links as they are. -Instructions are written only while the agent's `enabled` is true -(`agentLibrary.instructionsOff`). Text Lithe did not write is replaced only -with `replace: true` (`agentLibrary.otherInstructions`); an empty file and -the text Lithe last wrote are replaced without it. The file is replaced the -same way as a configuration file, and backed up first like one -(`agentProviders.backupFailed`), the write over text Lithe did not write -that `replace: true` allows included. An agent without `instructions` is -`agentLibrary.noInstructions`. +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`), @@ -4656,6 +4672,128 @@ 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. +#### Instruction files + +Lithe writes only its own block in an agent's instruction file; every other +line is the user's: + +```markdown +The user's own text, kept as it is. + + +The agent's instructions. + +``` + +- A line that, without its leading and trailing whitespace, starts with + `` is a begin line, and one that + starts with `` an end line, whatever + words come between. A block runs from a begin line to the first end line + after it and holds the lines between them. A marker line in no block, an + end line no begin line opened or a begin line no end line follows, is a + stray. +- A write keeps every line outside the blocks byte for byte; only the blank + lines next to the block become one blank line. The block stays where the + first block is, and a new block goes after the user's text, one blank + line apart. Every other block and every stray is removed. When the agent's + instructions are empty, the block is removed and the user's text stays, + an empty file when there is none. +- The block holds the agent's instructions with `\n` line breaks, or `\r\n` + when the file has any `\r\n`. Each `` 和 `` 之间的内容。块外每一行都是用户的,逐字节保留,只把紧挨块的空行收成一行;新块放在用户文字之后;多出来的块和落单的标记行会被清掉;指令为空时去掉整块。资源库文字里的 `` and ``. Every line outside is the user's and kept byte for byte; only the blank lines next to the block become one. A new block goes after the user's text, extra blocks and stray marker lines are removed, and empty instructions remove the block. A `` 到 ``):块外用户文字逐字节保留,新块追加在用户文字之后,资源库文字里的标记行写成失效形式,多余的块和落单的标记行被清掉,指令为空时去掉整块,重复写入不变大;`state.json` 改记块内文字的哈希,旧 Core 整份写过且哈希一致的文件下次写成只有块,其他没有块的文件当作用户文字直接追加,不需确认。指令集新增可选 `on`、`agents`(空为所有 Agent),按 `sets` 顺序拼接后加 Agent 的 `extra`;去掉 `active`:读取带 `active` 的旧 `library.json` 时换成“该套开、其余关”,拼接结果逐字节不变,`save` 带 `active` 以 `agentLibrary.invalidLibrary` 拒绝。宿主命令 `agentLibrary.read` 的 `instructions.state` 改为 `absent`、`noBlock`、`current`、`stale`、`edited`、`tooLarge`、`unreadable`,新增 `ownLines`(块外用户文字行数);`agentLibrary.save` 回答新增 `instructions`:保存后 Core 给每个跟随的 Agent 写块,逐个回答 `written`、`unchanged`、`skipped`(带 `reason`)或 `failed`(带 `reason`),不覆盖用户改过的块;`agentLibrary.apply` 新增 `{category: "instructions", op: "import", id, name?, revision, replace?}`,把块外用户文字并入新建或已有的一套,先备份,文件只剩块,回答 `{changed, revision, instructions}`;`agentLibrary.otherInstructions` 收窄为“块里有不是 Lithe 写的内容”。`agentProviders.restore` 放回指令文件时关掉该 Agent 的跟随,回答新增 `unfollowed`,日志 `agent.providers.restore_applied` 新增字段 `unfollowed`。新增错误码 `agentLibrary.setExists`(并入时新建的一套 `id` 已存在)。新增日志事件 `agent.library.cleanup_failed`:资源库删不掉不再需要的文件(写入失败留下的临时文件、暂存副本、导入一半的技能、备份基线或历史),或失败后放不回备份记录时记录,只带对象种类和文件系统错误类别,不带路径。样例见 `rust/fixtures/agents/library-instructions-v1.json`。没有新增插件可调用的宿主方法、通知、插件函数参数或能力版本,插件后端协议和四语 SDK 不变。 | ## 按协议查首次出现 @@ -130,7 +115,7 @@ | API-05 | `workspace/getFolders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-05 | `workspace/setDirectoryTypes` | 0 | 2026-11-27 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | | API-05 | `workspace/setDirectoryMarks` | 0 | 2026-11-27 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | -| API-05 | `workspace/setDirectoryMarks` | 0(接受内建 `package` role) | 待合入 | [#250](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/250) | +| API-05 | `workspace/setDirectoryMarks` | 0(接受内建 `package` role) | 2026-12-02 | [#250](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/250) | | API-06 | `workspace/readDirectory` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-06 | `workspace/readDirectory` | 0(执行/校验补充) | 2026-11-23 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-06 | `workspace/stat` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -217,8 +202,8 @@ | API-25 | `languageServer/didReceiveNotification`(通知) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-27 | `editor/registerActions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-27 | `editor/registerActions` | 0(`actionIcons` 新增 4 个导航图标 token) | 2026-11-24 | [#198](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/198) | -| API-29 | `tests/start` | 0 | 待合入 | [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234) | -| API-29 | `tests/results` | 0 | 待合入 | [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234) | +| API-29 | `tests/start` | 0 | 2026-12-01 | [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234) | +| API-29 | `tests/results` | 0 | 2026-12-01 | [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234) | | API-29 | `build/getOptions` | 0 | 2026-11-21 | [#155](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/155) | | API-29 | `build/watchConfiguration` | 0 | 2026-11-21 | [#155](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/155) | | API-29 | `lithe/build/prepareRun`(提供者方法) | `litheBuild` 0、1(返回值 `outputEncoding` 可选声明) | 2026-11-20 | [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) | @@ -231,19 +216,19 @@ | API-45 | `agents/write` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0(事件新增 `configOptions`) | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | -| API-45 | `agents/report` | 0(交互能力、提问/撤回、回答交付与立即补充确认;封闭失败分类;停止中抑制当前轮次问题,保留整批结束) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | -| API-45 | `agents/report` | 0(`toolCall` 新增 `command`,仅在 `didStart` 带 `toolCommands` 时发送) | 待合入 | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246) | +| API-45 | `agents/report` | 0(交互能力、提问/撤回、回答交付与立即补充确认;封闭失败分类;停止中抑制当前轮次问题,保留整批结束) | 2026-12-01 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | +| API-45 | `agents/report` | 0(`toolCall` 新增 `command`,仅在 `didStart` 带 `toolCommands` 时发送) | 2026-12-01 | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246) | | API-45 | `agents/usage` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/usage` | 0(回答新增 `speeds`) | 2026-11-28 | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | | API-45 | `agents/didStart`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/didStart`(通知) | 0(新增 `toolCommands: true`) | 待合入 | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246) | +| API-45 | `agents/didStart`(通知) | 0(新增 `toolCommands: true`) | 2026-12-01 | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246) | | API-45 | `agents/didOutput`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0(有附件时带 `attachments`) | 2026-11-28 | [#224](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/224) | -| API-45 | `agents/didPrompt`(通知) | 0(`mode: "steer"`、`input` 保留当前轮次身份) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | +| API-45 | `agents/didPrompt`(通知) | 0(`mode: "steer"`、`input` 保留当前轮次身份) | 2026-12-01 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | | API-45 | `agents/didCancel`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/didCancel`(通知) | 0(停止后暂停队列,等待真实轮次结束;主动取消不记错误终态) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | -| API-45 | `agents/didAnswerQuestion`(通知) | 0(`turn`、`request`、`answers`、`cancelled`,SDK 确认交付) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | +| API-45 | `agents/didCancel`(通知) | 0(停止后暂停队列,等待真实轮次结束;主动取消不记错误终态) | 2026-12-01 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | +| API-45 | `agents/didAnswerQuestion`(通知) | 0(`turn`、`request`、`answers`、`cancelled`,SDK 确认交付) | 2026-12-01 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | | API-45 | `agents/didDecidePermission`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didSetConfigOption`(通知) | 0 | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | | API-45 | `agents/didExit`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | @@ -252,6 +237,42 @@ ## 时间线(新的在上) +### 2026-12-03 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | +| --- | --- | --- | --- | --- | +| [#260](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/260) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的修改替换 Agent 的文件前也先备份,和 `agentProviders.apply` 共用同一份备份。`agentLibrary.apply` 为 MCP 服务器、Hooks 改声明文件,以及整份写入指令文件(包括 `replace: true` 覆盖不是 Lithe 写的内容)之前先备份,备份不成功就不写文件,复用已有错误码 `agentProviders.backupFailed`;技能的符号链接不覆盖内容,不备份。同一个文件无论资源库还是供应商先改,都只存一份“自上次恢复以来 Lithe 第一次修改前的原样”(按第一个解析到该路径的声明文件归并,指令文件不是声明文件时单独一项)。宿主命令 `agentLibrary.read` 的每个 Agent 新增可选 `backup {savedAtMs, modifiedSince}`,和 `agentProviders.read` 的 `backup` 相同;后者现在也覆盖指令文件和资源库的修改。`agentProviders.restore` 不再要求 Agent 声明 `providers`(原来以 `agentProviders.notDeclared` 拒绝),恢复该 Agent 所有备份过的文件;放回指令文件前先忘掉 Core 最后写入的指令哈希,恢复后 `instructions.state` 按文件实际内容显示、不会是 `written`,再写入要重新确认 `replace: true`。旧 Core 只备份 `agentProviders.apply` 的修改,`agentLibrary.read` 不带 `backup`,对不声明 `providers` 的 Agent 的恢复回答 `agentProviders.notDeclared`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 | +| [#251](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/251) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 内的补充 | 宿主 `agentSessions.stats` 增加可选 `overview`,在同一快照中返回总计、分组、按日或小时的序列。按日分桶使用概览日历。缺少分组维度沿用 `agentSessions.invalidSplit`;概览的分组、明细开关和日历错误分别返回 `agentSessions.invalidOverviewGroup`、`agentSessions.invalidOverviewDetail`、`agentSessions.invalidCalendar`。插件的 `agents/usage` 和四语 SDK 接口沿用原状。 | + +### 2026-12-02 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | +| --- | --- | --- | --- | --- | +| [#247](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/247) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 宿主命令说明 | 补充 `agents.prompt` 重试的发送模式、原始提示词校验和拒绝原因。 | +| [#250](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/250) | [@devin-ai-integration[bot]](https://github.com/apps/devin-ai-integration) | API-05 | `pluginAPIVersion` 0 / `litheFunctions` 0 内的修正 | `workspace/setDirectoryMarks` 接受解析器已有的内建 `package` 角色,项目树按包目录图标呈现;`workspace/setDirectoryTypes`、权限、数量上限、合并优先级和所有版本不变。四种官方 SDK 已以通用 JSON 参数暴露该方法,本 PR 无 SDK 类型或版本变化;旧 Core 会以参数无效拒绝包含 `package` 的整组标记,插件应按能力/错误降级。 | +| [#249](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/249) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 在 #248 的 `configuration.providers` 上补充密钥写入、Lithe 保存的供应商列表和备份恢复。`providers` 新增可选 `listKeptBy`(`cli` / `lithe`,默认 `cli`)。密钥只写不读:`agentProviders.apply` 的 `addProvider`/`updateProvider` 可带 `key`(1–1024 字节,无控制字符和换行,否则 `agentProviders.invalidKey`),`updateProvider` 可带 `clearKey`(不能与 `key` 同时给);Core 只在内存里把它交给插件的 `edit`,不写日志、不进错误信息,快照的供应商只回答 `keySet`。`listKeptBy` 为 `lithe` 时(CLI 配置只能放一个自定义端点),Core 在资源库目录的 `saved-providers.json` 保存用户的供应商列表(不含密钥),插件用已有的 `lithe/host/credentials/*` 存密钥;修改带 `active` 与 `setProvider` 的 `provider`,供应商可带 `model`;快照的供应商增加 `saved`、`origin`、`model`,每个 Agent 增加 `listKeptBy`;Core 先存列表再调插件,失败时恢复列表。`apply` 替换文件前先备份到资源库目录的 `backups/`(自上次恢复以来第一次修改前的原样,加最近 20 份历史;可能含密钥,只在本机、仅所有者可读,不发给插件、不经接口回答),快照增加 `backup {savedAtMs, modifiedSince}`。新增宿主命令 `agentProviders.restore {agent, discardLaterChanges?}`(只接受用户发起)。新增错误码 `agentProviders.invalidKey`、`endpointExists`、`activeProvider`、`backupFailed`、`noBackup`、`changedSinceApply`、`restoreFailed`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.restore_applied`、`restore_failed`。旧 Core 把 `listKeptBy`、`key`、`clearKey` 当未知字段拒绝,不认识 `agentProviders.restore`。没有新增插件可调用的宿主方法、通知或能力版本。 | +| [#248](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/248) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | Agent 配置新增可选 `configuration.providers {read, edit?, operations?}`:插件函数 `read` 回答模型与模型供应商快照(格式 `litheAgentProviders`),`edit` 在暂存副本上应用一项修改(格式 `litheAgentProvidersEdit`),Core 应用后重新读取确认。`operations` 从 `addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setProvider`、`setProfile` 中声明,未声明的操作以 `agentProviders.unsupportedOperation` 拒绝。Core 执行隐私规则:环境变量和密钥只回答名称,地址去掉 userinfo、查询和片段,名称、数量和长度设上限;插件不得读取凭据文件和钥匙串;设置里的端点环境变量(BASE_URL 一类)作为供应商的 `baseUrl` 回答,其他环境变量只给名称。新增宿主命令 `agentProviders.read`、`agentProviders.apply`,错误码 `agentProviders.*`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.read_finished`、`read_failed`、`change_applied`、`change_failed`。宿主命令 `agentLibrary.read` 新增可选 `query`、`agent`、`presence`、`sort`,回答在有筛选时增加 `matches`,新错误码 `agentLibrary.invalidFilter`;不带参数时行为不变。声明 `providers` 时配置 `read` 可省略,权限沿用 `agents.configuration`。旧 Core 把 `providers` 当未知字段拒绝清单,把新筛选参数当未知字段拒绝。同时修正 Agent 日志里耗时字段名,使 `duration_ms` 不再被丢弃。样例见 `fixtures/agents/agents.plugin.json` 和 `fixtures/manifest/invalid-manifests.json`。没有新增插件可调用的宿主方法、通知或能力版本。 | + +### 2026-12-01 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | +| --- | --- | --- | --- | --- | +| [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | 插件函数协议 0、标准测试报告 0 内的补充 | 新权限 `tests.start` 允许后端从构建实例或独立运行器启动原生 Tests 会话,并在完成回调中分页读取结果。四个 SDK 同步接入。Core 新增命令 `build.decodeInlineTestResults` 和日志事件 `run.tests.state_changed`。旧 Core 安装声明该权限的插件时会返回 `plugin.permission.unknown`。首个同时支持两种入口的 Core 修订为 [`5495f5e8`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/5495f5e873dcae185df276074c59d35c9bc952bf)。 | +| [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | `toolCall` 事件新增可选 `command`:`execute` 调用实际运行的命令行(1 字节到 1 MiB),此时 `title` 写这条命令要做什么(例如 CLI 给的描述),宿主把标题作为步骤标题、命令放进命令卡片,没有 `command` 时只用标题。`didStart` 新增 `toolCommands: true`,后端只在看到它时才发送 `command`;旧 Core 的 `toolCall` 严格解码,收到 `command` 会拒绝整批报告。会话来源 `read` 函数新增可选请求参数 `toolCommands`,`agentSessions.page` 随 `toolCalls` 一起发送,只有这时 `tool` 消息才可带 `command`,否则以 `agentSessions.invalidRead` 拒绝。四语 SDK 的 `AgentSessionStart` 新增 `toolCommands`(Rust `tool_commands`、Go `ToolCommands`、Java `toolCommands()`、Node `toolCommands`);记录读取仍是普通 JSON 函数,无类型变化。没有新增宿主方法、错误码或能力版本。样例见 `fixtures/agents/native-session.json` 与 `fixtures/agents/record-read.json`。 | +| [#245](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/245) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.stats` 新增可选 `splitBy`(`agent`/`model`/`provider`/`modelProvider`,在 `groupBy` 之后再拆一层,第二个键在 summary 的 `split`)、筛选 `models`、`providers`、`failed`、`search`(同时作用于 `summaries` 和 `speeds`)和 `detail`(每组增加 `speed` 速度中位数与 `firstToken` 平均首字耗时);`groupBy` 新增只给宿主的 `provider`、`modelProvider`、`all`。`agentSessions.calls` 新增 `models`、`providers`、`search`,与 stats 的筛选规则相同。新增错误码 `agentSessions.invalidSplit`、`agentSessions.invalidFilter`。`agents/usage`(插件)的分组和回答不变。旧 Core 把新字段当未知字段拒绝,把新分组名当 `agentSessions.invalidGroup` 拒绝。没有新增宿主方法、通知或能力版本。 | +| [#241](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/241) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.search` 的命中新增 `generation` 和 `readBytes`,都是命中所在文件(可能是子代理文件)的值,宿主据此从命中处用 `agentSessions.page` 分页读取该文件。旧 Core 不回答这两个字段。没有新增宿主方法、通知、错误码或能力版本。 | +| [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。事件重放同时限制 8192 条 / 16 MiB,交互状态只保留每会话最新快照;`agents.waitEvents` 增加 `recoveries` 与可选 `acknowledge`,拒绝的补充在预留的 64 条 / 16 MiB 容量中保留,直到宿主恢复并显式确认。停止后的有效当前轮次问题被抑制,不阻塞同批结束事件。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision 为 [`8e5ee03379cc2ad2b43bb24d1c31dfe011abd160`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/8e5ee03379cc2ad2b43bb24d1c31dfe011abd160)(本 PR 合入的提交);桌面端尚未发布。 | +| [#231](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/231) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 | `agents/usage` 支持按小时汇总。默认按指定 UTC 偏移对齐整点,也可用 `hourAnchorMs` 对齐滚动窗口。 | +| [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。同时增加可选请求参数 `toolCalls`:只有 `true` 时 `tool` 消息才可带实时 `toolCall` 的详情 `toolCallID`、`status`、`toolKind`、`title`、`locations`(同一调用和它的结果共用 `toolCallID`,宿主按实时方式合并,让历史轮次和实时显示一致)。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,两个参数都由它发送,旧 `agentSessions.read` 和标题读取不协商,回答里出现这些详情字段(包括显式 `null`)时以 `agentSessions.invalidRead` 拒绝。`agentSessions.list` 的会话新增 `generation`:文件只增长时不变,被替换或截断后重新读取时换新值;`agentSessions.page` 必须带上同一次列表的 `generation`,不一致时回答 `changed`。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `d84f71d`;宿主发布版本尚未产生。 | + +### 2026-11-29 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | +| --- | --- | --- | --- | --- | +| [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | +| [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | +| [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | + ### 2026-11-28 | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 |