diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 60f77ab1..8900fe4f 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -502,11 +502,13 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.stats` | Sum recorded agent usage with the latest rate limits; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs` | | `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | | `agentLibrary.configure` | Open the agent library in the platform's application data | -| `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold | +| `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | | `agentLibrary.save` | Replace the library the user edited if it is still at the revision read | | `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration | | `agentLibrary.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 | | `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 1f089040..57fe9d8c 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -10,11 +10,13 @@ //! Core knows no agent: every agent-specific name, argument, protocol and file //! layout comes from a plugin manifest and its backend. //! -//! The host drives the runtime with three command families. `agents.*` +//! The host drives the runtime with four command families. `agents.*` //! covers the catalog of declared agents and the live sessions; //! `agentSessions.*` covers the local session records; `agentLibrary.*` //! covers Lithe's library of MCP servers, hooks, skills and instructions and -//! applies them to the agents' own configuration (the `library` module). Backends reach it with +//! applies them to the agents' own configuration (the `library` module); +//! `agentProviders.*` reads and changes an agent's model, model providers +//! and profiles through the same staged copy. Backends reach it with //! `lithe/host/agents/*` requests, which the engine hands to the installed //! [`AgentHost`] and which never reach the host application. //! @@ -99,6 +101,9 @@ pub const AGENT_LIBRARY_COMMANDS: &[&str] = &[ "agentLibrary.removeSkill", ]; +/// The commands of the `agentProviders.*` family. +pub const AGENT_PROVIDER_COMMANDS: &[&str] = &["agentProviders.read", "agentProviders.apply"]; + /// The agent catalog, the live sessions, the session records and the /// agent library. pub(crate) struct Runtime { @@ -162,6 +167,8 @@ impl Runtime { "agentLibrary.apply" => self.library.apply(self, payload), "agentLibrary.importSkill" => self.library.import_skill(self, payload), "agentLibrary.removeSkill" => self.library.remove_skill(self, payload), + "agentProviders.read" => self.library.read_providers(self, payload), + "agentProviders.apply" => self.library.apply_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 f6f47665..25972ce4 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -28,10 +28,17 @@ //! - Instructions: Core writes the active instruction set and the agent's //! extra text, and refuses to replace text it did not write unless the user //! confirms. +//! - Model, providers and profiles (`providers` module): the same staged +//! copy, for the operations the manifest declares. //! //! Logs carry plugin and agent IDs, categories, counts and codes, never //! names, commands, paths or text. +mod providers; + +#[cfg(test)] +pub(crate) use providers::is_endpoint_for_test; + use crate::backend::BackendLink; use crate::catalog::CatalogAgent; use crate::{log, Runtime}; @@ -1086,6 +1093,14 @@ fn read_failure(failure: ReadFailure) -> CoreError { } } +fn backend_unavailable() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.backendUnavailable", + "The agent plugin's backend is not running.", + ) +} + fn invalid_change(message: &str) -> CoreError { refusal( ErrorCode::InvalidRequest, @@ -1136,6 +1151,36 @@ fn agent_paths(config: &Config, configuration: &ConfigurationDeclaration) -> Age } } +/// The `files` a read function receives: each declared file's ID, path and +/// whether it exists. +fn files_param(files: &[(String, PathBuf)]) -> Vec { + files + .iter() + .map(|(id, path)| { + json!({ + "id": id, + "path": path_text(path), + "exists": fs::symlink_metadata(path).is_ok(), + }) + }) + .collect() +} + +/// The declared files with `staging` standing in for the file `target`. +fn with_staged( + files: &[(String, PathBuf)], + target: &str, + staging: &Path, +) -> Vec<(String, PathBuf)> { + files + .iter() + .map(|(id, path)| { + let path = if id == target { staging } else { path }; + (id.clone(), path.to_path_buf()) + }) + .collect() +} + fn path_text(path: &Path) -> String { path.to_string_lossy().into_owned() } @@ -1161,24 +1206,8 @@ fn read_snapshot( }; let backend = link .session_for(&agent.plugin_id, function, None) - .ok_or_else(|| { - refusal( - ErrorCode::InvalidRequest, - "agentLibrary.backendUnavailable", - "The agent plugin's backend is not running.", - ) - })?; - let params = json!({ - "agentID": agent.agent.id, - "files": files - .iter() - .map(|(id, path)| json!({ - "id": id, - "path": path_text(path), - "exists": fs::symlink_metadata(path).is_ok(), - })) - .collect::>(), - }); + .ok_or_else(backend_unavailable)?; + let params = json!({ "agentID": agent.agent.id, "files": files_param(files) }); let answer = link .call( &backend, @@ -1236,9 +1265,125 @@ struct AgentView { // --------------------------------------------------------------------------- // Commands. -#[derive(Deserialize)] +/// Longest `query` of `agentLibrary.read`, in characters. +const MAX_QUERY_CHARS: usize = 256; + +/// Whether a library item is on for an agent (`present`) or not +/// (`missing`: off, a conflicting item of the same name, or unsupported). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Presence { + Present, + Missing, +} + +/// The order of the matches of `agentLibrary.read`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Sort { + /// By name, ignoring case. + Name, + /// By how many agents have the item on, most first, then by name. + AgentCount, +} + +/// `agentLibrary.read`'s optional filters. With none, the answer is the +/// whole library and has no `matches`. +#[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -struct EmptyRequest {} +struct ReadRequest { + /// Text the item's name or description contains, ignoring case. + #[serde(default)] + query: Option, + /// The agent key `presence` looks at; both come together. + #[serde(default)] + agent: Option, + #[serde(default)] + presence: Option, + #[serde(default)] + sort: Option, +} + +impl ReadRequest { + fn filters(&self) -> bool { + self.query.is_some() || self.agent.is_some() || self.sort.is_some() + } + + fn check(&self) -> Result<(), CoreError> { + let invalid = |message: &str| { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidFilter", + message, + ) + }; + if self + .query + .as_deref() + .is_some_and(|query| query.chars().count() > MAX_QUERY_CHARS || query.contains('\0')) + { + return Err(invalid("The query is at most 256 characters.")); + } + if self.agent.is_some() != self.presence.is_some() { + return Err(invalid( + "An agent filter names both the agent and the presence.", + )); + } + Ok(()) + } +} + +/// One library item as the filters see it. +struct Candidate<'a> { + key: &'a str, + /// The texts `query` looks in. + texts: Vec<&'a str>, + /// The item's state for each readable agent. + states: &'a Value, +} + +/// The keys of the items `request` keeps, in its order. +fn matching(request: &ReadRequest, candidates: Vec>) -> Vec { + let query = request.query.as_deref().map(str::to_lowercase); + let on = |states: &Value| { + states.as_object().map_or(0, |states| { + states.values().filter(|state| *state == "on").count() + }) + }; + let mut kept: Vec<(&str, usize)> = candidates + .into_iter() + .filter(|candidate| { + query.as_deref().is_none_or(|query| { + candidate + .texts + .iter() + .any(|text| text.to_lowercase().contains(query)) + }) + }) + .filter(|candidate| match (&request.agent, request.presence) { + (Some(agent), Some(presence)) => match candidate.states.get(agent.as_str()) { + Some(state) => (*state == "on") == (presence == Presence::Present), + // An agent whose configuration could not be read has no state. + None => false, + }, + _ => true, + }) + .map(|candidate| (candidate.key, on(candidate.states))) + .collect(); + let by_name = |left: &str, right: &str| { + left.to_lowercase() + .cmp(&right.to_lowercase()) + .then_with(|| left.cmp(right)) + }; + match request.sort { + Some(Sort::Name) => kept.sort_by(|left, right| by_name(left.0, right.0)), + Some(Sort::AgentCount) => { + kept.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| by_name(left.0, right.0))) + } + None => {} + } + kept.into_iter().map(|(key, _)| key.to_string()).collect() +} #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1403,9 +1548,13 @@ impl Library { /// `agentLibrary.read`: the library, its skills, and each agent that /// declares configuration with what its files hold. pub fn read(&self, runtime: &Runtime, payload: Value) -> Result { - let _: EmptyRequest = crate::decode(payload)?; + let request: ReadRequest = crate::decode(payload)?; + request.check()?; let started = Instant::now(); let config = self.config()?; + if let Some(key) = &request.agent { + configurable_agent(runtime, key)?; + } let (library, revision) = self.load(&config)?; let state = Self::load_state(&config); let skills = library_skills(&config.directory); @@ -1493,18 +1642,65 @@ impl Library { ("agents", json!(views.len())), ("failed", json!(failed)), ( - "duration", + "duration_ms", json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), ), ], ); - Ok(json!({ + // `library` stays whole, since `save` replaces all of it; the filters + // only choose and order item keys. + let matches = request.filters().then(|| { + let servers = library + .mcp_servers + .iter() + .map(|server| Candidate { + key: &server.name, + texts: vec![&server.name], + states: &server_states[&server.name], + }) + .collect(); + let hooks = library + .hooks + .iter() + .map(|hook| { + let mut texts = vec![hook.id.as_str(), &hook.event, &hook.command]; + texts.extend(hook.matcher.as_deref()); + Candidate { + key: &hook.id, + texts, + states: &hook_states[&hook.id], + } + }) + .collect(); + let skills = skill_rows + .iter() + .map(|row| { + let mut texts = vec![row["name"].as_str().unwrap_or_default()]; + texts.extend(row["description"].as_str()); + Candidate { + key: row["name"].as_str().unwrap_or_default(), + texts, + states: &row["agents"], + } + }) + .collect(); + json!({ + "mcpServers": matching(&request, servers), + "hooks": matching(&request, hooks), + "skills": matching(&request, skills), + }) + }); + let mut answer = json!({ "revision": revision, "library": library, "skills": skill_rows, "states": { "mcpServers": server_states, "hooks": hook_states }, "agents": views.into_iter().map(|view| view.entry).collect::>(), - })) + }); + if let Some(matches) = matches { + answer["matches"] = matches; + } + Ok(answer) } fn view( @@ -1695,7 +1891,7 @@ impl Library { ("change", json!(op.token())), ("changed", json!(changed)), ( - "duration", + "duration_ms", json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), ), ], @@ -1875,25 +2071,16 @@ impl Library { } }; - let real = real_file(&target_path)?; - let original = read_bounded(&real, MAX_CONFIGURATION_FILE_BYTES).map_err(read_failure)?; - let staging = self.stage(config, &real, original.as_deref())?; - let outcome = (|| { + let edit_file = |staging: &Path, exists: bool| -> Result { let backend = link .session_for(&agent.plugin_id, edit, None) - .ok_or_else(|| { - refusal( - ErrorCode::InvalidRequest, - "agentLibrary.backendUnavailable", - "The agent plugin's backend is not running.", - ) - })?; + .ok_or_else(backend_unavailable)?; let params = json!({ "agentID": agent.agent.id, "file": { "id": target_id, - "staging": path_text(&staging), - "exists": original.is_some(), + "staging": path_text(staging), + "exists": exists, }, "change": plugin_change, }); @@ -1916,7 +2103,44 @@ impl Library { "The agent plugin returned an invalid edit answer.", ) })?; - if !answer.changed { + Ok(answer.changed) + }; + // The plugin reads the staged copy in place of the file, which shows + // it can read what it wrote and that the change is there. + let shows_change = |staging: &Path| -> Result<(), CoreError> { + let staged_files = with_staged(&paths.files, &target_id, staging); + let staged = read_snapshot(link, agent, configuration, &staged_files)?; + if applied(&staged) { + Ok(()) + } else { + Err(refusal( + ErrorCode::ParseFailed, + "agentLibrary.editNotApplied", + "The agent plugin's edit did not make the change.", + )) + } + }; + self.edit_staged(config, &target_path, 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. + fn edit_staged( + &self, + config: &Config, + target: &Path, + edit: impl FnOnce(&Path, bool) -> Result, + shows_change: impl FnOnce(&Path) -> Result<(), CoreError>, + ) -> Result { + let real = real_file(target)?; + let original = read_bounded(&real, MAX_CONFIGURATION_FILE_BYTES).map_err(read_failure)?; + let staging = self.stage(config, &real, original.as_deref())?; + let outcome = (|| { + if !edit(&staging, original.is_some())? { return Ok(false); } let edited = read_bounded(&staging, MAX_CONFIGURATION_FILE_BYTES) @@ -1925,28 +2149,7 @@ impl Library { if original.as_deref() == Some(edited.as_slice()) { return Ok(false); } - - // The plugin reads the staged copy in place of the file, which - // shows it can read what it wrote and that the change is there. - let staged_files: Vec<(String, PathBuf)> = paths - .files - .iter() - .map(|(id, path)| { - if *id == target_id { - (id.clone(), staging.clone()) - } else { - (id.clone(), path.clone()) - } - }) - .collect(); - let staged = read_snapshot(link, agent, configuration, &staged_files)?; - if !applied(&staged) { - return Err(refusal( - ErrorCode::ParseFailed, - "agentLibrary.editNotApplied", - "The agent plugin's edit did not make the change.", - )); - } + shows_change(&staging)?; let _writing = self.lock_writing(); let now = read_bounded(&real, MAX_CONFIGURATION_FILE_BYTES).map_err(read_failure)?; diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs new file mode 100644 index 00000000..7de9cd47 --- /dev/null +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -0,0 +1,1012 @@ +//! An agent's model, model providers and profiles (`agentProviders.*`). +//! +//! A plugin that declares `configuration.providers` reads them from the +//! agent's declared files with its `read` function and changes one thing at +//! a time with its `edit` function, on a staged copy Core checks, exactly as +//! MCP servers and hooks change. Core knows no agent, variable or file +//! layout: every name comes from the plugin's answer. +//! +//! 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. +//! - 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::{ + agent_paths, backend_unavailable, check_name, configurable_agent, files_param, path_text, + refusal, require_user, with_staged, Check, 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_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +const READ_FORMAT: &str = "litheAgentProviders"; +const EDIT_FORMAT: &str = "litheAgentProvidersEdit"; + +const MAX_PROVIDERS: usize = 64; +const MAX_PROFILES: usize = 64; +const MAX_NAMES: usize = 64; +const MAX_ID_BYTES: usize = 128; +const MAX_TOKEN_BYTES: usize = 64; +const MAX_URL_BYTES: usize = 2048; +const MAX_PATH_BYTES: usize = 4096; + +// --------------------------------------------------------------------------- +// What a plugin reports. + +/// The configuration layer a value comes from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Layer { + /// The user's configuration file. + User, + /// A profile, named by `profile`. + Profile, + /// The CLI's own default. + Default, + /// An environment variable, named by `variable`. + Environment, +} + +/// Where a value comes from. `file` is a declared file's ID, to which Core +/// adds the `path` it resolved; `path` is an absolute path the plugin found +/// itself, shown as the plugin wrote it. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Source { + layer: Layer, + #[serde(default, skip_serializing_if = "Option::is_none")] + file: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + path: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + variable: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + profile: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CurrentModel { + id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CurrentProvider { + id: String, + /// The provider's display name; Core fills it from `providers` when the + /// plugin leaves it out. + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CurrentProfile { + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, +} + +/// One model provider. Its key, headers and query parameters are names only. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Provider { + id: String, + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + base_url: Option, + /// The wire protocol, as the CLI names it. + #[serde(default, skip_serializing_if = "Option::is_none")] + protocol: Option, + /// The environment variable the key is read from. + #[serde(default, skip_serializing_if = "Option::is_none")] + key_variable: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + header_names: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + query_parameter_names: Vec, + /// Absent when the CLI has no on/off switch for providers. + #[serde(default, skip_serializing_if = "Option::is_none")] + enabled: Option, + /// Built into the CLI: shown, never changed or removed. + #[serde(default)] + built_in: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Profile { + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, +} + +/// Who is signed in, as one label the plugin chose. Plugins never read +/// credential files or the keychain to find it. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Account { + label: String, +} + +/// The declared file a plugin changes for each kind of change. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProviderTargets { + #[serde(default, skip_serializing_if = "Option::is_none")] + providers: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + profile: Option, +} + +/// The answer of a providers `read` function. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProvidersSnapshot { + #[serde(skip_serializing)] + format: String, + #[serde(skip_serializing)] + version: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + cli_version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, + #[serde(default)] + providers: Vec, + #[serde(default)] + profiles: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + profile: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + account: Option, + /// Other environment variables the CLI reads, by name only. + #[serde(default)] + environment_names: Vec, + #[serde(default)] + targets: ProviderTargets, +} + +/// The answer of a providers `edit` function. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProvidersEditAnswer { + format: String, + version: u32, + changed: bool, +} + +// --------------------------------------------------------------------------- +// Checks. + +/// A provider ID: ASCII letters, digits, `-`, `_` and `.`, 1 to 128 bytes. +fn is_provider_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= MAX_ID_BYTES + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) +} + +/// A protocol or CLI version as the CLI names it: ASCII letters, digits, +/// `-`, `_`, `.` and `+`, 1 to 64 bytes. +fn is_token(token: &str) -> bool { + !token.is_empty() + && token.len() <= MAX_TOKEN_BYTES + && token + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '+')) +} + +/// An environment variable name: an ASCII letter or `_`, then ASCII +/// letters, digits and `_`, at most 128 bytes. +fn is_environment_name(name: &str) -> bool { + let mut chars = name.chars(); + chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && name.len() <= MAX_ID_BYTES + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// A header or query parameter name: ASCII letters, digits, `-`, `_` and +/// `.`, 1 to 128 bytes. +fn is_parameter_name(name: &str) -> bool { + is_provider_id(name) +} + +/// An endpoint URL: `http` or `https`, a host, no user or password, no query +/// and no fragment, no space or control character, at most 2048 bytes. +fn is_endpoint(url: &str) -> bool { + if url.len() > MAX_URL_BYTES + || url + .chars() + .any(|c| c.is_control() || c.is_whitespace() || c == '?' || c == '#') + { + return false; + } + let Some(rest) = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://")) + else { + return false; + }; + let authority = rest.split('/').next().unwrap_or_default(); + let host = authority.strip_prefix('[').map_or_else( + || authority.split(':').next().unwrap_or_default(), + |v6| v6.split(']').next().unwrap_or_default(), + ); + !authority.contains('@') && !host.is_empty() +} + +fn check_names(names: &[String], field: &str, valid: fn(&str) -> bool) -> Check { + if names.len() > MAX_NAMES { + return Err(field.to_string()); + } + let mut seen = BTreeSet::new(); + for (index, name) in names.iter().enumerate() { + if !valid(name) || !seen.insert(name.as_str()) { + return Err(format!("{field}[{index}]")); + } + } + Ok(()) +} + +impl Source { + fn check(&self, field: &str, file_ids: &BTreeSet<&str>) -> Check { + let invalid = |name: &str| Err(format!("{field}.{name}")); + if self.file.is_some() && self.path.is_some() { + return invalid("path"); + } + if self + .file + .as_deref() + .is_some_and(|id| !file_ids.contains(id)) + { + return invalid("file"); + } + if self.path.as_deref().is_some_and(|path| { + path.len() > MAX_PATH_BYTES + || path.chars().any(char::is_control) + || !Path::new(path).is_absolute() + }) { + return invalid("path"); + } + match (&self.layer, &self.variable) { + (Layer::Environment, Some(name)) if is_environment_name(name) => {} + (Layer::Environment, _) => return invalid("variable"), + (_, Some(_)) => return invalid("variable"), + (_, None) => {} + } + match (&self.layer, &self.profile) { + (Layer::Profile, Some(name)) => check_name(name, &format!("{field}.profile")), + (Layer::Profile, None) | (_, Some(_)) => invalid("profile"), + (_, None) => Ok(()), + } + } +} + +fn check_source(source: Option<&Source>, field: &str, file_ids: &BTreeSet<&str>) -> Check { + source.map_or(Ok(()), |source| source.check(field, file_ids)) +} + +/// The fields a provider and a change's provider share. +fn check_provider_fields( + field: &str, + id: &str, + name: &str, + base_url: Option<&str>, + protocol: Option<&str>, + key_variable: Option<&str>, +) -> Check { + if !is_provider_id(id) { + return Err(format!("{field}.id")); + } + check_name(name, &format!("{field}.name"))?; + if base_url.is_some_and(|url| !is_endpoint(url)) { + return Err(format!("{field}.baseUrl")); + } + if protocol.is_some_and(|protocol| !is_token(protocol)) { + return Err(format!("{field}.protocol")); + } + if key_variable.is_some_and(|name| !is_environment_name(name)) { + return Err(format!("{field}.keyVariable")); + } + Ok(()) +} + +impl ProvidersSnapshot { + fn check(&self, file_ids: &BTreeSet<&str>) -> Check { + if self.format != READ_FORMAT || self.version != 0 { + return Err("format".into()); + } + if self.cli_version.as_deref().is_some_and(|v| !is_token(v)) { + return Err("cliVersion".into()); + } + if let Some(model) = &self.model { + check_name(&model.id, "model.id")?; + check_source(model.source.as_ref(), "model.source", file_ids)?; + } + if let Some(provider) = &self.provider { + if !is_provider_id(&provider.id) { + return Err("provider.id".into()); + } + if let Some(name) = &provider.name { + check_name(name, "provider.name")?; + } + check_source(provider.source.as_ref(), "provider.source", file_ids)?; + } + if self.providers.len() > MAX_PROVIDERS { + return Err("providers".into()); + } + let mut ids = BTreeSet::new(); + for (index, provider) in self.providers.iter().enumerate() { + let field = format!("providers[{index}]"); + check_provider_fields( + &field, + &provider.id, + &provider.name, + provider.base_url.as_deref(), + provider.protocol.as_deref(), + provider.key_variable.as_deref(), + )?; + if !ids.insert(provider.id.as_str()) { + return Err(format!("{field}.id")); + } + check_names( + &provider.header_names, + &format!("{field}.headerNames"), + is_parameter_name, + )?; + check_names( + &provider.query_parameter_names, + &format!("{field}.queryParameterNames"), + is_parameter_name, + )?; + check_source( + provider.source.as_ref(), + &format!("{field}.source"), + file_ids, + )?; + } + if self.profiles.len() > MAX_PROFILES { + return Err("profiles".into()); + } + let mut names = BTreeSet::new(); + for (index, profile) in self.profiles.iter().enumerate() { + let field = format!("profiles[{index}]"); + check_name(&profile.name, &format!("{field}.name"))?; + if !names.insert(profile.name.as_str()) { + return Err(format!("{field}.name")); + } + if let Some(model) = &profile.model { + check_name(model, &format!("{field}.model"))?; + } + if profile + .provider + .as_deref() + .is_some_and(|id| !is_provider_id(id)) + { + return Err(format!("{field}.provider")); + } + check_source( + profile.source.as_ref(), + &format!("{field}.source"), + file_ids, + )?; + } + if let Some(profile) = &self.profile { + check_name(&profile.name, "profile.name")?; + check_source(profile.source.as_ref(), "profile.source", file_ids)?; + } + if let Some(account) = &self.account { + check_name(&account.label, "account.label")?; + } + check_names( + &self.environment_names, + "environmentNames", + is_environment_name, + )?; + for (field, target) in [ + ("targets.providers", &self.targets.providers), + ("targets.model", &self.targets.model), + ("targets.provider", &self.targets.provider), + ("targets.profile", &self.targets.profile), + ] { + if target.as_deref().is_some_and(|id| !file_ids.contains(id)) { + return Err(field.into()); + } + } + Ok(()) + } + + fn find(&self, id: &str) -> Option<&Provider> { + self.providers.iter().find(|provider| provider.id == id) + } +} + +// --------------------------------------------------------------------------- +// Changes. + +/// A provider as a change gives it: no headers or query parameters, which +/// the plugin keeps as they are. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProviderInput { + id: String, + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + base_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + protocol: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + key_variable: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + enabled: Option, +} + +impl ProviderInput { + /// Whether `provider` holds what this input asks for. + fn is_in(&self, provider: &Provider) -> bool { + provider.id == self.id + && provider.name == self.name + && provider.base_url == self.base_url + && provider.protocol == self.protocol + && provider.key_variable == self.key_variable + && self + .enabled + .is_none_or(|enabled| provider.enabled == Some(enabled)) + } +} + +/// 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 }, +} + +/// The file a change goes to. +#[derive(Debug, Clone, Copy)] +enum Target { + Providers, + Model, + Provider, + Profile, +} + +impl ProviderChange { + fn target(&self) -> Target { + match self { + Self::AddProvider { .. } + | Self::UpdateProvider { .. } + | Self::RemoveProvider { .. } + | Self::SetProviderEnabled { .. } => Target::Providers, + Self::SetModel { .. } => Target::Model, + Self::SetProvider { .. } => Target::Provider, + Self::SetProfile { .. } => Target::Profile, + } + } + + /// Checks the change's own fields; a bad endpoint has its own code. + fn check(&self) -> Result<(), CoreError> { + let fields = match self { + Self::AddProvider { provider } | Self::UpdateProvider { provider } => { + if provider + .base_url + .as_deref() + .is_some_and(|url| !is_endpoint(url)) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentProviders.invalidEndpoint", + "An endpoint is an http or https URL without a user, password, query or fragment.", + )); + } + check_provider_fields( + "provider", + &provider.id, + &provider.name, + None, + provider.protocol.as_deref(), + provider.key_variable.as_deref(), + ) + } + Self::RemoveProvider { id } + | Self::SetProviderEnabled { id, .. } + | Self::SetProvider { id } => { + if is_provider_id(id) { + Ok(()) + } else { + Err("id".into()) + } + } + Self::SetModel { model } => check_name(model, "model"), + Self::SetProfile { name } => check_name(name, "name"), + }; + fields.map_err(|field| invalid_change(&format!("The change's {field} is invalid."))) + } + + /// 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.", + ) + }; + 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.", + )); + } + Ok(provider) + }; + // A value an environment variable sets would hide the file's. + let overridden = |source: Option<&Source>| { + if source.is_some_and(|source| source.layer == Layer::Environment) { + Err(refusal( + ErrorCode::NotSupported, + "agentProviders.overridden", + "An environment variable sets this, so changing the file would not take effect.", + )) + } else { + Ok(()) + } + }; + match self { + 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.", + )); + } + } + Self::UpdateProvider { provider } => { + changeable(&provider.id)?; + } + Self::RemoveProvider { id } => { + changeable(id)?; + } + Self::SetProviderEnabled { id, .. } => { + if changeable(id)?.enabled.is_none() { + return Err(refusal( + ErrorCode::NotSupported, + "agentProviders.noEnabledState", + "The CLI has no on/off switch for this provider.", + )); + } + } + Self::SetModel { .. } => { + overridden(snapshot.model.as_ref().and_then(|m| m.source.as_ref()))?; + } + Self::SetProvider { id } => { + snapshot.find(id).ok_or_else(unknown_provider)?; + overridden(snapshot.provider.as_ref().and_then(|p| p.source.as_ref()))?; + } + Self::SetProfile { name } => { + if !snapshot + .profiles + .iter() + .any(|profile| profile.name == *name) + { + return Err(refusal( + ErrorCode::EntryNotFound, + "agentProviders.unknownProfile", + "The agent has no profile with this name.", + )); + } + overridden(snapshot.profile.as_ref().and_then(|p| p.source.as_ref()))?; + } + } + Ok(()) + } + + /// Whether a re-read staged copy holds the change. + fn shows_in(&self, snapshot: &ProvidersSnapshot) -> bool { + match self { + Self::AddProvider { provider } | Self::UpdateProvider { provider } => snapshot + .find(&provider.id) + .is_some_and(|found| provider.is_in(found)), + Self::RemoveProvider { id } => snapshot.find(id).is_none(), + Self::SetProviderEnabled { id, enabled } => snapshot + .find(id) + .is_some_and(|found| found.enabled == Some(*enabled)), + Self::SetModel { model } => snapshot.model.as_ref().is_some_and(|m| m.id == *model), + Self::SetProvider { id } => snapshot.provider.as_ref().is_some_and(|p| p.id == *id), + Self::SetProfile { name } => snapshot.profile.as_ref().is_some_and(|p| p.name == *name), + } + } +} + +fn invalid_change(message: &str) -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentProviders.invalidChange", + message, + ) +} + +// --------------------------------------------------------------------------- +// Plugin calls. + +/// The declared providers of a configurable agent. +fn declaration(agent: &CatalogAgent) -> Option<(&ConfigurationDeclaration, &ProvidersDeclaration)> { + let configuration = agent.agent.configuration.as_ref()?; + Some((configuration, configuration.providers.as_ref()?)) +} + +fn not_declared() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentProviders.notDeclared", + "The agent plugin does not report this agent's models and providers.", + ) +} + +fn read_providers( + link: &dyn BackendLink, + agent: &CatalogAgent, + configuration: &ConfigurationDeclaration, + declared: &ProvidersDeclaration, + files: &[(String, PathBuf)], +) -> Result { + let function = declared.read.as_str(); + let backend = link + .session_for(&agent.plugin_id, function, None) + .ok_or_else(backend_unavailable)?; + let params = json!({ "agentID": agent.agent.id, "files": files_param(files) }); + let answer = link + .call( + &backend, + &agent.plugin_id, + function, + params, + FUNCTION_TIMEOUT, + ) + .map_err(|_| { + refusal( + ErrorCode::ProcessFailed, + "agentProviders.readFailed", + "The agent plugin could not report the agent's models and providers.", + ) + })?; + let invalid = || { + refusal( + ErrorCode::ParseFailed, + "agentProviders.invalidSnapshot", + "The agent plugin returned invalid models or providers.", + ) + }; + let snapshot: ProvidersSnapshot = serde_json::from_value(answer).map_err(|_| invalid())?; + let ids: BTreeSet<&str> = configuration.files.iter().map(|f| f.id.as_str()).collect(); + snapshot.check(&ids).map_err(|_| invalid())?; + Ok(snapshot) +} + +/// The snapshot as the host sees it: each `source.file` gains the `path` +/// Core resolved for it, and the current provider its name. +fn snapshot_view(snapshot: &ProvidersSnapshot, files: &[(String, PathBuf)]) -> Value { + fn add_path(value: &mut Value, files: &[(String, PathBuf)]) { + match value { + Value::Object(map) => { + if let Some(Value::Object(source)) = map.get_mut("source") { + let path = source + .get("file") + .and_then(Value::as_str) + .and_then(|id| files.iter().find(|(file, _)| file == id)) + .map(|(_, path)| path_text(path)); + if let Some(path) = path { + source.insert("path".into(), json!(path)); + } + } + for (key, child) in map.iter_mut() { + if key != "source" { + add_path(child, files); + } + } + } + Value::Array(items) => items.iter_mut().for_each(|item| add_path(item, files)), + _ => {} + } + } + let mut view = json!(snapshot); + add_path(&mut view, files); + if let Some(current) = &snapshot.provider { + if current.name.is_none() { + if let Some(found) = snapshot.find(¤t.id) { + view["provider"]["name"] = json!(found.name); + } + } + } + view +} + +fn elapsed_ms(started: Instant) -> u64 { + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +// --------------------------------------------------------------------------- +// Commands. + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ReadRequest { + #[serde(default)] + agent: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ApplyRequest { + agent: String, + change: Value, +} + +impl Library { + /// `agentProviders.read`: each agent that declares providers (or the one + /// `agent` names) with its model, providers, profiles and account label. + pub fn read_providers(&self, runtime: &Runtime, payload: Value) -> Result { + let request: ReadRequest = crate::decode(payload)?; + let started = Instant::now(); + let config = self.config()?; + let agents = match &request.agent { + Some(key) => { + let agent = configurable_agent(runtime, key)?; + declaration(&agent).ok_or_else(not_declared)?; + vec![agent] + } + None => runtime + .catalog + .configurable() + .into_iter() + .filter(|agent| declaration(agent).is_some()) + .collect(), + }; + let mut failed = 0u64; + let entries: Vec = agents + .iter() + .map(|agent| { + let (configuration, declared) = declaration(agent).expect("filtered above"); + let mut entry = json!({ + "agent": agent.record_key(), + "pluginID": agent.plugin_id, + "agentID": agent.agent.id, + "displayName": agent.agent.display_name, + "mayConfigure": agent.may_configure, + "operations": declared.operations, + }); + 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 (Value::Object(entry), Value::Object(view)) = (&mut entry, view) { + entry.extend(view); + } + } + Err(error) => { + failed += 1; + let reason = error + .details + .as_deref() + .unwrap_or("agentProviders.readFailed"); + log( + "agent.providers.read_failed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("reason", json!(reason)), + ], + ); + entry["readError"] = json!(reason); + } + } + entry + }) + .collect(); + log( + "agent.providers.read_finished", + [ + ("agents", json!(entries.len())), + ("failed", json!(failed)), + ("duration_ms", json!(elapsed_ms(started))), + ], + ); + Ok(json!({ "agents": entries })) + } + + /// `agentProviders.apply`: one declared change to one agent's model, + /// providers or profile. + pub fn apply_providers(&self, runtime: &Runtime, payload: Value) -> Result { + require_user()?; + let request: ApplyRequest = crate::decode(payload)?; + let started = Instant::now(); + let agent = configurable_agent(runtime, &request.agent)?; + let op = request + .change + .get("op") + .and_then(Value::as_str) + .filter(|op| PROVIDER_OPERATIONS.contains(op)) + .unwrap_or("invalid") + .to_string(); + let outcome = self.apply_providers_checked(runtime, &agent, &op, request.change); + match &outcome { + Ok(changed) => log( + "agent.providers.change_applied", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("change", json!(op)), + ("changed", json!(changed)), + ("duration_ms", json!(elapsed_ms(started))), + ], + ), + Err(error) => log( + "agent.providers.change_failed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("change", json!(op)), + ( + "reason", + json!(error + .details + .as_deref() + .unwrap_or("agentProviders.applyFailed")), + ), + ], + ), + } + outcome.map(|changed| json!({ "changed": changed })) + } + + fn apply_providers_checked( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + op: &str, + change: Value, + ) -> Result { + let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; + if op == "invalid" { + return Err(invalid_change( + "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 { + 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 config = self.config()?; + let paths = agent_paths(&config, configuration); + let link = &*runtime.link; + let snapshot = read_providers(link, agent, configuration, declared, &paths.files)?; + change.check_against(&snapshot)?; + let target = match change.target() { + Target::Providers => snapshot.targets.providers.as_deref(), + Target::Model => snapshot.targets.model.as_deref(), + Target::Provider => snapshot.targets.provider.as_deref(), + Target::Profile => snapshot.targets.profile.as_deref(), + }; + let Some((target_id, target_path)) = target + .and_then(|id| paths.files.iter().find(|(file, _)| file == id)) + .cloned() + else { + return Err(refusal( + ErrorCode::NotSupported, + "agentProviders.noTarget", + "The agent keeps no editable file for this change.", + )); + }; + + let edit_file = |staging: &Path, exists: bool| -> Result { + let backend = link + .session_for(&agent.plugin_id, edit, None) + .ok_or_else(backend_unavailable)?; + let params = json!({ + "agentID": agent.agent.id, + "file": { "id": target_id, "staging": path_text(staging), "exists": exists }, + "change": change, + }); + let answer = link + .call(&backend, &agent.plugin_id, edit, params, FUNCTION_TIMEOUT) + .map_err(|_| { + refusal( + ErrorCode::ProcessFailed, + "agentProviders.editFailed", + "The agent plugin could not change the agent's models or providers.", + ) + })?; + let answer: ProvidersEditAnswer = serde_json::from_value(answer) + .ok() + .filter(|answer: &ProvidersEditAnswer| { + answer.format == EDIT_FORMAT && answer.version == 0 + }) + .ok_or_else(|| { + refusal( + ErrorCode::ParseFailed, + "agentProviders.invalidEdit", + "The agent plugin returned an invalid edit answer.", + ) + })?; + Ok(answer.changed) + }; + 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) { + Ok(()) + } else { + Err(refusal( + ErrorCode::ParseFailed, + "agentProviders.editNotApplied", + "The agent plugin's edit did not make the change.", + )) + } + }; + self.edit_staged(&config, &target_path, edit_file, shows_change) + } +} + +#[cfg(test)] +pub(crate) fn is_endpoint_for_test(url: &str) -> bool { + is_endpoint(url) +} diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index 3bd19211..0e915915 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -958,7 +958,7 @@ fn finish(runtime: &Arc, session: &Arc) { ("session", json!(session.id)), ("reason", json!(reason.token())), ( - "duration", + "duration_ms", json!(u64::try_from(session.started.elapsed().as_millis()).unwrap_or(u64::MAX)), ), ]; diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index a773780b..0d204abc 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -254,7 +254,7 @@ impl Records { ("files_read", report["filesRead"].clone()), ("files_failed", report["filesFailed"].clone()), ( - "duration", + "duration_ms", json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), ), ], diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index d75e1558..8b744297 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -2287,6 +2287,7 @@ fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { } mod library; +mod providers; #[test] fn turn_interaction_follows_the_shared_application_fixture() { diff --git a/rust/crates/agent-runtime/src/tests/library.rs b/rust/crates/agent-runtime/src/tests/library.rs index 0db77e55..eebe140c 100644 --- a/rust/crates/agent-runtime/src/tests/library.rs +++ b/rust/crates/agent-runtime/src/tests/library.rs @@ -638,6 +638,92 @@ fn skill_front_matter_and_instruction_text_are_read_as_written() { assert_eq!(compose_for_test(library, "a/c"), ""); } +#[test] +fn library_read_filters_and_sorts_item_keys_and_keeps_the_library_whole() { + let test = LibraryTest::new("library filters", CONFIGURATION_GRANTS); + test.save(library_with( + json!([ + { "name": "beta-web", "transport": "http", "url": "https://beta.example.test/mcp" }, + { "name": "alpha-docs", "transport": "stdio", "command": "alpha-docs" }, + { "name": "Alpha-files", "transport": "stdio", "command": "alpha-files" } + ]), + json!([ + { "id": "check-on-stop", "event": "Stop", "command": "beta-check" }, + { "id": "guard", "event": "PreToolUse", "command": "alpha-guard", "matcher": "Write" } + ]), + )); + let (changed, logs) = capture::run(false, || { + test.apply(json!({ "category": "mcpServers", "op": "put", "name": "beta-web" })) + }); + assert!(changed); + assert!( + logs.iter() + .any(|log| log.event == "agent.library.change_applied" + && log.fields.contains_key("duration_ms")), + "the change is logged with its duration" + ); + assert!(test.apply(json!({ "category": "hooks", "op": "put", "id": "guard" }))); + + let whole = test.read(); + assert!( + whole.get("matches").is_none(), + "without filters the answer is as before" + ); + let read = |request: Value| test.harness.run("agentLibrary.read", request); + let filtered = read(json!({ "query": "ALPHA" })); + assert_eq!( + filtered["library"], whole["library"], + "the library stays whole" + ); + assert_eq!(filtered["states"], whole["states"]); + assert_eq!( + filtered["matches"], + json!({ "mcpServers": ["alpha-docs", "Alpha-files"], "hooks": ["guard"], "skills": [] }), + "without a sort the library order is kept; hooks match their command" + ); + assert_eq!( + read(json!({ "query": "write" }))["matches"]["hooks"], + json!(["guard"]), + "a hook's matcher is searched" + ); + assert_eq!( + read(json!({ "agent": AGENT_KEY, "presence": "present" }))["matches"], + json!({ "mcpServers": ["beta-web"], "hooks": ["guard"], "skills": [] }) + ); + assert_eq!( + read(json!({ "agent": AGENT_KEY, "presence": "missing", "sort": "name" }))["matches"], + json!({ "mcpServers": ["alpha-docs", "Alpha-files"], "hooks": ["check-on-stop"], "skills": [] }) + ); + assert_eq!( + read(json!({ "sort": "name" }))["matches"]["mcpServers"], + json!(["alpha-docs", "Alpha-files", "beta-web"]) + ); + assert_eq!( + read(json!({ "sort": "agentCount" }))["matches"]["mcpServers"], + json!(["beta-web", "alpha-docs", "Alpha-files"]) + ); + + let refused = |request: Value| test.harness.refused("agentLibrary.read", request); + assert_eq!( + refused(json!({ "agent": AGENT_KEY })), + "agentLibrary.invalidFilter" + ); + assert_eq!( + refused(json!({ "presence": "present" })), + "agentLibrary.invalidFilter" + ); + assert_eq!( + refused(json!({ "query": "a".repeat(257) })), + "agentLibrary.invalidFilter" + ); + assert_eq!( + refused(json!({ "agent": "dev.lithe.test.agents/absent", "presence": "present" })), + "agentLibrary.unknownAgent" + ); + assert_eq!(refused(json!({ "sort": "size" })), "agents.invalidPayload"); + assert_eq!(refused(json!({ "limit": 1 })), "agents.invalidPayload"); +} + #[test] fn malformed_requests_and_a_damaged_library_file_are_refused_each_with_its_own_code() { let test = LibraryTest::new("library refusals", CONFIGURATION_GRANTS); diff --git a/rust/crates/agent-runtime/src/tests/providers.rs b/rust/crates/agent-runtime/src/tests/providers.rs new file mode 100644 index 00000000..3836ddd3 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers.rs @@ -0,0 +1,636 @@ +//! An agent's model, providers and profiles: what Core lets a plugin report, +//! the operations it declares, and changes through a staged copy. + +use super::*; + +const PROVIDER_GRANTS: &[&str] = &[ + "agents.native", + "agents.run", + "agents.sessions.read", + "agents.configuration", + "backend.launch", +]; + +const ALL_OPERATIONS: &[&str] = &[ + "addProvider", + "updateProvider", + "removeProvider", + "setProviderEnabled", + "setModel", + "setProvider", + "setProfile", +]; + +/// The synthetic plugin with providers declared for its agent, editing only +/// `operations`. +fn providers_manifest(operations: &[&str]) -> Value { + let mut manifest = manifest(); + manifest["permissions"] = json!(PROVIDER_GRANTS); + manifest["agents"][0]["configuration"] = json!({ + "files": [{ "id": "main", "roots": ["${userHome}/.sample/config.json"] }], + "providers": { + "read": "providers.read", + "edit": "providers.edit", + "operations": operations + } + }); + manifest +} + +fn read_json(path: &Path) -> Value { + match fs::read(path) { + Ok(bytes) if !bytes.is_empty() => serde_json::from_slice(&bytes).expect("JSON"), + _ => json!({}), + } +} + +/// The synthetic plugin's `providers.read`. Its file keeps providers by ID, +/// profiles by name and an `env` table; an endpoint in `env` is reported as +/// a provider's typed endpoint and every other variable by name only. +fn providers_read(params: &Value) -> Result { + let file = params["files"] + .as_array() + .and_then(|files| files.iter().find(|file| file["id"] == "main")) + .ok_or_else(|| failure("plugin.params.invalid"))?; + let config = read_json(Path::new(file["path"].as_str().unwrap())); + let user = json!({ "layer": "user", "file": "main" }); + let mut providers = vec![json!({ + "id": "local", "name": "Local", "protocol": "chat", "builtIn": true + })]; + if let Some(table) = config["providers"].as_object() { + for (id, provider) in table { + let mut row = provider.clone(); + row["id"] = json!(id); + row["source"] = user.clone(); + providers.push(row); + } + } + let env = config["env"].as_object().cloned().unwrap_or_default(); + if let Some(url) = env.get("BETA_BASE_URL") { + providers.push(json!({ + "id": "beta", "name": "Beta", "baseUrl": url, "keyVariable": "BETA_TOKEN", + "source": { "layer": "environment", "variable": "BETA_BASE_URL" } + })); + } + let environment_names: Vec<&String> = + env.keys().filter(|name| *name != "BETA_BASE_URL").collect(); + let model = match (env.get("ALPHA_MODEL"), config["model"].as_str()) { + (Some(model), _) => json!({ + "id": model, "source": { "layer": "environment", "variable": "ALPHA_MODEL" } + }), + (None, Some(model)) => json!({ "id": model, "source": user }), + (None, None) => json!({ "id": "alpha-default", "source": { "layer": "default" } }), + }; + let profiles: Vec = config["profiles"] + .as_object() + .map(|table| { + table + .iter() + .map(|(name, profile)| { + let mut row = profile.clone(); + row["name"] = json!(name); + row["source"] = json!({ "layer": "user", "path": "/etc/sample/profiles.json" }); + row + }) + .collect() + }) + .unwrap_or_default(); + let mut answer = json!({ + "format": "litheAgentProviders", + "version": 0, + "cliVersion": "1.2.3", + "model": model, + "providers": providers, + "profiles": profiles, + "account": { "label": "Signed in with a subscription" }, + "environmentNames": environment_names, + "targets": { "providers": "main", "model": "main", "provider": "main", "profile": "main" } + }); + if let Some(provider) = config["provider"].as_str() { + answer["provider"] = json!({ "id": provider, "source": user }); + } + if let Some(profile) = config["profile"].as_str() { + answer["profile"] = json!({ "name": profile, "source": user }); + } + Ok(answer) +} + +/// How the synthetic plugin's `providers.edit` behaves. +#[derive(Clone, Copy)] +enum Edit { + Apply, + /// Reports a change but writes something else. + Wrong, +} + +fn providers_edit(params: &Value, edit: Edit) -> 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"]; + match change["op"].as_str().unwrap() { + "addProvider" | "updateProvider" => { + let mut provider = change["provider"].clone(); + let id = provider["id"].as_str().unwrap().to_string(); + provider.as_object_mut().unwrap().remove("id"); + config["providers"][id.as_str()] = provider; + } + "removeProvider" => { + config["providers"] + .as_object_mut() + .unwrap() + .remove(change["id"].as_str().unwrap()); + } + "setProviderEnabled" => { + config["providers"][change["id"].as_str().unwrap()]["enabled"] = + change["enabled"].clone(); + } + "setModel" => config["model"] = change["model"].clone(), + "setProvider" => config["provider"] = change["id"].clone(), + "setProfile" => config["profile"] = change["name"].clone(), + _ => return Err(failure("plugin.params.invalid")), + } + if let Edit::Wrong = edit { + config = json!({ "noise": true }); + } + 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 ProvidersTest { + harness: Harness, + edit: Arc>, + /// An answer `providers.read` gives in place of reading the file. + answer: Arc>>, + home: PathBuf, + library: PathBuf, +} + +impl ProvidersTest { + fn new(name: &str, grants: &[&str], operations: &[&str]) -> Self { + let harness = Harness::new(name, ALL_GRANTS); + harness.run( + "agents.configure", + json!({ "plugins": [{ "manifest": providers_manifest(operations), "grantedPermissions": grants }] }), + ); + let home = harness.dir.path().join("home"); + let library = harness.dir.path().join("library"); + harness.run( + "agentLibrary.configure", + json!({ "directory": path_text(&library), "userHome": path_text(&home) }), + ); + let edit = Arc::new(Mutex::new(Edit::Apply)); + let answer: Arc>> = Arc::new(Mutex::new(None)); + let (current_edit, current_answer) = (edit.clone(), answer.clone()); + harness + .link + .set_answer(move |function, params| match function { + "providers.read" => match current_answer.lock().unwrap().clone() { + Some(answer) => Ok(answer), + None => providers_read(params), + }, + "providers.edit" => providers_edit(params, *current_edit.lock().unwrap()), + other => sample_backend(other, params), + }); + fs::create_dir_all(home.join(".sample")).unwrap(); + Self { + harness, + edit, + answer, + home, + library, + } + } + + fn config_file(&self) -> PathBuf { + self.home.join(".sample").join("config.json") + } + + fn write_config(&self, config: Value) { + fs::write(self.config_file(), serde_json::to_vec(&config).unwrap()).unwrap(); + } + + fn read(&self) -> Value { + self.harness + .run("agentProviders.read", json!({ "agent": AGENT_KEY }))["agents"][0] + .clone() + } + + fn apply(&self, change: Value) -> bool { + self.harness.run( + "agentProviders.apply", + json!({ "agent": AGENT_KEY, "change": change }), + )["changed"] + .as_bool() + .unwrap() + } + + fn refused(&self, change: Value) -> String { + self.harness.refused( + "agentProviders.apply", + json!({ "agent": AGENT_KEY, "change": change }), + ) + } + + /// The `readError` of an answer `providers.read` gives. + fn read_error(&self, answer: Value) -> Value { + *self.answer.lock().unwrap() = Some(answer); + let error = self.read()["readError"].clone(); + *self.answer.lock().unwrap() = None; + error + } + + fn staged_files(&self) -> usize { + fs::read_dir(self.library.join("staging")).map_or(0, |entries| entries.count()) + } +} + +fn sample_config() -> Value { + json!({ + "model": "alpha-large", + "provider": "alpha", + "providers": { + "alpha": { + "name": "Alpha", "baseUrl": "https://alpha.example.test/v1", + "protocol": "responses", "keyVariable": "ALPHA_API_KEY", "enabled": true + } + }, + "profiles": { "work": { "model": "beta-small", "provider": "beta" } }, + "env": { "BETA_BASE_URL": "https://beta.example.test", "BETA_TOKEN": "beta-secret-value" } + }) +} + +fn snapshot(extra: Value) -> Value { + let mut answer = json!({ + "format": "litheAgentProviders", + "version": 0, + "providers": [{ "id": "alpha", "name": "Alpha" }] + }); + for (key, value) in extra.as_object().unwrap() { + answer[key.as_str()] = value.clone(); + } + answer +} + +#[test] +fn providers_are_read_with_their_sources_and_names_only() { + let test = ProvidersTest::new("providers read", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let agent = test.read(); + let config_path = path_text(&test.config_file()); + assert_eq!(agent["agent"], AGENT_KEY); + assert_eq!(agent["mayConfigure"], true); + assert_eq!(agent["operations"], json!(ALL_OPERATIONS)); + assert_eq!(agent["cliVersion"], "1.2.3"); + assert_eq!(agent["model"]["id"], "alpha-large"); + assert_eq!( + agent["model"]["source"], + json!({ "layer": "user", "file": "main", "path": config_path }), + "Core adds the path it resolved for a declared file" + ); + assert_eq!( + agent["provider"]["name"], "Alpha", + "the current provider's name comes from the list" + ); + let providers = agent["providers"].as_array().unwrap(); + assert_eq!(providers.len(), 3); + assert_eq!(providers[0]["builtIn"], true); + assert_eq!(providers[1]["keyVariable"], "ALPHA_API_KEY"); + assert_eq!( + providers[2]["baseUrl"], "https://beta.example.test", + "an endpoint kept in the environment table is a typed endpoint" + ); + assert_eq!(providers[2]["source"]["variable"], "BETA_BASE_URL"); + assert_eq!( + agent["profiles"][0]["source"]["path"], "/etc/sample/profiles.json", + "a path the plugin found is shown as written" + ); + assert_eq!(agent["environmentNames"], json!(["BETA_TOKEN"])); + assert_eq!(agent["account"]["label"], "Signed in with a subscription"); + assert_eq!(agent["files"][0]["path"], config_path); + assert!( + !agent.to_string().contains("beta-secret-value"), + "a variable's value never reaches the host" + ); + + let listed = test.harness.run("agentProviders.read", json!({})); + assert_eq!(listed["agents"].as_array().unwrap().len(), 1); + + let not_granted = ProvidersTest::new("providers not granted", ALL_GRANTS, ALL_OPERATIONS); + let entry = not_granted.harness.run("agentProviders.read", json!({}))["agents"][0].clone(); + assert_eq!(entry["mayConfigure"], false); + assert!(entry.get("providers").is_none()); + assert!(not_granted + .harness + .link + .calls_of("providers.read") + .is_empty()); +} + +#[test] +fn answers_that_could_carry_secrets_or_exceed_limits_are_refused() { + let test = ProvidersTest::new("providers privacy", PROVIDER_GRANTS, ALL_OPERATIONS); + let invalid = json!("agentProviders.invalidSnapshot"); + let provider = |extra: Value| { + let mut row = json!({ "id": "alpha", "name": "Alpha" }); + for (key, value) in extra.as_object().unwrap() { + row[key.as_str()] = value.clone(); + } + snapshot(json!({ "providers": [row] })) + }; + for (case, answer) in [ + ("a key value", provider(json!({ "apiKey": "alpha-secret" }))), + ( + "header values", + provider(json!({ "headers": { "X-Alpha": "secret" } })), + ), + ( + "a header value as a name", + provider(json!({ "headerNames": ["Bearer alpha-secret"] })), + ), + ( + "a key value as a variable", + provider(json!({ "keyVariable": "sk-alpha-secret" })), + ), + ( + "a user and password", + provider(json!({ "baseUrl": "https://user:pass@alpha.example.test" })), + ), + ( + "a query", + provider(json!({ "baseUrl": "https://alpha.example.test/v1?key=secret" })), + ), + ( + "a fragment", + provider(json!({ "baseUrl": "https://alpha.example.test/v1#token" })), + ), + ( + "another scheme", + provider(json!({ "baseUrl": "file:///etc/alpha" })), + ), + ("a long name", provider(json!({ "name": "a".repeat(129) }))), + ( + "too many providers", + snapshot( + json!({ "providers": (0..65).map(|i| json!({ "id": format!("p{i}"), "name": "P" })).collect::>() }), + ), + ), + ( + "too many names", + snapshot( + json!({ "environmentNames": (0..65).map(|i| format!("ALPHA_{i}")).collect::>() }), + ), + ), + ( + "a repeated ID", + snapshot( + json!({ "providers": [{ "id": "alpha", "name": "A" }, { "id": "alpha", "name": "B" }] }), + ), + ), + ( + "an undeclared file", + snapshot( + json!({ "model": { "id": "alpha-large", "source": { "layer": "user", "file": "other" } } }), + ), + ), + ( + "a relative path", + snapshot( + json!({ "model": { "id": "alpha-large", "source": { "layer": "user", "path": "config.json" } } }), + ), + ), + ( + "an environment layer without its variable", + snapshot( + json!({ "model": { "id": "alpha-large", "source": { "layer": "environment" } } }), + ), + ), + ( + "an undeclared target", + snapshot(json!({ "targets": { "model": "other" } })), + ), + ( + "another format", + snapshot(json!({ "format": "litheAgentConfiguration" })), + ), + ] { + assert_eq!(test.read_error(answer), invalid, "{case}"); + } + let accepted = test.read_error(provider(json!({ + "baseUrl": "http://[::1]:8080/v1", + "headerNames": ["X-Alpha-Key"], + "queryParameterNames": ["api-version"] + }))); + assert!(accepted.is_null(), "names and a clean endpoint pass"); + + use crate::library::is_endpoint_for_test as is_endpoint; + assert!(is_endpoint("https://alpha.example.test")); + assert!(is_endpoint("http://127.0.0.1:4000/v1/")); + assert!(!is_endpoint("https://")); + assert!(!is_endpoint("https://@alpha.example.test")); + assert!(!is_endpoint("https://alpha.example.test/a b")); + assert!(!is_endpoint(&format!( + "https://alpha.example.test/{}", + "a".repeat(2048) + ))); +} + +#[test] +fn changes_go_through_a_checked_staged_copy() { + let test = ProvidersTest::new("providers changes", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let file = test.config_file(); + + let (changed, logs) = capture::run(false, || { + test.apply(json!({ "op": "addProvider", "provider": { + "id": "gamma", "name": "Gamma", "baseUrl": "https://gamma.example.test/v1", + "protocol": "chat", "keyVariable": "GAMMA_API_KEY", "enabled": false + } })) + }); + assert!(changed); + let applied = logs + .iter() + .find(|log| log.event == "agent.providers.change_applied") + .expect("the change is logged"); + assert_eq!(applied.fields["change"], json!("addProvider")); + assert!(applied.fields.contains_key("duration_ms")); + assert!(!format!("{:?}", applied.fields).contains("gamma.example")); + assert_eq!(read_json(&file)["providers"]["gamma"]["name"], "Gamma"); + assert_eq!( + read_json(&file)["env"]["BETA_TOKEN"], + "beta-secret-value", + "the plugin keeps what it does not change" + ); + let edits = test.harness.link.calls_of("providers.edit"); + assert!(PathBuf::from(edits[0]["file"]["staging"].as_str().unwrap()) + .starts_with(test.library.join("staging"))); + assert_eq!(test.staged_files(), 0); + + assert!(test.apply(json!({ "op": "updateProvider", "provider": { + "id": "gamma", "name": "Gamma Two", "baseUrl": "https://gamma.example.test/v2" + } }))); + assert!(test.apply(json!({ "op": "setProviderEnabled", "id": "alpha", "enabled": false }))); + assert!(!test.apply(json!({ "op": "setProviderEnabled", "id": "alpha", "enabled": false }))); + assert!(test.apply(json!({ "op": "setModel", "model": "alpha-small" }))); + assert!(test.apply(json!({ "op": "setProvider", "id": "gamma" }))); + assert!(test.apply(json!({ "op": "setProfile", "name": "work" }))); + assert!(test.apply(json!({ "op": "removeProvider", "id": "gamma" }))); + let agent = test.read(); + assert_eq!(agent["model"]["id"], "alpha-small"); + assert_eq!(agent["profile"]["name"], "work"); + assert!(agent["providers"] + .as_array() + .unwrap() + .iter() + .all(|provider| provider["id"] != "gamma")); + + let expect = |change: Value, code: &str| assert_eq!(test.refused(change), code); + expect( + json!({ "op": "addProvider", "provider": { "id": "alpha", "name": "Alpha" } }), + "agentProviders.providerExists", + ); + expect( + json!({ "op": "removeProvider", "id": "local" }), + "agentProviders.builtInProvider", + ); + expect( + json!({ "op": "updateProvider", "provider": { "id": "absent", "name": "A" } }), + "agentProviders.unknownProvider", + ); + expect( + json!({ "op": "setProvider", "id": "absent" }), + "agentProviders.unknownProvider", + ); + expect( + json!({ "op": "setProviderEnabled", "id": "beta", "enabled": true }), + "agentProviders.noEnabledState", + ); + expect( + json!({ "op": "setProfile", "name": "absent" }), + "agentProviders.unknownProfile", + ); + expect( + json!({ "op": "addProvider", "provider": { "id": "delta", "name": "Delta", "baseUrl": "https://delta.example.test/?key=secret" } }), + "agentProviders.invalidEndpoint", + ); + expect( + json!({ "op": "addProvider", "provider": { "id": "delta", "name": "Delta", "apiKey": "secret" } }), + "agentProviders.invalidChange", + ); + expect( + json!({ "op": "addProvider", "provider": { "id": "delta", "name": "Delta", "keyVariable": "delta secret" } }), + "agentProviders.invalidChange", + ); + expect(json!({ "op": "setModel" }), "agentProviders.invalidChange"); + expect(json!({ "op": "rename" }), "agentProviders.invalidChange"); + + let mut config = read_json(&file); + config["env"]["ALPHA_MODEL"] = json!("alpha-env"); + test.write_config(config); + expect( + json!({ "op": "setModel", "model": "alpha-large" }), + "agentProviders.overridden", + ); + + let before = fs::read(&file).unwrap(); + *test.edit.lock().unwrap() = Edit::Wrong; + expect( + json!({ "op": "setProvider", "id": "alpha" }), + "agentProviders.editNotApplied", + ); + assert_eq!( + fs::read(&file).unwrap(), + before, + "a wrong edit never reaches the file" + ); + assert_eq!(test.staged_files(), 0); + + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let background = test.refused(json!({ "op": "setProvider", "id": "alpha" })); + trace::replace(previous); + assert_eq!(background, "agentLibrary.userActionRequired"); +} + +#[test] +fn only_declared_operations_and_declaring_agents_are_served() { + let test = ProvidersTest::new("providers declared", PROVIDER_GRANTS, &["setModel"]); + test.write_config(sample_config()); + assert_eq!(test.read()["operations"], json!(["setModel"])); + let (refused, logs) = capture::run(false, || { + test.refused(json!({ "op": "removeProvider", "id": "alpha" })) + }); + assert_eq!(refused, "agentProviders.unsupportedOperation"); + let failed = logs + .iter() + .find(|log| log.event == "agent.providers.change_failed") + .expect("the refusal is logged"); + assert_eq!( + failed.fields["reason"], + json!("agentProviders.unsupportedOperation") + ); + assert!( + test.harness.link.calls_of("providers.edit").is_empty(), + "an undeclared operation never reaches the plugin" + ); + assert!(test.apply(json!({ "op": "setModel", "model": "alpha-small" }))); + + let library = LibraryHarness::without_providers(); + assert_eq!( + library.run("agentProviders.read", json!({}))["agents"], + json!([]) + ); + assert_eq!( + library.refused("agentProviders.read", json!({ "agent": AGENT_KEY })), + "agentProviders.notDeclared" + ); + assert_eq!( + library.refused( + "agentProviders.apply", + json!({ "agent": AGENT_KEY, "change": { "op": "setModel", "model": "alpha-small" } }), + ), + "agentProviders.notDeclared" + ); + assert_eq!( + library.refused( + "agentProviders.read", + json!({ "agent": AGENT_KEY, "extra": 1 }) + ), + "agents.invalidPayload" + ); + + let unconfigured = Harness::new("providers unconfigured", ALL_GRANTS); + assert_eq!( + unconfigured.refused("agentProviders.read", json!({})), + "agentLibrary.notConfigured" + ); +} + +/// A harness whose agent declares configuration files but no providers. +struct LibraryHarness; + +impl LibraryHarness { + fn without_providers() -> Harness { + let harness = Harness::new("providers undeclared", ALL_GRANTS); + let mut manifest = manifest(); + manifest["permissions"] = json!(PROVIDER_GRANTS); + manifest["agents"][0]["configuration"] = json!({ + "instructions": { "roots": ["${userHome}/.sample/INSTRUCTIONS.md"] } + }); + harness.run( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": PROVIDER_GRANTS }] }), + ); + let dir = harness.dir.path().to_path_buf(); + harness.run( + "agentLibrary.configure", + json!({ "directory": path_text(&dir.join("library")), "userHome": path_text(&dir.join("home")) }), + ); + harness + } +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index f2a3d780..515ac6d5 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -276,6 +276,10 @@ pub enum AgentsCommand { LibraryImportSkill, /// Removes a library skill and its links (`agentLibrary.removeSkill`). LibraryRemoveSkill, + /// Reads each agent's model, providers and profiles (`agentProviders.read`). + ProvidersRead, + /// Applies one declared model or provider change (`agentProviders.apply`). + ProvidersApply, } impl AgentsCommand { @@ -309,6 +313,8 @@ impl AgentsCommand { Self::LibraryApply => "agentLibrary.apply", Self::LibraryImportSkill => "agentLibrary.importSkill", Self::LibraryRemoveSkill => "agentLibrary.removeSkill", + Self::ProvidersRead => "agentProviders.read", + Self::ProvidersApply => "agentProviders.apply", } } } @@ -1318,6 +1324,8 @@ impl CoreCommand { "agentLibrary.apply" => Some(Self::Agents(AgentsCommand::LibraryApply)), "agentLibrary.importSkill" => Some(Self::Agents(AgentsCommand::LibraryImportSkill)), "agentLibrary.removeSkill" => Some(Self::Agents(AgentsCommand::LibraryRemoveSkill)), + "agentProviders.read" => Some(Self::Agents(AgentsCommand::ProvidersRead)), + "agentProviders.apply" => Some(Self::Agents(AgentsCommand::ProvidersApply)), "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } diff --git a/rust/crates/core/src/runtime/dispatcher/agents.rs b/rust/crates/core/src/runtime/dispatcher/agents.rs index 80150192..d35ea35f 100644 --- a/rust/crates/core/src/runtime/dispatcher/agents.rs +++ b/rust/crates/core/src/runtime/dispatcher/agents.rs @@ -1,4 +1,4 @@ -//! `agents.*`, `agentSessions.*` and `agentLibrary.*` commands, run by +//! `agents.*`, `agentSessions.*`, `agentLibrary.*` and `agentProviders.*` commands, run by //! `lithe-agent-runtime` (plan API-45). use crate::protocol::{AgentsCommand, CoreResponse}; diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 61ca9709..0034b81c 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -322,7 +322,8 @@ fn agents_are_reviewed_programs() { "files": [{"id": "main", "roots": ["${userHome}/.example/config.json"]}], "editable": true, "instructions": ["${env:EXAMPLE_HOME}/INSTRUCTIONS.md", "${userHome}/.example/INSTRUCTIONS.md"], - "skills": ["${userHome}/.example/skills"] + "skills": ["${userHome}/.example/skills"], + "providers": {"operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setProvider"]} }), json!({ "kind": "agentSessions", diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 151e75ad..b410fb9e 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -121,6 +121,65 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.providers.change_applied", + channel: "agent", + level: LogLevel::Info, + message: "A model or provider change was applied to an agent's configuration", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Operation applied, such as addProvider or setModel", reason: None }, + FieldMetadata { name: "changed", field_type: FieldType::Bool, required: true, description: "False when the agent's configuration already matched", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took, including plugin calls", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.providers.change_failed", + channel: "agent", + level: LogLevel::Warn, + message: "A model or provider change to an agent's configuration was refused", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Operation asked for, such as addProvider or setModel; invalid when it is not one", 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.unsupportedOperation; never names, URLs, paths or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.providers.read_failed", + channel: "agent", + level: LogLevel::Warn, + message: "An agent plugin could not report the agent's models and providers", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", 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.invalidSnapshot; never names, URLs, paths or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.providers.read_finished", + channel: "agent", + level: LogLevel::Debug, + message: "Agents' models and providers read", + fields: &[ + FieldMetadata { name: "agents", field_type: FieldType::Int, required: true, description: "Agents declaring providers that were reported", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took, including plugin calls", reason: None }, + FieldMetadata { name: "failed", field_type: FieldType::Int, required: true, description: "Agents whose plugin could not report their models and providers", 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 a191ca19..771c78b0 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -21,6 +21,8 @@ //! the files that hold its MCP servers and hooks, and the backend functions //! that read and edit those files. Core writes them only when the user //! applies a change, and only through a staged copy it checks first. +//! `configuration.providers` names the backend functions that report and +//! change the CLI's model, model providers and profiles in those files. //! //! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-25-agent-native-cli-and-local-session-records.md @@ -88,6 +90,18 @@ pub const PERMISSION_AGENTS_CONFIGURATION: &str = "agents.configuration"; /// Most configuration files one agent declares. pub const MAX_CONFIGURATION_FILES: usize = 8; +/// The changes a providers `edit` function can make, in the order the +/// contract lists them. An agent declares the ones its CLI supports. +pub const PROVIDER_OPERATIONS: [&str; 7] = [ + "addProvider", + "updateProvider", + "removeProvider", + "setProviderEnabled", + "setModel", + "setProvider", + "setProfile", +]; + /// Template variable of the user's home directory in a session root. const USER_HOME_VARIABLE: &str = "${userHome}"; @@ -147,6 +161,29 @@ pub struct ConfigurationDeclaration { /// Backend function that applies changes to a staged copy of one file. #[serde(default, skip_serializing_if = "Option::is_none")] pub edit: Option, + /// Backend functions that report and change the CLI's model, model + /// providers and profiles kept in `files`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub providers: Option, +} + +/// 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. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProvidersDeclaration { + /// Backend function that reports the model, providers, profiles and + /// account label. + pub read: String, + /// Backend function that applies one change to a staged copy of one + /// file. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edit: Option, + /// The changes `edit` makes, from [`PROVIDER_OPERATIONS`]; Core refuses + /// any other before calling the plugin. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub operations: Vec, } /// A path given as root candidates; the first that resolves is used. @@ -256,10 +293,9 @@ impl AgentDeclaration { pub fn needs_backend(&self) -> bool { self.native.is_some() || !self.session_sources.is_empty() - || self - .configuration - .as_ref() - .is_some_and(|configuration| configuration.read.is_some()) + || self.configuration.as_ref().is_some_and(|configuration| { + configuration.read.is_some() || configuration.providers.is_some() + }) } } @@ -549,7 +585,7 @@ fn check_configuration(configuration: &ConfigurationDeclaration, field: &str) -> check_roots(&file.roots, &format!("{file_field}.roots"))?; } match (configuration.files.is_empty(), &configuration.read) { - (false, None) => { + (false, None) if configuration.providers.is_none() => { return Err(invalid( format!("{field}.read"), "Configuration files need a read function.", @@ -580,6 +616,58 @@ fn check_configuration(configuration: &ConfigurationDeclaration, field: &str) -> )); } } + if let Some(providers) = &configuration.providers { + check_providers(providers, configuration, &format!("{field}.providers"))?; + } + Ok(()) +} + +fn check_providers( + providers: &ProvidersDeclaration, + configuration: &ConfigurationDeclaration, + field: &str, +) -> Validation<()> { + if configuration.files.is_empty() { + return Err(invalid( + field, + "Providers are read from the declared configuration files.", + )); + } + for (name, function) in [ + ("read", Some(&providers.read)), + ("edit", providers.edit.as_ref()), + ] { + if function.is_some_and(|function| !is_function_id(function)) { + return Err(invalid( + format!("{field}.{name}"), + "A providers function ID is dot-separated lowerCamelCase segments.", + )); + } + } + match (&providers.edit, providers.operations.is_empty()) { + (Some(_), true) => { + return Err(invalid( + format!("{field}.operations"), + "A providers edit function declares the changes it makes.", + )) + } + (None, false) => { + return Err(invalid( + format!("{field}.edit"), + "Provider operations need an edit function.", + )) + } + _ => {} + } + let mut seen = BTreeSet::new(); + for (index, operation) in providers.operations.iter().enumerate() { + if !PROVIDER_OPERATIONS.contains(&operation.as_str()) || !seen.insert(operation.as_str()) { + return Err(invalid( + format!("{field}.operations[{index}]"), + "A provider operation is one of the contract's operations, listed once.", + )); + } + } Ok(()) } @@ -769,6 +857,9 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { "files": !configuration.files.is_empty(), "editable": configuration.edit.is_some(), }); + if let Some(providers) = &configuration.providers { + entry["configuration"]["providers"] = json!({ "operations": providers.operations }); + } } if let Some(icon) = &agent.icon { entry["icon"] = json!(icon); @@ -847,6 +938,9 @@ pub fn programs(agent: &AgentDeclaration) -> Vec { if let Some(skills) = &configuration.skills { program["skills"] = json!(skills.roots); } + if let Some(providers) = &configuration.providers { + program["providers"] = json!({ "operations": providers.operations }); + } programs.push(program); } programs diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs index 64412a0b..9517054f 100644 --- a/rust/crates/plugin-agents/src/tests.rs +++ b/rust/crates/plugin-agents/src/tests.rs @@ -401,3 +401,109 @@ fn configuration_is_bounded_and_consistent() { unknown["configuration"]["environment"] = json!({}); assert!(serde_json::from_value::(unknown).is_err()); } + +fn with_providers(providers: Value) -> Value { + let mut value = configured(); + value["configuration"]["providers"] = providers; + value +} + +#[test] +fn accepts_providers_and_reports_their_operations() { + let mut agents = [agent(with_providers(json!({ + "read": "configuration.providers.read", + "edit": "configuration.providers.edit", + "operations": ["addProvider", "setModel"] + })))]; + check(&mut agents, true).expect("providers validate"); + let entry = catalog_entry("dev.lithe.test.agents", &agents[0]); + assert_eq!( + entry["configuration"]["providers"], + json!({ "operations": ["addProvider", "setModel"] }) + ); + let programs = programs(&agents[0]); + let program = programs + .iter() + .find(|program| program["kind"] == "agentConfiguration") + .expect("configuration is in the install review"); + assert_eq!( + program["providers"], + json!({ "operations": ["addProvider", "setModel"] }) + ); + + // A read-only providers function needs no edit and no operations, and + // serves the files even without a library read function. + let mut value = with_providers(json!({ "read": "configuration.providers.read" })); + let configuration = value["configuration"].as_object_mut().unwrap(); + configuration.remove("read"); + configuration.remove("edit"); + let mut agents = [agent(value)]; + check(&mut agents, true).expect("providers alone read the files"); + assert!(agents[0].needs_backend()); + assert_eq!( + catalog_entry("dev.lithe.test.agents", &agents[0])["configuration"]["providers"], + json!({ "operations": [] }) + ); +} + +#[test] +fn providers_are_consistent_with_files_and_operations() { + let cases: [(&str, Value, &str); 6] = [ + ( + "without files", + json!({ + "instructions": { "roots": ["${userHome}/A.md"] }, + "providers": { "read": "configuration.providers.read" } + }), + "agents[0].configuration.providers", + ), + ( + "an invalid read ID", + json!({ + "files": [{ "id": "settings", "roots": ["${userHome}/a.json"] }], + "providers": { "read": "Providers Read" } + }), + "agents[0].configuration.providers.read", + ), + ( + "edit without operations", + json!({ + "files": [{ "id": "settings", "roots": ["${userHome}/a.json"] }], + "providers": { "read": "providers.read", "edit": "providers.edit" } + }), + "agents[0].configuration.providers.operations", + ), + ( + "operations without edit", + json!({ + "files": [{ "id": "settings", "roots": ["${userHome}/a.json"] }], + "providers": { "read": "providers.read", "operations": ["setModel"] } + }), + "agents[0].configuration.providers.edit", + ), + ( + "an unknown operation", + json!({ + "files": [{ "id": "settings", "roots": ["${userHome}/a.json"] }], + "providers": { "read": "providers.read", "edit": "providers.edit", "operations": ["setKey"] } + }), + "agents[0].configuration.providers.operations[0]", + ), + ( + "a repeated operation", + json!({ + "files": [{ "id": "settings", "roots": ["${userHome}/a.json"] }], + "providers": { "read": "providers.read", "edit": "providers.edit", "operations": ["setModel", "setModel"] } + }), + "agents[0].configuration.providers.operations[1]", + ), + ]; + for (name, configuration, field) in cases { + let mut value = sample(); + value["configuration"] = configuration; + assert_eq!(rejected_field(value, true), field, "{name}"); + } + + let unknown = with_providers(json!({ "read": "providers.read", "secrets": true })); + assert!(serde_json::from_value::(unknown).is_err()); +} diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 88a536ed..4e0e79de 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -381,6 +381,121 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "agent.providers.read_finished", + "channel": "agent", + "level": "debug", + "message": "Agents' models and providers read", + "fields": { + "agents": { + "type": "int", + "required": true, + "description": "Agents declaring providers that were reported" + }, + "failed": { + "type": "int", + "required": true, + "description": "Agents whose plugin could not report their models and providers" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took, including plugin calls" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.providers.read_failed", + "channel": "agent", + "level": "warn", + "message": "An agent plugin could not report the agent's models and providers", + "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.invalidSnapshot; never names, URLs, paths or text" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.providers.change_applied", + "channel": "agent", + "level": "info", + "message": "A model or provider change was applied to an agent's configuration", + "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" + }, + "change": { + "type": "token", + "required": true, + "description": "Operation applied, such as addProvider or setModel" + }, + "changed": { + "type": "bool", + "required": true, + "description": "False when the agent's configuration already matched" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took, including plugin calls" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.providers.change_failed", + "channel": "agent", + "level": "warn", + "message": "A model or provider change to an agent's configuration was refused", + "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" + }, + "change": { + "type": "token", + "required": true, + "description": "Operation asked for, such as addProvider or setModel; invalid when it is not one" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code such as agentProviders.unsupportedOperation; never names, URLs, paths or text" + } + }, + "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 8bca53bb..58d79496 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4382,7 +4382,12 @@ and keeps no name or icon of its own for any agent. "skills": {"roots": ["${userHome}/.sample/skills"]}, "files": [{"id": "main", "roots": ["${userHome}/.sample/config.json"]}], "read": "configuration.read", - "edit": "configuration.edit" + "edit": "configuration.edit", + "providers": { + "read": "providers.read", + "edit": "providers.edit", + "operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setProvider"] + } } ``` @@ -4390,9 +4395,10 @@ and keeps no name or icon of its own for any agent. | --- | --- | | `instructions` | `{roots}`: the Markdown file the CLI reads as the user's own instructions. Core reads and writes it. | | `skills` | `{roots}`: the directory of the CLI's user skills, one directory with a `SKILL.md` per skill. Core reads it and links library skills into it. | -| `files` | At most 8 `{id, roots}`: the files in the CLI's own format that hold its MCP servers and hooks. `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 what `files` hold. Required with `files` and refused without them. | +| `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`. | - A configuration declares at least one of `instructions`, `skills` and `files`. A function ID is dot-separated lowerCamelCase segments. @@ -4407,6 +4413,12 @@ and keeps no name or icon of its own for any agent. refuses a manifest that declares it as invalid (`configuration` is an unknown field of the agent), and answers none of the `agentLibrary.*` commands. +- `providers` and the filters of `agentLibrary.read` were added later within + `agents` 0. A Core that predates them refuses a manifest that declares + `providers` as invalid, refuses a `read` payload with filters as + `agents.invalidPayload`, and answers no `agentProviders.*` command. A + host that sees no `configuration.providers` in the catalog shows no + models or providers for the agent. #### The library @@ -4452,7 +4464,7 @@ neither has text. | Command | Payload | Result | | --- | --- | --- | | `agentLibrary.configure` | `{directory, userHome, environment?}` | `{}` | -| `agentLibrary.read` | `{}` | `{revision, library, skills, states, agents}` | +| `agentLibrary.read` | `{query?, agent?, presence?, sort?}` | `{revision, library, skills, states, agents, matches?}` | | `agentLibrary.save` | `{revision, library}` | `{revision}` | | `agentLibrary.apply` | `{agent, change}` | `{changed}` | | `agentLibrary.importSkill` | `{agent, name}` or `{directory}` | `{name, files, skipped}` | @@ -4510,6 +4522,25 @@ neither has text. `agentLibrary.readFailed` or `agentLibrary.invalidSnapshot`); the rest of the entry still answers. +The filters of `read` are optional. Without any, the answer is exactly as +above and has no `matches`. With any, `library`, `skills`, `states` and +`agents` are still whole, because `save` replaces the whole library, and +`matches` is `{mcpServers, hooks, skills}`: the keys (server name, hook +`id`, skill name) of the library items the filters keep, in the order +`sort` gives, or in library order without `sort`. + +| Filter | Keeps | +| --- | --- | +| `query` | Items whose text contains it, ignoring case: a server's name; a hook's `id`, `event`, `matcher` and `command`; a skill's name and description. At most 256 characters without NUL. | +| `agent` with `presence` | Items whose state for the agent key `agent` is `on` (`presence: "present"`) or anything else (`"missing"`: `off`, `conflict` or `unsupported`). An agent with no state for the item, such as one whose `read` failed, keeps nothing. The two come together. | +| `sort` | `name` orders by name ignoring case; `agentCount` orders by how many agents have the item `on`, most first, then by name. | + +A query that is too long or holds NUL, or an `agent` without `presence` or +the other way round, is `agentLibrary.invalidFilter`. An `agent` that is not +a configurable agent is `agentLibrary.unknownAgent`, and one whose plugin is +not granted `agentLibrary.notGranted`. Any other field or value is +`agents.invalidPayload`. + `apply` makes one `change`, and answers `changed: false` when the agent already had what it asks for: @@ -4623,6 +4654,166 @@ seconds. Any other answer is `agentLibrary.invalidEdit`; a failed call is `agentLibrary.editFailed`. The backend never learns the file's own path from `edit`. +#### Models and providers + +An agent whose plugin declares `configuration.providers` shows the model +the CLI uses, the model providers it can reach, its profiles and who is +signed in, and lets the user change the operations the plugin declares. +Core knows no CLI, variable or file layout: every name comes from the +plugin, and the host draws the views. + +| Command | Payload | Result | +| --- | --- | --- | +| `agentProviders.read` | `{agent?}` | `{agents}` | +| `agentProviders.apply` | `{agent, change}` | `{changed}` | + +`read` answers one entry per agent that declares `providers`, in catalog +order, or only the agent `agent` names (`agentLibrary.unknownAgent`, +`agentLibrary.notGranted`, and `agentProviders.notDeclared` for an agent +without `providers`): + +```json +{ + "agents": [{ + "agent": "dev.example.agents/alpha", + "pluginID": "dev.example.agents", + "agentID": "alpha", + "displayName": "Alpha", + "mayConfigure": true, + "operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setProvider"], + "files": [{"id": "main", "path": "/home/user/.alpha/config.json", "exists": true}], + "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": "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"}} + ], + "profiles": [{"name": "fast", "model": "model-b", "provider": "gateway"}], + "profile": {"name": "fast", "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}}, + "account": {"label": "Team plan"}, + "environmentNames": ["ALPHA_TIMEOUT"], + "targets": {"providers": "main", "model": "main", "provider": "main", "profile": "main"} + }] +} +``` + +- An agent whose plugin is not granted `agents.configuration` gives only + the fields up to `operations`, and is not read. +- The rest is what the plugin's `read` reported, after Core's checks: Core + 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. +- A failed read gives `readError` (`agentLibrary.backendUnavailable`, + `agentProviders.readFailed` or `agentProviders.invalidSnapshot`) in place + of the snapshot; the other agents still answer. + +`apply` runs only for a request whose origin is the user +(`agentLibrary.userActionRequired`) and makes one `change`: + +| `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: "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` | +| `{op: "setProvider", id}` | sets the provider the CLI uses | `provider` | +| `{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: + +1. The agent declares `providers` (`agentProviders.notDeclared`); `op` is + one of the operations above (`agentProviders.invalidChange`) and one the + manifest lists (`agentProviders.unsupportedOperation`). +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`. +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. +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 + holds the bytes Core copied (`agentLibrary.fileChanged`), with the same + `agentLibrary.brokenLink`, `agentLibrary.fileTooLarge`, + `agentLibrary.unreadable` and `agentLibrary.writeFailed` refusals. + +`apply` answers `changed: false` when the file already held the change. + +`providers.read` receives `{agentID, files: [{id, path, exists}]}`, like the +configuration `read`, and answers within 10 seconds exactly: + +- `format: "litheAgentProviders"` and `version: 0`; +- `cliVersion?`, the CLI's version as it names it; +- `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; + `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; +- `profiles`: at most 64 `{name, model?, provider?, source?}`, names unique; +- `profile?`: `{name, source?}`, the profile in use; +- `account?`: `{label}`, who is signed in as the plugin labels it; +- `environmentNames`: at most 64 names of other environment variables the + CLI reads; +- `targets`: `{providers?, model?, provider?, profile?}`, the declared file + `id` each kind of change goes to. + +A `source` is `{layer, file?, path?, variable?, profile?}`: `layer` is +`user`, `profile`, `default` or `environment`; `file` is a declared file's +`id` and `path` an absolute path of at most 4096 bytes the plugin found +itself, never both; `variable` names the variable of the `environment` +layer and `profile` the profile of the `profile` layer, each required there +and refused elsewhere. + +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 + 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`. +- **Endpoints carry no credentials.** A `baseUrl` is `http://` or + `https://` with a host, and has no user or password, no query, no + fragment, no space or control character, and at most 2048 bytes. +- **Names have limits.** A provider ID, header or query parameter name is + 1–128 bytes of ASCII letters, digits, `-`, `_` and `.`; an environment + variable name is an ASCII letter or `_` followed by ASCII letters, digits + and `_`, at most 128 bytes; `protocol` and `cliVersion` are 1–64 bytes of + ASCII letters, digits, `-`, `_`, `.` and `+`; a display name, model, + profile name or account label is 1–128 characters without leading or + 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. + +`providers.edit` receives `{agentID, file: {id, staging, exists}, change}` +with `change` as the host gave it, changes only the file at `staging` in the +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. + #### Limits, refusals and logging - Core reads at most 8 MiB of `library.json`, 16 MiB of a configuration @@ -4637,7 +4828,11 @@ seconds. Any other answer is `agentLibrary.invalidEdit`; a failed call is - Changes never interleave: Core checks and replaces one file at a time, never while waiting for a backend. - Core logs plugin and agent IDs, categories, operations, counts, durations - and refusal codes, never names, commands, paths or text. + 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. ### Privacy and logging diff --git a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json index e934f2e2..ab0a9a57 100644 --- a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -81,7 +81,18 @@ } ], "read": "example.configuration.read", - "edit": "example.configuration.edit" + "edit": "example.configuration.edit", + "providers": { + "read": "example.providers.read", + "edit": "example.providers.edit", + "operations": [ + "addProvider", + "updateProvider", + "removeProvider", + "setModel", + "setProvider" + ] + } } } ], diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index bc573805..2b837771 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -1002,7 +1002,14 @@ {"name": "a configuration path names something below its variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/skills/roots", "value": ["${userHome}"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.skills.roots[0]"}, {"name": "a configuration path does not leave its variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files/0/roots", "value": ["${userHome}/../config.json"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.files[0].roots[0]"}, {"name": "a configuration file is declared once", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": [{"id": "main", "roots": ["${userHome}/.example/a.json"]}, {"id": "main", "roots": ["${userHome}/.example/b.json"]}]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.files[1].id"}, - {"name": "configuration files need a read function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/edit"}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.read"}, + {"name": "configuration files need a read function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/edit"}, {"op": "remove", "path": "/agents/0/configuration/read"}, {"op": "remove", "path": "/agents/0/configuration/providers"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.read"}, + {"name": "providers are read from configuration files", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/edit"}, {"op": "remove", "path": "/agents/0/configuration/read"}, {"op": "set", "path": "/agents/0/configuration/files", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers"}, + {"name": "a providers function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/read", "value": "Example Read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.read"}, + {"name": "provider operations need an edit function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/providers/edit"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.edit"}, + {"name": "a providers edit function declares its operations", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations"}, + {"name": "a provider operation is a contract operation", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": ["setModel", "setSecret"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations[1]"}, + {"name": "a provider operation is listed once", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": ["setModel", "setModel"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations[1]"}, + {"name": "a providers field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/secrets", "value": "example.providers.secrets"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a configuration edit function needs read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": []}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "a configuration function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/edit", "value": "Example Edit"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "an agent field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/environment", "value": {"EXAMPLE": "1"}}], "expectedCode": "plugin.manifest.invalid"} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 686c2cb5..ddf585e3 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -12,6 +12,7 @@ {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["sessionSources"]}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}, "permissions": {"contains": {"const": "agents.sessions.read"}}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"]}}}}, "then": {"properties": {"permissions": {"contains": {"const": "agents.configuration"}}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"], "properties": {"configuration": {"required": ["read"]}}}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, + {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"], "properties": {"configuration": {"required": ["providers"]}}}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, {"if": {"required": ["permissions"], "properties": {"permissions": {"contains": {"const": "agents.usage.read"}}}}, "then": {"required": ["backend"]}}, {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, @@ -467,7 +468,7 @@ } }, "agentConfiguration": { - "description": "Where the CLI keeps the instructions, skills, MCP servers and hooks Lithe's agent library manages. Core reads and changes them only for a change the user applies; needs agents.configuration. Declares at least one of instructions, skills and files; files and read come together, and edit needs read.", + "description": "Where the CLI keeps the instructions, skills, MCP servers, hooks, model and model providers Lithe's agent library manages. Core reads and changes them only for a change the user applies; needs agents.configuration. Declares at least one of instructions, skills and files; files need read or providers, read and providers need files, and edit needs read.", "type": "object", "additionalProperties": false, "anyOf": [ @@ -477,11 +478,12 @@ ], "dependentRequired": { "read": ["files"], - "edit": ["read"] + "edit": ["read"], + "providers": ["files"] }, "if": {"required": ["files"], "properties": {"files": {"minItems": 1}}}, - "then": {"required": ["read"]}, - "else": {"properties": {"read": false}}, + "then": {"anyOf": [{"required": ["read"]}, {"required": ["providers"]}]}, + "else": {"properties": {"read": false, "providers": false}}, "properties": { "instructions": { "description": "The Markdown file the CLI reads as the user's own instructions. Core reads and writes it.", @@ -517,6 +519,35 @@ "edit": { "description": "Backend function that applies one change to a staged copy of one file: {agentID, file: {id, staging, exists}, change} to a litheAgentConfigurationEdit answer.", "$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.", + "type": "object", + "additionalProperties": false, + "required": ["read"], + "dependentRequired": { + "edit": ["operations"], + "operations": ["edit"] + }, + "properties": { + "read": { + "description": "{agentID, files: [{id, path, exists}]} to a litheAgentProviders answer.", + "$ref": "#/$defs/pluginFunctionID" + }, + "edit": { + "description": "{agentID, file: {id, staging, exists}, change} to a litheAgentProvidersEdit answer.", + "$ref": "#/$defs/pluginFunctionID" + }, + "operations": { + "description": "The changes edit makes; Core refuses any other with agentProviders.unsupportedOperation.", + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "enum": ["addProvider", "updateProvider", "removeProvider", "setProviderEnabled", "setModel", "setProvider", "setProfile"] + } + } + } } } }, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index c018eccf..22e5172f 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 自己的配置 | 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 内的补充),密钥、请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串 | 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 | 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, 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) | ### Planned APIs diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 7df285e7..241e82c8 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` | ✅ | 待宿主接入 | [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.*` 命令 | ✅ | 待宿主接入 | [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` | ✅ | 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 | ✅ | 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 e2d44b00..ab407e46 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -9,12 +9,12 @@ | 项目 | 内容 | | --- | --- | | 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`,每个插件最多 8 个 | -| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read` 的 `configuration` 时还需要 `backend` 0。`configuration`、`agents.configuration`、`native.imageTypes` 和提示附件是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单和带 `attachments` 的 `agents.prompt`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read`、`providers` 的 `configuration` 时还需要 `backend` 0。`configuration`、`agents.configuration`、`native.imageTypes`、提示附件、`configuration.providers` 和 `agentLibrary.read` 的筛选排序参数是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单、带 `attachments` 的 `agents.prompt` 和带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | API 编号 | API-45 | | 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.configuration`(有 `configuration`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | -| 激活事件 | 声明了 `native`、`sessionSources` 或带 `read` 的 `configuration` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | +| 激活事件 | 声明了 `native`、`sessionSources` 或带 `read`、`providers` 的 `configuration` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | | 后端启动 | 只有终端形式的 Agent 不需要后端 | -| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有。`configuration` 的 `read` 和 `edit` 是普通插件函数,任何 SDK 版本都能注册,见各 SDK 的 Agent configuration functions 一节 | +| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有。`configuration` 的 `read`、`edit` 和 `providers` 的 `read`、`edit` 都是普通插件函数,任何 SDK 版本都能注册,见各 SDK 的 Agent configuration functions 一节 | | 安装审查 | 每种运行形式列成一条 `agent` 程序,每个会话来源列成一条 `agentSessions` 程序,声明了 `configuration` 的 Agent 列成一条 `agentConfiguration` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录和文件会被读取或修改 | | Lithe 桌面端 | 接入中,尚未声明 `agents` | @@ -58,6 +58,21 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 所有改动都只能由用户的操作发起;Core 只读写声明的路径;插件没有获得 `agents.configuration` 授权时,它的 Agent 以 `mayConfigure: false` 列出,Core 什么都不读、不改。命令见 Rust Core API 的 `agentLibrary.*`。 +`agentLibrary.read` 可以带可选参数 `query`(名称、描述等文字,忽略大小写)、`agent` 加 `presence`(`present` 或 `missing`,两者一起给)和 `sort`(`name` 或 `agentCount`)。不带参数时结果和以前完全一样;带了参数,资源库本身仍完整返回(`save` 要整份替换),另加 `matches`,按顺序列出留下的 MCP 服务器名、Hook `id` 和技能名。 + +### 模型与模型供应商 + +`configuration` 里再声明 `providers: {read, edit?, operations?}`,宿主就能显示 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`。 +- 端点只能是不带用户名、密码、查询和片段的 `http`/`https` 地址;名称、列表都有上限。 +- 插件不得读取 CLI 的凭据文件(如 `auth.json`、`.credentials.json`)和系统钥匙串,账号标签只来自不含凭据的设置或 CLI 命令。 +- 被环境变量覆盖的当前模型、供应商或配置档改文件不会生效,Core 以 `agentProviders.overridden` 拒绝;CLI 内置的供应商只显示,不能改或删。 + +命令是 `agentProviders.read {agent?}` 和 `agentProviders.apply {agent, change}`,字段、拒绝码和完整示例见[契约](../../contract/v1/README.md#models-and-providers)。 + ### 契约章节 | 章节 | 内容 | @@ -68,10 +83,11 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 | [Host commands](../../contract/v1/README.md#host-commands) | 宿主调用的 `agents.*` 命令和事件队列 | | [Native sessions](../../contract/v1/README.md#native-sessions) | 启动流程、通知、宿主方法、会话事件 | | [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | -| [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储和命令、`read` 与 `edit` 函数、限制和拒绝码 | +| [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储、命令和筛选、`read` 与 `edit` 函数、限制和拒绝码 | +| [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`、`agentProviders.*` 命令、快照与修改、隐私规则和拒绝码 | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | 日志只记 ID 和元数据,不读凭据文件 | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | 不运行 ACP 客户端,只在可信本地工作区运行 | -| [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*`、`agentSessions.*` 与 `agentLibrary.*` 命令(Rust Core API 文档) | +| [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*`、`agentSessions.*`、`agentLibrary.*` 与 `agentProviders.*` 命令(Rust Core API 文档) | ### 示例与用例 @@ -91,12 +107,12 @@ A plugin can connect an agent command-line tool that the user installed and sign | Item | Value | | --- | --- | | Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`, at most 8 per plugin | -| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read`. `configuration`, `agents.configuration`, `native.imageTypes` and prompt attachments were added within `agents` 0; a Core that does not know them refuses such a manifest and an `agents.prompt` with `attachments`. See [versions](../capabilities-and-versions.md#capability-versions-requires) | +| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read` or `providers`. `configuration`, `agents.configuration`, `native.imageTypes`, prompt attachments, `configuration.providers` and the filter and sort parameters of `agentLibrary.read` were added within `agents` 0; a Core that does not know them refuses such a manifest, an `agents.prompt` with `attachments` and an `agentLibrary.read` with filters, and answers no `agentProviders.*` command. See [versions](../capabilities-and-versions.md#capability-versions-requires) | | API IDs | API-45 | | Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.configuration` (with `configuration`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | -| Activation events | An agent that declares `native`, `sessionSources` or a `configuration` with `read` needs `onAgent:`; other agents may not have one | +| Activation events | An agent that declares `native`, `sessionSources` or a `configuration` with `read` or `providers` needs `onAgent:`; other agents may not have one | | Backend launch | A terminal-only agent needs no backend | -| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not. The `read` and `edit` of `configuration` are ordinary plugin functions any SDK version registers; see each SDK's Agent configuration functions section | +| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not. The `read` and `edit` of `configuration` and of `providers` are ordinary plugin functions any SDK version registers; see each SDK's Agent configuration functions section | | Install review | Each form is an `agent` program, each session source an `agentSessions` program, and each agent that declares `configuration` an `agentConfiguration` program, so the user sees how the CLI will run and which directories and files will be read or changed before installing | | Lithe desktop | Integration in progress; does not declare `agents` yet | @@ -158,6 +174,21 @@ The host's agent library keeps one copy of instructions, skills, MCP servers and Every change comes only from a user action. Core reads and writes only the declared paths. An agent whose plugin is not granted `agents.configuration` is listed with `mayConfigure: false`, and Core reads and changes nothing of it. The commands are the `agentLibrary.*` commands of the Rust Core API. +`agentLibrary.read` takes optional `query` (text in a name, description and so on, ignoring case), `agent` with `presence` (`present` or `missing`, given together) and `sort` (`name` or `agentCount`). Without them the answer is exactly as before; with them the library still comes whole, since `save` replaces all of it, and `matches` lists the kept MCP server names, hook `id`s and skill names in order. + +### 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: + +- `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`. +- 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. + +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). + ### Contract sections | Section | Content | @@ -168,10 +199,11 @@ Every change comes only from a user action. Core reads and writes only the decla | [Host commands](../../contract/v1/README.md#host-commands) | The `agents.*` commands the host calls and the event queue | | [Native sessions](../../contract/v1/README.md#native-sessions) | Launch flow, notifications, host methods, session events | | [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | -| [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage and commands, the `read` and `edit` functions, limits, and refusal codes | +| [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage, commands and filters, the `read` and `edit` functions, limits, and refusal codes | +| [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`, the `agentProviders.*` commands, snapshots and changes, privacy rules, and refusal codes | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | Logs carry only IDs and metadata; no credential file is read | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | No ACP client; trusted local workspaces only | -| [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*`, `agentSessions.*`, and `agentLibrary.*` commands (Rust Core API document) | +| [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*`, `agentSessions.*`, `agentLibrary.*`, and `agentProviders.*` commands (Rust Core API document) | ### Examples and cases diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index ee89d8e2..a3d40be8 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#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` 拒绝。没有新增宿主方法、通知或能力版本。 | | [#241](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/241)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.search` 的命中新增 `generation` 和 `readBytes`,都是命中所在文件(可能是子代理文件)的值,宿主据此从命中处用 `agentSessions.page` 分页读取该文件。旧 Core 不回答这两个字段。没有新增宿主方法、通知、错误码或能力版本。 | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index d8c0f6a7..767690a9 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -696,6 +696,25 @@ and gives each call 10 seconds. `origin: "agent"`; it never opens credential files. `edit` writes only the file at `staging`. +An agent may also declare +[`configuration.providers`](../../contract/v1/README.md#models-and-providers) +with a `read` function, an optional `edit` function and the `operations` +`edit` makes. They are ordinary plugin functions too, registered the same +way, with the same 10 seconds and the same `agents.configuration` permission: + +- `providers.read` receives `{agentID, files: [{id, path, exists}]}` and + answers `{format: "litheAgentProviders", version: 0, ...}`: the model, + provider and profile in use, the providers, profiles, account label, other + environment variable names and the file `targets` of each kind of change. +- `providers.edit` receives `{agentID, file: {id, staging, exists}, change}`, + 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. + ## Testing Run these from this directory: diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 50a39af6..3af41f1f 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -663,6 +663,25 @@ and gives each call 10 seconds. `origin: "agent"`; it never opens credential files. `edit` writes only the file at `staging`. +An agent may also declare +[`configuration.providers`](../../contract/v1/README.md#models-and-providers) +with a `read` function, an optional `edit` function and the `operations` +`edit` makes. They are ordinary plugin functions too, registered the same +way, with the same 10 seconds and the same `agents.configuration` permission: + +- `providers.read` receives `{agentID, files: [{id, path, exists}]}` and + answers `{format: "litheAgentProviders", version: 0, ...}`: the model, + provider and profile in use, the providers, profiles, account label, other + environment variable names and the file `targets` of each kind of change. +- `providers.edit` receives `{agentID, file: {id, staging, exists}, change}`, + 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. + ## Testing Run these from the root of this repository: diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 2693f77e..2b44c5f7 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -676,6 +676,25 @@ and gives each call 10 seconds. `origin: "agent"`; it never opens credential files. `edit` writes only the file at `staging`. +An agent may also declare +[`configuration.providers`](../../contract/v1/README.md#models-and-providers) +with a `read` function, an optional `edit` function and the `operations` +`edit` makes. They are ordinary plugin functions too, registered the same +way, with the same 10 seconds and the same `agents.configuration` permission: + +- `providers.read` receives `{agentID, files: [{id, path, exists}]}` and + answers `{format: "litheAgentProviders", version: 0, ...}`: the model, + provider and profile in use, the providers, profiles, account label, other + environment variable names and the file `targets` of each kind of change. +- `providers.edit` receives `{agentID, file: {id, staging, exists}, change}`, + 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. + ## Testing Run these from the root of this repository: diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index ecb72c78..8c764821 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -786,6 +786,25 @@ and gives each call 10 seconds. `origin: "agent"`; it never opens credential files. `edit` writes only the file at `staging`. +An agent may also declare +[`configuration.providers`](../../contract/v1/README.md#models-and-providers) +with a `read` function, an optional `edit` function and the `operations` +`edit` makes. They are ordinary plugin functions too, registered the same +way, with the same 10 seconds and the same `agents.configuration` permission: + +- `providers.read` receives `{agentID, files: [{id, path, exists}]}` and + answers `{format: "litheAgentProviders", version: 0, ...}`: the model, + provider and profile in use, the providers, profiles, account label, other + environment variable names and the file `targets` of each kind of change. +- `providers.edit` receives `{agentID, file: {id, staging, exists}, change}`, + 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. + ## Testing Run these from the root of this repository: