Repository navigation
feat(agents): 资源库改写 Agent 文件前也先备份,恢复覆盖资源库与供应商的全部修改 #260
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,8 +5,9 @@ | |
| //! application data that the host names with `agentLibrary.configure`: | ||
| //! `library.json` holds the servers, hooks and instruction sets, | ||
| //! `skills/<name>/` holds one directory per skill, `state.json` records what | ||
| //! Core last wrote to each agent's instruction file, and `staging/` holds the | ||
| //! copies plugins edit. | ||
| //! Core last wrote to each agent's instruction file, `staging/` holds the | ||
| //! copies plugins edit, and `backups/` the agents' files as they were before | ||
| //! Lithe changed them (`backups` module). | ||
| //! | ||
| //! What an agent has is read from the agent's own files every time and never | ||
| //! kept. An agent plugin declares where they are (`configuration` in the | ||
|
|
@@ -31,6 +32,11 @@ | |
| //! - Model, providers and profiles (`providers` module): the same staged | ||
| //! copy, for the operations the manifest declares. | ||
| //! | ||
| //! Every file Core replaces, the instruction file included, is backed up | ||
| //! first, and the change fails unwritten when it cannot be; a skill link | ||
| //! replaces nothing. A restore puts the agent's files back whichever kind of | ||
| //! change wrote them. | ||
| //! | ||
| //! Logs carry plugin and agent IDs, categories, counts and codes, never | ||
| //! names, commands, paths or text. | ||
|
|
||
|
|
@@ -65,6 +71,10 @@ const STAGING_DIRECTORY: &str = "staging"; | |
| const SKILL_FILE: &str = "SKILL.md"; | ||
| /// The revision of a library that was never saved. | ||
| const EMPTY_REVISION: &str = "empty"; | ||
| /// The backup ID of an instruction file no declared file names. Declared | ||
| /// file IDs are lowercase ASCII letters, digits and `-`, so the `:` keeps | ||
| /// this one apart from all of them. | ||
| const INSTRUCTIONS_BACKUP_ID: &str = "lithe:instructions"; | ||
|
|
||
| const READ_FORMAT: &str = "litheAgentConfiguration"; | ||
| const EDIT_FORMAT: &str = "litheAgentConfigurationEdit"; | ||
|
|
@@ -242,6 +252,8 @@ struct LibraryFile { | |
| struct StateFile { | ||
| version: u32, | ||
| /// SHA-256 of the text Core last wrote to each agent's instruction file. | ||
| /// A restore that puts the file back forgets it, so the restored text | ||
| /// reads as text Lithe did not write. | ||
| #[serde(default)] | ||
| instructions: BTreeMap<String, String>, | ||
| } | ||
|
|
@@ -1134,6 +1146,31 @@ struct AgentPaths { | |
| files: Vec<(String, PathBuf)>, | ||
| } | ||
|
|
||
| impl AgentPaths { | ||
| /// The backup ID of the file at `path`: the first declared file that | ||
| /// resolves there, else `own`. A file then has one backup ID, and one | ||
| /// baseline, whichever change reaches it first. | ||
| fn backup_id(&self, path: &Path, own: &str) -> String { | ||
| self.files | ||
| .iter() | ||
| .find(|(_, declared)| declared == path) | ||
| .map_or(own, |(id, _)| id.as_str()) | ||
| .to_string() | ||
| } | ||
|
|
||
| /// Every file a backup of the agent may hold, by backup ID: the declared | ||
| /// files, then the instruction file unless a declared file is that file. | ||
| fn backed_up(&self) -> Vec<(String, PathBuf)> { | ||
| let mut files = self.files.clone(); | ||
| if let Some(path) = &self.instructions { | ||
| if !files.iter().any(|(_, declared)| declared == path) { | ||
| files.push((INSTRUCTIONS_BACKUP_ID.to_string(), path.clone())); | ||
| } | ||
| } | ||
| files | ||
| } | ||
| } | ||
|
|
||
| fn agent_paths(config: &Config, configuration: &ConfigurationDeclaration) -> AgentPaths { | ||
| let resolve = |roots: &[String]| resolve_root(roots, &config.user_home, &config.environment); | ||
| AgentPaths { | ||
|
|
@@ -1547,6 +1584,17 @@ impl Library { | |
| write_replacing(&config.directory.join(STATE_FILE), &bytes).map_err(|_| write_failed()) | ||
| } | ||
|
|
||
| /// Forgets what Core last wrote to the instruction file of the agent | ||
| /// `key`, before a restore puts back what the file held before Lithe's | ||
| /// first change: none of Lithe's text is left there to claim. | ||
| fn forget_written_instructions(config: &Config, key: &str) -> Result<(), CoreError> { | ||
| let mut state = Self::load_state(config); | ||
| if state.instructions.remove(key).is_none() { | ||
| return Ok(()); | ||
| } | ||
| Self::store_state(config, &state) | ||
| } | ||
|
|
||
| /// `agentLibrary.read`: the library, its skills, and each agent that | ||
| /// declares configuration with what its files hold. | ||
| pub fn read(&self, runtime: &Runtime, payload: Value) -> Result<Value, CoreError> { | ||
|
|
@@ -1740,6 +1788,11 @@ impl Library { | |
| return view; | ||
| } | ||
| let paths = agent_paths(config, &configuration); | ||
| // The same backup `agentProviders.read` reports: an agent without | ||
| // providers has one too once the library changed its files. | ||
| if let Some(backup) = backups::status(config, &key, &paths.backed_up()) { | ||
| 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); | ||
|
|
@@ -2122,22 +2175,30 @@ impl Library { | |
| )) | ||
| } | ||
| }; | ||
| self.edit_staged(config, &target_path, None, edit_file, shows_change) | ||
| let agent_key = agent.record_key(); | ||
| let backup_id = paths.backup_id(&target_path, &target_id); | ||
| self.edit_staged( | ||
| config, | ||
| &target_path, | ||
| (&agent_key, &backup_id), | ||
| edit_file, | ||
| shows_change, | ||
| ) | ||
| } | ||
|
|
||
| /// Changes the file at `target` through a plugin: copies it into | ||
| /// `staging/`, lets `edit` change only the copy and report whether it | ||
| /// changed, lets `shows_change` confirm the copy holds the change, and | ||
| /// replaces the file with the copy if the file is unchanged meanwhile. | ||
| /// The staged copy is removed whatever happens. With `backup` (the | ||
| /// agent's record key and the declared file's ID), the file's bytes are | ||
| /// backed up first and the change fails, unwritten, if they cannot be. | ||
| /// Answers whether the file changed. | ||
| /// The staged copy is removed whatever happens. Before the file is | ||
| /// replaced its bytes are backed up under `backup` (the agent's record | ||
| /// key and the file's backup ID), and the change fails, unwritten, if | ||
| /// they cannot be. Answers whether the file changed. | ||
| fn edit_staged( | ||
| &self, | ||
| config: &Config, | ||
| target: &Path, | ||
| backup: Option<(&str, &str)>, | ||
| backup: (&str, &str), | ||
| edit: impl FnOnce(&Path, bool) -> Result<bool, CoreError>, | ||
| shows_change: impl FnOnce(&Path) -> Result<(), CoreError>, | ||
| ) -> Result<bool, CoreError> { | ||
|
|
@@ -2165,17 +2226,14 @@ impl Library { | |
| "The configuration file changed while it was being edited.", | ||
| )); | ||
| } | ||
| let taken = backup | ||
| .map(|(agent, file)| backups::take(config, agent, file, now.as_deref(), &edited)) | ||
| .transpose()?; | ||
| let (agent, file) = backup; | ||
| let taken = backups::take(config, agent, file, now.as_deref(), &edited)?; | ||
|
Comment on lines
+2229
to
+2230
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 CLI edits lost during backup If the CLI saves settings during Learn moreedit_staged checks that the original snapshot still matches before it takes the new backup. Its mutex serializes only Lithe’s library commands. take snapshots those already-read bytes and synchronously writes backup data and the record. An independent CLI can save after the check, and the final rename replaces that save. apply_instructions adds the same backup window between reading the file and replacing it. Example: Turn on an MCP server in Lithe while the CLI saves a preference. If the CLI save completes during backup sync, the staged file wins and neither the baseline nor the history for that write contains the preference. Recommended fix: Revalidate the target and original bytes after the backup and as close to the rename as possible, undoing the pending backup on a mismatch. Apply the same check to instructions. A strict guarantee against arbitrary external writers requires a conditional replacement or a lock those writers honor. Was this helpful? React with 👍 or 👎 to provide feedback. |
||
| let written = real | ||
| .parent() | ||
| .map_or(Ok(()), ensure_directory) | ||
| .and_then(|()| write_replacing(&real, &edited).map_err(|_| write_failed())); | ||
| if let Err(error) = written { | ||
| if let Some(taken) = taken { | ||
| backups::undo(taken); | ||
| } | ||
| backups::undo(taken); | ||
| return Err(error); | ||
| } | ||
| Ok(true) | ||
|
|
@@ -2333,10 +2391,23 @@ impl Library { | |
| )); | ||
| } | ||
| } | ||
| if let Some(parent) = real.parent() { | ||
| ensure_directory(parent)?; | ||
| // 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); | ||
| } | ||
| write_replacing(&real, text.as_bytes()).map_err(|_| write_failed())?; | ||
| state.version = 0; | ||
| state | ||
| .instructions | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 Restore silently discards intervening settings edits
After a CLI settings edit,
edit_stagedcan carry it into a library write and mark the whole file unchanged. Restore then rolls back the CLI edit without discard confirmation.Learn more
The plugin edits a copy and keeps unrelated settings, as the configuration edit contract requires. If the same file already has a baseline, take leaves that baseline intact but replaces the recorded digest with the digest of the entire new file. restore compares only that digest before putting the baseline back. Before this PR a library write left the provider backup’s digest unchanged, so restore still required confirmation.
Example: Change the model in Lithe, enable a logging setting in the CLI, then add an MCP server in the library. The MCP edit keeps logging enabled, but restore now accepts the default request and disables logging along with undoing the model and MCP edits.
Recommended fix: Detect divergence from an existing backup’s last-write digest before advancing it. Preserve a separate indication that restoring the baseline would discard outside changes and honor it in both read status and restore until the baseline is retired.
Was this helpful? React with 👍 or 👎 to provide feedback.