From cd745c022bcb76b71ea8b4c798de63e2ad542695 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 2 Dec 2026 13:21:20 +0800 Subject: [PATCH] =?UTF-8?q?feat(agents):=20=E4=BE=9B=E5=BA=94=E5=95=86?= =?UTF-8?q?=E5=AF=86=E9=92=A5=E5=8F=AA=E5=86=99=E4=B8=8D=E8=AF=BB=EF=BC=8C?= =?UTF-8?q?Lithe=20=E4=BF=9D=E5=AD=98=E4=BE=9B=E5=BA=94=E5=95=86=E5=88=97?= =?UTF-8?q?=E8=A1=A8=EF=BC=8C=E4=BF=AE=E6=94=B9=E5=89=8D=E5=A4=87=E4=BB=BD?= =?UTF-8?q?=E5=B9=B6=E5=8F=AF=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit agentProviders.apply 的 addProvider/updateProvider 可带 key、clearKey;configuration.providers 新增 listKeptBy;替换配置文件前由 Core 备份,新增 agentProviders.restore。agents 0 内的补充,不升能力版本。 --- rust/contracts/rust-core-api.md | 5 +- rust/crates/agent-runtime/src/lib.rs | 7 +- rust/crates/agent-runtime/src/library.rs | 26 +- .../agent-runtime/src/library/backups.rs | 395 +++++++++++ .../agent-runtime/src/library/providers.rs | 637 ++++++++++++++++-- .../crates/agent-runtime/src/library/saved.rs | 83 +++ .../agent-runtime/src/tests/providers.rs | 13 + .../src/tests/providers/backups.rs | 244 +++++++ .../agent-runtime/src/tests/providers/keys.rs | 136 ++++ .../src/tests/providers/saved.rs | 358 ++++++++++ rust/crates/core/src/protocol/command.rs | 4 + .../diagnostics/src/catalog_generated.rs | 31 + rust/crates/plugin-agents/src/lib.rs | 29 +- rust/logging/events/agent.json | 65 ++ shared/plugins/contract/v1/README.md | 156 ++++- .../contract/v1/plugin-manifest.schema.json | 6 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 16 +- .../plugins/reference/protocol-changelog.md | 1 + shared/plugins/sdk/go/README.md | 15 +- shared/plugins/sdk/java/README.md | 15 +- shared/plugins/sdk/node/README.md | 15 +- shared/plugins/sdk/rust/README.md | 15 +- 24 files changed, 2163 insertions(+), 117 deletions(-) create mode 100644 rust/crates/agent-runtime/src/library/backups.rs create mode 100644 rust/crates/agent-runtime/src/library/saved.rs create mode 100644 rust/crates/agent-runtime/src/tests/providers/backups.rs create mode 100644 rust/crates/agent-runtime/src/tests/providers/keys.rs create mode 100644 rust/crates/agent-runtime/src/tests/providers/saved.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 8900fe4f..4eb1c36d 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -507,8 +507,9 @@ or removing a command fails until the table changes in the same commit. | `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration | | `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 secrets reported as variable names only | -| `agentProviders.apply` | Apply one model, provider or profile change the plugin declares, through a checked staged copy of the agent's file | +| `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` | | `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 57fe9d8c..4aab4cc6 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -102,7 +102,11 @@ pub const AGENT_LIBRARY_COMMANDS: &[&str] = &[ ]; /// The commands of the `agentProviders.*` family. -pub const AGENT_PROVIDER_COMMANDS: &[&str] = &["agentProviders.read", "agentProviders.apply"]; +pub const AGENT_PROVIDER_COMMANDS: &[&str] = &[ + "agentProviders.read", + "agentProviders.apply", + "agentProviders.restore", +]; /// The agent catalog, the live sessions, the session records and the /// agent library. @@ -169,6 +173,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), _ => 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 25972ce4..c525db6b 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -34,7 +34,9 @@ //! Logs carry plugin and agent IDs, categories, counts and codes, never //! names, commands, paths or text. +mod backups; mod providers; +mod saved; #[cfg(test)] pub(crate) use providers::is_endpoint_for_test; @@ -2120,19 +2122,22 @@ impl Library { )) } }; - self.edit_staged(config, &target_path, edit_file, shows_change) + self.edit_staged(config, &target_path, None, 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. Answers whether the file - /// changed. + /// 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. fn edit_staged( &self, config: &Config, target: &Path, + backup: Option<(&str, &str)>, edit: impl FnOnce(&Path, bool) -> Result, shows_change: impl FnOnce(&Path) -> Result<(), CoreError>, ) -> Result { @@ -2160,10 +2165,19 @@ impl Library { "The configuration file changed while it was being edited.", )); } - if let Some(parent) = real.parent() { - ensure_directory(parent)?; + let taken = backup + .map(|(agent, file)| backups::take(config, agent, file, now.as_deref(), &edited)) + .transpose()?; + 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); + } + return Err(error); } - write_replacing(&real, &edited).map_err(|_| write_failed())?; Ok(true) })(); let _ = fs::remove_file(&staging); diff --git a/rust/crates/agent-runtime/src/library/backups.rs b/rust/crates/agent-runtime/src/library/backups.rs new file mode 100644 index 00000000..6aa99cd4 --- /dev/null +++ b/rust/crates/agent-runtime/src/library/backups.rs @@ -0,0 +1,395 @@ +//! Backups of the files `agentProviders.apply` replaces, and their restore. +//! +//! 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: +//! +//! ```text +//! /backups//record.json what Core keeps per file +//! /backups//baseline/ the bytes before Lithe's first change +//! /backups//history/ the bytes before each later change +//! ``` +//! +//! `` and `` are digests of the agent's record key and the +//! declared file's 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. +//! - 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 +//! newest [`MAX_HISTORY`] per agent. +//! - Every directory is owner-only and every file is created owner-only. The +//! bytes may hold secrets: they are never logged, sent to a plugin or +//! answered; answers carry only a time and booleans. +//! +//! A backup is written before the file is replaced and taken back when the +//! file cannot be written, so a change either has its backup or did not +//! happen. + +use super::{ + digest, ensure_private_directory, read_bounded, real_file, refusal, write_replacing, Config, + MAX_CONFIGURATION_FILE_BYTES, MAX_LIBRARY_FILE_BYTES, +}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +const BACKUPS_DIRECTORY: &str = "backups"; +const RECORD_FILE: &str = "record.json"; +const BASELINE_DIRECTORY: &str = "baseline"; +const HISTORY_DIRECTORY: &str = "history"; +/// Suffix of a history entry that stands for a file that did not exist. +const ABSENT_SUFFIX: &str = ".absent"; + +/// History entries kept per agent; the oldest go first. +pub(super) const MAX_HISTORY: usize = 20; + +/// What Core keeps about one backed-up file. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FileRecord { + /// Whether the file existed before Lithe's first change. + existed: bool, + /// When the baseline was kept, in milliseconds since the epoch. + saved_at_ms: i64, + /// SHA-256 of the bytes Lithe last wrote, in lowercase hex. + written: String, +} + +/// One agent's backups, by declared file ID. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Record { + #[serde(default)] + version: u32, + #[serde(default)] + files: BTreeMap, +} + +/// What `agentProviders.read` reports about an agent's backup. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Status { + /// When the oldest baseline was kept. + pub saved_at_ms: i64, + /// Whether a backed-up file now differs from what Lithe last wrote. + pub modified_since: bool, +} + +/// A backup taken before a write, to take back if the write fails. +pub(super) struct Taken { + directory: PathBuf, + previous: Option, + /// The baseline this backup created, if it was the first. + baseline: Option, + history: PathBuf, +} + +/// The refusal when a backup cannot be kept; the file is then not written. +pub(super) fn backup_failed() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentProviders.backupFailed", + "The configuration file could not be backed up, so it was not changed.", + ) +} + +fn restore_failed() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentProviders.restoreFailed", + "The configuration file could not be restored from its backup.", + ) +} + +fn agent_directory(config: &Config, agent_key: &str) -> PathBuf { + config + .directory + .join(BACKUPS_DIRECTORY) + .join(&digest(agent_key.as_bytes())[..32]) +} + +fn file_key(file_id: &str) -> String { + digest(file_id.as_bytes())[..32].to_string() +} + +/// The agent's record; none when it has no backup or the record cannot be +/// read, which reads as no backup. +fn load(directory: &Path) -> Option { + let bytes = read_bounded(&directory.join(RECORD_FILE), MAX_LIBRARY_FILE_BYTES) + .ok() + .flatten()?; + serde_json::from_slice::(&bytes) + .ok() + .filter(|record| record.version == 0 && !record.files.is_empty()) +} + +fn store(directory: &Path, record: &Record) -> io::Result<()> { + if record.files.is_empty() { + return match fs::remove_file(directory.join(RECORD_FILE)) { + Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), + _ => Ok(()), + }; + } + let bytes = serde_json::to_vec_pretty(record).map_err(io::Error::other)?; + write_replacing(&directory.join(RECORD_FILE), &bytes) +} + +/// Writes `bytes` to a new owner-only file at `path`. +fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> { + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + lithe_platform::fs::owner_only_file(&mut options); + let result = options.open(path).and_then(|mut file| { + file.write_all(bytes)?; + file.sync_all() + }); + if result.is_err() { + let _ = fs::remove_file(path); + } + result +} + +/// Creates the agent's backup directories owner-only. +fn prepare(config: &Config, directory: &Path) -> Result<(), CoreError> { + let map = |_| backup_failed(); + ensure_private_directory(&config.directory).map_err(map)?; + ensure_private_directory(&config.directory.join(BACKUPS_DIRECTORY)).map_err(map)?; + ensure_private_directory(directory).map_err(map)?; + ensure_private_directory(&directory.join(BASELINE_DIRECTORY)).map_err(map)?; + ensure_private_directory(&directory.join(HISTORY_DIRECTORY)).map_err(map) +} + +/// Keeps `bytes` (none for a file that did not exist) as a new history entry +/// and drops the oldest beyond [`MAX_HISTORY`]. Entry names sort by time. +fn keep_history(directory: &Path, file_id: &str, bytes: Option<&[u8]>) -> io::Result { + static NEXT: AtomicU64 = AtomicU64::new(0); + let history = directory.join(HISTORY_DIRECTORY); + let name = format!( + "{:016}-{:010}-{:06}-{}{}", + crate::now_ms().max(0), + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) % 1_000_000, + file_key(file_id), + if bytes.is_none() { ABSENT_SUFFIX } else { "" } + ); + let path = history.join(name); + write_private(&path, bytes.unwrap_or_default())?; + prune_history(&history); + Ok(path) +} + +fn prune_history(history: &Path) { + let Ok(entries) = fs::read_dir(history) else { + return; + }; + let mut names: Vec<_> = entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .map(|entry| entry.file_name()) + .collect(); + if names.len() <= MAX_HISTORY { + return; + } + names.sort(); + for name in &names[..names.len() - MAX_HISTORY] { + let _ = fs::remove_file(history.join(name)); + } +} + +/// 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. +pub(super) fn take( + config: &Config, + agent_key: &str, + file_id: &str, + original: Option<&[u8]>, + edited: &[u8], +) -> Result { + let directory = agent_directory(config, agent_key); + prepare(config, &directory)?; + let previous = load(&directory); + let mut record = previous.clone().unwrap_or_default(); + let mut baseline = None; + if !record.files.contains_key(file_id) { + let path = directory.join(BASELINE_DIRECTORY).join(file_key(file_id)); + let _ = fs::remove_file(&path); + if let Some(bytes) = original { + write_private(&path, bytes).map_err(|_| backup_failed())?; + baseline = Some(path); + } + record.files.insert( + file_id.to_string(), + FileRecord { + existed: original.is_some(), + saved_at_ms: crate::now_ms(), + written: String::new(), + }, + ); + } + let undo_baseline = |baseline: &Option| { + if let Some(path) = baseline { + let _ = fs::remove_file(path); + } + }; + let history = match keep_history(&directory, file_id, original) { + Ok(path) => path, + Err(_) => { + undo_baseline(&baseline); + return Err(backup_failed()); + } + }; + if let Some(file) = record.files.get_mut(file_id) { + file.written = digest(edited); + } + if store(&directory, &record).is_err() { + undo_baseline(&baseline); + let _ = fs::remove_file(&history); + return Err(backup_failed()); + } + Ok(Taken { + directory, + previous, + baseline, + history, + }) +} + +/// Takes back a backup whose file could not be written. +pub(super) fn undo(taken: Taken) { + let _ = store(&taken.directory, &taken.previous.unwrap_or_default()); + if let Some(path) = taken.baseline { + let _ = fs::remove_file(path); + } + let _ = fs::remove_file(taken.history); +} + +/// Whether the file at `path` differs from what Lithe last wrote. +fn modified(path: &Path, file: &FileRecord) -> bool { + match real_file(path) + .ok() + .and_then(|real| read_bounded(&real, MAX_CONFIGURATION_FILE_BYTES).ok()) + { + Some(Some(bytes)) => digest(&bytes) != file.written, + _ => true, + } +} + +/// The agent's backup as `agentProviders.read` reports it, if it has one. +/// `files` are the agent's declared files by ID. +pub(super) fn status( + config: &Config, + agent_key: &str, + files: &[(String, PathBuf)], +) -> Option { + let record = load(&agent_directory(config, agent_key))?; + let saved_at_ms = record.files.values().map(|file| file.saved_at_ms).min()?; + let modified_since = record.files.iter().any(|(id, file)| { + files + .iter() + .find(|(declared, _)| declared == id) + .is_none_or(|(_, path)| modified(path, file)) + }); + Some(Status { + saved_at_ms, + modified_since, + }) +} + +/// Why a restore was refused or failed. +pub(super) enum RestoreRefusal { + NoBackup, + ChangedSinceApply, + Failed, +} + +/// 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. +pub(super) fn restore( + config: &Config, + agent_key: &str, + files: &[(String, PathBuf)], + discard: bool, +) -> Result { + let directory = agent_directory(config, agent_key); + let record = load(&directory).ok_or(RestoreRefusal::NoBackup)?; + let mut targets = Vec::with_capacity(record.files.len()); + for (id, file) in &record.files { + let (_, path) = files + .iter() + .find(|(declared, _)| declared == id) + .ok_or(RestoreRefusal::Failed)?; + let real = real_file(path).map_err(|_| RestoreRefusal::Failed)?; + let current = read_bounded(&real, MAX_CONFIGURATION_FILE_BYTES) + .map_err(|_| RestoreRefusal::Failed)?; + if !discard + && current + .as_deref() + .is_none_or(|bytes| digest(bytes) != file.written) + { + return Err(RestoreRefusal::ChangedSinceApply); + } + let baseline = if file.existed { + let path = directory.join(BASELINE_DIRECTORY).join(file_key(id)); + Some( + read_bounded(&path, MAX_CONFIGURATION_FILE_BYTES) + .ok() + .flatten() + .ok_or(RestoreRefusal::Failed)?, + ) + } else { + None + }; + targets.push((id.clone(), real, current, baseline)); + } + prepare(config, &directory).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)?; + let put_back = match baseline { + Some(bytes) => write_replacing(real, bytes), + None => match fs::remove_file(real) { + Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), + _ => Ok(()), + }, + }; + if put_back.is_err() { + // Files already put back are no longer backed up; the rest are. + let _ = store(&directory, &remaining); + return Err(RestoreRefusal::Failed); + } + remaining.files.remove(id); + let _ = fs::remove_file(directory.join(BASELINE_DIRECTORY).join(file_key(id))); + } + store(&directory, &remaining).map_err(|_| RestoreRefusal::Failed)?; + Ok(targets.len()) +} + +/// The refusal a [`RestoreRefusal`] answers with. +pub(super) fn restore_error(refusal_kind: &RestoreRefusal) -> CoreError { + match refusal_kind { + RestoreRefusal::NoBackup => refusal( + ErrorCode::EntryNotFound, + "agentProviders.noBackup", + "Lithe has no backup of this agent's configuration to restore.", + ), + RestoreRefusal::ChangedSinceApply => refusal( + ErrorCode::InvalidRequest, + "agentProviders.changedSinceApply", + "The configuration file changed after Lithe's last change; restoring would discard that.", + ), + RestoreRefusal::Failed => restore_failed(), + } +} diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs index 7de9cd47..b469b511 100644 --- a/rust/crates/agent-runtime/src/library/providers.rs +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -6,29 +6,43 @@ //! MCP servers and hooks change. Core knows no agent, variable or file //! layout: every name comes from the plugin's answer. //! +//! A plugin whose manifest says `listKeptBy: "lithe"` serves a CLI whose +//! configuration holds one active custom endpoint. Core then keeps the list +//! of providers the user saved (`saved` module), without keys; the plugin +//! keeps each key in its own credentials, and `setProvider` hands it the +//! chosen provider's whole definition to write. +//! //! Privacy rules Core enforces on every answer and change: //! -//! - Secret values never pass. A provider's key, headers and query -//! parameters are reported by name only, and the answer has no field that -//! could carry a value: an unknown field refuses the whole answer. +//! - Keys are write-only. A change may carry a `key`, which Core checks and +//! hands only to the plugin's `edit` in memory; no log, error, event or +//! debug output shows it. Answers say only whether a key is set +//! (`keySet`); a provider's headers and query parameters are reported by +//! name only, and the answer has no field that could carry a value: an +//! unknown field refuses the whole answer. //! - An endpoint URL with a user, a password, a query or a fragment is //! refused, in an answer and in a change. //! - Names, text and lists have upper limits. //! - Only a request the user started changes anything, and only operations //! the manifest declares. +use super::backups; +use super::saved::{self, SavedProvider}; use super::{ agent_paths, backend_unavailable, check_name, configurable_agent, files_param, path_text, - refusal, require_user, with_staged, Check, Library, FUNCTION_TIMEOUT, + refusal, require_user, with_staged, AgentPaths, Check, Config, Library, FUNCTION_TIMEOUT, }; use crate::backend::BackendLink; use crate::catalog::CatalogAgent; use crate::{log, Runtime}; -use lithe_plugin_agents::{ConfigurationDeclaration, ProvidersDeclaration, PROVIDER_OPERATIONS}; +use lithe_plugin_agents::{ + ConfigurationDeclaration, ListKeptBy, ProvidersDeclaration, PROVIDER_OPERATIONS, +}; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::BTreeSet; +use std::fmt; use std::path::{Path, PathBuf}; use std::time::Instant; @@ -42,6 +56,44 @@ const MAX_ID_BYTES: usize = 128; const MAX_TOKEN_BYTES: usize = 64; const MAX_URL_BYTES: usize = 2048; const MAX_PATH_BYTES: usize = 4096; +/// Longest key a change may carry. Windows Credential Manager holds at most +/// 2560 bytes per item, where a plugin may keep it; this leaves room. +pub(super) const MAX_KEY_BYTES: usize = 1024; + +// --------------------------------------------------------------------------- +// Keys. + +/// A provider's key as a change carries it to the plugin. Its `Debug` output +/// is redacted, and nothing else in Core formats it. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +struct Secret(String); + +impl fmt::Debug for Secret { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("Secret()") + } +} + +impl Secret { + /// Non-empty, at most [`MAX_KEY_BYTES`], no control character or line + /// break. + fn is_valid(&self) -> bool { + !self.0.is_empty() && self.0.len() <= MAX_KEY_BYTES && !self.0.chars().any(char::is_control) + } +} + +fn invalid_key() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentProviders.invalidKey", + "A key is 1 to 1024 bytes without control characters or line breaks.", + ) +} + +fn is_false(value: &bool) -> bool { + !*value +} // --------------------------------------------------------------------------- // What a plugin reports. @@ -105,7 +157,8 @@ struct CurrentProfile { source: Option, } -/// One model provider. Its key, headers and query parameters are names only. +/// One model provider. Whether it has a key is a boolean; its headers and +/// query parameters are names only. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Provider { @@ -119,6 +172,12 @@ struct Provider { /// The environment variable the key is read from. #[serde(default, skip_serializing_if = "Option::is_none")] key_variable: Option, + /// Whether the configuration holds a key value for the provider. + #[serde(default)] + key_set: bool, + /// The model the configuration pairs with this provider, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] header_names: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -382,6 +441,9 @@ impl ProvidersSnapshot { if !ids.insert(provider.id.as_str()) { return Err(format!("{field}.id")); } + if let Some(model) = &provider.model { + check_name(model, &format!("{field}.model"))?; + } check_names( &provider.header_names, &format!("{field}.headerNames"), @@ -458,7 +520,8 @@ impl ProvidersSnapshot { // Changes. /// A provider as a change gives it: no headers or query parameters, which -/// the plugin keeps as they are. +/// the plugin keeps as they are, and no key, which the change carries +/// beside it. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ProviderInput { @@ -472,6 +535,9 @@ struct ProviderInput { key_variable: Option, #[serde(default, skip_serializing_if = "Option::is_none")] enabled: Option, + /// The model to use with the provider; only where Lithe keeps the list. + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, } impl ProviderInput { @@ -486,19 +552,53 @@ impl ProviderInput { .enabled .is_none_or(|enabled| provider.enabled == Some(enabled)) } + + fn saved(&self, key_set: bool) -> SavedProvider { + SavedProvider { + id: self.id.clone(), + name: self.name.clone(), + base_url: self.base_url.clone().unwrap_or_default(), + protocol: self.protocol.clone(), + model: self.model.clone(), + key_set, + } + } } /// One change, by its `op`. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)] enum ProviderChange { - AddProvider { provider: ProviderInput }, - UpdateProvider { provider: ProviderInput }, - RemoveProvider { id: String }, - SetProviderEnabled { id: String, enabled: bool }, - SetModel { model: String }, - SetProvider { id: String }, - SetProfile { name: String }, + AddProvider { + provider: ProviderInput, + #[serde(default, skip_serializing_if = "Option::is_none")] + key: Option, + }, + UpdateProvider { + provider: ProviderInput, + /// A new key; none keeps the current one. + #[serde(default, skip_serializing_if = "Option::is_none")] + key: Option, + /// Removes the key. + #[serde(default, rename = "clearKey", skip_serializing_if = "is_false")] + clear_key: bool, + }, + RemoveProvider { + id: String, + }, + SetProviderEnabled { + id: String, + enabled: bool, + }, + SetModel { + model: String, + }, + SetProvider { + id: String, + }, + SetProfile { + name: String, + }, } /// The file a change goes to. @@ -523,10 +623,46 @@ impl ProviderChange { } } - /// Checks the change's own fields; a bad endpoint has its own code. - fn check(&self) -> Result<(), CoreError> { + /// Checks the change's own fields; a bad endpoint and a bad key have + /// their own codes. Where Lithe keeps the list, a provider has an + /// endpoint and may name a model; elsewhere it names none. + fn check(&self, kept_by: ListKeptBy) -> Result<(), CoreError> { + let (key, clear_key) = match self { + Self::AddProvider { key, .. } => (key.as_ref(), false), + Self::UpdateProvider { key, clear_key, .. } => (key.as_ref(), *clear_key), + _ => (None, false), + }; + if key.is_some_and(|key| !key.is_valid()) { + return Err(invalid_key()); + } + if key.is_some() && clear_key { + return Err(invalid_change( + "A change sets a key or clears it, not both.", + )); + } let fields = match self { - Self::AddProvider { provider } | Self::UpdateProvider { provider } => { + Self::AddProvider { provider, .. } | Self::UpdateProvider { provider, .. } => { + match (kept_by, &provider.model, &provider.base_url) { + (ListKeptBy::Cli, Some(_), _) => return Err(invalid_change( + "A provider names a model only where Lithe keeps the list of providers.", + )), + (ListKeptBy::Lithe, _, None) => { + return Err(invalid_change("A provider Lithe keeps has an endpoint.")) + } + (ListKeptBy::Lithe, _, _) + if provider.key_variable.is_some() || provider.enabled.is_some() => + { + return Err(invalid_change( + "A provider Lithe keeps has no keyVariable or enabled.", + )) + } + (_, Some(model), _) => { + check_name(model, "provider.model").map_err(|field| { + invalid_change(&format!("The change's {field} is invalid.")) + })?; + } + _ => {} + } if provider .base_url .as_deref() @@ -563,23 +699,18 @@ impl ProviderChange { } /// Refuses a change the current snapshot rules out, before the plugin - /// is asked. - fn check_against(&self, snapshot: &ProvidersSnapshot) -> Result<(), CoreError> { - let unknown_provider = || { - refusal( - ErrorCode::EntryNotFound, - "agentProviders.unknownProvider", - "The agent has no provider with this ID.", - ) - }; + /// is asked. `saved` is the list Lithe keeps, empty where the CLI keeps + /// it. + fn check_against( + &self, + snapshot: &ProvidersSnapshot, + kept_by: ListKeptBy, + saved: &[SavedProvider], + ) -> Result<(), CoreError> { let changeable = |id: &str| -> Result<&Provider, CoreError> { let provider = snapshot.find(id).ok_or_else(unknown_provider)?; if provider.built_in { - return Err(refusal( - ErrorCode::NotSupported, - "agentProviders.builtInProvider", - "A provider built into the CLI cannot be changed or removed.", - )); + return Err(built_in_provider()); } Ok(provider) }; @@ -595,17 +726,18 @@ impl ProviderChange { Ok(()) } }; + if kept_by == ListKeptBy::Lithe { + if let Some(checked) = self.check_against_saved(snapshot, saved) { + return checked; + } + } match self { - Self::AddProvider { provider } => { + Self::AddProvider { provider, .. } => { if snapshot.find(&provider.id).is_some() { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentProviders.providerExists", - "The agent already has a provider with this ID.", - )); + return Err(provider_exists()); } } - Self::UpdateProvider { provider } => { + Self::UpdateProvider { provider, .. } => { changeable(&provider.id)?; } Self::RemoveProvider { id } => { @@ -624,7 +756,9 @@ impl ProviderChange { overridden(snapshot.model.as_ref().and_then(|m| m.source.as_ref()))?; } Self::SetProvider { id } => { - snapshot.find(id).ok_or_else(unknown_provider)?; + if !saved.iter().any(|provider| provider.id == *id) { + snapshot.find(id).ok_or_else(unknown_provider)?; + } overridden(snapshot.provider.as_ref().and_then(|p| p.source.as_ref()))?; } Self::SetProfile { name } => { @@ -645,12 +779,116 @@ impl ProviderChange { Ok(()) } - /// Whether a re-read staged copy holds the change. - fn shows_in(&self, snapshot: &ProvidersSnapshot) -> bool { + /// The checks of add, update and remove where Lithe keeps the list: + /// they go to the saved providers, not the configuration. None for the + /// other changes, which the snapshot checks as usual. + fn check_against_saved( + &self, + snapshot: &ProvidersSnapshot, + saved: &[SavedProvider], + ) -> Option> { + let find = |id: &str| saved.iter().find(|provider| provider.id == id); + let unknown = |id: &str| { + if snapshot.find(id).is_some_and(|provider| provider.built_in) { + built_in_provider() + } else { + unknown_provider() + } + }; + let endpoint_taken = |provider: &ProviderInput| { + saved.iter().any(|other| { + other.id != provider.id && Some(&other.base_url) == provider.base_url.as_ref() + }) + }; + Some(match self { + Self::AddProvider { provider, .. } => { + if find(&provider.id).is_some() || snapshot.find(&provider.id).is_some() { + Err(provider_exists()) + } else if endpoint_taken(provider) { + Err(endpoint_exists()) + } else { + Ok(()) + } + } + Self::UpdateProvider { provider, .. } => match find(&provider.id) { + None => Err(unknown(&provider.id)), + Some(_) if endpoint_taken(provider) => Err(endpoint_exists()), + Some(_) => Ok(()), + }, + Self::RemoveProvider { id } => match find(id) { + None => Err(unknown(id)), + Some(_) if active_saved(snapshot, saved).is_some_and(|active| active.id == *id) => { + Err(refusal( + ErrorCode::InvalidRequest, + "agentProviders.activeProvider", + "The provider is in use; switch to another before removing it.", + )) + } + Some(_) => Ok(()), + }, + _ => return None, + }) + } + + /// The saved providers after the change, where Lithe keeps the list. + /// The key itself is never kept; only whether the plugin has one. + fn saved_after(&self, saved: &[SavedProvider]) -> Vec { + let mut after = saved.to_vec(); + match self { + Self::AddProvider { provider, key } => after.push(provider.saved(key.is_some())), + Self::UpdateProvider { + provider, + key, + clear_key, + } => { + if let Some(entry) = after.iter_mut().find(|entry| entry.id == provider.id) { + let key_set = key.is_some() || (entry.key_set && !*clear_key); + *entry = provider.saved(key_set); + } + } + Self::RemoveProvider { id } => after.retain(|entry| entry.id != *id), + _ => {} + } + after + } + + /// Whether a re-read staged copy holds the change. `saved` is the list + /// Lithe keeps after the change, none where the CLI keeps it. + fn shows_in(&self, snapshot: &ProvidersSnapshot, saved: Option<&[SavedProvider]>) -> bool { + let key_shows = |found: &Provider, key: &Option, clear_key: bool| { + (key.is_none() || found.key_set) && (!clear_key || !found.key_set) + }; + if let Some(saved) = saved { + return match self { + // A saved provider that is not in use has nothing in the + // configuration to show. + Self::AddProvider { .. } | Self::RemoveProvider { .. } => true, + Self::UpdateProvider { + provider, + key, + clear_key, + } => active_saved(snapshot, saved).is_some_and(|active| { + active.id == provider.id + && current_provider(snapshot) + .is_some_and(|found| key_shows(found, key, *clear_key)) + }), + Self::SetProvider { id } if saved.iter().any(|provider| provider.id == *id) => { + active_saved(snapshot, saved).is_some_and(|active| active.id == *id) + } + _ => self.shows_in(snapshot, None), + }; + } match self { - Self::AddProvider { provider } | Self::UpdateProvider { provider } => snapshot + Self::AddProvider { provider, key } => snapshot .find(&provider.id) - .is_some_and(|found| provider.is_in(found)), + .is_some_and(|found| provider.is_in(found) && key_shows(found, key, false)), + Self::UpdateProvider { + provider, + key, + clear_key, + } => snapshot + .find(&provider.id) + .is_some_and(|found| provider.is_in(found) && key_shows(found, key, *clear_key)), Self::RemoveProvider { id } => snapshot.find(id).is_none(), Self::SetProviderEnabled { id, enabled } => snapshot .find(id) @@ -662,6 +900,57 @@ impl ProviderChange { } } +/// The provider the configuration currently uses, as the plugin listed it. +fn current_provider(snapshot: &ProvidersSnapshot) -> Option<&Provider> { + snapshot + .provider + .as_ref() + .and_then(|current| snapshot.find(¤t.id)) +} + +/// The saved provider the configuration currently uses: the one whose +/// endpoint the active custom provider has. +fn active_saved<'a>( + snapshot: &ProvidersSnapshot, + saved: &'a [SavedProvider], +) -> Option<&'a SavedProvider> { + let current = current_provider(snapshot).filter(|provider| !provider.built_in)?; + let base_url = current.base_url.as_ref()?; + saved.iter().find(|provider| provider.base_url == *base_url) +} + +fn unknown_provider() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentProviders.unknownProvider", + "The agent has no provider with this ID.", + ) +} + +fn built_in_provider() -> CoreError { + refusal( + ErrorCode::NotSupported, + "agentProviders.builtInProvider", + "A provider built into the CLI cannot be changed or removed.", + ) +} + +fn provider_exists() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentProviders.providerExists", + "The agent already has a provider with this ID.", + ) +} + +fn endpoint_exists() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentProviders.endpointExists", + "Lithe already keeps a provider with this endpoint for the agent.", + ) +} + fn invalid_change(message: &str) -> CoreError { refusal( ErrorCode::InvalidRequest, @@ -765,6 +1054,51 @@ fn snapshot_view(snapshot: &ProvidersSnapshot, files: &[(String, PathBuf)]) -> V view } +/// Marks where each provider of `view` comes from. Where Lithe keeps the +/// list (`saved` is some), the provider in use takes the ID and name of the +/// saved provider with its endpoint, and the saved providers not in use +/// follow, as Lithe keeps them; what is in use is always what the plugin +/// read from the configuration. +fn list_view(view: &mut Value, snapshot: &ProvidersSnapshot, saved: Option<&[SavedProvider]>) { + let active = saved.and_then(|saved| active_saved(snapshot, saved)); + let current_id = snapshot + .provider + .as_ref() + .map(|current| current.id.as_str()); + if let Some(Value::Array(providers)) = view.get_mut("providers") { + for provider in providers.iter_mut() { + let in_use = active.is_some() && provider["id"].as_str() == current_id; + if let (true, Some(active)) = (in_use, active) { + provider["id"] = json!(active.id); + provider["name"] = json!(active.name); + } + provider["saved"] = json!(in_use); + provider["origin"] = json!("configuration"); + } + } + if let Some(active) = active { + view["provider"]["id"] = json!(active.id); + view["provider"]["name"] = json!(active.name); + } + let Some(saved) = saved else { + return; + }; + let listed: Vec = saved + .iter() + .filter(|provider| active.is_none_or(|active| active.id != provider.id)) + .map(|provider| { + let mut entry = json!(provider); + entry["saved"] = json!(true); + entry["origin"] = json!("lithe"); + entry + }) + .collect(); + match view.get_mut("providers") { + Some(Value::Array(providers)) => providers.extend(listed), + _ => view["providers"] = json!(listed), + } +} + fn elapsed_ms(started: Instant) -> u64 { u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) } @@ -781,6 +1115,15 @@ struct ReadRequest { #[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)] struct ApplyRequest { agent: String, change: Value, @@ -818,15 +1161,30 @@ impl Library { "displayName": agent.agent.display_name, "mayConfigure": agent.may_configure, "operations": declared.operations, + "listKeptBy": declared.list_kept_by, }); if !agent.may_configure { return entry; } let paths = agent_paths(&config, configuration); entry["files"] = json!(files_param(&paths.files)); - match read_providers(&*runtime.link, agent, configuration, declared, &paths.files) { - Ok(snapshot) => { - let view = snapshot_view(&snapshot, &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, + }); + } + let read = + read_providers(&*runtime.link, agent, configuration, declared, &paths.files) + .and_then(|snapshot| match declared.list_kept_by { + ListKeptBy::Lithe => saved::load(&config, &agent.record_key()) + .map(|saved| (snapshot, Some(saved))), + ListKeptBy::Cli => Ok((snapshot, None)), + }); + match read { + Ok((snapshot, saved)) => { + let mut view = snapshot_view(&snapshot, &paths.files); + list_view(&mut view, &snapshot, saved.as_deref()); if let (Value::Object(entry), Value::Object(view)) = (&mut entry, view) { entry.extend(view); } @@ -920,26 +1278,114 @@ impl Library { "A change's op is one of addProvider, updateProvider, removeProvider, setProviderEnabled, setModel, setProvider or setProfile.", )); } - let Some(edit) = declared - .edit - .as_deref() - .filter(|_| declared.operations.iter().any(|declared| declared == op)) - else { + if declared.edit.is_none() || !declared.operations.iter().any(|declared| declared == op) { return Err(refusal( ErrorCode::NotSupported, "agentProviders.unsupportedOperation", "The agent plugin does not declare this change.", )); - }; + } let change: ProviderChange = serde_json::from_value(change) .map_err(|_| invalid_change("The change does not have the fields its op takes."))?; - change.check()?; + let kept_by = declared.list_kept_by; + change.check(kept_by)?; let config = self.config()?; let paths = agent_paths(&config, configuration); let link = &*runtime.link; + let agent_key = agent.record_key(); let snapshot = read_providers(link, agent, configuration, declared, &paths.files)?; - change.check_against(&snapshot)?; + let saved_before = match kept_by { + ListKeptBy::Lithe => Some(saved::load(&config, &agent_key)?), + ListKeptBy::Cli => None, + }; + change.check_against( + &snapshot, + kept_by, + saved_before.as_deref().unwrap_or_default(), + )?; + let Some(saved_before) = saved_before else { + let params = json!(change); + return self.edit_providers( + runtime, agent, &config, &paths, &snapshot, &change, params, None, + ); + }; + + // Lithe keeps the list: the saved providers change first, and go + // back as they were when the plugin's part fails. + let saved_after = change.saved_after(&saved_before); + let mut params = json!(change); + let calls_plugin = match &change { + ProviderChange::AddProvider { key, .. } => key.is_some(), + ProviderChange::UpdateProvider { + provider, + key, + clear_key, + } => { + let active = active_saved(&snapshot, &saved_before) + .is_some_and(|active| active.id == provider.id); + params["active"] = json!(active); + key.is_some() || *clear_key || active + } + ProviderChange::SetProvider { id } => { + if let Some(chosen) = saved_before.iter().find(|provider| provider.id == *id) { + let mut definition = json!(chosen); + if let Value::Object(fields) = &mut definition { + fields.remove("keySet"); + } + params["provider"] = definition; + } + true + } + _ => true, + }; + let listed = saved_after != saved_before; + if listed { + let _writing = self.lock_writing(); + saved::store(&config, &agent_key, saved_after.clone())?; + } + let edited = if calls_plugin { + self.edit_providers( + runtime, + agent, + &config, + &paths, + &snapshot, + &change, + params, + Some(&saved_after), + ) + } else { + Ok(false) + }; + if edited.is_err() && listed { + let _writing = self.lock_writing(); + // The plugin's refusal is what the user needs to see; a list + // that cannot be put back reads as it was written. + let _ = saved::store(&config, &agent_key, saved_before); + } + edited.map(|changed| changed || listed) + } + + /// Hands `change` (as `params`, which may carry more than the change) + /// to the plugin's `edit` on a staged copy of the change's target file, + /// and writes the copy when a re-read shows the change. `saved` is the + /// list Lithe keeps after the change, none where the CLI keeps it. + #[allow(clippy::too_many_arguments)] + fn edit_providers( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + config: &Config, + paths: &AgentPaths, + snapshot: &ProvidersSnapshot, + change: &ProviderChange, + params: Value, + saved: Option<&[SavedProvider]>, + ) -> Result { + let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; + let edit = declared.edit.as_deref().ok_or_else(not_declared)?; + let link = &*runtime.link; let target = match change.target() { Target::Providers => snapshot.targets.providers.as_deref(), Target::Model => snapshot.targets.model.as_deref(), @@ -964,7 +1410,7 @@ impl Library { let params = json!({ "agentID": agent.agent.id, "file": { "id": target_id, "staging": path_text(staging), "exists": exists }, - "change": change, + "change": params, }); let answer = link .call(&backend, &agent.plugin_id, edit, params, FUNCTION_TIMEOUT) @@ -992,7 +1438,7 @@ impl Library { let shows_change = |staging: &Path| -> Result<(), CoreError> { let staged_files = with_staged(&paths.files, &target_id, staging); let staged = read_providers(link, agent, configuration, declared, &staged_files)?; - if change.shows_in(&staged) { + if change.shows_in(&staged, saved) { Ok(()) } else { Err(refusal( @@ -1002,7 +1448,65 @@ impl Library { )) } }; - self.edit_staged(&config, &target_path, edit_file, shows_change) + let agent_key = agent.record_key(); + self.edit_staged( + config, + &target_path, + Some((&agent_key, &target_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 })) } } @@ -1010,3 +1514,22 @@ impl Library { pub(crate) fn is_endpoint_for_test(url: &str) -> bool { is_endpoint(url) } + +#[cfg(test)] +mod debug_tests { + use super::ProviderChange; + use serde_json::json; + + #[test] + fn a_change_never_formats_its_key() { + let change: ProviderChange = serde_json::from_value(json!({ + "op": "updateProvider", + "provider": { "id": "gamma", "name": "Gamma" }, + "key": "test-key-not-real" + })) + .unwrap(); + let text = format!("{change:?} {change:#?}"); + assert!(!text.contains("test-key-not-real")); + assert!(text.contains("")); + } +} diff --git a/rust/crates/agent-runtime/src/library/saved.rs b/rust/crates/agent-runtime/src/library/saved.rs new file mode 100644 index 00000000..ccaded45 --- /dev/null +++ b/rust/crates/agent-runtime/src/library/saved.rs @@ -0,0 +1,83 @@ +//! The providers the user saved for an agent whose plugin declares +//! `listKeptBy: "lithe"`. +//! +//! Such a CLI's configuration holds one active custom endpoint, so Core +//! keeps the list: `saved-providers.json` in the agent library directory, +//! owner-only, one list per agent record key. An entry has a provider's ID, +//! name, endpoint, protocol and model, and whether the plugin keeps a key +//! for it; never the key itself, which the plugin keeps in its own +//! credentials. The file lives as long as the library directory; removing +//! a saved provider removes its entry. + +use super::{ + ensure_private_directory, read_bounded, unreadable_file, write_failed, write_replacing, Config, + MAX_LIBRARY_FILE_BYTES, +}; +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +const SAVED_FILE: &str = "saved-providers.json"; + +/// One saved provider. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct SavedProvider { + pub id: String, + pub name: String, + pub base_url: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub protocol: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + /// Whether the plugin keeps a key for the provider. + #[serde(default)] + pub key_set: bool, +} + +/// The whole file. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SavedFile { + #[serde(default)] + version: u32, + #[serde(default)] + agents: BTreeMap>, +} + +fn read_file(config: &Config) -> Result { + let bytes = read_bounded(&config.directory.join(SAVED_FILE), MAX_LIBRARY_FILE_BYTES) + .map_err(|_| unreadable_file())?; + match bytes { + None => Ok(SavedFile::default()), + Some(bytes) => serde_json::from_slice::(&bytes) + .ok() + .filter(|file| file.version == 0) + .ok_or_else(unreadable_file), + } +} + +/// The agent's saved providers, in the order they were added. +pub(super) fn load(config: &Config, agent_key: &str) -> Result, CoreError> { + Ok(read_file(config)? + .agents + .remove(agent_key) + .unwrap_or_default()) +} + +/// Replaces the agent's saved providers; an empty list removes its entry. +pub(super) fn store( + config: &Config, + agent_key: &str, + providers: Vec, +) -> Result<(), CoreError> { + let mut file = read_file(config)?; + if providers.is_empty() { + file.agents.remove(agent_key); + } else { + file.agents.insert(agent_key.to_string(), providers); + } + ensure_private_directory(&config.directory)?; + let bytes = serde_json::to_vec_pretty(&file).map_err(|_| write_failed())?; + write_replacing(&config.directory.join(SAVED_FILE), &bytes).map_err(|_| write_failed()) +} diff --git a/rust/crates/agent-runtime/src/tests/providers.rs b/rust/crates/agent-runtime/src/tests/providers.rs index 3836ddd3..8b192b6e 100644 --- a/rust/crates/agent-runtime/src/tests/providers.rs +++ b/rust/crates/agent-runtime/src/tests/providers.rs @@ -60,7 +60,10 @@ fn providers_read(params: &Value) -> Result { if let Some(table) = config["providers"].as_object() { for (id, provider) in table { let mut row = provider.clone(); + // A key is reported only as whether there is one. + let key_set = row.as_object_mut().unwrap().remove("key").is_some(); row["id"] = json!(id); + row["keySet"] = json!(key_set); row["source"] = user.clone(); providers.push(row); } @@ -133,6 +136,12 @@ fn providers_edit(params: &Value, edit: Edit) -> Result let mut provider = change["provider"].clone(); let id = provider["id"].as_str().unwrap().to_string(); provider.as_object_mut().unwrap().remove("id"); + let kept = config["providers"][id.as_str()]["key"].clone(); + if change.get("key").is_some() { + provider["key"] = change["key"].clone(); + } else if change["clearKey"] != true && !kept.is_null() { + provider["key"] = kept; + } config["providers"][id.as_str()] = provider; } "removeProvider" => { @@ -634,3 +643,7 @@ impl LibraryHarness { harness } } + +mod backups; +mod keys; +mod saved; diff --git a/rust/crates/agent-runtime/src/tests/providers/backups.rs b/rust/crates/agent-runtime/src/tests/providers/backups.rs new file mode 100644 index 00000000..87d5d0ec --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers/backups.rs @@ -0,0 +1,244 @@ +//! Backups Core keeps before `agentProviders.apply` replaces a file, and +//! `agentProviders.restore`. + +use super::*; + +impl ProvidersTest { + fn backups(&self) -> PathBuf { + self.library.join("backups") + } + + /// The single agent directory under `backups/`. + fn agent_backups(&self) -> PathBuf { + let mut entries: Vec = fs::read_dir(self.backups()) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(entries.len(), 1, "one directory per agent"); + entries.pop().unwrap() + } + + fn history(&self) -> Vec> { + let mut entries: Vec = fs::read_dir(self.agent_backups().join("history")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + entries.sort(); + entries.iter().map(|path| fs::read(path).unwrap()).collect() + } + + fn restore(&self, discard: Option) -> Value { + let mut payload = json!({ "agent": AGENT_KEY }); + if let Some(discard) = discard { + payload["discardLaterChanges"] = json!(discard); + } + self.harness.run("agentProviders.restore", payload) + } + + fn restore_refused(&self, discard: Option) -> String { + let mut payload = json!({ "agent": AGENT_KEY }); + if let Some(discard) = discard { + payload["discardLaterChanges"] = json!(discard); + } + self.harness.refused("agentProviders.restore", payload) + } +} + +#[test] +fn apply_keeps_the_original_once_and_restore_puts_it_back() { + let test = ProvidersTest::new("providers backup", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let file = test.config_file(); + let original = fs::read(&file).unwrap(); + assert!( + test.read().get("backup").is_none(), + "no backup before a change" + ); + + let before = crate::now_ms(); + assert!(test.apply(json!({ "op": "setModel", "model": "alpha-small" }))); + let backup = test.read()["backup"].clone(); + assert_eq!(backup["modifiedSince"], false); + let saved_at = backup["savedAtMs"].as_i64().unwrap(); + assert!(saved_at >= before); + assert_eq!( + backup.as_object().unwrap().len(), + 2, + "only a time and a boolean" + ); + let baseline_directory = test.agent_backups().join("baseline"); + let baselines: Vec = fs::read_dir(&baseline_directory) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(baselines.len(), 1); + assert_eq!(fs::read(&baselines[0]).unwrap(), original); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&test.backups()), 0o700); + assert_eq!(mode(&test.agent_backups()), 0o700); + assert_eq!(mode(&baseline_directory), 0o700); + assert_eq!(mode(&baselines[0]), 0o600); + assert_eq!(mode(&test.agent_backups().join("record.json")), 0o600); + } + + let (_, logs) = capture::run(false, || { + assert!(test.apply(json!({ "op": "setProfile", "name": "work" }))); + }); + assert_eq!( + fs::read(&baselines[0]).unwrap(), + original, + "a later change keeps the first baseline" + ); + assert_eq!(test.read()["backup"]["savedAtMs"], json!(saved_at)); + assert_eq!( + test.history().len(), + 2, + "each change keeps what it replaced" + ); + + let (restored, restore_logs) = capture::run(false, || test.restore(None)); + assert_eq!(restored, json!({ "restored": true })); + assert_eq!(fs::read(&file).unwrap(), original, "byte for byte"); + assert!( + test.read().get("backup").is_none(), + "a restore forgets the baseline" + ); + assert!(fs::read_dir(&baseline_directory).unwrap().next().is_none()); + assert_eq!(test.history().len(), 3, "a restore keeps what it replaced"); + let applied = restore_logs + .iter() + .find(|log| log.event == "agent.providers.restore_applied") + .expect("the restore is logged"); + assert_eq!(applied.fields["files"], json!(1)); + assert_eq!(applied.fields["discarded"], json!(false)); + assert!(applied.fields.contains_key("duration_ms")); + for log in logs.iter().chain(restore_logs.iter()) { + let text = format!("{:?}", log.fields); + assert!(!text.contains("beta-secret-value"), "{}", log.event); + assert!(!text.contains("backups"), "{}", log.event); + } + + assert!(test.apply(json!({ "op": "setModel", "model": "alpha-small" }))); + assert!( + test.read()["backup"]["savedAtMs"].as_i64().unwrap() >= saved_at, + "the first change after a restore keeps a new baseline" + ); + test.restore(None); + assert_eq!(fs::read(&file).unwrap(), original); +} + +#[test] +fn restoring_a_file_that_did_not_exist_removes_it() { + let test = ProvidersTest::new("providers backup absent", PROVIDER_GRANTS, ALL_OPERATIONS); + let file = test.config_file(); + assert!(!file.exists()); + assert!(test.apply(json!({ "op": "setModel", "model": "alpha-small" }))); + assert!(file.exists()); + assert_eq!(test.read()["backup"]["modifiedSince"], false); + test.restore(None); + assert!(!file.exists(), "the file Lithe created is removed"); + assert_eq!( + test.restore_refused(None), + "agentProviders.noBackup", + "nothing is left to restore" + ); +} + +#[test] +fn restore_refuses_to_discard_later_changes_unless_asked() { + let test = ProvidersTest::new("providers backup changed", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let file = test.config_file(); + let original = fs::read(&file).unwrap(); + assert!(test.apply(json!({ "op": "setModel", "model": "alpha-small" }))); + + let mut config = read_json(&file); + config["model"] = json!("changed-elsewhere"); + test.write_config(config); + let external = fs::read(&file).unwrap(); + assert_eq!(test.read()["backup"]["modifiedSince"], true); + + let (refused, logs) = capture::run(false, || test.restore_refused(None)); + assert_eq!(refused, "agentProviders.changedSinceApply"); + assert_eq!(fs::read(&file).unwrap(), external, "the file is untouched"); + let failed = logs + .iter() + .find(|log| log.event == "agent.providers.restore_failed") + .expect("the refusal is logged"); + assert_eq!( + failed.fields["reason"], + json!("agentProviders.changedSinceApply") + ); + assert_eq!( + test.restore_refused(Some(false)), + "agentProviders.changedSinceApply" + ); + + assert_eq!(test.restore(Some(true)), json!({ "restored": true })); + assert_eq!(fs::read(&file).unwrap(), original); + assert!( + test.history().contains(&external), + "the discarded content is kept in history" + ); + + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let background = test.restore_refused(None); + trace::replace(previous); + assert_eq!(background, "agentLibrary.userActionRequired"); +} + +#[test] +fn restore_without_a_backup_is_refused() { + let test = ProvidersTest::new("providers backup none", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + assert_eq!(test.restore_refused(None), "agentProviders.noBackup"); + assert_eq!( + test.harness.refused( + "agentProviders.restore", + json!({ "agent": AGENT_KEY, "extra": true }) + ), + "agents.invalidPayload" + ); +} + +#[test] +fn a_change_whose_backup_fails_is_not_written() { + let test = ProvidersTest::new("providers backup fails", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let file = test.config_file(); + let original = fs::read(&file).unwrap(); + fs::create_dir_all(&test.library).unwrap(); + // A file where the backups directory goes cannot hold one. + fs::write(test.backups(), b"not a directory").unwrap(); + assert_eq!( + test.refused(json!({ "op": "setModel", "model": "alpha-small" })), + "agentProviders.backupFailed" + ); + assert_eq!(fs::read(&file).unwrap(), original, "the file is untouched"); + assert_eq!(test.staged_files(), 0); + assert!(test.read().get("backup").is_none()); +} + +#[test] +fn history_keeps_only_the_newest_entries() { + let test = ProvidersTest::new("providers backup history", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + for index in 0..25 { + assert!(test.apply(json!({ "op": "setModel", "model": format!("model-{index}") }))); + } + let history = test.history(); + assert_eq!(history.len(), 20); + assert!( + String::from_utf8_lossy(history.last().unwrap()).contains("model-23"), + "the newest entry is what the last change replaced" + ); + assert!(history + .iter() + .all(|entry| !String::from_utf8_lossy(entry).contains("\"model-0\""))); +} diff --git a/rust/crates/agent-runtime/src/tests/providers/keys.rs b/rust/crates/agent-runtime/src/tests/providers/keys.rs new file mode 100644 index 00000000..dc5de488 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers/keys.rs @@ -0,0 +1,136 @@ +//! Keys a change carries where the CLI keeps the list of providers: they +//! reach the plugin's `edit` and nothing else. + +use super::*; + +/// A synthetic key; no real service accepts it. +const KEY: &str = "test-key-not-real"; + +impl ProvidersTest { + /// The whole error of a refused change, as Core would format it. + fn refusal_text(&self, change: Value) -> String { + match self.harness.runtime.execute( + "agentProviders.apply", + json!({ "agent": AGENT_KEY, "change": change }), + ) { + Ok(answer) => panic!("the change was not refused: {answer}"), + Err(error) => format!("{error:?}"), + } + } + + fn provider(&self, id: &str) -> Value { + self.read()["providers"] + .as_array() + .unwrap() + .iter() + .find(|provider| provider["id"] == id) + .cloned() + .unwrap_or(Value::Null) + } +} + +/// Fails when `text` shows the synthetic key. +pub(super) fn assert_hidden(text: &str, place: &str) { + assert!(!text.contains(KEY), "the key shows in {place}"); +} + +#[test] +fn a_key_reaches_only_the_plugin_edit() { + let test = ProvidersTest::new("providers keys", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let gamma = + json!({ "id": "gamma", "name": "Gamma", "baseUrl": "https://gamma.example.test/v1" }); + + let ((), logs) = capture::run(false, || { + assert!(test.apply(json!({ "op": "addProvider", "provider": gamma, "key": KEY }))); + let edits = test.harness.link.calls_of("providers.edit"); + assert_eq!(edits[0]["change"]["key"], KEY, "the plugin gets the key"); + assert_eq!(test.provider("gamma")["keySet"], true); + assert_eq!(test.provider("alpha")["keySet"], false); + assert_hidden(&test.read().to_string(), "the read answer"); + + assert!(test.apply(json!({ "op": "updateProvider", "provider": { + "id": "gamma", "name": "Gamma Two", "baseUrl": "https://gamma.example.test/v1" + } }))); + assert_eq!( + test.provider("gamma")["keySet"], + true, + "a change without a key keeps it" + ); + assert!(test.apply(json!({ "op": "updateProvider", "provider": gamma, "clearKey": true }))); + assert_eq!(test.provider("gamma")["keySet"], false); + assert!(test.apply(json!({ "op": "updateProvider", "provider": gamma, "key": KEY }))); + assert_eq!(test.provider("gamma")["keySet"], true); + + // An edit that does not show the change is refused without the key. + *test.edit.lock().unwrap() = Edit::Wrong; + let text = + test.refusal_text(json!({ "op": "updateProvider", "provider": gamma, "key": KEY })); + assert!(text.contains("agentProviders.editNotApplied")); + assert_hidden(&text, "an edit refusal"); + *test.edit.lock().unwrap() = Edit::Apply; + }); + for log in &logs { + assert_hidden(&format!("{:?}", log.fields), &log.event); + } + assert!(logs + .iter() + .any(|log| log.event == "agent.providers.change_applied")); +} + +#[test] +fn invalid_keys_are_refused_without_being_shown() { + let test = ProvidersTest::new("providers bad keys", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let gamma = json!({ "id": "gamma", "name": "Gamma" }); + let ((), logs) = capture::run(false, || { + for (case, key) in [ + ("empty", String::new()), + ("a line break", format!("{KEY}\n")), + ("a control character", format!("{KEY}\u{7}")), + ("too long", format!("{KEY}{}", "k".repeat(1024))), + ] { + let change = json!({ "op": "addProvider", "provider": gamma, "key": key }); + assert_eq!( + test.refused(change.clone()), + "agentProviders.invalidKey", + "{case}" + ); + assert_hidden(&test.refusal_text(change), case); + } + assert!( + test.apply(json!({ "op": "addProvider", "provider": gamma, "key": "k".repeat(1024) })) + ); + let both = + json!({ "op": "updateProvider", "provider": gamma, "key": KEY, "clearKey": true }); + assert_eq!(test.refused(both.clone()), "agentProviders.invalidChange"); + assert_hidden(&test.refusal_text(both), "a key and clearKey"); + assert_eq!( + test.refused(json!({ "op": "addProvider", "provider": gamma, "key": 7 })), + "agentProviders.invalidChange" + ); + assert_eq!( + test.refused(json!({ "op": "setModel", "model": "alpha-small", "key": KEY })), + "agentProviders.invalidChange", + "only add and update carry a key" + ); + assert_eq!( + test.refused(json!({ "op": "addProvider", "provider": { + "id": "delta", "name": "Delta", "model": "delta-large" + } })), + "agentProviders.invalidChange", + "a provider names a model only where Lithe keeps the list" + ); + }); + for log in &logs { + assert_hidden(&format!("{:?}", log.fields), &log.event); + } + assert!( + test.harness + .link + .calls_of("providers.edit") + .iter() + .all(|edit| edit["change"]["key"] != KEY), + "a refused key never reaches the plugin" + ); +} diff --git a/rust/crates/agent-runtime/src/tests/providers/saved.rs b/rust/crates/agent-runtime/src/tests/providers/saved.rs new file mode 100644 index 00000000..3a97c5da --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers/saved.rs @@ -0,0 +1,358 @@ +//! Providers Lithe keeps for an agent whose CLI holds one active custom +//! endpoint (`listKeptBy: "lithe"`). The synthetic plugin keeps keys in a +//! stand-in for its credentials, never the platform's. + +use super::keys::assert_hidden; +use super::*; + +const KEY: &str = "test-key-not-real"; +const BASE_URL: &str = "SAMPLE_BASE_URL"; +const TOKEN: &str = "SAMPLE_TOKEN"; +const MODEL: &str = "SAMPLE_MODEL"; + +const LITHE_OPERATIONS: &[&str] = &[ + "addProvider", + "updateProvider", + "removeProvider", + "setProvider", + "setModel", +]; + +/// The plugin's stand-in credentials, by provider ID. +type Credentials = Arc>>; + +/// `providers.read` of a CLI whose `env` holds one endpoint and its key. +fn lithe_read(params: &Value) -> Result { + let path = params["files"][0]["path"].as_str().unwrap(); + let env = read_json(Path::new(path))["env"].clone(); + let mut providers = vec![json!({ "id": "official", "name": "Official", "builtIn": true })]; + let mut answer = json!({ + "format": "litheAgentProviders", + "version": 0, + "targets": { "providers": "main", "model": "main", "provider": "main" } + }); + if let Some(url) = env[BASE_URL].as_str() { + let mut custom = json!({ + "id": "custom", "name": "Custom endpoint", "baseUrl": url, + "keySet": env.get(TOKEN).is_some() + }); + if let Some(model) = env.get(MODEL) { + custom["model"] = model.clone(); + } + providers.push(custom); + answer["provider"] = json!({ "id": "custom" }); + } else { + answer["provider"] = json!({ "id": "official" }); + } + if let Some(model) = env.get(MODEL) { + answer["model"] = json!({ "id": model }); + } + answer["providers"] = json!(providers); + Ok(answer) +} + +/// `providers.edit` that keeps keys in `credentials` and writes the chosen +/// provider's endpoint, key and model into `env`. +fn lithe_edit(params: &Value, credentials: &Credentials) -> Result { + let staging = PathBuf::from(params["file"]["staging"].as_str().unwrap()); + let mut config = read_json(&staging); + let before = config.clone(); + let change = ¶ms["change"]; + let mut credentials = credentials.lock().unwrap(); + let write = |config: &mut Value, provider: &Value, key: Option<&String>| { + config["env"][BASE_URL] = provider["baseUrl"].clone(); + let env = config["env"].as_object_mut().unwrap(); + match key { + Some(key) => env.insert(TOKEN.into(), json!(key)), + None => env.remove(TOKEN), + }; + match provider.get("model") { + Some(model) => env.insert(MODEL.into(), model.clone()), + None => env.remove(MODEL), + }; + }; + match change["op"].as_str().unwrap() { + "addProvider" | "updateProvider" => { + let id = change["provider"]["id"].as_str().unwrap().to_string(); + if let Some(key) = change["key"].as_str() { + credentials.insert(id.clone(), key.into()); + } else if change["clearKey"] == true { + credentials.remove(&id); + } + if change["active"] == true { + write(&mut config, &change["provider"], credentials.get(&id)); + } + } + "removeProvider" => { + credentials.remove(change["id"].as_str().unwrap()); + } + "setProvider" => match change.get("provider") { + Some(provider) => { + let key = credentials.get(provider["id"].as_str().unwrap()); + write(&mut config, provider, key); + } + None => { + if let Some(env) = config["env"].as_object_mut() { + env.remove(BASE_URL); + env.remove(TOKEN); + } + } + }, + "setModel" => config["env"][MODEL] = change["model"].clone(), + _ => return Err(failure("plugin.params.invalid")), + } + let changed = config != before; + if changed { + fs::write(&staging, serde_json::to_vec(&config).unwrap()).unwrap(); + } + Ok(json!({ "format": "litheAgentProvidersEdit", "version": 0, "changed": changed })) +} + +struct LitheTest { + test: ProvidersTest, + credentials: Credentials, + /// Whether `providers.edit` fails. + failing: Arc>, +} + +impl LitheTest { + fn new(name: &str) -> Self { + let test = ProvidersTest::new(name, PROVIDER_GRANTS, LITHE_OPERATIONS); + let mut manifest = providers_manifest(LITHE_OPERATIONS); + manifest["agents"][0]["configuration"]["providers"]["listKeptBy"] = json!("lithe"); + test.harness.run( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": PROVIDER_GRANTS }] }), + ); + let credentials = Credentials::default(); + let failing = Arc::new(Mutex::new(false)); + let (kept, fails) = (credentials.clone(), failing.clone()); + test.harness + .link + .set_answer(move |function, params| match function { + "providers.read" => lithe_read(params), + "providers.edit" if *fails.lock().unwrap() => Err(failure("plugin.failed")), + "providers.edit" => lithe_edit(params, &kept), + other => sample_backend(other, params), + }); + test.write_config(json!({ "env": { "OTHER": "kept" } })); + Self { + test, + credentials, + failing, + } + } + + fn env(&self) -> Value { + read_json(&self.test.config_file())["env"].clone() + } + + fn edits(&self) -> usize { + self.test.harness.link.calls_of("providers.edit").len() + } + + fn saved_file(&self) -> PathBuf { + self.test.library.join("saved-providers.json") + } +} + +fn relay() -> Value { + json!({ + "id": "relay", "name": "Relay", "baseUrl": "https://relay.example.test", + "protocol": "messages", "model": "relay-large" + }) +} + +fn spare() -> Value { + json!({ "id": "spare", "name": "Spare", "baseUrl": "https://spare.example.test" }) +} + +#[test] +fn saved_providers_are_listed_and_switched_with_their_keys() { + let lithe = LitheTest::new("providers saved"); + let test = &lithe.test; + let initial = test.read(); + assert_eq!(initial["listKeptBy"], "lithe"); + assert_eq!( + initial["providers"], + json!([{ + "id": "official", "name": "Official", "builtIn": true, "keySet": false, + "saved": false, "origin": "configuration" + }]) + ); + + let ((), logs) = capture::run(false, || { + assert!(test.apply(json!({ "op": "addProvider", "provider": relay(), "key": KEY }))); + assert_eq!(lithe.credentials.lock().unwrap()["relay"], KEY); + assert_eq!( + lithe.env(), + json!({ "OTHER": "kept" }), + "saving a provider does not use it" + ); + let edits = lithe.edits(); + assert!(test.apply(json!({ "op": "addProvider", "provider": spare() }))); + assert_eq!(lithe.edits(), edits, "no key, nothing for the plugin"); + let listed = test.read(); + assert_hidden(&listed.to_string(), "the read answer"); + assert_eq!(listed["providers"][1]["id"], "relay"); + assert_eq!(listed["providers"][1]["origin"], "lithe"); + assert_eq!(listed["providers"][1]["saved"], true); + assert_eq!(listed["providers"][1]["keySet"], true); + assert_eq!(listed["providers"][1]["model"], "relay-large"); + assert_eq!(listed["providers"][2]["keySet"], false); + let file = fs::read_to_string(lithe.saved_file()).unwrap(); + assert_hidden(&file, "the saved providers file"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(lithe.saved_file()) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + } + + assert!(test.apply(json!({ "op": "setProvider", "id": "relay" }))); + let env = lithe.env(); + assert_eq!(env[BASE_URL], "https://relay.example.test"); + assert_eq!(env[TOKEN], KEY, "the plugin writes the key it keeps"); + assert_eq!(env[MODEL], "relay-large"); + assert_eq!(env["OTHER"], "kept"); + let edits = test.harness.link.calls_of("providers.edit"); + let set = &edits.last().unwrap()["change"]; + assert_eq!(set["provider"]["baseUrl"], "https://relay.example.test"); + assert!(set["provider"].get("keySet").is_none()); + let active = test.read(); + assert_hidden(&active.to_string(), "the read answer"); + assert_eq!(active["provider"]["id"], "relay"); + assert_eq!(active["provider"]["name"], "Relay"); + let providers = active["providers"].as_array().unwrap(); + assert_eq!(providers.len(), 3, "the provider in use is listed once"); + assert_eq!(providers[1]["id"], "relay"); + assert_eq!(providers[1]["origin"], "configuration"); + assert_eq!(providers[1]["saved"], true); + assert_eq!(providers[1]["keySet"], true); + assert_eq!(providers[2]["id"], "spare"); + + assert_eq!( + test.refused(json!({ "op": "removeProvider", "id": "relay" })), + "agentProviders.activeProvider" + ); + assert!( + test.apply(json!({ "op": "updateProvider", "provider": relay(), "clearKey": true })) + ); + assert!(lithe.env().get(TOKEN).is_none(), "the key in use goes too"); + assert!(!lithe.credentials.lock().unwrap().contains_key("relay")); + assert_eq!(test.read()["providers"][1]["keySet"], false); + assert!(test.apply(json!({ "op": "updateProvider", "provider": relay(), "key": KEY }))); + assert_eq!(lithe.env()[TOKEN], KEY); + + assert!(test.apply(json!({ "op": "setProvider", "id": "spare" }))); + assert_eq!(lithe.env()[BASE_URL], "https://spare.example.test"); + assert!( + lithe.env().get(TOKEN).is_none(), + "a provider without a key is written without one" + ); + assert_eq!(test.read()["provider"]["id"], "spare"); + assert_eq!(test.read()["providers"][1]["keySet"], false); + + assert!(test.apply(json!({ "op": "setProvider", "id": "official" }))); + assert_eq!( + lithe.env(), + json!({ "OTHER": "kept" }), + "the official provider removes only the endpoint and key" + ); + assert_eq!(test.read()["provider"]["id"], "official"); + + assert!(test.apply(json!({ "op": "removeProvider", "id": "relay" }))); + assert!( + !lithe.credentials.lock().unwrap().contains_key("relay"), + "removing a provider removes its key" + ); + let ids: Vec = test.read()["providers"] + .as_array() + .unwrap() + .iter() + .map(|provider| provider["id"].clone()) + .collect(); + assert_eq!(ids, vec![json!("official"), json!("spare")]); + }); + for log in &logs { + assert_hidden(&format!("{:?}", log.fields), &log.event); + } +} + +#[test] +fn saved_providers_are_checked_and_put_back_when_the_plugin_fails() { + let lithe = LitheTest::new("providers saved checks"); + let test = &lithe.test; + assert!(test.apply(json!({ "op": "addProvider", "provider": relay(), "key": KEY }))); + + let expect = |change: Value, code: &str| assert_eq!(test.refused(change), code); + expect( + json!({ "op": "addProvider", "provider": relay() }), + "agentProviders.providerExists", + ); + expect( + json!({ "op": "addProvider", "provider": { "id": "official", "name": "O", "baseUrl": "https://o.example.test" } }), + "agentProviders.providerExists", + ); + expect( + json!({ "op": "addProvider", "provider": { "id": "twin", "name": "Twin", "baseUrl": "https://relay.example.test" } }), + "agentProviders.endpointExists", + ); + expect( + json!({ "op": "addProvider", "provider": { "id": "bare", "name": "Bare" } }), + "agentProviders.invalidChange", + ); + expect( + json!({ "op": "addProvider", "provider": { "id": "bare", "name": "Bare", "baseUrl": "https://bare.example.test", "keyVariable": "BARE_KEY" } }), + "agentProviders.invalidChange", + ); + expect( + json!({ "op": "updateProvider", "provider": { "id": "official", "name": "O", "baseUrl": "https://o.example.test" } }), + "agentProviders.builtInProvider", + ); + expect( + json!({ "op": "updateProvider", "provider": { "id": "absent", "name": "A", "baseUrl": "https://a.example.test" } }), + "agentProviders.unknownProvider", + ); + expect( + json!({ "op": "removeProvider", "id": "absent" }), + "agentProviders.unknownProvider", + ); + expect( + json!({ "op": "setProvider", "id": "absent" }), + "agentProviders.unknownProvider", + ); + + let saved = fs::read(lithe.saved_file()).unwrap(); + *lithe.failing.lock().unwrap() = true; + let ((), logs) = capture::run(false, || { + expect( + json!({ "op": "addProvider", "provider": spare(), "key": KEY }), + "agentProviders.editFailed", + ); + expect( + json!({ "op": "removeProvider", "id": "relay" }), + "agentProviders.editFailed", + ); + }); + for log in &logs { + assert_hidden(&format!("{:?}", log.fields), &log.event); + } + assert_eq!( + fs::read(lithe.saved_file()).unwrap(), + saved, + "a change the plugin fails leaves the saved providers as they were" + ); + *lithe.failing.lock().unwrap() = false; + let ids: Vec = test.read()["providers"] + .as_array() + .unwrap() + .iter() + .map(|provider| provider["id"].clone()) + .collect(); + assert_eq!(ids, vec![json!("official"), json!("relay")]); + assert!(!lithe.credentials.lock().unwrap().contains_key("spare")); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 515ac6d5..62dcf750 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -280,6 +280,8 @@ pub enum AgentsCommand { ProvidersRead, /// Applies one declared model or provider change (`agentProviders.apply`). ProvidersApply, + /// Puts an agent's configuration back as Lithe backed it up (`agentProviders.restore`). + ProvidersRestore, } impl AgentsCommand { @@ -315,6 +317,7 @@ impl AgentsCommand { Self::LibraryRemoveSkill => "agentLibrary.removeSkill", Self::ProvidersRead => "agentProviders.read", Self::ProvidersApply => "agentProviders.apply", + Self::ProvidersRestore => "agentProviders.restore", } } } @@ -1326,6 +1329,7 @@ impl CoreCommand { "agentLibrary.removeSkill" => Some(Self::Agents(AgentsCommand::LibraryRemoveSkill)), "agentProviders.read" => Some(Self::Agents(AgentsCommand::ProvidersRead)), "agentProviders.apply" => Some(Self::Agents(AgentsCommand::ProvidersApply)), + "agentProviders.restore" => Some(Self::Agents(AgentsCommand::ProvidersRestore)), "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index b410fb9e..8837d28b 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -180,6 +180,37 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.providers.restore_applied", + channel: "agent", + level: LogLevel::Info, + message: "An agent's configuration was restored from Lithe's backup", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "discarded", field_type: FieldType::Bool, required: true, description: "Whether the user chose to discard changes made after Lithe's last write", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took", reason: None }, + FieldMetadata { name: "files", field_type: FieldType::Int, required: true, description: "Configuration files put back", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.providers.restore_failed", + channel: "agent", + level: LogLevel::Warn, + message: "Restoring an agent's configuration from Lithe's backup was refused or failed", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code such as agentProviders.noBackup; never names, paths or file contents", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.records.inspected", channel: "agent", diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index 771c78b0..ece0671e 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -168,8 +168,9 @@ pub struct ConfigurationDeclaration { } /// The model and model providers of an agent, read and changed by backend -/// functions in the declared configuration files. Secrets never pass: the -/// functions report names of environment variables, never their values. +/// functions in the declared configuration files. Keys are write-only: a +/// change may carry one to `edit`, and `read` reports only whether one is +/// set, never a value. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProvidersDeclaration { @@ -184,6 +185,30 @@ pub struct ProvidersDeclaration { /// any other before calling the plugin. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub operations: Vec, + /// Who keeps the list of custom providers. + #[serde(default, skip_serializing_if = "ListKeptBy::is_cli")] + pub list_kept_by: ListKeptBy, +} + +/// Who keeps an agent's list of custom providers. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ListKeptBy { + /// The CLI's configuration holds every provider, each with its key. + #[default] + Cli, + /// The CLI's configuration holds one active custom endpoint; Lithe keeps + /// the providers the user saved, without keys, and hands the chosen one + /// to the plugin's `edit` on `setProvider`. The plugin keeps each key in + /// its own credentials. + Lithe, +} + +impl ListKeptBy { + /// Whether this is the default, which a manifest leaves out. + pub fn is_cli(&self) -> bool { + *self == Self::Cli + } } /// A path given as root candidates; the first that resolves is used. diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 4e0e79de..58776c48 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -496,6 +496,71 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "agent.providers.restore_applied", + "channel": "agent", + "level": "info", + "message": "An agent's configuration was restored from Lithe's backup", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "files": { + "type": "int", + "required": true, + "description": "Configuration files put back" + }, + "discarded": { + "type": "bool", + "required": true, + "description": "Whether the user chose to discard changes made after Lithe's last write" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.providers.restore_failed", + "channel": "agent", + "level": "warn", + "message": "Restoring an agent's configuration from Lithe's backup was refused or failed", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code such as agentProviders.noBackup; never names, paths or file contents" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "agent.library.skill_import_finished", "channel": "agent", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 58d79496..6c36cd6b 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4398,7 +4398,7 @@ and keeps no name or icon of its own for any agent. | `files` | At most 8 `{id, roots}`: the files in the CLI's own format that hold its MCP servers, hooks, model and model providers. `id` is 1–64 bytes of lowercase ASCII letters, digits and `-`, not starting or ending with `-`, unique in the agent. Only the backend reads their format. | | `read` | Backend function that reports the MCP servers and hooks `files` hold. Required with `files`, unless `providers` is declared, and refused without them. | | `edit` | Backend function that applies one change to a staged copy of one of `files`. Needs `read`. Without it the agent's MCP servers and hooks are shown, never changed. | -| `providers` | `{read, edit?, operations?}`: backend functions that report and change the CLI's model, model providers and profiles kept in `files` (see [Models and providers](#models-and-providers)). Needs `files`. `edit` and `operations` come together; `operations` lists each change `edit` makes at most once, from `addProvider`, `updateProvider`, `removeProvider`, `setProviderEnabled`, `setModel`, `setProvider` and `setProfile`. | +| `providers` | `{read, edit?, operations?, listKeptBy?}`: backend functions that report and change the CLI's model, model providers and profiles kept in `files` (see [Models and providers](#models-and-providers)). Needs `files`. `edit` and `operations` come together; `operations` lists each change `edit` makes at most once, from `addProvider`, `updateProvider`, `removeProvider`, `setProviderEnabled`, `setModel`, `setProvider` and `setProfile`. `listKeptBy` is `cli` (the default) when the CLI's configuration holds every custom provider, or `lithe` when it holds one active custom endpoint and Lithe keeps the list the user saved (see [Providers Lithe keeps](#providers-lithe-keeps)). | - A configuration declares at least one of `instructions`, `skills` and `files`. A function ID is dot-separated lowerCamelCase segments. @@ -4666,6 +4666,7 @@ plugin, and the host draws the views. | --- | --- | --- | | `agentProviders.read` | `{agent?}` | `{agents}` | | `agentProviders.apply` | `{agent, change}` | `{changed}` | +| `agentProviders.restore` | `{agent, discardLaterChanges?}` | `{restored: true}` | `read` answers one entry per agent that declares `providers`, in catalog order, or only the agent `agent` names (`agentLibrary.unknownAgent`, @@ -4681,15 +4682,18 @@ without `providers`): "displayName": "Alpha", "mayConfigure": true, "operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setProvider"], + "listKeptBy": "cli", "files": [{"id": "main", "path": "/home/user/.alpha/config.json", "exists": true}], + "backup": {"savedAtMs": 1764633600000, "modifiedSince": false}, "cliVersion": "1.4.0", "model": {"id": "model-a", "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}}, "provider": {"id": "gateway", "name": "Gateway", "source": {"layer": "environment", "variable": "ALPHA_PROVIDER"}}, "providers": [ - {"id": "builtin", "name": "Built-in", "builtIn": true}, + {"id": "builtin", "name": "Built-in", "keySet": false, "builtIn": true, "saved": false, "origin": "configuration"}, {"id": "gateway", "name": "Gateway", "baseUrl": "https://gateway.example.com/v1", "protocol": "responses", - "keyVariable": "GATEWAY_KEY", "headerNames": ["X-Team"], "enabled": true, "builtIn": false, - "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}} + "keyVariable": "GATEWAY_KEY", "keySet": true, "headerNames": ["X-Team"], "enabled": true, "builtIn": false, + "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}, + "saved": false, "origin": "configuration"} ], "profiles": [{"name": "fast", "model": "model-b", "provider": "gateway"}], "profile": {"name": "fast", "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}}, @@ -4706,6 +4710,16 @@ without `providers`): adds the resolved `path` to each `source` that names a declared `file`, and the current provider's `name` from `providers` when the plugin left it out. `files` lists the declared files Core resolved. +- `listKeptBy` is the manifest's, `cli` when it leaves it out. Each + provider gains `saved` and `origin`: `origin: "configuration"` is a + provider the plugin read from the CLI's configuration, `origin: "lithe"` + one Lithe saved that the configuration does not use now (only with + `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. - A failed read gives `readError` (`agentLibrary.backendUnavailable`, `agentProviders.readFailed` or `agentProviders.invalidSnapshot`) in place of the snapshot; the other agents still answer. @@ -4715,8 +4729,8 @@ without `providers`): | `change` | Effect | Target | | --- | --- | --- | -| `{op: "addProvider", provider}` | adds a provider of a new `id` (`agentProviders.providerExists`) | `providers` | -| `{op: "updateProvider", provider}` | replaces the provider's `name`, `baseUrl`, `protocol`, `keyVariable` and, when given, `enabled` | `providers` | +| `{op: "addProvider", provider, key?}` | adds a provider of a new `id` (`agentProviders.providerExists`) | `providers` | +| `{op: "updateProvider", provider, key?, clearKey?}` | replaces the provider's `name`, `baseUrl`, `protocol`, `keyVariable` and, when given, `enabled`; a `key` replaces its key, `clearKey: true` removes it, neither keeps it | `providers` | | `{op: "removeProvider", id}` | removes the provider | `providers` | | `{op: "setProviderEnabled", id, enabled}` | turns the provider on or off (`agentProviders.noEnabledState` when its `enabled` was not reported) | `providers` | | `{op: "setModel", model}` | sets the model the CLI uses | `model` | @@ -4724,8 +4738,18 @@ without `providers`): | `{op: "setProfile", name}` | sets the profile the CLI uses (`agentProviders.unknownProfile`) | `profile` | `provider` in a change is `{id, name, baseUrl?, protocol?, keyVariable?, -enabled?}`; the provider's header and query parameter names stay as the -plugin keeps them. Core checks, in this order: +enabled?, model?}`; the provider's header and query parameter names stay as +the plugin keeps them. With `listKeptBy: "lithe"` it is `{id, name, +baseUrl, protocol?, model?}`: `baseUrl` is required, `model` is the model +to use with the provider, and `keyVariable` and `enabled` are refused; +elsewhere `model` is refused. + +A `key` is the provider's key value, **write-only**: 1–1024 bytes (well +under the 2560 bytes a Windows Credential Manager item holds) without a +control character or line break. Core hands it in memory to the plugin's +`edit` and nowhere else: no answer, log, event, error message or debug +output of Core carries it, and no answer reads it back; `keySet` says only +whether there is one. Core checks, in this order: 1. The agent declares `providers` (`agentProviders.notDeclared`); `op` is one of the operations above (`agentProviders.invalidChange`) and one the @@ -4733,25 +4757,98 @@ plugin keeps them. Core checks, in this order: 2. The change has exactly the fields its `op` takes, each following the rules of the snapshot below (`agentProviders.invalidChange`); a `baseUrl` that is not an allowed endpoint is - `agentProviders.invalidEndpoint`. + `agentProviders.invalidEndpoint`; a `key` that breaks the rule above is + `agentProviders.invalidKey`; `key` with `clearKey: true` is + `agentProviders.invalidChange`. 3. Core calls `read`. `updateProvider`, `removeProvider`, `setProviderEnabled` and `setProvider` name a provider the agent has (`agentProviders.unknownProvider`); the first three refuse a `builtIn` one (`agentProviders.builtInProvider`). `setModel`, `setProvider` and `setProfile` refuse a current value whose `source.layer` is `environment` (`agentProviders.overridden`): the file would change and - the CLI would still use the variable. + the CLI would still use the variable. With `listKeptBy: "lithe"`, the + provider changes check the saved list instead, as + [Providers Lithe keeps](#providers-lithe-keeps) describes. 4. The snapshot's `targets` names the file for the change (`agentProviders.noTarget`). The file changes through a staged copy exactly like a server or hook: Core calls `edit` on the copy, reads the copy back with `read`, and the change must show there - (`agentProviders.editNotApplied`); the file is replaced only if it still + (`agentProviders.editNotApplied`; a `key` shows as `keySet: true`, + `clearKey` as `keySet: false`); the file is replaced only if it still holds the bytes Core copied (`agentLibrary.fileChanged`), with the same `agentLibrary.brokenLink`, `agentLibrary.fileTooLarge`, `agentLibrary.unreadable` and `agentLibrary.writeFailed` refusals. +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`). `apply` answers `changed: false` when the file already held the change. +##### Providers Lithe keeps + +Some CLIs keep one custom endpoint in their configuration, not a list. A +plugin for such a CLI declares `listKeptBy: "lithe"`, and Core keeps the +providers the user saved for each agent: `{id, name, baseUrl, protocol?, +model?}` and whether the plugin keeps a key for it, in +`saved-providers.json` in the library directory, owner-only (`0600`), never +with a key. The plugin keeps each key in its own credentials, with +[`lithe/host/credentials/set|get|delete`](#host-services) under the +`credentials.store` permission, by a key name it derives from the provider +ID. + +- `read` lists the providers the configuration holds, as the plugin read + them; the custom provider in use takes the `id` and `name` of the saved + provider with the same `baseUrl`, and `provider` names that saved + provider. The saved providers not in use follow with + `origin: "lithe"`, their `keySet` being what Core recorded. What is in + use is always what the plugin read back from the configuration. +- `addProvider` refuses an `id` the agent or the saved list already has + (`agentProviders.providerExists`) and a `baseUrl` another saved provider + has (`agentProviders.endpointExists`). `updateProvider` and + `removeProvider` name a saved provider (`agentProviders.unknownProvider`, + or `agentProviders.builtInProvider` for a built-in one), `updateProvider` + refuses another saved provider's `baseUrl` + (`agentProviders.endpointExists`), and `removeProvider` refuses the + provider in use (`agentProviders.activeProvider`); switch first. +- Core saves the list first and then calls the plugin's `edit`: `addProvider` + with a `key`, `updateProvider` with a `key`, `clearKey` or of the provider + in use, `removeProvider`, and `setProvider`. When the call or its check + fails, Core puts the list back as it was, so a list never names a key the + plugin did not store. A change with nothing for the plugin changes only + the list, and `apply` answers `changed: true`. +- `edit`'s `change` then carries more than the host gave: `updateProvider` + has `active`, whether the provider is in use (the plugin then writes it + into the configuration too); `setProvider` of a saved provider has + `provider: {id, name, baseUrl, protocol?, model?}`, which the plugin + writes with the key it keeps, or without a key when it keeps none (then + `read` says `keySet: false`; this is not an error). `setProvider` of a + built-in provider has no `provider`: the plugin removes the endpoint and + key it wrote, and nothing else. `removeProvider` deletes the key the + 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. + `providers.read` receives `{agentID, files: [{id, path, exists}]}`, like the configuration `read`, and answers within 10 seconds exactly: @@ -4760,8 +4857,11 @@ configuration `read`, and answers within 10 seconds exactly: - `model?`: `{id, source?}`, the model in use; - `provider?`: `{id, name?, source?}`, the provider in use; - `providers`: at most 64 `{id, name, baseUrl?, protocol?, keyVariable?, - headerNames?, queryParameterNames?, enabled?, builtIn?, source?}`, IDs - unique. `keyVariable` is the environment variable the key is read from; + keySet?, model?, headerNames?, queryParameterNames?, enabled?, builtIn?, + source?}`, IDs unique. `keyVariable` is the environment variable the key + is read from; `keySet` (default `false`) is whether the configuration + holds a key value for the provider, the value itself never reported; + `model` is the model the configuration pairs with the provider; `headerNames` and `queryParameterNames` are at most 64 names each. `enabled` is left out when the CLI has no on/off switch; `builtIn` marks a provider built into the CLI, which is shown and never changed; @@ -4784,8 +4884,10 @@ Every answer follows these rules, and any other answer, including one with an unknown field, is `agentProviders.invalidSnapshot`; a failed call is `agentProviders.readFailed`: -- **No secret value passes.** A key, header or query parameter is reported - by name only, and no field can hold a value. When the CLI keeps a +- **Keys are write-only; no secret value is read.** A key goes one way, + from the host's change to the plugin's `edit`; a read reports only + `keySet`. A key variable, header or query parameter is reported by name + only, and no field of an answer can hold a value. When the CLI keeps a provider's endpoint in an environment block of its settings, the plugin reports it as that provider's `baseUrl`; every other variable of the block is reported by name only, in `environmentNames`. @@ -4801,9 +4903,11 @@ an unknown field, is `agentProviders.invalidSnapshot`; a failed call is trailing spaces or control characters. - **Plugins do not read credentials.** `read` and `edit` never open a CLI's credential files (such as `auth.json` or `.credentials.json`) or the - system keychain, and never put a token, key or password in any field. - `account.label` comes from what the CLI's settings or a CLI command - report without credentials, and is left out otherwise. + system keychain, and never put a token, key or password in any field of + an answer or a log. `account.label` comes from what the CLI's settings or + a CLI command report without credentials, and is left out otherwise. The + credentials a plugin keeps through + [`lithe/host/credentials`](#host-services) are its own, not the CLI's. `providers.edit` receives `{agentID, file: {id, staging, exists}, change}` with `change` as the host gave it, changes only the file at `staging` in the @@ -4811,8 +4915,13 @@ CLI's own format, keeping everything else it holds, and answers `{format: "litheAgentProvidersEdit", version: 0, changed}` within 10 seconds. Any other answer is `agentProviders.invalidEdit`; a failed call is `agentProviders.editFailed`. A provider `edit` adds is enabled unless -`enabled` is `false`; `keyVariable` names where the key is read from, and -the user puts the key itself there outside Lithe. +`enabled` is `false`; `keyVariable` names where the key is read from. A +`key` in `change` is written into the provider's entry in the CLI's own +field for it, or, with `listKeptBy: "lithe"`, stored in the plugin's +credentials and written when the provider is in use; `clearKey: true` +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. #### Limits, refusals and logging @@ -4831,8 +4940,11 @@ the user puts the key itself there outside Lithe. 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, never a model, - provider, URL, variable name or label. + `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. ### Privacy and logging diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index ddf585e3..804a85e5 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -521,7 +521,7 @@ "$ref": "#/$defs/pluginFunctionID" }, "providers": { - "description": "Added within agents 0. Backend functions that report and change the CLI's model, model providers and profiles kept in files. Needs files. Answers carry names only, never a key, token, header or query value; endpoints have no user, password, query or fragment; plugins never read credential files or the keychain.", + "description": "Added within agents 0. Backend functions that report and change the CLI's model, model providers and profiles kept in files. Needs files. Keys are write-only: a change may carry one to the edit function, and answers report only whether one is set (keySet), never a key, token, header or query value; endpoints have no user, password, query or fragment; plugins never read credential files or the keychain.", "type": "object", "additionalProperties": false, "required": ["read"], @@ -546,6 +546,10 @@ "items": { "enum": ["addProvider", "updateProvider", "removeProvider", "setProviderEnabled", "setModel", "setProvider", "setProfile"] } + }, + "listKeptBy": { + "description": "Added within agents 0. Who keeps the list of custom providers. cli (the default): the CLI's configuration holds every provider, each with its key if one is set. lithe: the CLI's configuration holds one active custom endpoint, Lithe keeps the list of providers the user saved (without keys; the plugin keeps each key through credentials), and setProvider hands the plugin the chosen provider's whole definition.", + "enum": ["cli", "lithe"] } } } diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 22e5172f..939baf08 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 内的补充),密钥、请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串 | 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"`,密钥由插件存进自己的凭据),Core 替换文件前先备份,`agentProviders.restore` 由用户恢复原样 | 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, 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 | 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 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) | ### Planned APIs diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 241e82c8..b2718026 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.*` 命令 | ✅ | 待宿主接入 | [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` 同属这项补充 | ✅ | 待宿主接入 | [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 | ✅ | 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 | ✅ | 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 ab407e46..7faa7d1e 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -62,16 +62,18 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 ### 模型与模型供应商 -`configuration` 里再声明 `providers: {read, edit?, operations?}`,宿主就能显示 CLI 当前用的模型、可用的模型供应商、配置档和登录账号标签,并让用户修改。它和 MCP 服务器、Hooks 共用 `files`、`agents.configuration` 授权和暂存副本流程: +`configuration` 里再声明 `providers: {read, edit?, operations?, listKeptBy?}`,宿主就能显示 CLI 当前用的模型、可用的模型供应商、配置档和登录账号标签,并让用户修改。它和 MCP 服务器、Hooks 共用 `files`、`agents.configuration` 授权和暂存副本流程: - `read` 报告 `litheAgentProviders` 快照,每个值带来源层(`user`、`profile`、`default`、`environment`)和来源文件或变量名;`edit` 只改 Core 给的暂存副本,Core 再读一遍副本确认改动生效后原子替换。 - `operations` 列出 `edit` 支持的操作(`addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setProvider`、`setProfile`);没列出的操作 Core 在调用插件前就以 `agentProviders.unsupportedOperation` 拒绝。 -- **密钥永远不经过这个接口**:供应商的密钥只给环境变量名 `keyVariable`,请求头和查询参数只给名字,快照里没有能放值的字段,多一个字段整份拒绝。CLI 把端点写在设置文件的环境变量块里时,插件把它报成该供应商的 `baseUrl`,块里其他变量只把名字放进 `environmentNames`。 +- **密钥只写不读**:`addProvider`、`updateProvider` 可以带 `key`(1–1024 字节,不含控制字符和换行,否则 `agentProviders.invalidKey`),`updateProvider` 可以带 `clearKey: true`,两者同时给是 `agentProviders.invalidChange`,都不给就保留原来的密钥。Core 只在内存里把密钥交给插件的 `edit`,任何回答、日志、事件和错误都不带它;读取只回答 `keySet` 表示有没有密钥。密钥的环境变量名 `keyVariable`、请求头和查询参数只给名字,快照里没有能放值的字段,多一个字段整份拒绝。CLI 把端点写在设置文件的环境变量块里时,插件把它报成该供应商的 `baseUrl`,块里其他变量只把名字放进 `environmentNames`。 - 端点只能是不带用户名、密码、查询和片段的 `http`/`https` 地址;名称、列表都有上限。 - 插件不得读取 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}`。 -命令是 `agentProviders.read {agent?}` 和 `agentProviders.apply {agent, change}`,字段、拒绝码和完整示例见[契约](../../contract/v1/README.md#models-and-providers)。 +命令是 `agentProviders.read {agent?}`、`agentProviders.apply {agent, change}` 和 `agentProviders.restore {agent, discardLaterChanges?}`,字段、拒绝码和完整示例见[契约](../../contract/v1/README.md#models-and-providers)。 ### 契约章节 @@ -178,16 +180,18 @@ Every change comes only from a user action. Core reads and writes only the decla ### Models and model providers -An agent whose `configuration` also declares `providers: {read, edit?, operations?}` lets the host show the model the CLI uses, its model providers, profiles and signed-in account label, and lets the user change them. It shares `files`, the `agents.configuration` grant and the staged-copy flow with MCP servers and hooks: +An agent whose `configuration` also declares `providers: {read, edit?, operations?, listKeptBy?}` lets the host show the model the CLI uses, its model providers, profiles and signed-in account label, and lets the user change them. It shares `files`, the `agents.configuration` grant and the staged-copy flow with MCP servers and hooks: - `read` reports a `litheAgentProviders` snapshot, each value with its layer (`user`, `profile`, `default`, `environment`) and its source file or variable name; `edit` changes only the staged copy Core gives it, and Core reads the copy back to see the change before replacing the file atomically. - `operations` lists what `edit` does (`addProvider`, `updateProvider`, `removeProvider`, `setProviderEnabled`, `setModel`, `setProvider`, `setProfile`); Core refuses any other with `agentProviders.unsupportedOperation` before calling the plugin. -- **No secret passes through this interface**: a provider's key is only the name of its environment variable, `keyVariable`; headers and query parameters are names only; the snapshot has no field that could hold a value, and an extra field refuses the whole answer. When the CLI keeps an endpoint in its settings' environment block, the plugin reports it as that provider's `baseUrl` and every other variable of the block by name only, in `environmentNames`. +- **Keys are write-only**: `addProvider` and `updateProvider` may carry a `key` (1–1024 bytes without control characters or line breaks, else `agentProviders.invalidKey`), and `updateProvider` may carry `clearKey: true`; both together are `agentProviders.invalidChange`, and neither keeps the key. Core hands the key in memory to the plugin's `edit` only; no answer, log, event or error carries it, and a read answers only `keySet`, whether there is one. The key's environment variable `keyVariable`, headers and query parameters are names only; the snapshot has no field that could hold a value, and an extra field refuses the whole answer. When the CLI keeps an endpoint in its settings' environment block, the plugin reports it as that provider's `baseUrl` and every other variable of the block by name only, in `environmentNames`. - An endpoint is an `http` or `https` URL without a user, password, query or fragment; names and lists have upper limits. - 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. -The commands are `agentProviders.read {agent?}` and `agentProviders.apply {agent, change}`; fields, refusal codes and a full example are in the [contract](../../contract/v1/README.md#models-and-providers). +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). ### Contract sections diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index a3d40be8..c2f2f5b0 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#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`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | `toolCall` 事件新增可选 `command`:`execute` 调用实际运行的命令行(1 字节到 1 MiB),此时 `title` 写这条命令要做什么(例如 CLI 给的描述),宿主把标题作为步骤标题、命令放进命令卡片,没有 `command` 时只用标题。`didStart` 新增 `toolCommands: true`,后端只在看到它时才发送 `command`;旧 Core 的 `toolCall` 严格解码,收到 `command` 会拒绝整批报告。会话来源 `read` 函数新增可选请求参数 `toolCommands`,`agentSessions.page` 随 `toolCalls` 一起发送,只有这时 `tool` 消息才可带 `command`,否则以 `agentSessions.invalidRead` 拒绝。四语 SDK 的 `AgentSessionStart` 新增 `toolCommands`(Rust `tool_commands`、Go `ToolCommands`、Java `toolCommands()`、Node `toolCommands`);记录读取仍是普通 JSON 函数,无类型变化。没有新增宿主方法、错误码或能力版本。样例见 `fixtures/agents/native-session.json` 与 `fixtures/agents/record-read.json`。 | | [#245](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/245)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.stats` 新增可选 `splitBy`(`agent`/`model`/`provider`/`modelProvider`,在 `groupBy` 之后再拆一层,第二个键在 summary 的 `split`)、筛选 `models`、`providers`、`failed`、`search`(同时作用于 `summaries` 和 `speeds`)和 `detail`(每组增加 `speed` 速度中位数与 `firstToken` 平均首字耗时);`groupBy` 新增只给宿主的 `provider`、`modelProvider`、`all`。`agentSessions.calls` 新增 `models`、`providers`、`search`,与 stats 的筛选规则相同。新增错误码 `agentSessions.invalidSplit`、`agentSessions.invalidFilter`。`agents/usage`(插件)的分组和回答不变。旧 Core 把新字段当未知字段拒绝,把新分组名当 `agentSessions.invalidGroup` 拒绝。没有新增宿主方法、通知或能力版本。 | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index 767690a9..36ab1444 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -710,10 +710,17 @@ way, with the same 10 seconds and the same `agents.configuration` permission: where `change.op` is one of the declared `operations`, changes only the file at `staging` and answers `{format: "litheAgentProvidersEdit", version: 0, changed}`. -- Keys, headers and query parameters are reported by name only; a `baseUrl` - has no user, password, query or fragment. Neither function opens a CLI's - credential files (such as `auth.json` or `.credentials.json`) or the - system keychain. Core refuses any answer that breaks these rules. +- Keys are write-only: a `change` may carry a `key` (or `clearKey`) for + `edit` to write, and `read` reports only `keySet`, never the value; no + answer, error or log carries a key. Headers and query parameters are + reported by name only; a `baseUrl` has no user, password, query or + fragment. Neither function opens a CLI's credential files (such as + `auth.json` or `.credentials.json`) or the system keychain. Core refuses + any answer that breaks these rules. +- With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the + plugin keeps their keys with `lithe/host/credentials/*` under the + `credentials.store` permission; see the contract for the extra `change` + fields. ## Testing diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 3af41f1f..6491daae 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -677,10 +677,17 @@ way, with the same 10 seconds and the same `agents.configuration` permission: where `change.op` is one of the declared `operations`, changes only the file at `staging` and answers `{format: "litheAgentProvidersEdit", version: 0, changed}`. -- Keys, headers and query parameters are reported by name only; a `baseUrl` - has no user, password, query or fragment. Neither function opens a CLI's - credential files (such as `auth.json` or `.credentials.json`) or the - system keychain. Core refuses any answer that breaks these rules. +- Keys are write-only: a `change` may carry a `key` (or `clearKey`) for + `edit` to write, and `read` reports only `keySet`, never the value; no + answer, error or log carries a key. Headers and query parameters are + reported by name only; a `baseUrl` has no user, password, query or + fragment. Neither function opens a CLI's credential files (such as + `auth.json` or `.credentials.json`) or the system keychain. Core refuses + any answer that breaks these rules. +- With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the + plugin keeps their keys with `lithe/host/credentials/*` under the + `credentials.store` permission; see the contract for the extra `change` + fields. ## Testing diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 2b44c5f7..e57ef4dd 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -690,10 +690,17 @@ way, with the same 10 seconds and the same `agents.configuration` permission: where `change.op` is one of the declared `operations`, changes only the file at `staging` and answers `{format: "litheAgentProvidersEdit", version: 0, changed}`. -- Keys, headers and query parameters are reported by name only; a `baseUrl` - has no user, password, query or fragment. Neither function opens a CLI's - credential files (such as `auth.json` or `.credentials.json`) or the - system keychain. Core refuses any answer that breaks these rules. +- Keys are write-only: a `change` may carry a `key` (or `clearKey`) for + `edit` to write, and `read` reports only `keySet`, never the value; no + answer, error or log carries a key. Headers and query parameters are + reported by name only; a `baseUrl` has no user, password, query or + fragment. Neither function opens a CLI's credential files (such as + `auth.json` or `.credentials.json`) or the system keychain. Core refuses + any answer that breaks these rules. +- With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the + plugin keeps their keys with `lithe/host/credentials/*` under the + `credentials.store` permission; see the contract for the extra `change` + fields. ## Testing diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 8c764821..5a818d51 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -800,10 +800,17 @@ way, with the same 10 seconds and the same `agents.configuration` permission: where `change.op` is one of the declared `operations`, changes only the file at `staging` and answers `{format: "litheAgentProvidersEdit", version: 0, changed}`. -- Keys, headers and query parameters are reported by name only; a `baseUrl` - has no user, password, query or fragment. Neither function opens a CLI's - credential files (such as `auth.json` or `.credentials.json`) or the - system keychain. Core refuses any answer that breaks these rules. +- Keys are write-only: a `change` may carry a `key` (or `clearKey`) for + `edit` to write, and `read` reports only `keySet`, never the value; no + answer, error or log carries a key. Headers and query parameters are + reported by name only; a `baseUrl` has no user, password, query or + fragment. Neither function opens a CLI's credential files (such as + `auth.json` or `.credentials.json`) or the system keychain. Core refuses + any answer that breaks these rules. +- With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the + plugin keeps their keys with `lithe/host/credentials/*` under the + `credentials.store` permission; see the contract for the extra `change` + fields. ## Testing