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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` |
| `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 |
| `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.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 an agent's files back as they were before Lithe's first change since the last restore; 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; 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 |
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/agent-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ impl Runtime {
"agentLibrary.removeSkill" => self.library.remove_skill(self, payload),
"agentProviders.read" => self.library.read_providers(self, payload),
"agentProviders.apply" => self.library.apply_providers(self, payload),
"agentProviders.restore" => self.library.restore_providers(self, payload),
"agentProviders.restore" => self.library.restore_backup(self, payload),
_ => Err(CoreError::new(
ErrorCode::NotSupported,
format!("Unknown agent command {command}."),
Expand Down
105 changes: 88 additions & 17 deletions rust/crates/agent-runtime/src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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>,
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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> {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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> {
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

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_staged can 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +2229 to +2230

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 CLI edits lost during backup

If the CLI saves settings during backups::take, edit_staged can overwrite them without a fresh file check. The backup holds the earlier bytes, so it cannot recover that save.

Learn more

edit_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.

Devin Review


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)
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading