From d455c9d60c9ac91445ce1d7bed5868895ec0f2a6 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 3 Dec 2026 18:24:46 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(agents):=20=E8=B5=84=E6=BA=90=E5=BA=93?= =?UTF-8?q?=E6=94=B9=E5=86=99=20Agent=20=E6=96=87=E4=BB=B6=E5=89=8D?= =?UTF-8?q?=E4=B9=9F=E5=85=88=E5=A4=87=E4=BB=BD=EF=BC=8C=E6=81=A2=E5=A4=8D?= =?UTF-8?q?=E8=A6=86=E7=9B=96=E8=B5=84=E6=BA=90=E5=BA=93=E4=B8=8E=E4=BE=9B?= =?UTF-8?q?=E5=BA=94=E5=95=86=E7=9A=84=E5=85=A8=E9=83=A8=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - agentLibrary.apply 写 MCP 服务器、Hooks 和整份指令文件(含 replace 覆盖)前先备份,备份失败不写 - 同一个文件不论资源库还是供应商先改,只留一份基线 - agentLibrary.read 的每个 Agent 带 backup {savedAtMs, modifiedSince},与 agentProviders.read 相同 - agentProviders.restore 不再要求声明 providers;放回指令文件前先忘掉 Core 记的指令哈希 - 契约、领域文档、Core API 文档与协议更新记录同步;agents 0 内的补充,不升版本 Refs 1lck/Lithe-IDEA#2654 --- rust/contracts/rust-core-api.md | 6 +- rust/crates/agent-runtime/src/lib.rs | 2 +- rust/crates/agent-runtime/src/library.rs | 105 ++++- .../agent-runtime/src/library/backups.rs | 158 ++++++- .../agent-runtime/src/library/providers.rs | 75 +--- .../crates/agent-runtime/src/tests/library.rs | 13 +- .../src/tests/library/backups.rs | 407 ++++++++++++++++++ shared/plugins/contract/v1/README.md | 140 ++++-- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 30 +- .../plugins/reference/protocol-changelog.md | 1 + 12 files changed, 795 insertions(+), 150 deletions(-) create mode 100644 rust/crates/agent-runtime/src/tests/library/backups.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index e5dff2fb..5b3f7791 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; `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 | diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index bbe66b4b..6044731d 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -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}."), diff --git a/rust/crates/agent-runtime/src/library.rs b/rust/crates/agent-runtime/src/library.rs index c525db6b..4da51532 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -5,8 +5,9 @@ //! application data that the host names with `agentLibrary.configure`: //! `library.json` holds the servers, hooks and instruction sets, //! `skills//` 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, } @@ -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 { @@ -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, shows_change: impl FnOnce(&Path) -> Result<(), CoreError>, ) -> Result { @@ -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)?; 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 diff --git a/rust/crates/agent-runtime/src/library/backups.rs b/rust/crates/agent-runtime/src/library/backups.rs index 6aa99cd4..a9c84ace 100644 --- a/rust/crates/agent-runtime/src/library/backups.rs +++ b/rust/crates/agent-runtime/src/library/backups.rs @@ -1,9 +1,13 @@ -//! Backups of the files `agentProviders.apply` replaces, and their restore. +//! Backups of the files Core replaces in an agent's configuration, and +//! `agentProviders.restore`, which puts them back. //! -//! Before Core replaces an agent's configuration file for a providers -//! change, it keeps the file's bytes in the library directory, which the host -//! puts in the platform's application data and never in the app bundle, an -//! install directory, a temporary directory or next to the CLI's own files: +//! Before Core replaces one of an agent's files, it keeps the file's bytes in +//! the library directory, which the host puts in the platform's application +//! data and never in the app bundle, an install directory, a temporary +//! directory or next to the CLI's own files. Every replacement goes through +//! here: a declared file that a library change (MCP servers, hooks) or a +//! providers change edits, and the instruction file a library change writes. +//! Linking a skill replaces no file and keeps nothing. //! //! ```text //! /backups//record.json what Core keeps per file @@ -12,11 +16,14 @@ //! ``` //! //! `` and `` are digests of the agent's record key and the -//! declared file's ID, so no name a plugin chose becomes a path. +//! file's backup ID (`AgentPaths::backup_id`), so no name a plugin chose +//! becomes a path. //! -//! - The baseline is the file as it was before Lithe's first change since the -//! last restore; later changes never replace it. A file that did not exist -//! is kept as "absent", and restoring it removes the file Lithe created. +//! - One file has one backup ID, whichever kind of change reaches it, so it +//! has one baseline: the file as it was before Lithe's first change since +//! the last restore; later changes never replace it. A file that did not +//! exist is kept as "absent", and restoring it removes the file Lithe +//! created. //! - The record holds the digest of what Lithe last wrote, so a read can tell //! whether something else changed the file since. //! - History keeps the bytes before each change and before each restore, the @@ -30,16 +37,20 @@ //! happen. use super::{ - digest, ensure_private_directory, read_bounded, real_file, refusal, write_replacing, Config, + 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, }; +use crate::{log, Runtime}; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; use std::collections::BTreeMap; use std::fs; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Instant; const BACKUPS_DIRECTORY: &str = "backups"; const RECORD_FILE: &str = "record.json"; @@ -63,7 +74,7 @@ struct FileRecord { written: String, } -/// One agent's backups, by declared file ID. +/// One agent's backups, by backup ID (`AgentPaths::backup_id`). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Record { @@ -73,7 +84,8 @@ struct Record { files: BTreeMap, } -/// What `agentProviders.read` reports about an agent's backup. +/// What `agentLibrary.read` and `agentProviders.read` report about an +/// agent's backup. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct Status { /// When the oldest baseline was kept. @@ -82,6 +94,17 @@ pub(super) struct Status { pub modified_since: bool, } +impl Status { + /// The `backup` field of an agent in either read: a time and a boolean, + /// never anything the files hold. + pub(super) fn answer(self) -> Value { + json!({ + "savedAtMs": self.saved_at_ms, + "modifiedSince": self.modified_since, + }) + } +} + /// A backup taken before a write, to take back if the write fails. pub(super) struct Taken { directory: PathBuf, @@ -204,10 +227,10 @@ fn prune_history(history: &Path) { } /// Keeps a backup of `original` (none when the file does not exist) before -/// Lithe writes `edited` to the agent's file `file_id`: the baseline if this -/// is the first change since the last restore, a history entry always, and -/// the digest of `edited` in the record. Fails without changing anything -/// kept so far when any of it cannot be written. +/// Lithe writes `edited` to the agent's file of backup ID `file_id`: the +/// baseline if this is the first change since the last restore, a history +/// entry always, and the digest of `edited` in the record. Fails without +/// changing anything kept so far when any of it cannot be written. pub(super) fn take( config: &Config, agent_key: &str, @@ -284,8 +307,8 @@ fn modified(path: &Path, file: &FileRecord) -> bool { } } -/// The agent's backup as `agentProviders.read` reports it, if it has one. -/// `files` are the agent's declared files by ID. +/// The agent's backup as both reads report it, if it has one. `files` are +/// the agent's files by backup ID (`AgentPaths::backed_up`). pub(super) fn status( config: &Config, agent_key: &str, @@ -315,13 +338,16 @@ pub(super) enum RestoreRefusal { /// Puts each backed-up file back as its baseline holds it, removing a file /// that did not exist, then forgets the backup. A file something else /// changed since Lithe's last write is put back only with `discard`. Each -/// file's current bytes are kept in history first. Answers how many files -/// were restored. +/// file's current bytes are kept in history first. `files` are the agent's +/// files by backup ID. Once every check passed and before the first file is +/// written, `before_write` gets the backup IDs about to be put back; when it +/// fails, nothing is written. Answers how many files were restored. pub(super) fn restore( config: &Config, agent_key: &str, files: &[(String, PathBuf)], discard: bool, + before_write: impl FnOnce(&[&str]) -> Result<(), CoreError>, ) -> Result { let directory = agent_directory(config, agent_key); let record = load(&directory).ok_or(RestoreRefusal::NoBackup)?; @@ -355,6 +381,8 @@ pub(super) fn restore( targets.push((id.clone(), real, current, baseline)); } prepare(config, &directory).map_err(|_| RestoreRefusal::Failed)?; + let restoring: Vec<&str> = targets.iter().map(|(id, ..)| id.as_str()).collect(); + before_write(&restoring).map_err(|_| RestoreRefusal::Failed)?; let mut remaining = record.clone(); for (id, real, current, baseline) in &targets { keep_history(&directory, id, current.as_deref()).map_err(|_| RestoreRefusal::Failed)?; @@ -393,3 +421,93 @@ pub(super) fn restore_error(refusal_kind: &RestoreRefusal) -> CoreError { RestoreRefusal::Failed => restore_failed(), } } + +// --------------------------------------------------------------------------- +// Command. + +/// `agentProviders.restore`'s payload. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RestoreRequest { + agent: String, + #[serde(default)] + discard_later_changes: bool, +} + +impl Library { + /// `agentProviders.restore`: puts back every file of the agent's + /// configuration Core backed up, as it was before Lithe's first change + /// 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`. + 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 outcome = (|| { + let config = self.config()?; + let configuration = agent + .agent + .configuration + .as_ref() + .expect("configurable agents declare configuration"); + let paths = agent_paths(&config, configuration); + let instructions = paths + .instructions + .as_deref() + .map(|path| paths.backup_id(path, INSTRUCTIONS_BACKUP_ID)); + let _writing = self.lock_writing(); + restore( + &config, + &key, + &paths.backed_up(), + 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. + match &instructions { + Some(id) if restoring.contains(&id.as_str()) => { + Self::forget_written_instructions(&config, &key) + } + _ => Ok(()), + } + }, + ) + .map_err(|refused| restore_error(&refused)) + })(); + let duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + match &outcome { + Ok(files) => log( + "agent.providers.restore_applied", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("files", json!(files)), + ("discarded", json!(request.discard_later_changes)), + ("duration_ms", json!(duration_ms)), + ], + ), + Err(error) => log( + "agent.providers.restore_failed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ( + "reason", + json!(error + .details + .as_deref() + .unwrap_or("agentProviders.restoreFailed")), + ), + ("duration_ms", json!(duration_ms)), + ], + ), + } + outcome.map(|_| json!({ "restored": true })) + } +} diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs index b469b511..b03925c4 100644 --- a/rust/crates/agent-runtime/src/library/providers.rs +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -1113,14 +1113,6 @@ struct ReadRequest { agent: Option, } -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct RestoreRequest { - agent: String, - #[serde(default)] - discard_later_changes: bool, -} - /// No `Debug`: `change` may carry a key. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -1168,11 +1160,12 @@ impl Library { } let paths = agent_paths(&config, configuration); entry["files"] = json!(files_param(&paths.files)); - if let Some(backup) = backups::status(&config, &agent.record_key(), &paths.files) { - entry["backup"] = json!({ - "savedAtMs": backup.saved_at_ms, - "modifiedSince": backup.modified_since, - }); + // The agent's whole backup, as `agentLibrary.read` reports + // it: a library change may have written the same files. + if let Some(backup) = + backups::status(&config, &agent.record_key(), &paths.backed_up()) + { + entry["backup"] = backup.answer(); } let read = read_providers(&*runtime.link, agent, configuration, declared, &paths.files) @@ -1449,65 +1442,17 @@ impl Library { } }; let agent_key = agent.record_key(); + // The same ID a library change uses for this file, so the file keeps + // one baseline whichever kind of change came first. + let backup_id = paths.backup_id(&target_path, &target_id); self.edit_staged( config, &target_path, - Some((&agent_key, &target_id)), + (&agent_key, &backup_id), edit_file, shows_change, ) } - - /// `agentProviders.restore`: puts the agent's files back as they were - /// before Lithe's first change since the last restore. Refuses when a - /// file changed after Lithe's last write, unless `discardLaterChanges`. - pub fn restore_providers(&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 outcome = (|| { - let (configuration, _) = declaration(&agent).ok_or_else(not_declared)?; - let config = self.config()?; - let paths = agent_paths(&config, configuration); - let _writing = self.lock_writing(); - backups::restore( - &config, - &agent.record_key(), - &paths.files, - request.discard_later_changes, - ) - .map_err(|refused| backups::restore_error(&refused)) - })(); - match &outcome { - Ok(files) => log( - "agent.providers.restore_applied", - [ - ("plugin", json!(agent.plugin_id)), - ("agent", json!(agent.agent.id)), - ("files", json!(files)), - ("discarded", json!(request.discard_later_changes)), - ("duration_ms", json!(elapsed_ms(started))), - ], - ), - Err(error) => log( - "agent.providers.restore_failed", - [ - ("plugin", json!(agent.plugin_id)), - ("agent", json!(agent.agent.id)), - ( - "reason", - json!(error - .details - .as_deref() - .unwrap_or("agentProviders.restoreFailed")), - ), - ("duration_ms", json!(elapsed_ms(started))), - ], - ), - } - outcome.map(|_| json!({ "restored": true })) - } } #[cfg(test)] diff --git a/rust/crates/agent-runtime/src/tests/library.rs b/rust/crates/agent-runtime/src/tests/library.rs index eebe140c..4a318c47 100644 --- a/rust/crates/agent-runtime/src/tests/library.rs +++ b/rust/crates/agent-runtime/src/tests/library.rs @@ -154,10 +154,17 @@ struct LibraryTest { impl LibraryTest { fn new(name: &str, grants: &[&str]) -> Self { + Self::with_manifest(name, grants, configuration_manifest()) + } + + /// The harness with `manifest` in place of the configuration plugin's; + /// a manifest that also declares providers gets the minimal + /// `providers.read` and `providers.edit` of the `backups` tests. + fn with_manifest(name: &str, grants: &[&str], manifest: Value) -> Self { let harness = Harness::new(name, ALL_GRANTS); harness.run( "agents.configure", - json!({ "plugins": [{ "manifest": configuration_manifest(), "grantedPermissions": grants }] }), + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": grants }] }), ); let home = harness.dir.path().join("home"); let library = harness.dir.path().join("library"); @@ -175,6 +182,8 @@ impl LibraryTest { let edit = current.lock().unwrap().clone(); configuration_edit(params, &edit) } + "providers.read" => backups::model_read(params), + "providers.edit" => backups::model_edit(params), other => sample_backend(other, params), }); fs::create_dir_all(home.join(".sample")).unwrap(); @@ -761,3 +770,5 @@ fn malformed_requests_and_a_damaged_library_file_are_refused_each_with_its_own_c "agentLibrary.invalidLibraryFile" ); } + +mod backups; diff --git a/rust/crates/agent-runtime/src/tests/library/backups.rs b/rust/crates/agent-runtime/src/tests/library/backups.rs new file mode 100644 index 00000000..9ea5df75 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/library/backups.rs @@ -0,0 +1,407 @@ +//! Backups Core keeps before the library replaces an agent's files (MCP +//! servers, hooks and the instruction file), the one baseline a file keeps +//! when providers changes reach it too, and `agentProviders.restore` for an +//! agent with or without providers. + +use super::*; + +/// The configuration plugin with providers on the same declared file as its +/// MCP servers and hooks, as a CLI that keeps both in one file has. +fn shared_file_manifest() -> Value { + let mut manifest = configuration_manifest(); + manifest["agents"][0]["configuration"]["providers"] = json!({ + "read": "providers.read", + "edit": "providers.edit", + "operations": ["setModel"] + }); + manifest +} + +/// A minimal `providers.read`: the model kept in the `main` file, which the +/// configuration plugin's servers and hooks share. +pub(super) fn model_read(params: &Value) -> Result { + let file = params["files"] + .as_array() + .and_then(|files| files.iter().find(|file| file["id"] == "main")) + .ok_or_else(|| failure("plugin.params.invalid"))?; + let config = read_file(Path::new(file["path"].as_str().unwrap())); + let model = match config["model"].as_str() { + Some(model) => json!({ "id": model, "source": { "layer": "user", "file": "main" } }), + None => json!({ "id": "sample-default", "source": { "layer": "default" } }), + }; + Ok(json!({ + "format": "litheAgentProviders", + "version": 0, + "model": model, + "providers": [], + "targets": { "model": "main" } + })) +} + +/// A minimal `providers.edit` that only sets the model, keeping everything +/// else the staged copy holds. +pub(super) fn model_edit(params: &Value) -> Result { + if params["change"]["op"] != "setModel" { + return Err(failure("plugin.params.invalid")); + } + let staging = PathBuf::from(params["file"]["staging"].as_str().unwrap()); + let mut config = read_file(&staging); + let before = config.clone(); + config["model"] = params["change"]["model"].clone(); + let changed = config != before; + if changed { + fs::write(&staging, serde_json::to_vec(&config).unwrap()).unwrap(); + } + Ok(json!({ "format": "litheAgentProvidersEdit", "version": 0, "changed": changed })) +} + +/// A library with one server, one hook and instructions on for the agent. +fn full_library(rule: &str) -> 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 } } + } + }) +} + +/// 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 { + self.home.join(".sample").join("INSTRUCTIONS.md") + } + + fn agent(&self) -> Value { + self.read()["agents"][0].clone() + } + + fn backup(&self) -> Option { + self.agent().get("backup").cloned() + } + + /// The single agent directory under `backups/`. + fn backup_directory(&self) -> PathBuf { + let mut entries: Vec = fs::read_dir(self.library.join("backups")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(entries.len(), 1, "one directory per agent"); + entries.pop().unwrap() + } + + /// The baselines kept, sorted by content. + 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()) + .collect(); + baselines.sort(); + baselines + } + + /// The digest `state.json` keeps of what Core last wrote to the agent's + /// instruction file, if any. + 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() + } + + fn restore_payload(discard: Option) -> Value { + let mut payload = json!({ "agent": AGENT_KEY }); + if let Some(discard) = discard { + payload["discardLaterChanges"] = json!(discard); + } + payload + } + + fn restore(&self, discard: Option) -> Value { + self.harness + .run("agentProviders.restore", Self::restore_payload(discard)) + } + + fn restore_refused(&self, discard: Option) -> String { + self.harness + .refused("agentProviders.restore", Self::restore_payload(discard)) + } + + fn set_model(&self, model: &str) -> bool { + self.harness.run( + "agentProviders.apply", + json!({ "agent": AGENT_KEY, "change": { "op": "setModel", "model": model } }), + )["changed"] + .as_bool() + .unwrap() + } +} + +#[test] +fn library_changes_back_up_each_file_once_and_restore_puts_them_back() { + let test = LibraryTest::new("library backup", CONFIGURATION_GRANTS); + let config = test.config_file(); + 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.")); + assert!(test.backup().is_none(), "no backup before a change"); + + let before = crate::now_ms(); + let (_, logs) = capture::run(false, || { + assert!(test.apply(json!({ "category": "mcpServers", "op": "put", "name": "docs" }))); + assert!(test.apply(json!({ "category": "hooks", "op": "put", "id": "check-on-stop" }))); + }); + let backup = test + .backup() + .expect("the first library change keeps a backup"); + assert_eq!(backup["modifiedSince"], false); + assert_eq!( + backup.as_object().unwrap().len(), + 2, + "only a time and a boolean" + ); + let saved_at = backup["savedAtMs"].as_i64().unwrap(); + assert!(saved_at >= before); + assert_eq!( + test.baselines(), + vec![ORIGINAL_CONFIG.to_vec()], + "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"); + assert_eq!(test.agent()["instructions"]["state"], "current"); + assert!(test.written_instructions().is_some()); + assert_eq!( + test.baselines(), + vec![b"My own notes\n".to_vec(), ORIGINAL_CONFIG.to_vec()], + "the instruction file has its own baseline" + ); + assert_eq!( + test.backup().unwrap()["savedAtMs"], + json!(saved_at), + "the oldest baseline dates the backup" + ); + + // The agent declares no providers; its backup is still restored. + assert_eq!( + test.harness.run("agentProviders.read", json!({}))["agents"], + json!([]) + ); + let (restored, restore_logs) = capture::run(false, || test.restore(None)); + assert_eq!(restored, json!({ "restored": true })); + assert_eq!(fs::read(&config).unwrap(), ORIGINAL_CONFIG, "byte for byte"); + assert_eq!( + fs::read(&instructions).unwrap(), + b"My own notes\n", + "the text the user replaced is back" + ); + let read = test.read(); + let agent = &read["agents"][0]; + assert!( + agent.get("backup").is_none(), + "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" + ); + assert_eq!(read["states"]["mcpServers"]["docs"][AGENT_KEY], "off"); + assert_eq!(read["states"]["hooks"]["check-on-stop"][AGENT_KEY], "off"); + assert!( + test.written_instructions().is_none(), + "Core no longer claims the instruction file" + ); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.otherInstructions", + "writing over the restored text needs the user's consent again" + ); + + 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)); + let home = path_text(&test.home); + for log in logs.iter().chain(&write_logs).chain(&restore_logs) { + let text = format!("{:?}", log.fields); + for secret in [ + "My own notes", + "Shared rule", + "docs-mcp", + "sample-check", + "backups", + ] { + assert!(!text.contains(secret), "{} logs {secret}", log.event); + } + assert!(!text.contains(&home), "{} logs a path", log.event); + } +} + +#[test] +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!(test.backup().unwrap()["modifiedSince"], false); + + test.restore(None); + assert!(!file.exists(), "the file Lithe created is removed"); + 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. + fs::write(&file, "First rule.\n").unwrap(); + test.save(full_library("Second rule.")); + assert_eq!(test.agent()["instructions"]["state"], "other"); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.otherInstructions" + ); + assert_eq!(fs::read_to_string(&file).unwrap(), "First rule.\n"); +} + +#[test] +fn restore_discards_later_changes_to_library_files_only_when_asked() { + let test = LibraryTest::new("library backup changed", CONFIGURATION_GRANTS); + let config = test.config_file(); + fs::write(&config, ORIGINAL_CONFIG).unwrap(); + 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_eq!(test.backup().unwrap()["modifiedSince"], false); + + fs::write(&instructions, "Shared rule.\nEdited by hand.\n").unwrap(); + assert_eq!( + test.backup().unwrap()["modifiedSince"], + true, + "an edit to the instruction file after Lithe's write shows" + ); + assert_eq!( + test.restore_refused(None), + "agentProviders.changedSinceApply" + ); + assert_eq!( + test.restore_refused(Some(false)), + "agentProviders.changedSinceApply" + ); + assert_eq!( + fs::read_to_string(&instructions).unwrap(), + "Shared rule.\nEdited by hand.\n", + "a refused restore writes nothing" + ); + assert!( + test.written_instructions().is_some(), + "a refused restore keeps Core's record" + ); + + assert_eq!(test.restore(Some(true)), json!({ "restored": true })); + assert_eq!(fs::read(&config).unwrap(), ORIGINAL_CONFIG); + assert!(!instructions.exists()); + assert!(test.backup().is_none()); +} + +#[test] +fn a_library_change_whose_backup_fails_is_not_written() { + let test = LibraryTest::new("library backup fails", CONFIGURATION_GRANTS); + let config = test.config_file(); + 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.")); + // A file where the backups directory goes cannot hold one. + fs::write(test.library.join("backups"), b"not a directory").unwrap(); + + let (refused, logs) = capture::run(false, || { + test.refused_change(json!({ "category": "mcpServers", "op": "put", "name": "docs" })) + }); + assert_eq!(refused, "agentProviders.backupFailed"); + assert_eq!(fs::read(&config).unwrap(), ORIGINAL_CONFIG, "untouched"); + assert_eq!(test.staged_files(), 0); + let failed = logs + .iter() + .find(|log| log.event == "agent.library.change_failed") + .expect("the refusal is logged"); + assert_eq!(failed.fields["category"], json!("mcpServers")); + assert_eq!( + failed.fields["reason"], + json!("agentProviders.backupFailed") + ); + + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write", "replace": true })), + "agentProviders.backupFailed" + ); + assert_eq!(fs::read(&instructions).unwrap(), b"My own notes\n"); + assert!(test.written_instructions().is_none()); + assert!(test.backup().is_none()); +} + +#[test] +fn a_file_the_library_and_providers_both_change_keeps_one_baseline() { + let test = LibraryTest::with_manifest( + "library backup shared file", + CONFIGURATION_GRANTS, + shared_file_manifest(), + ); + let config = test.config_file(); + fs::write(&config, ORIGINAL_CONFIG).unwrap(); + test.save(full_library("Shared rule.")); + let providers_backup = || { + test.harness + .run("agentProviders.read", json!({ "agent": AGENT_KEY }))["agents"][0]["backup"] + .clone() + }; + + // The library first, then a providers change to the same file. + assert!(test.apply(json!({ "category": "mcpServers", "op": "put", "name": "docs" }))); + assert!(test.set_model("sample-large")); + assert_eq!(test.baselines(), vec![ORIGINAL_CONFIG.to_vec()]); + let backup = test.backup().unwrap(); + assert_eq!( + providers_backup(), + backup, + "both reads report the one backup" + ); + test.restore(None); + assert_eq!( + fs::read(&config).unwrap(), + ORIGINAL_CONFIG, + "the server and the model are both undone" + ); + + // Providers first, then the library. + assert!(test.set_model("sample-large")); + assert!(test.apply(json!({ "category": "mcpServers", "op": "put", "name": "docs" }))); + assert_eq!(test.baselines(), vec![ORIGINAL_CONFIG.to_vec()]); + assert_eq!(providers_backup(), test.backup().unwrap()); + + // 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. + let instructions = test.instructions_file(); + assert!(test.apply(json!({ "category": "instructions", "op": "write" }))); + assert_eq!(providers_backup()["modifiedSince"], false); + fs::write(&instructions, "Shared rule.\nEdited by hand.\n").unwrap(); + assert_eq!(providers_backup()["modifiedSince"], true); + assert_eq!(providers_backup(), test.backup().unwrap()); + test.restore(Some(true)); + assert_eq!(fs::read(&config).unwrap(), ORIGINAL_CONFIG); + assert!(!instructions.exists()); + assert_eq!(test.agent()["instructions"]["state"], "absent"); + assert!(providers_backup().is_null()); +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 381d2e5e..f953ed35 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4421,6 +4421,10 @@ and keeps no name or icon of its own for any agent. `agents.invalidPayload`, and answers no `agentProviders.*` command. A host that sees no `configuration.providers` in the catalog shows no models or providers for the agent. +- The backups of the library's own changes, `backup` in + `agentLibrary.read` and restoring an agent without `providers` were added + later still within `agents` 0; see [Backups and restore](#backups-and-restore) + for what a Core that predates them does. #### The library @@ -4433,7 +4437,9 @@ 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) and `staging/` (the copies plugins edit). +file), `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)). The library is `{mcpServers, hooks, instructions}`: @@ -4504,9 +4510,13 @@ neither has text. read, or that declares no `skills`, is in no skill's `agents`. - `agents`: one entry per agent that declares `configuration`, in catalog order: `{agent, pluginID, agentID, displayName, icon?, mayConfigure, - editable, instructions?, skills?, mcpServers?, hooks?, hookEvents?, - providedSkills?, targets?, readError?}`. An agent whose plugin is not - granted gives only the fields up to `editable`. + editable, backup?, instructions?, skills?, mcpServers?, hooks?, + hookEvents?, providedSkills?, targets?, readError?}`. An agent whose + plugin is not granted gives only the fields up to `editable`. + - `backup`: `{savedAtMs, modifiedSince}` while Core keeps a backup of the + 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 @@ -4578,19 +4588,26 @@ A server or hook changes through the plugin, on a copy: (`agentLibrary.fileChanged`): a new file next to it, with the old file's permissions (owner-only for a new file), written to disk and renamed over it. The copy is removed either way. +5. Before replacing the file, Core backs it up + ([Backups and restore](#backups-and-restore)); when it cannot, the file + is not changed (`agentProviders.backupFailed`). A skill is linked as a symbolic link to `skills/` of the library. Unlinking removes only a link into the library (`agentLibrary.notLibraryLink`); linking over an entry of the agent's own is `agentLibrary.agentSkillExists`. On Windows a link needs Developer Mode or an elevated process, otherwise `agentLibrary.linkFailed`. An agent without -`skills` is `agentLibrary.noSkills`. +`skills` is `agentLibrary.noSkills`. A link replaces and removes nothing of +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. An agent without `instructions` is +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`. `importSkill` copies a skill into the library: `{agent, name}` the agent's @@ -4670,6 +4687,10 @@ plugin, and the host draws the views. | `agentProviders.apply` | `{agent, change}` | `{changed}` | | `agentProviders.restore` | `{agent, discardLaterChanges?}` | `{restored: true}` | +`restore` puts back every file of the agent Lithe changed, for any agent +that declares `configuration`, with or without `providers`; see +[Backups and restore](#backups-and-restore). + `read` answers one entry per agent that declares `providers`, in catalog order, or only the agent `agent` names (`agentLibrary.unknownAgent`, `agentLibrary.notGranted`, and `agentProviders.notDeclared` for an agent @@ -4719,9 +4740,10 @@ without `providers`): `listKeptBy: "lithe"`); `saved` is whether Lithe keeps it. `keySet` is always there. - `backup?: {savedAtMs, modifiedSince}` is there while Core keeps a backup - of the agent's files (see [Backups and restore](#backups-and-restore)): - when it was kept, in milliseconds since the epoch, and whether a file - now differs from what Lithe last wrote. + of the agent's files (see [Backups and restore](#backups-and-restore)), + whichever command changed them: when it was kept, in milliseconds since + the epoch, and whether a file now differs from what Lithe last wrote. It + is the same `backup` that `agentLibrary.read` gives the agent. - A failed read gives `readError` (`agentLibrary.backendUnavailable`, `agentProviders.readFailed` or `agentProviders.invalidSnapshot`) in place of the snapshot; the other agents still answer. @@ -4829,27 +4851,7 @@ ID. plugin keeps. A plugin that stores a key and changes no file answers `changed: false`. -##### Backups and restore - -Before `apply` replaces a file, Core backs it up under -`/backups//`: directories `0700`, -files `0600`. For each declared file it keeps the baseline (the file as it -was before Lithe's first change since the last restore, or that it did not -exist), the SHA-256 of the bytes Lithe last wrote, and the newest 20 earlier -contents of the agent's files. A backup is a byte-for-byte copy of the -CLI's configuration, so it **may hold keys and other secrets**; it stays in -the local Lithe library directory, and Core never logs it, sends it to a -plugin or the host, or names it in an error. - -`agentProviders.restore {agent, discardLaterChanges?}` runs only for a -request whose origin is the user (`agentLibrary.userActionRequired`). It -puts each backed-up file back as its baseline, removing a file that did not -exist, and forgets the baseline; what it replaces goes into the history. It -refuses when there is no backup (`agentProviders.noBackup`) and, unless -`discardLaterChanges` is `true`, when a file changed after Lithe's last -write (`agentProviders.changedSinceApply`). A restore that cannot be written -is `agentProviders.restoreFailed`. Restoring files does not change the list -of providers Lithe keeps or the keys a plugin keeps. +##### Provider functions `providers.read` receives `{agentID, files: [{id, path, exists}]}`, like the configuration `read`, and answers within 10 seconds exactly: @@ -4925,6 +4927,74 @@ removes it. With `listKeptBy: "lithe"`, `change` carries the extra fields [Providers Lithe keeps](#providers-lithe-keeps) lists. A plugin never puts a key in its answer, an error message or a log. +#### Backups and restore + +Before Core replaces a file of an agent's configuration, it backs the file +up under `/backups//`: +directories `0700`, files `0600`. Every replacement is backed up, whichever +command makes it: + +- a declared file `agentProviders.apply` changes; +- a declared file `agentLibrary.apply` changes for an MCP server or hook; +- the instruction file `agentLibrary.apply` writes, the write over text + Lithe did not write that `replace: true` allows included. + +Linking or unlinking a skill replaces and removes nothing of the agent's +own, so it keeps nothing. When the backup cannot be kept, the file is not +changed, and either command refuses with `agentProviders.backupFailed`. + +For each file Core keeps one baseline: the file as it was before Lithe's +first change since the last restore, or that it did not exist. A file has +one baseline whichever command reaches it first; a later change by either +command, such as the providers change to a file that also holds the CLI's +MCP servers, never replaces it. A file is known by the first declared file +whose path resolves to it; an instruction file that no declared file names +has an entry of its own. Core also keeps the SHA-256 of the bytes +Lithe last wrote to each file, and the newest 20 earlier contents of the +agent's files. A backup is a byte-for-byte copy of the CLI's configuration +and instructions, so it **may hold keys and other secrets**; it stays in +the local Lithe library directory, and Core never logs it, sends it to a +plugin or the host, or names it in an error. + +While Core keeps a backup of an agent's files, `agentLibrary.read` and, +for an agent that declares `providers`, `agentProviders.read` give the +agent the same `backup: {savedAtMs, modifiedSince}`: when the oldest +baseline was kept, in milliseconds since the epoch, and whether a +backed-up file now differs from what Lithe last wrote (a file that is gone +or cannot be read counts as changed). Without a backup, neither gives +`backup`. + +`agentProviders.restore {agent, discardLaterChanges?}` runs only for a +request whose origin is the user (`agentLibrary.userActionRequired`), for an +agent that declares `configuration` (`agentLibrary.unknownAgent`) and whose +plugin is granted (`agentLibrary.notGranted`), whether or not it declares +`providers`. It puts each backed-up file back as its baseline, removing a +file that did not exist, and forgets the baselines; what it replaces goes +into the history. + +- It refuses when there is no backup (`agentProviders.noBackup`) and, unless + `discardLaterChanges` is `true`, when a file changed after Lithe's last + write (`agentProviders.changedSinceApply`); a refused restore writes + nothing. +- A restore that cannot be written is `agentProviders.restoreFailed`; files + it already put back stay put back. +- Before it puts the instruction file back, Core forgets what it last wrote + there. `instructions.state` then follows what the restored file holds and + is never `written`, and writing the library's instructions over restored + text needs `replace: true` again. +- The MCP servers and hooks the plugin reads from the restored files follow + them. Nothing of the library changes, including whether an agent follows + its instructions, nor the list of providers Lithe keeps or the keys a + plugin keeps; skill links stay as they are. + +The backups of `agentLibrary.apply`, `backup` in `agentLibrary.read` and +restoring an agent without `providers` were added within `agents` 0, after +the backups of `agentProviders.apply`. A Core that predates them backs up +only what `agentProviders.apply` replaces, gives `agentLibrary.read` no +`backup`, and refuses `agentProviders.restore` for an agent without +`providers` with `agentProviders.notDeclared`; a host that sees no `backup` +in `agentLibrary.read` offers no restore there. + #### Limits, refusals and logging - Core reads at most 8 MiB of `library.json`, 16 MiB of a configuration @@ -4942,11 +5012,11 @@ a key in its answer, an error message or a log. and refusal codes, never names, commands, paths or text. Models and providers log `agent.providers.read_finished`, `agent.providers.read_failed`, `agent.providers.change_applied` and - `agent.providers.change_failed` with the `op` only, and - `agent.providers.restore_applied` (file count and whether later changes - were discarded) and `agent.providers.restore_failed` (refusal code), - never a model, provider, URL, - variable name, label, key or backup content. + `agent.providers.change_failed` with the `op` only. A restore, of any + agent, logs `agent.providers.restore_applied` (file count and whether + later changes were discarded) or `agent.providers.restore_failed` + (refusal code). None of them carries a model, provider, URL, variable + name, label, key or backup content. ### Privacy and logging diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 939baf08..a599265d 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -61,7 +61,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-38 | 受管网络 | 部分完成 | `network/request`:可取消、有界 HTTP(S) | 下载文件、身份验证会话 | [工作流](../guides/plugin-workflows.md) | | API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | -| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),Core 替换文件前先备份,`agentProviders.restore` 由用户恢复原样 | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | ### 计划中的 API @@ -284,7 +284,7 @@ Status meanings: | API-38 | Managed network | Partial | `network/request`: bounded HTTP(S) with cancellation | File downloads and authentication sessions | [Workflows](../guides/plugin-workflows.md) | | API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | -| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before replacing it, and `agentProviders.restore` puts it back on the user's request | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | +| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | ### Planned APIs diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index b2718026..25d0efae 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -67,7 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -188,7 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition | ✅ | Pending host integration | [Agents](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared` | ✅ | Pending host integration | [Agents](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | | `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | ✅ | [Toolchains](domains/toolchains.md) | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 7faa7d1e..8f656e34 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -56,7 +56,7 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 - CLI 自己装的内容(比如 CLI 插件带来的 MCP 服务器、Hooks 和技能)标为 `origin: "agent"`,宿主只显示、不改。 - 宿主按插件声明的 `displayName` 和 `icon` 显示每个 Agent,不按名字特殊处理。 -所有改动都只能由用户的操作发起;Core 只读写声明的路径;插件没有获得 `agents.configuration` 授权时,它的 Agent 以 `mayConfigure: false` 列出,Core 什么都不读、不改。命令见 Rust Core API 的 `agentLibrary.*`。 +所有改动都只能由用户的操作发起;Core 只读写声明的路径;插件没有获得 `agents.configuration` 授权时,它的 Agent 以 `mayConfigure: false` 列出,Core 什么都不读、不改。Core 替换指令文件或配置文件之前都先备份,见下面的“修改前备份与恢复”。命令见 Rust Core API 的 `agentLibrary.*`。 `agentLibrary.read` 可以带可选参数 `query`(名称、描述等文字,忽略大小写)、`agent` 加 `presence`(`present` 或 `missing`,两者一起给)和 `sort`(`name` 或 `agentCount`)。不带参数时结果和以前完全一样;带了参数,资源库本身仍完整返回(`save` 要整份替换),另加 `matches`,按顺序列出留下的 MCP 服务器名、Hook `id` 和技能名。 @@ -71,10 +71,20 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 - 插件不得读取 CLI 的凭据文件(如 `auth.json`、`.credentials.json`)和系统钥匙串,账号标签只来自不含凭据的设置或 CLI 命令。 - 被环境变量覆盖的当前模型、供应商或配置档改文件不会生效,Core 以 `agentProviders.overridden` 拒绝;CLI 内置的供应商只显示,不能改或删。 - **由 Lithe 保存供应商列表**:配置里只能放一个自定义端点的 CLI,插件声明 `listKeptBy: "lithe"`。Core 把用户保存的供应商 `{id, name, baseUrl, protocol?, model?}` 和“插件是否存了密钥”记在资源库目录的 `saved-providers.json`(仅所有者可读写,不含密钥);密钥由插件用 `lithe/host/credentials/set|get|delete`(`credentials.store` 权限)存在自己的命名空间。读取时正在用的自定义供应商按 `baseUrl` 对上已保存的供应商,没在用的已保存供应商以 `origin: "lithe"` 追加。重复的 ID 是 `agentProviders.providerExists`,重复的端点是 `agentProviders.endpointExists`,删正在用的供应商是 `agentProviders.activeProvider`。Core 先存列表再调用插件,插件失败就把列表恢复原样。 -- **备份与恢复**:`apply` 替换文件前,Core 把它备份到资源库目录的 `backups/` 下(目录 `0700`、文件 `0600`),保留 Lithe 第一次修改前的原样和最近 20 份历史;备份不成功就不改文件(`agentProviders.backupFailed`)。备份是原配置的逐字节副本,可能含密钥,只存在本机 Lithe 数据目录,不进日志、不发给插件或宿主。`agentProviders.restore {agent, discardLaterChanges?}` 只接受用户发起的请求,把文件放回原样;没有备份是 `agentProviders.noBackup`,Lithe 最后一次写入后文件又被改过、且没给 `discardLaterChanges: true` 是 `agentProviders.changedSinceApply`,写不回去是 `agentProviders.restoreFailed`。读取在有备份时带 `backup: {savedAtMs, modifiedSince}`。 +- **备份与恢复**:`apply` 替换文件前先备份,和资源库的改动共用同一份备份,见下面的“修改前备份与恢复”。 命令是 `agentProviders.read {agent?}`、`agentProviders.apply {agent, change}` 和 `agentProviders.restore {agent, discardLaterChanges?}`,字段、拒绝码和完整示例见[契约](../../contract/v1/README.md#models-and-providers)。 +### 修改前备份与恢复 + +Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库目录的 `backups/` 下(目录 `0700`、文件 `0600`),不管是哪条命令改的:`agentProviders.apply` 改的声明文件、`agentLibrary.apply` 为 MCP 服务器和 Hooks 改的声明文件、`agentLibrary.apply` 整份写入的指令文件(包括用户确认 `replace: true` 覆盖非 Lithe 内容的那一次)。技能的符号链接不覆盖、不删除 Agent 自己的内容,不备份,恢复时也不动。备份不成功就不改文件,两条命令都以 `agentProviders.backupFailed` 拒绝。 + +- **一个文件一份基线**:基线是“自上次恢复以来 Lithe 第一次修改前的原样”(或“原来不存在”),无论资源库还是供应商先改到这个文件,都只存这一次,之后的修改不会替换它;例如 CLI 把 MCP 服务器和模型供应商放在同一个文件里时也是如此。另外保留 Lithe 最后一次写入内容的 SHA-256 和最近 20 份历史。备份是逐字节副本,可能含密钥,只存在本机 Lithe 数据目录,不进日志、不发给插件或宿主。 +- **状态**:有备份时,`agentLibrary.read` 的每个 Agent 和 `agentProviders.read`(只列声明了 `providers` 的 Agent)都带同一个 `backup: {savedAtMs, modifiedSince}`:最早基线的保存时间,以及备份过的文件现在是否和 Lithe 最后写入的不一样(文件不见了或读不出也算改过)。 +- **恢复**:`agentProviders.restore {agent, discardLaterChanges?}` 只接受用户发起的请求,接受任何声明了 `configuration` 且已授权的 Agent,不要求声明 `providers`。它把备份过的每个文件放回基线,原来不存在的就删掉;没有备份是 `agentProviders.noBackup`,Lithe 最后一次写入后文件又被改过、且没给 `discardLaterChanges: true` 是 `agentProviders.changedSinceApply`(都不写任何文件),写不回去是 `agentProviders.restoreFailed`。 +- **恢复后状态与磁盘一致**:放回指令文件之前,Core 先忘掉“最后写入的指令内容哈希”,所以恢复后 `instructions.state` 只按文件实际内容显示、不会是 `written`,再写入资源库的指令要重新确认 `replace: true`。MCP 服务器和 Hooks 的状态按恢复后的文件读取。资源库本身(包括 Agent 是否跟随资源库指令)、Lithe 保存的供应商列表和插件保存的密钥都不变。 +- 资源库改动的备份、`agentLibrary.read` 的 `backup` 和不声明 `providers` 的 Agent 的恢复是 `agents` 0 内的补充。旧 Core 只备份 `agentProviders.apply` 的改动,`agentLibrary.read` 不带 `backup`,对没有 `providers` 的 Agent 的 `agentProviders.restore` 以 `agentProviders.notDeclared` 拒绝。详见[契约](../../contract/v1/README.md#backups-and-restore)。 + ### 契约章节 | 章节 | 内容 | @@ -87,6 +97,7 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 | [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储、命令和筛选、`read` 与 `edit` 函数、限制和拒绝码 | | [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`、`agentProviders.*` 命令、快照与修改、隐私规则和拒绝码 | +| [Backups and restore](../../contract/v1/README.md#backups-and-restore) | 资源库和供应商修改前的备份、`backup` 状态、`agentProviders.restore` 与拒绝码 | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | 日志只记 ID 和元数据,不读凭据文件 | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | 不运行 ACP 客户端,只在可信本地工作区运行 | | [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*`、`agentSessions.*`、`agentLibrary.*` 与 `agentProviders.*` 命令(Rust Core API 文档) | @@ -174,7 +185,7 @@ The host's agent library keeps one copy of instructions, skills, MCP servers and - What the CLI installed itself, such as the MCP servers, hooks and skills a CLI plugin brings, has `origin: "agent"`; the host shows it and never changes it. - The host shows each agent by the `displayName` and `icon` its plugin declares and never special-cases agents by name. -Every change comes only from a user action. Core reads and writes only the declared paths. An agent whose plugin is not granted `agents.configuration` is listed with `mayConfigure: false`, and Core reads and changes nothing of it. The commands are the `agentLibrary.*` commands of the Rust Core API. +Every change comes only from a user action. Core reads and writes only the declared paths. An agent whose plugin is not granted `agents.configuration` is listed with `mayConfigure: false`, and Core reads and changes nothing of it. Core backs up an instruction or configuration file before replacing it; see "Backups before a change, and restore" below. The commands are the `agentLibrary.*` commands of the Rust Core API. `agentLibrary.read` takes optional `query` (text in a name, description and so on, ignoring case), `agent` with `presence` (`present` or `missing`, given together) and `sort` (`name` or `agentCount`). Without them the answer is exactly as before; with them the library still comes whole, since `save` replaces all of it, and `matches` lists the kept MCP server names, hook `id`s and skill names in order. @@ -189,10 +200,20 @@ An agent whose `configuration` also declares `providers: {read, edit?, operation - Plugins never read the CLI's credential files (such as `auth.json` or `.credentials.json`) or the system keychain; the account label comes only from settings or CLI commands that carry no credentials. - A current model, provider or profile an environment variable sets would not change by editing the file, so Core refuses it with `agentProviders.overridden`; providers built into the CLI are shown, never changed or removed. - **Providers Lithe keeps**: a plugin for a CLI whose configuration holds one custom endpoint declares `listKeptBy: "lithe"`. Core keeps the providers the user saved, `{id, name, baseUrl, protocol?, model?}` and whether the plugin stored a key, in `saved-providers.json` in the library directory (owner-only, never a key); the plugin keeps each key in its own namespace with `lithe/host/credentials/set|get|delete` (the `credentials.store` permission). A read matches the custom provider in use to a saved one by `baseUrl` and appends the saved providers not in use with `origin: "lithe"`. A taken ID is `agentProviders.providerExists`, a taken endpoint `agentProviders.endpointExists`, and removing the provider in use `agentProviders.activeProvider`. Core saves the list before calling the plugin and puts it back when the plugin fails. -- **Backups and restore**: before `apply` replaces a file, Core backs it up under `backups/` in the library directory (directories `0700`, files `0600`), keeping the file as it was before Lithe's first change and the newest 20 earlier contents; when it cannot, the file is not changed (`agentProviders.backupFailed`). A backup is a byte-for-byte copy of the configuration and may hold keys; it stays in the local Lithe data directory and never goes into a log, a plugin or the host. `agentProviders.restore {agent, discardLaterChanges?}` accepts only a request the user started and puts the files back; no backup is `agentProviders.noBackup`, a file changed after Lithe's last write without `discardLaterChanges: true` is `agentProviders.changedSinceApply`, and a restore that cannot be written is `agentProviders.restoreFailed`. A read carries `backup: {savedAtMs, modifiedSince}` while a backup exists. +- **Backups and restore**: `apply` backs a file up before replacing it, in the same backup the library's changes use; see "Backups before a change, and restore" below. The commands are `agentProviders.read {agent?}`, `agentProviders.apply {agent, change}` and `agentProviders.restore {agent, discardLaterChanges?}`; fields, refusal codes and a full example are in the [contract](../../contract/v1/README.md#models-and-providers). +### Backups before a change, and restore + +Before Core replaces any of an agent's files, it backs the file up under `backups/` in the library directory (directories `0700`, files `0600`), whichever command replaces it: a declared file `agentProviders.apply` changes, a declared file `agentLibrary.apply` changes for an MCP server or hook, and the instruction file `agentLibrary.apply` writes, including the write over text Lithe did not write that the user confirmed with `replace: true`. A skill link replaces and removes nothing of the agent's own, so it is not backed up, and a restore leaves it as it is. When the backup cannot be kept, the file is not changed and either command refuses with `agentProviders.backupFailed`. + +- **One baseline per file**: the baseline is the file as it was before Lithe's first change since the last restore, or that it did not exist. Whether the library or a providers change reaches the file first, it is kept once and later changes never replace it, also when a CLI keeps its MCP servers and model providers in one file. Core also keeps the SHA-256 of what Lithe last wrote and the newest 20 earlier contents. A backup is a byte-for-byte copy and may hold keys; it stays in the local Lithe data directory and never goes into a log, a plugin or the host. +- **Status**: while a backup exists, each agent of `agentLibrary.read`, and of `agentProviders.read` for an agent that declares `providers`, carries the same `backup: {savedAtMs, modifiedSince}`: when the oldest baseline was kept, and whether a backed-up file now differs from what Lithe last wrote (a file that is gone or cannot be read counts as changed). +- **Restore**: `agentProviders.restore {agent, discardLaterChanges?}` accepts only a request the user started, for any agent that declares `configuration` and whose plugin is granted, with or without `providers`. It puts each backed-up file back as its baseline, removing a file that did not exist. No backup is `agentProviders.noBackup`, a file changed after Lithe's last write without `discardLaterChanges: true` is `agentProviders.changedSinceApply` (neither writes anything), and a restore that cannot be written is `agentProviders.restoreFailed`. +- **State follows the disk after a restore**: before it puts the instruction file back, Core forgets the digest of what it last wrote there, so `instructions.state` then follows what the file holds and is never `written`, and writing the library's instructions over the restored text needs `replace: true` again. MCP servers and hooks are read from the restored files. The library itself (including whether an agent follows its instructions), the providers Lithe keeps and the keys a plugin keeps do not change. +- The backups of library changes, `backup` in `agentLibrary.read` and restoring an agent without `providers` were added within `agents` 0. An older Core backs up only what `agentProviders.apply` replaces, gives no `backup` in `agentLibrary.read`, and refuses `agentProviders.restore` for an agent without `providers` with `agentProviders.notDeclared`. See the [contract](../../contract/v1/README.md#backups-and-restore). + ### Contract sections | Section | Content | @@ -205,6 +226,7 @@ The commands are `agentProviders.read {agent?}`, `agentProviders.apply {agent, c | [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage, commands and filters, the `read` and `edit` functions, limits, and refusal codes | | [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`, the `agentProviders.*` commands, snapshots and changes, privacy rules, and refusal codes | +| [Backups and restore](../../contract/v1/README.md#backups-and-restore) | Backups before library and providers changes, the `backup` status, `agentProviders.restore` and its refusal codes | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | Logs carry only IDs and metadata; no credential file is read | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | No ACP client; trusted local workspaces only | | [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*`, `agentSessions.*`, `agentLibrary.*`, and `agentProviders.*` commands (Rust Core API document) | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 0738e86c..8f4d0676 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| #TBD(待合入,2026-12-03) | [@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`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 | | [#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`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#247](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/247)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 宿主命令说明 | 补充 `agents.prompt` 重试的发送模式、原始提示词校验和拒绝原因。 | From 668ea7528809eb8701f60e4c03fb3d6c88eb3711 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 3 Dec 2026 18:25:40 +0800 Subject: [PATCH 2/2] =?UTF-8?q?docs(plugins):=20=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=AE=B0=E5=BD=95=E5=9B=9E=E5=A1=AB=20#260?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 8f4d0676..3992ff23 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| #TBD(待合入,2026-12-03) | [@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`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 | +| [#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`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 | | [#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`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#247](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/247)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 宿主命令说明 | 补充 `agents.prompt` 重试的发送模式、原始提示词校验和拒绝原因。 |