diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c4d468b3..bfec6cc5 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -509,9 +509,12 @@ or removing a command fails until the table changes in the same commit. | `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration, backing up the configuration or instruction file it replaces first; an instruction `write` changes only Lithe's block and needs `replace` over an edited one, and `import` moves the user's own text outside the block into a new or existing set at the library revision read, leaving only the block, and answers `{changed, revision, instructions}` | | `agentLibrary.importSkill` | Copy a skill from an agent or a directory the user chose into the library | | `agentLibrary.removeSkill` | Remove a library skill and its links from agents | -| `agentProviders.read` | Read each agent's model, model providers, profiles and account label through its plugin, with a key reported only as `keySet` and other secrets as variable names; adds the providers Lithe saved (`listKeptBy: "lithe"`) and the agent's `backup: {savedAtMs, modifiedSince}` | -| `agentProviders.apply` | Apply one model, provider or profile change the plugin declares, through a checked staged copy of the agent's file backed up first; `addProvider`/`updateProvider` may carry a write-only `key` (or `clearKey`), handed only to the plugin's `edit` | +| `agentProviders.read` | Read each agent's model, model providers, profiles and account label through its plugin, with a key reported only as `keySet` and other secrets as variable names; adds the providers Lithe saved (`listKeptBy: "lithe"`) and the agent's `backup: {savedAtMs, modifiedSince}`; always answers `models`, the models the plugin lists (none when it lists none), each with `shown`, beside the `efforts`, `speeds`, `effort` and `speed` it reports | +| `agentProviders.apply` | Apply one model, provider or profile change the plugin declares, through a checked staged copy of the agent's file backed up first; `addProvider`/`updateProvider` may carry a write-only `key` (or `clearKey`), handed only to the plugin's `edit`; `setModel` (which may carry `effort` and `speed`), `setEffort` and `setSpeed` are refused with `unknownModel`, `unknownEffort`, `unknownSpeed` or `unsupportedCombination` when the listed models do not take them, and `setModelMenu` is Core's own | | `agentProviders.restore` | Put every file of any configurable agent, with or without providers, back as it was before Lithe's first change since the last restore, whether `agentProviders.apply` or `agentLibrary.apply` changed it, and forget what Core last wrote to a restored instruction file and stop the agent following the library's instructions (`unfollowed`); refused when a file changed after Lithe's last write unless `discardLaterChanges` | +| `agentProviders.showModels` | Show or hide listed models of an agent in Lithe's pickers (user requests only), keeping the hidden ones in `models.json` in the library directory; when the plugin declares `setModelMenu`, also has it write the shown models into the CLI's own model menu, putting the switches back when it fails; answers `{changed}` | +| `agentProviders.readModelSettings` | Read an agent's model settings as one group, `{settings: {hidden, model?, effort?, speed?}}`, for saving as a plan | +| `agentProviders.applyModelSettings` | Write a group from `agentProviders.readModelSettings` back (user requests only): checks every model, effort and speed change first and changes nothing when one is refused, then makes them, replaces the hidden models and has the CLI's menu follow; answers `{changed}` | | `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 3f5f0118..2ae3836b 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -138,6 +138,9 @@ impl Runtime { "agentProviders.read" => self.library.read_providers(self, payload), "agentProviders.apply" => self.library.apply_providers(self, payload), "agentProviders.restore" => self.library.restore_backup(self, payload), + "agentProviders.showModels" => self.library.show_models(self, payload), + "agentProviders.readModelSettings" => self.library.read_model_settings(self, payload), + "agentProviders.applyModelSettings" => self.library.apply_model_settings(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 b1748d7a..9f416ad3 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -6,8 +6,11 @@ //! `library.json` holds the servers, hooks and instruction sets, //! `skills//` holds one directory per skill, `state.json` records what //! Core last wrote to each agent's instruction file, `staging/` holds the -//! copies plugins edit, and `backups/` the agents' files as they were before -//! Lithe changed them (`backups` module). +//! copies plugins edit, `backups/` the agents' files as they were before +//! Lithe changed them (`backups` module), `saved-providers.json` the +//! providers Lithe keeps for an agent whose CLI holds one endpoint, and +//! `models.json` the models the user hid from Lithe's pickers +//! (`providers` module). //! //! What an agent has is read from the agent's own files every time and never //! kept. An agent plugin declares where they are (`configuration` in the @@ -120,6 +123,8 @@ pub(crate) struct Library { /// Held while a change checks and replaces a file, so two changes never /// interleave. Never held across a backend call. writing: Mutex<()>, + /// The models each agent's plugin last listed. + catalogs: providers::Catalogs, } // --------------------------------------------------------------------------- diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs index 8a446ec6..dca8a641 100644 --- a/rust/crates/agent-runtime/src/library/providers.rs +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -25,12 +25,22 @@ //! - Names, text and lists have upper limits. //! - Only a request the user started changes anything, and only operations //! the manifest declares. +//! +//! A plugin may also list the models an agent offers, with the reasoning +//! efforts and speeds each takes. Core checks a change of model, effort or +//! speed against that list, and keeps which listed models Lithe's pickers +//! show (`models` module). + +mod models; + +pub(super) use models::Catalogs; use super::backups; use super::saved::{self, SavedProvider}; use super::{ - agent_paths, backend_unavailable, check_name, configurable_agent, files_param, path_text, - refusal, require_user, with_staged, AgentPaths, Check, Config, Library, FUNCTION_TIMEOUT, + agent_paths, backend_unavailable, check_description, check_name, configurable_agent, + files_param, path_text, refusal, require_user, with_staged, AgentPaths, Check, Config, Library, + FUNCTION_TIMEOUT, }; use crate::backend::BackendLink; use crate::catalog::CatalogAgent; @@ -56,6 +66,12 @@ const MAX_ID_BYTES: usize = 128; const MAX_TOKEN_BYTES: usize = 64; const MAX_URL_BYTES: usize = 2048; const MAX_PATH_BYTES: usize = 4096; +/// Most models a plugin lists for one agent. +const MAX_MODELS: usize = 512; +/// Most reasoning efforts or speeds an agent offers. +const MAX_LEVELS: usize = 16; +/// Largest context window a listed model may state, in tokens. +const MAX_CONTEXT_WINDOW: u64 = 1_000_000_000; /// Longest key a change may carry. Windows Credential Manager holds at most /// 2560 bytes per item, where a plugin may keep it; this leaves room. pub(super) const MAX_KEY_BYTES: usize = 1024; @@ -212,7 +228,66 @@ struct Account { label: String, } -/// The declared file a plugin changes for each kind of change. +/// A level of a setting the CLI offers for its models: a reasoning effort, +/// or a speed such as a fast mode. `id` is the value as the CLI writes it. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Level { + id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, +} + +/// The effort or speed in use. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CurrentLevel { + id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, +} + +impl CurrentLevel { + /// Whether the CLI's own default sets it, so it follows the model. + fn is_default(&self) -> bool { + self.source + .as_ref() + .is_some_and(|source| source.layer == Layer::Default) + } +} + +/// One model the agent offers. Its efforts and speeds are IDs of the +/// agent's `efforts` and `speeds`; a model that lists none of a kind takes +/// no setting of that kind. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ListedModel { + id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, + /// The provider that serves it, an ID of the snapshot's `providers`. + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + efforts: Vec, + /// The effort the CLI uses with the model when none is set. + #[serde(default, skip_serializing_if = "Option::is_none")] + default_effort: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + speeds: Vec, + /// The speed the CLI uses with the model when none is set. + #[serde(default, skip_serializing_if = "Option::is_none")] + default_speed: Option, + /// How many tokens a prompt may hold. + #[serde(default, skip_serializing_if = "Option::is_none")] + context_window: Option, + /// A line about the model, as the plugin words it. + #[serde(default, skip_serializing_if = "Option::is_none")] + description: Option, +} + +/// The declared file a plugin changes for each kind of change. Changes of +/// the model, effort and speed all go to `model`. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ProviderTargets { @@ -224,6 +299,9 @@ struct ProviderTargets { provider: Option, #[serde(default, skip_serializing_if = "Option::is_none")] profile: Option, + /// The file that holds the CLI's own model menu. + #[serde(default, skip_serializing_if = "Option::is_none")] + model_menu: Option, } /// The answer of a providers `read` function. @@ -251,6 +329,23 @@ struct ProvidersSnapshot { /// Other environment variables the CLI reads, by name only. #[serde(default)] environment_names: Vec, + /// The models the agent offers; empty when the plugin lists none. + #[serde(default)] + models: Vec, + /// The reasoning efforts the CLI offers, lowest first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + efforts: Vec, + /// The speeds the CLI offers. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + speeds: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + effort: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + speed: Option, + /// The listed models the CLI's own model menu shows, from a plugin that + /// writes that menu. + #[serde(default, skip_serializing_if = "Option::is_none")] + model_menu: Option>, #[serde(default)] targets: ProviderTargets, } @@ -340,6 +435,45 @@ fn check_names(names: &[String], field: &str, valid: fn(&str) -> bool) -> Check Ok(()) } +/// The efforts or speeds an agent offers: at most [`MAX_LEVELS`], IDs +/// unique. Answers the IDs. +fn check_levels<'a>(levels: &'a [Level], field: &str) -> Result, String> { + if levels.len() > MAX_LEVELS { + return Err(field.to_string()); + } + let mut ids = BTreeSet::new(); + for (index, level) in levels.iter().enumerate() { + if !is_token(&level.id) || !ids.insert(level.id.as_str()) { + return Err(format!("{field}[{index}].id")); + } + if let Some(name) = &level.name { + check_name(name, &format!("{field}[{index}].name"))?; + } + } + Ok(ids) +} + +/// The efforts or speeds one model takes: offered ones, each once, and a +/// default among them. +fn check_takes( + takes: &[String], + default: Option<&str>, + offered: &BTreeSet<&str>, + field: &str, + default_field: &str, +) -> Check { + let mut seen = BTreeSet::new(); + for (index, id) in takes.iter().enumerate() { + if !offered.contains(id.as_str()) || !seen.insert(id.as_str()) { + return Err(format!("{field}[{index}]")); + } + } + if default.is_some_and(|id| !seen.contains(id)) { + return Err(default_field.to_string()); + } + Ok(()) +} + impl Source { fn check(&self, field: &str, file_ids: &BTreeSet<&str>) -> Check { let invalid = |name: &str| Err(format!("{field}.{name}")); @@ -498,11 +632,13 @@ impl ProvidersSnapshot { "environmentNames", is_environment_name, )?; + self.check_models(&ids, file_ids)?; for (field, target) in [ ("targets.providers", &self.targets.providers), ("targets.model", &self.targets.model), ("targets.provider", &self.targets.provider), ("targets.profile", &self.targets.profile), + ("targets.modelMenu", &self.targets.model_menu), ] { if target.as_deref().is_some_and(|id| !file_ids.contains(id)) { return Err(field.into()); @@ -511,9 +647,166 @@ impl ProvidersSnapshot { Ok(()) } + /// The listed models, the efforts and speeds the agent offers and the + /// ones in use, and the models the CLI's menu shows. `provider_ids` are + /// the providers the snapshot lists. + fn check_models(&self, provider_ids: &BTreeSet<&str>, file_ids: &BTreeSet<&str>) -> Check { + let efforts = check_levels(&self.efforts, "efforts")?; + let speeds = check_levels(&self.speeds, "speeds")?; + for (field, current) in [("effort", &self.effort), ("speed", &self.speed)] { + if let Some(current) = current { + if !is_token(¤t.id) { + return Err(format!("{field}.id")); + } + check_source( + current.source.as_ref(), + &format!("{field}.source"), + file_ids, + )?; + } + } + if self.models.len() > MAX_MODELS { + return Err("models".into()); + } + let mut ids = BTreeSet::new(); + for (index, model) in self.models.iter().enumerate() { + let field = format!("models[{index}]"); + check_name(&model.id, &format!("{field}.id"))?; + if !ids.insert(model.id.as_str()) { + return Err(format!("{field}.id")); + } + if let Some(name) = &model.name { + check_name(name, &format!("{field}.name"))?; + } + if model + .provider + .as_deref() + .is_some_and(|id| !provider_ids.contains(id)) + { + return Err(format!("{field}.provider")); + } + check_takes( + &model.efforts, + model.default_effort.as_deref(), + &efforts, + &format!("{field}.efforts"), + &format!("{field}.defaultEffort"), + )?; + check_takes( + &model.speeds, + model.default_speed.as_deref(), + &speeds, + &format!("{field}.speeds"), + &format!("{field}.defaultSpeed"), + )?; + if model + .context_window + .is_some_and(|tokens| tokens == 0 || tokens > MAX_CONTEXT_WINDOW) + { + return Err(format!("{field}.contextWindow")); + } + check_description( + model.description.as_deref(), + &format!("{field}.description"), + )?; + } + if let Some(menu) = &self.model_menu { + if menu.len() > MAX_MODELS { + return Err("modelMenu".into()); + } + let mut seen = BTreeSet::new(); + for (index, id) in menu.iter().enumerate() { + if !ids.contains(id.as_str()) || !seen.insert(id.as_str()) { + return Err(format!("modelMenu[{index}]")); + } + } + } + Ok(()) + } + fn find(&self, id: &str) -> Option<&Provider> { self.providers.iter().find(|provider| provider.id == id) } + + fn listed(&self, id: &str) -> Option<&ListedModel> { + self.models.iter().find(|model| model.id == id) + } + + /// Refuses a model, effort or speed the listed models rule out. A model + /// the change sets is one the plugin lists, when it lists any. An effort + /// or speed the change sets is one the agent offers and, when the plugin + /// lists the model in use after the change, one that model takes. A new + /// model also takes the effort and speed the change keeps, unless the + /// CLI's default sets them or the model lists none of that kind. + fn check_selection( + &self, + model: Option<&str>, + effort: Option<&str>, + speed: Option<&str>, + ) -> Result<(), CoreError> { + if model.is_some_and(|id| !self.models.is_empty() && self.listed(id).is_none()) { + return Err(unknown_model()); + } + let listed = model + .or(self.model.as_ref().map(|current| current.id.as_str())) + .and_then(|id| self.listed(id)); + // One kind of level: the ID the change sets, the levels the agent + // offers, the level in use, the levels a listed model takes, and the + // refusal of an ID the agent does not offer. + struct Kind<'a> { + set: Option<&'a str>, + offered: &'a [Level], + current: Option<&'a CurrentLevel>, + taken_by: fn(&ListedModel) -> &[String], + unknown: fn() -> CoreError, + } + let kinds = [ + Kind { + set: effort, + offered: &self.efforts, + current: self.effort.as_ref(), + taken_by: |model| &model.efforts, + unknown: unknown_effort, + }, + Kind { + set: speed, + offered: &self.speeds, + current: self.speed.as_ref(), + taken_by: |model| &model.speeds, + unknown: unknown_speed, + }, + ]; + for Kind { + set, + offered, + current, + taken_by, + unknown, + } in kinds + { + let takes = listed.map(taken_by); + let takes_it = |id: &str| takes.is_none_or(|takes| takes.iter().any(|took| took == id)); + match set { + Some(value) => { + if !offered.iter().any(|level| level.id == value) { + return Err(unknown()); + } + if !takes_it(value) { + return Err(unsupported_combination()); + } + } + None if model.is_some() => { + let kept = current.filter(|current| !current.is_default()); + let some_taken = takes.is_some_and(|takes| !takes.is_empty()); + if kept.is_some_and(|kept| some_taken && !takes_it(&kept.id)) { + return Err(unsupported_combination()); + } + } + None => {} + } + } + Ok(()) + } } // --------------------------------------------------------------------------- @@ -592,6 +885,25 @@ enum ProviderChange { }, SetModel { model: String, + /// The effort to use with the model; only for an agent that + /// declares `setEffort`. + #[serde(default, skip_serializing_if = "Option::is_none")] + effort: Option, + /// The speed to use with the model; only for an agent that declares + /// `setSpeed`. + #[serde(default, skip_serializing_if = "Option::is_none")] + speed: Option, + }, + SetEffort { + effort: String, + }, + SetSpeed { + speed: String, + }, + /// The listed models the CLI's own model menu shows. Core makes this + /// change when the models Lithe shows change; the host never does. + SetModelMenu { + models: Vec, }, SetProvider { id: String, @@ -606,6 +918,7 @@ enum ProviderChange { enum Target { Providers, Model, + ModelMenu, Provider, Profile, } @@ -617,7 +930,8 @@ impl ProviderChange { | Self::UpdateProvider { .. } | Self::RemoveProvider { .. } | Self::SetProviderEnabled { .. } => Target::Providers, - Self::SetModel { .. } => Target::Model, + Self::SetModel { .. } | Self::SetEffort { .. } | Self::SetSpeed { .. } => Target::Model, + Self::SetModelMenu { .. } => Target::ModelMenu, Self::SetProvider { .. } => Target::Provider, Self::SetProfile { .. } => Target::Profile, } @@ -692,7 +1006,16 @@ impl ProviderChange { Err("id".into()) } } - Self::SetModel { model } => check_name(model, "model"), + Self::SetModel { + model, + effort, + speed, + } => check_name(model, "model") + .and_then(|()| check_level_value(effort.as_deref(), "effort")) + .and_then(|()| check_level_value(speed.as_deref(), "speed")), + Self::SetEffort { effort } => check_level_value(Some(effort), "effort"), + Self::SetSpeed { speed } => check_level_value(Some(speed), "speed"), + Self::SetModelMenu { models } => check_model_ids(models, "models", MAX_MODELS), Self::SetProfile { name } => check_name(name, "name"), }; fields.map_err(|field| invalid_change(&format!("The change's {field} is invalid."))) @@ -752,9 +1075,30 @@ impl ProviderChange { )); } } - Self::SetModel { .. } => { + Self::SetModel { + model, + effort, + speed, + } => { overridden(snapshot.model.as_ref().and_then(|m| m.source.as_ref()))?; + if effort.is_some() { + overridden(snapshot.effort.as_ref().and_then(|e| e.source.as_ref()))?; + } + if speed.is_some() { + overridden(snapshot.speed.as_ref().and_then(|s| s.source.as_ref()))?; + } + snapshot.check_selection(Some(model), effort.as_deref(), speed.as_deref())?; + } + Self::SetEffort { effort } => { + overridden(snapshot.effort.as_ref().and_then(|e| e.source.as_ref()))?; + snapshot.check_selection(None, Some(effort), None)?; } + Self::SetSpeed { speed } => { + overridden(snapshot.speed.as_ref().and_then(|s| s.source.as_ref()))?; + snapshot.check_selection(None, None, Some(speed))?; + } + // Core builds the menu from the listed models itself. + Self::SetModelMenu { .. } => {} Self::SetProvider { id } => { if !saved.iter().any(|provider| provider.id == *id) { snapshot.find(id).ok_or_else(unknown_provider)?; @@ -893,13 +1237,55 @@ impl ProviderChange { 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::SetModel { + model, + effort, + speed, + } => { + snapshot.model.as_ref().is_some_and(|m| m.id == *model) + && level_shows(snapshot.effort.as_ref(), effort.as_deref()) + && level_shows(snapshot.speed.as_ref(), speed.as_deref()) + } + Self::SetEffort { effort } => level_shows(snapshot.effort.as_ref(), Some(effort)), + Self::SetSpeed { speed } => level_shows(snapshot.speed.as_ref(), Some(speed)), + Self::SetModelMenu { models } => snapshot.model_menu.as_ref().is_some_and(|menu| { + menu.iter().collect::>() == models.iter().collect::>() + }), 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), } } } +/// Whether a re-read effort or speed is `wanted`; nothing wanted always +/// shows. +fn level_shows(current: Option<&CurrentLevel>, wanted: Option<&str>) -> bool { + wanted.is_none_or(|wanted| current.is_some_and(|current| current.id == wanted)) +} + +/// An effort or speed a change sets, as the CLI names it. +fn check_level_value(value: Option<&str>, field: &str) -> Check { + if value.is_some_and(|value| !is_token(value)) { + return Err(field.to_string()); + } + Ok(()) +} + +/// At most `max` distinct model IDs. +fn check_model_ids(ids: &[String], field: &str, max: usize) -> Check { + if ids.len() > max { + return Err(field.to_string()); + } + let mut seen = BTreeSet::new(); + for (index, id) in ids.iter().enumerate() { + check_name(id, &format!("{field}[{index}]"))?; + if !seen.insert(id.as_str()) { + return Err(format!("{field}[{index}]")); + } + } + Ok(()) +} + /// The provider the configuration currently uses, as the plugin listed it. fn current_provider(snapshot: &ProvidersSnapshot) -> Option<&Provider> { snapshot @@ -959,6 +1345,46 @@ fn invalid_change(message: &str) -> CoreError { ) } +fn unsupported_operation() -> CoreError { + refusal( + ErrorCode::NotSupported, + "agentProviders.unsupportedOperation", + "The agent plugin does not declare this change.", + ) +} + +fn unknown_model() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentProviders.unknownModel", + "The agent plugin does not list this model.", + ) +} + +fn unknown_effort() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentProviders.unknownEffort", + "The agent offers no reasoning effort with this ID.", + ) +} + +fn unknown_speed() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentProviders.unknownSpeed", + "The agent offers no speed with this ID.", + ) +} + +fn unsupported_combination() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentProviders.unsupportedCombination", + "The model does not take this reasoning effort or speed.", + ) +} + // --------------------------------------------------------------------------- // Plugin calls. @@ -1079,6 +1505,13 @@ fn list_view(view: &mut Value, snapshot: &ProvidersSnapshot, saved: Option<&[Sav if let Some(active) = active { view["provider"]["id"] = json!(active.id); view["provider"]["name"] = json!(active.name); + if let Some(Value::Array(models)) = view.get_mut("models") { + for model in models.iter_mut() { + if model["provider"].as_str() == current_id { + model["provider"] = json!(active.id); + } + } + } } let Some(saved) = saved else { return; @@ -1099,6 +1532,90 @@ fn list_view(view: &mut Value, snapshot: &ProvidersSnapshot, saved: Option<&[Sav } } +/// The operation of the change to the CLI's own model menu. +const MODEL_MENU_OPERATION: &str = "setModelMenu"; + +/// Whether the agent's plugin writes the CLI's own model menu. +fn writes_model_menu(declared: &ProvidersDeclaration) -> bool { + declared.edit.is_some() + && declared + .operations + .iter() + .any(|op| op == MODEL_MENU_OPERATION) +} + +/// Decodes a change of `op` the manifest declares and checks its own +/// fields. A model change carries an effort or speed only for an agent that +/// also declares `setEffort` or `setSpeed`. +fn prepared_change( + declared: &ProvidersDeclaration, + op: &str, + change: Value, +) -> Result { + if op == "invalid" { + let host_operations: Vec<&str> = PROVIDER_OPERATIONS + .into_iter() + .filter(|op| *op != MODEL_MENU_OPERATION) + .collect(); + return Err(invalid_change(&format!( + "A change's op is one of {}.", + host_operations.join(", ") + ))); + } + let declares = |op: &str| declared.operations.iter().any(|declared| declared == op); + if declared.edit.is_none() || !declares(op) { + return Err(unsupported_operation()); + } + let change: ProviderChange = serde_json::from_value(change) + .map_err(|_| invalid_change("The change does not have the fields its op takes."))?; + if let ProviderChange::SetModel { effort, speed, .. } = &change { + if (effort.is_some() && !declares("setEffort")) + || (speed.is_some() && !declares("setSpeed")) + { + return Err(unsupported_operation()); + } + } + change.check(declared.list_kept_by)?; + Ok(change) +} + +/// Logs the outcome of one command that changes an agent's models or +/// providers; `change` is the operation or the command's own name. +fn log_change( + agent: &CatalogAgent, + change: &str, + started: Instant, + outcome: &Result, +) { + match outcome { + Ok(changed) => log( + "agent.providers.change_applied", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("change", json!(change)), + ("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!(change)), + ( + "reason", + json!(error + .details + .as_deref() + .unwrap_or("agentProviders.applyFailed")), + ), + ], + ), + } +} + fn elapsed_ms(started: Instant) -> u64 { u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) } @@ -1122,8 +1639,24 @@ struct ApplyRequest { } impl Library { + /// Reads the agent's snapshot through its plugin and remembers the models + /// it lists. + fn read_and_remember( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + paths: &AgentPaths, + ) -> Result { + let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; + let snapshot = + read_providers(&*runtime.link, agent, configuration, declared, &paths.files)?; + self.catalogs.remember(&agent.record_key(), &snapshot); + Ok(snapshot) + } + /// `agentProviders.read`: each agent that declares providers (or the one - /// `agent` names) with its model, providers, profiles and account label. + /// `agent` names) with its model, providers, profiles, account label and + /// the models it offers, each with whether Lithe's pickers show it. pub fn read_providers(&self, runtime: &Runtime, payload: Value) -> Result { let request: ReadRequest = crate::decode(payload)?; let started = Instant::now(); @@ -1134,12 +1667,17 @@ impl Library { declaration(&agent).ok_or_else(not_declared)?; vec![agent] } - None => runtime - .catalog - .configurable() - .into_iter() - .filter(|agent| declaration(agent).is_some()) - .collect(), + None => { + let agents: Vec = runtime + .catalog + .configurable() + .into_iter() + .filter(|agent| declaration(agent).is_some()) + .collect(); + self.catalogs + .retain(&agents.iter().map(CatalogAgent::record_key).collect()); + agents + } }; let mut failed = 0u64; let entries: Vec = agents @@ -1167,17 +1705,23 @@ impl Library { { entry["backup"] = backup.answer(); } - let read = - read_providers(&*runtime.link, agent, configuration, declared, &paths.files) - .and_then(|snapshot| match declared.list_kept_by { - ListKeptBy::Lithe => saved::load(&config, &agent.record_key()) - .map(|saved| (snapshot, Some(saved))), - ListKeptBy::Cli => Ok((snapshot, None)), - }); + let key = agent.record_key(); + let read = self + .read_and_remember(runtime, agent, &paths) + .and_then(|snapshot| match declared.list_kept_by { + ListKeptBy::Lithe => { + saved::load(&config, &key).map(|saved| (snapshot, Some(saved))) + } + ListKeptBy::Cli => Ok((snapshot, None)), + }) + .and_then(|(snapshot, saved)| { + models::hidden(&config, &key).map(|hidden| (snapshot, saved, hidden)) + }); match read { - Ok((snapshot, saved)) => { + Ok((snapshot, saved, hidden)) => { let mut view = snapshot_view(&snapshot, &paths.files); list_view(&mut view, &snapshot, saved.as_deref()); + models::shown_view(&mut view, &hidden); if let (Value::Object(entry), Value::Object(view)) = (&mut entry, view) { entry.extend(view); } @@ -1228,33 +1772,7 @@ impl Library { .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")), - ), - ], - ), - } + log_change(&agent, &op, started, &outcome); outcome.map(|changed| json!({ "changed": changed })) } @@ -1266,28 +1784,18 @@ impl Library { change: Value, ) -> Result { let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; - if op == "invalid" { + if op == MODEL_MENU_OPERATION { return Err(invalid_change( - "A change's op is one of addProvider, updateProvider, removeProvider, setProviderEnabled, setModel, setProvider or setProfile.", - )); - } - if declared.edit.is_none() || !declared.operations.iter().any(|declared| declared == op) { - return Err(refusal( - ErrorCode::NotSupported, - "agentProviders.unsupportedOperation", - "The agent plugin does not declare this change.", + "The CLI's model menu follows the models Lithe shows; change them with agentProviders.showModels.", )); } - let change: ProviderChange = serde_json::from_value(change) - .map_err(|_| invalid_change("The change does not have the fields its op takes."))?; + let change = prepared_change(declared, op, change)?; let kept_by = declared.list_kept_by; - change.check(kept_by)?; let config = self.config()?; let paths = agent_paths(&config, configuration); - let link = &*runtime.link; let agent_key = agent.record_key(); - let snapshot = read_providers(link, agent, configuration, declared, &paths.files)?; + let snapshot = self.read_and_remember(runtime, agent, &paths)?; let saved_before = match kept_by { ListKeptBy::Lithe => Some(saved::load(&config, &agent_key)?), ListKeptBy::Cli => None, @@ -1383,6 +1891,7 @@ impl Library { let target = match change.target() { Target::Providers => snapshot.targets.providers.as_deref(), Target::Model => snapshot.targets.model.as_deref(), + Target::ModelMenu => snapshot.targets.model_menu.as_deref(), Target::Provider => snapshot.targets.provider.as_deref(), Target::Profile => snapshot.targets.profile.as_deref(), }; diff --git a/rust/crates/agent-runtime/src/library/providers/models.rs b/rust/crates/agent-runtime/src/library/providers/models.rs new file mode 100644 index 00000000..65229abc --- /dev/null +++ b/rust/crates/agent-runtime/src/library/providers/models.rs @@ -0,0 +1,455 @@ +//! Which listed models Lithe's pickers show for each agent +//! (`agentProviders.showModels`), and an agent's model settings as one group +//! (`agentProviders.readModelSettings` and `agentProviders.applyModelSettings`). +//! +//! A plugin may list the models an agent offers in its providers `read` +//! answer. Core keeps the models the user hid, in `models.json` in the +//! library directory, owner-only: one entry per agent record key with the +//! IDs hidden, in the order they were hidden. Every listed model the user did +//! not hide is shown, so a model the plugin adds later is shown, and a hidden +//! model the plugin stops listing keeps its record for when it comes back. +//! A change drops the oldest records of models no longer listed once an +//! agent has more than [`MAX_HIDDEN`]. The file lives as long as the library +//! directory and holds no secret. +//! +//! A plugin that declares `setModelMenu` writes the shown models into the +//! CLI's own model menu: Core saves the switches, then hands the plugin's +//! `edit` the shown models through a staged copy, and puts the switches back +//! when the edit fails. Without it, the switches change only Lithe's pickers. +//! +//! Core remembers the model IDs each agent's plugin last listed, in memory +//! ([`Catalogs`]), so a switch the user flips is checked without asking the +//! plugin again; a plugin that writes the menu is always read again. + +use super::super::{ + agent_paths, check_name, configurable_agent, ensure_private_directory, read_bounded, + require_user, unreadable_file, write_failed, write_replacing, Config, Library, + MAX_LIBRARY_FILE_BYTES, +}; +use super::{ + check_level_value, check_model_ids, declaration, invalid_change, log_change, not_declared, + prepared_change, unknown_model, writes_model_menu, ProviderChange, ProvidersSnapshot, +}; +use crate::catalog::CatalogAgent; +use crate::Runtime; +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Mutex, PoisonError}; +use std::time::Instant; + +const MODELS_FILE: &str = "models.json"; +/// Most hidden models Core keeps for one agent. +const MAX_HIDDEN: usize = 1024; + +// --------------------------------------------------------------------------- +// The switches Core keeps. + +/// One agent's switches. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AgentModels { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + hidden: Vec, +} + +/// The whole file. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ModelsFile { + #[serde(default)] + version: u32, + #[serde(default)] + agents: BTreeMap, +} + +fn read_file(config: &Config) -> Result { + let bytes = read_bounded(&config.directory.join(MODELS_FILE), MAX_LIBRARY_FILE_BYTES) + .map_err(|_| unreadable_file())?; + match bytes { + None => Ok(ModelsFile::default()), + Some(bytes) => serde_json::from_slice::(&bytes) + .ok() + .filter(|file| { + file.version == 0 + && file + .agents + .values() + .all(|agent| check_model_ids(&agent.hidden, "hidden", MAX_HIDDEN).is_ok()) + }) + .ok_or_else(unreadable_file), + } +} + +/// The models the user hid for the agent, in the order they were hidden. +pub(super) fn hidden(config: &Config, agent_key: &str) -> Result, CoreError> { + Ok(read_file(config)? + .agents + .remove(agent_key) + .map(|agent| agent.hidden) + .unwrap_or_default()) +} + +/// Replaces the agent's hidden models; an empty list removes its entry. +fn store(config: &Config, agent_key: &str, hidden: &[String]) -> Result<(), CoreError> { + let mut file = read_file(config)?; + if hidden.is_empty() { + file.agents.remove(agent_key); + } else { + file.agents.insert( + agent_key.to_string(), + AgentModels { + hidden: hidden.to_vec(), + }, + ); + } + ensure_private_directory(&config.directory)?; + let bytes = serde_json::to_vec_pretty(&file).map_err(|_| write_failed())?; + write_replacing(&config.directory.join(MODELS_FILE), &bytes).map_err(|_| write_failed()) +} + +/// Keeps at most [`MAX_HIDDEN`] records, dropping the oldest of the models +/// the plugin no longer lists first. `listed` holds at most `MAX_MODELS` +/// IDs, fewer than `MAX_HIDDEN`, so this always fits. +fn pruned(mut hidden: Vec, listed: &BTreeSet<&str>) -> Vec { + let mut excess = hidden.len().saturating_sub(MAX_HIDDEN); + hidden.retain(|id| { + let drop = excess > 0 && !listed.contains(id.as_str()); + if drop { + excess -= 1; + } + !drop + }); + hidden +} + +/// Adds `shown` to each model of an `agentProviders.read` entry. +pub(super) fn shown_view(view: &mut Value, hidden: &[String]) { + if let Some(Value::Array(models)) = view.get_mut("models") { + for model in models.iter_mut() { + let shown = model["id"] + .as_str() + .is_none_or(|id| !hidden.iter().any(|hidden| hidden == id)); + model["shown"] = json!(shown); + } + } +} + +// --------------------------------------------------------------------------- +// The models each plugin last listed. + +/// The IDs of the models each agent's plugin last listed, by agent record +/// key, from the last snapshot Core read for the agent itself (never from a +/// staged copy). At most one list of at most `MAX_MODELS` IDs per agent the +/// catalog has. +#[derive(Default)] +pub(in crate::library) struct Catalogs(Mutex>>); + +impl Catalogs { + fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap>> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Remembers the models a snapshot of the agent lists. + pub(super) fn remember(&self, agent_key: &str, snapshot: &ProvidersSnapshot) { + self.lock() + .insert(agent_key.to_string(), listed_ids(snapshot)); + } + + /// Forgets the agents not in `keys`, such as those of a removed plugin. + pub(super) fn retain(&self, keys: &BTreeSet) { + self.lock().retain(|key, _| keys.contains(key)); + } + + fn get(&self, agent_key: &str) -> Option> { + self.lock().get(agent_key).cloned() + } +} + +fn listed_ids(snapshot: &ProvidersSnapshot) -> Vec { + snapshot + .models + .iter() + .map(|model| model.id.clone()) + .collect() +} + +// --------------------------------------------------------------------------- +// The settings as one group. + +/// An agent's model settings as one group: the models Lithe's pickers hide, +/// and the model, reasoning effort and speed the CLI uses. A model plan +/// keeps one of these and applies it whole. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ModelSettings { + /// Every record the agent keeps, also of models no longer listed. + hidden: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + effort: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + speed: Option, +} + +impl ModelSettings { + fn check(&self) -> Result<(), CoreError> { + check_model_ids(&self.hidden, "hidden", MAX_HIDDEN) + .and_then(|()| match &self.model { + Some(model) => check_name(model, "model"), + None => Ok(()), + }) + .and_then(|()| check_level_value(self.effort.as_deref(), "effort")) + .and_then(|()| check_level_value(self.speed.as_deref(), "speed")) + .map_err(|field| invalid_change(&format!("The settings' {field} is invalid."))) + } + + /// The changes that make the CLI use the settings' model, effort and + /// speed, in order: one `setModel` that carries the effort and speed + /// that change with it, or a `setEffort` and a `setSpeed`. A value the + /// settings leave out, or that is already in use, changes nothing. + fn selection_changes(&self, snapshot: &ProvidersSnapshot) -> Vec<(&'static str, Value)> { + let differs = |wanted: &Option, now: Option<&str>| { + wanted.clone().filter(|wanted| Some(wanted.as_str()) != now) + }; + let model = differs(&self.model, snapshot.model.as_ref().map(|m| m.id.as_str())); + let effort = differs( + &self.effort, + snapshot.effort.as_ref().map(|e| e.id.as_str()), + ); + let speed = differs(&self.speed, snapshot.speed.as_ref().map(|s| s.id.as_str())); + if let Some(model) = model { + let change = ProviderChange::SetModel { + model, + effort, + speed, + }; + return vec![("setModel", json!(change))]; + } + let mut changes = Vec::new(); + if let Some(effort) = effort { + changes.push(("setEffort", json!(ProviderChange::SetEffort { effort }))); + } + if let Some(speed) = speed { + changes.push(("setSpeed", json!(ProviderChange::SetSpeed { speed }))); + } + changes + } +} + +// --------------------------------------------------------------------------- +// Commands. + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ShowRequest { + agent: String, + #[serde(default)] + show: Vec, + #[serde(default)] + hide: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SettingsRequest { + agent: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ApplySettingsRequest { + agent: String, + settings: ModelSettings, +} + +impl Library { + /// `agentProviders.showModels`: shows and hides listed models in Lithe's + /// pickers, and in the CLI's own menu when the plugin writes it. + pub fn show_models(&self, runtime: &Runtime, payload: Value) -> Result { + require_user()?; + let request: ShowRequest = crate::decode(payload)?; + let started = Instant::now(); + let agent = configurable_agent(runtime, &request.agent)?; + let outcome = self.show_models_checked(runtime, &agent, request.show, request.hide); + log_change(&agent, "showModels", started, &outcome); + outcome.map(|changed| json!({ "changed": changed })) + } + + fn show_models_checked( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + show: Vec, + hide: Vec, + ) -> Result { + check_model_ids(&show, "show", super::MAX_MODELS) + .and_then(|()| check_model_ids(&hide, "hide", super::MAX_MODELS)) + .map_err(|field| invalid_change(&format!("The change's {field} is invalid.")))?; + if show.is_empty() && hide.is_empty() { + return Err(invalid_change( + "A change shows or hides at least one model.", + )); + } + if show.iter().any(|id| hide.contains(id)) { + return Err(invalid_change("A change shows or hides a model, not both.")); + } + self.change_hidden(runtime, agent, |listed, mut hidden| { + if show + .iter() + .chain(&hide) + .any(|id| !listed.contains(id.as_str())) + { + return Err(unknown_model()); + } + hidden.retain(|id| !show.contains(id)); + for id in hide { + if !hidden.contains(&id) { + hidden.push(id); + } + } + Ok(pruned(hidden, listed)) + }) + } + + /// Replaces the agent's hidden models with what `change` makes of them, + /// given the listed model IDs, and has the CLI's menu follow when the + /// plugin writes it. Answers whether anything changed. + fn change_hidden( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + change: impl FnOnce(&BTreeSet<&str>, Vec) -> Result, CoreError>, + ) -> Result { + let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; + let config = self.config()?; + let paths = agent_paths(&config, configuration); + let key = agent.record_key(); + // The menu is written from the configuration as it is now. + let snapshot = if writes_model_menu(declared) { + Some(self.read_and_remember(runtime, agent, &paths)?) + } else { + None + }; + let ids = match (&snapshot, self.catalogs.get(&key)) { + (Some(snapshot), _) => listed_ids(snapshot), + (None, Some(ids)) => ids, + (None, None) => listed_ids(&self.read_and_remember(runtime, agent, &paths)?), + }; + let listed: BTreeSet<&str> = ids.iter().map(String::as_str).collect(); + let (before, after) = { + let _writing = self.lock_writing(); + let before = hidden(&config, &key)?; + let after = change(&listed, before.clone())?; + if after != before { + store(&config, &key, &after)?; + } + (before, after) + }; + let saved = after != before; + let Some(snapshot) = snapshot else { + return Ok(saved); + }; + let shown: Vec = ids + .iter() + .filter(|id| !after.contains(id)) + .cloned() + .collect(); + let in_menu: Option> = snapshot + .model_menu + .as_ref() + .map(|menu| menu.iter().collect()); + if in_menu == Some(shown.iter().collect()) { + return Ok(saved); + } + let menu = ProviderChange::SetModelMenu { models: shown }; + let edited = self.edit_providers( + runtime, + agent, + &config, + &paths, + &snapshot, + &menu, + json!(menu), + None, + ); + if edited.is_err() && saved { + let _writing = self.lock_writing(); + // The plugin's refusal is what the user needs to see; switches + // that cannot be put back read as the user just set them. + // log-exempt: Same failure already recorded: this put-back follows the menu edit failure returned below, which the command logs as agent.providers.change_failed and the request trace records; switches it cannot put back stay as the user set them, and Lithe's pickers show them. + let _ = store(&config, &key, &before); + } + edited.map(|changed| changed || saved) + } + + /// `agentProviders.readModelSettings`: the agent's switches and the + /// model, effort and speed it uses, as one group. + pub fn read_model_settings( + &self, + runtime: &Runtime, + payload: Value, + ) -> Result { + let request: SettingsRequest = crate::decode(payload)?; + let agent = configurable_agent(runtime, &request.agent)?; + let (configuration, _) = declaration(&agent).ok_or_else(not_declared)?; + let config = self.config()?; + let paths = agent_paths(&config, configuration); + let snapshot = self.read_and_remember(runtime, &agent, &paths)?; + let settings = ModelSettings { + hidden: hidden(&config, &agent.record_key())?, + model: snapshot.model.map(|model| model.id), + effort: snapshot.effort.map(|effort| effort.id), + speed: snapshot.speed.map(|speed| speed.id), + }; + Ok(json!({ "settings": settings })) + } + + /// `agentProviders.applyModelSettings`: makes the agent use the + /// settings' model, effort and speed, then replaces its switches. + pub fn apply_model_settings( + &self, + runtime: &Runtime, + payload: Value, + ) -> Result { + require_user()?; + let request: ApplySettingsRequest = crate::decode(payload)?; + let started = Instant::now(); + let agent = configurable_agent(runtime, &request.agent)?; + let outcome = self.apply_model_settings_checked(runtime, &agent, request.settings); + log_change(&agent, "applyModelSettings", started, &outcome); + outcome.map(|changed| json!({ "changed": changed })) + } + + fn apply_model_settings_checked( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + settings: ModelSettings, + ) -> Result { + settings.check()?; + let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; + let config = self.config()?; + let paths = agent_paths(&config, configuration); + let snapshot = self.read_and_remember(runtime, agent, &paths)?; + // Every change is checked before the first is made, so a refused + // one leaves the configuration as it was. + let changes = settings.selection_changes(&snapshot); + for (op, change) in &changes { + prepared_change(declared, op, change.clone())?.check_against( + &snapshot, + declared.list_kept_by, + &[], + )?; + } + let mut changed = false; + for (op, change) in changes { + changed |= self.apply_providers_checked(runtime, agent, op, change)?; + } + let hidden = settings.hidden; + changed |= self.change_hidden(runtime, agent, |_, _| Ok(hidden))?; + Ok(changed) + } +} diff --git a/rust/crates/agent-runtime/src/tests/providers.rs b/rust/crates/agent-runtime/src/tests/providers.rs index fa77425f..9524ef36 100644 --- a/rust/crates/agent-runtime/src/tests/providers.rs +++ b/rust/crates/agent-runtime/src/tests/providers.rs @@ -649,4 +649,5 @@ impl LibraryHarness { mod backups; mod keys; +mod models; mod saved; diff --git a/rust/crates/agent-runtime/src/tests/providers/models.rs b/rust/crates/agent-runtime/src/tests/providers/models.rs new file mode 100644 index 00000000..631249b3 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers/models.rs @@ -0,0 +1,794 @@ +//! The models a plugin lists for an agent: what Core accepts from it, which +//! models Lithe's pickers show, the checks of a model, effort or speed +//! change, the CLI's own model menu and the settings as one group. + +use super::*; + +const MODEL_OPERATIONS: &[&str] = &["setModel", "setEffort", "setSpeed"]; +const MENU_OPERATIONS: &[&str] = &["setModel", "setEffort", "setSpeed", "setModelMenu"]; + +/// The models the synthetic CLI offers, the way a plugin would list them. +fn catalog() -> Value { + json!([ + { + "id": "alpha-large", "name": "Alpha Large", "provider": "local", + "efforts": ["low", "medium", "high", "xhigh"], "defaultEffort": "medium", + "speeds": ["standard", "fast"], "defaultSpeed": "standard", + "contextWindow": 400000, "description": "The largest Alpha model." + }, + { + "id": "alpha-mini", "name": "Alpha Mini", "provider": "local", + "efforts": ["low", "medium"], "defaultEffort": "medium", + "speeds": ["standard"], "contextWindow": 128000 + }, + { "id": "gateway-chat", "name": "Gateway Chat", "provider": "gateway", "contextWindow": 200000 } + ]) +} + +/// `providers.read` of a CLI that keeps its model, effort, speed and model +/// menu in `main`. Without a menu in the file the CLI's menu lists every +/// model. +fn models_read(params: &Value, catalog: &Value) -> Value { + let config = read_json(Path::new(params["files"][0]["path"].as_str().unwrap())); + let user = json!({ "layer": "user", "file": "main" }); + let current = |key: &str, default: &str| match config[key].as_str() { + Some(id) => json!({ "id": id, "source": user }), + None => json!({ "id": default, "source": { "layer": "default" } }), + }; + let listed: Vec<&Value> = catalog + .as_array() + .unwrap() + .iter() + .map(|model| &model["id"]) + .collect(); + let menu: Vec<&Value> = match config["menu"].as_array() { + Some(menu) => listed + .iter() + .copied() + .filter(|id| menu.contains(id)) + .collect(), + None => listed, + }; + json!({ + "format": "litheAgentProviders", + "version": 0, + "providers": [ + { "id": "local", "name": "Local", "builtIn": true }, + { "id": "gateway", "name": "Gateway", "baseUrl": "https://gateway.example.test/v1" } + ], + "model": current("model", "alpha-large"), + "models": catalog, + "efforts": [ + { "id": "low", "name": "Low" }, { "id": "medium", "name": "Medium" }, + { "id": "high", "name": "High" }, { "id": "xhigh", "name": "Extra high" } + ], + "speeds": [{ "id": "standard", "name": "Standard" }, { "id": "fast", "name": "Fast" }], + "effort": current("effort", "medium"), + "speed": current("speed", "standard"), + "modelMenu": menu, + "targets": { "model": "main", "modelMenu": "main" } + }) +} + +fn models_edit(params: &Value) -> 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() { + "setModel" => { + config["model"] = change["model"].clone(); + for key in ["effort", "speed"] { + if let Some(value) = change.get(key) { + config[key] = value.clone(); + } + } + } + "setEffort" => config["effort"] = change["effort"].clone(), + "setSpeed" => config["speed"] = change["speed"].clone(), + "setModelMenu" => config["menu"] = change["models"].clone(), + _ => return Err(failure("plugin.params.invalid")), + } + let changed = config != before; + if changed { + fs::write(&staging, serde_json::to_vec(&config).unwrap()).unwrap(); + } + Ok(json!({ "format": "litheAgentProvidersEdit", "version": 0, "changed": changed })) +} + +struct ModelsTest { + test: ProvidersTest, + /// The models the synthetic plugin lists now. + catalog: Arc>, + /// Whether `providers.edit` fails. + failing: Arc>, +} + +impl ModelsTest { + fn new(name: &str, operations: &[&str]) -> Self { + let test = ProvidersTest::new(name, PROVIDER_GRANTS, operations); + let catalog = Arc::new(Mutex::new(catalog())); + let failing = Arc::new(Mutex::new(false)); + let (listed, fails) = (catalog.clone(), failing.clone()); + test.harness + .link + .set_answer(move |function, params| match function { + "providers.read" => Ok(models_read(params, &listed.lock().unwrap())), + "providers.edit" if *fails.lock().unwrap() => Err(failure("plugin.failed")), + "providers.edit" => models_edit(params), + other => sample_backend(other, params), + }); + test.write_config(json!({ "model": "alpha-large" })); + Self { + test, + catalog, + failing, + } + } + + /// Each listed model's ID and whether it is shown. + fn shown(&self) -> Vec<(String, bool)> { + self.test.read()["models"] + .as_array() + .unwrap() + .iter() + .map(|model| { + ( + model["id"].as_str().unwrap().to_string(), + model["shown"].as_bool().unwrap(), + ) + }) + .collect() + } + + fn show(&self, show: &[&str], hide: &[&str]) -> bool { + self.test.harness.run( + "agentProviders.showModels", + json!({ "agent": AGENT_KEY, "show": show, "hide": hide }), + )["changed"] + .as_bool() + .unwrap() + } + + fn show_refused(&self, show: &[&str], hide: &[&str]) -> String { + self.test.harness.refused( + "agentProviders.showModels", + json!({ "agent": AGENT_KEY, "show": show, "hide": hide }), + ) + } + + fn settings(&self) -> Value { + self.test.harness.run( + "agentProviders.readModelSettings", + json!({ "agent": AGENT_KEY }), + )["settings"] + .clone() + } + + fn apply_settings(&self, settings: Value) -> bool { + self.test.harness.run( + "agentProviders.applyModelSettings", + json!({ "agent": AGENT_KEY, "settings": settings }), + )["changed"] + .as_bool() + .unwrap() + } + + fn settings_refused(&self, settings: Value) -> String { + self.test.harness.refused( + "agentProviders.applyModelSettings", + json!({ "agent": AGENT_KEY, "settings": settings }), + ) + } + + fn set_catalog(&self, catalog: Value) { + *self.catalog.lock().unwrap() = catalog; + } + + fn models_file(&self) -> PathBuf { + self.test.library.join("models.json") + } +} + +fn shown(pairs: &[(&str, bool)]) -> Vec<(String, bool)> { + pairs + .iter() + .map(|(id, shown)| (id.to_string(), *shown)) + .collect() +} + +#[test] +fn an_agent_whose_plugin_lists_no_models_has_none() { + let test = ProvidersTest::new("models none", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + let agent = test.read(); + assert_eq!( + agent["models"], + json!([]), + "no list unless the plugin gives one" + ); + assert!(agent.get("efforts").is_none()); + assert!(agent.get("speeds").is_none()); + assert_eq!( + test.harness.refused( + "agentProviders.showModels", + json!({ "agent": AGENT_KEY, "hide": ["alpha-large"] }), + ), + "agentProviders.unknownModel" + ); + assert_eq!( + test.harness.run( + "agentProviders.readModelSettings", + json!({ "agent": AGENT_KEY }) + )["settings"], + json!({ "hidden": [], "model": "alpha-large" }) + ); + assert!( + test.apply(json!({ "op": "setModel", "model": "any-model-name" })), + "without a list, any model name is the plugin's to judge" + ); + assert_eq!( + test.refused(json!({ "op": "setEffort", "effort": "high" })), + "agentProviders.unsupportedOperation" + ); +} + +#[test] +fn a_listed_model_follows_the_limits() { + let test = ProvidersTest::new("models limits", PROVIDER_GRANTS, MODEL_OPERATIONS); + let invalid = json!("agentProviders.invalidSnapshot"); + let model = |extra: Value| { + let mut row = json!({ "id": "alpha-large", "efforts": ["high"], "speeds": ["fast"] }); + for (key, value) in extra.as_object().unwrap() { + row[key.as_str()] = value.clone(); + } + row + }; + let answer = |models: Value, extra: Value| { + let mut answer = snapshot(json!({ + "models": models, + "efforts": [{ "id": "high" }], + "speeds": [{ "id": "fast" }] + })); + for (key, value) in extra.as_object().unwrap() { + answer[key.as_str()] = value.clone(); + } + answer + }; + let many = |count: usize| { + json!((0..count) + .map(|i| json!({ "id": format!("model-{i}") })) + .collect::>()) + }; + for (case, bad) in [ + ("too many models", answer(many(513), json!({}))), + ( + "a repeated model", + answer(json!([model(json!({})), model(json!({}))]), json!({})), + ), + ( + "a blank model ID", + answer(json!([model(json!({ "id": " " }))]), json!({})), + ), + ( + "a provider the snapshot does not list", + answer(json!([model(json!({ "provider": "absent" }))]), json!({})), + ), + ( + "an effort the agent does not offer", + answer(json!([model(json!({ "efforts": ["max"] }))]), json!({})), + ), + ( + "a default the model does not take", + answer( + json!([model(json!({ "defaultSpeed": "standard" }))]), + json!({}), + ), + ), + ( + "too many efforts", + answer( + json!([]), + json!({ "efforts": (0..17).map(|i| json!({ "id": format!("e{i}") })).collect::>() }), + ), + ), + ( + "an effort ID with a space", + answer(json!([]), json!({ "efforts": [{ "id": "very high" }] })), + ), + ( + "a context window of nothing", + answer(json!([model(json!({ "contextWindow": 0 }))]), json!({})), + ), + ( + "a context window too large", + answer( + json!([model(json!({ "contextWindow": 1_000_000_001_u64 }))]), + json!({}), + ), + ), + ( + "a long description", + answer( + json!([model(json!({ "description": "a".repeat(1025) }))]), + json!({}), + ), + ), + ( + "a field Core does not know", + answer(json!([model(json!({ "price": 3 }))]), json!({})), + ), + ( + "a menu with a model not listed", + answer(json!([model(json!({}))]), json!({ "modelMenu": ["gamma"] })), + ), + ( + "an undeclared menu target", + answer(json!([]), json!({ "targets": { "modelMenu": "other" } })), + ), + ( + "an effort in use from an undeclared file", + answer( + json!([]), + json!({ "effort": { "id": "high", "source": { "layer": "user", "file": "other" } } }), + ), + ), + ] { + assert_eq!(test.read_error(bad), invalid, "{case}"); + } + assert!( + test.read_error(answer(many(512), json!({}))).is_null(), + "512 models are within the limit" + ); + assert!(test + .read_error(answer( + json!([model( + json!({ "provider": "alpha", "contextWindow": 1_000_000_000_u64 }) + )]), + json!({ "modelMenu": ["alpha-large"], "effort": { "id": "high" } }) + )) + .is_null()); +} + +#[test] +fn every_listed_model_is_shown_until_the_user_hides_it() { + let test = ModelsTest::new("models shown", MODEL_OPERATIONS); + assert_eq!( + test.shown(), + shown(&[ + ("alpha-large", true), + ("alpha-mini", true), + ("gateway-chat", true) + ]), + "every listed model is shown by default" + ); + let agent = test.test.read(); + assert_eq!(agent["models"][0]["contextWindow"], 400000); + assert_eq!(agent["models"][0]["defaultEffort"], "medium"); + assert_eq!( + agent["efforts"][3], + json!({ "id": "xhigh", "name": "Extra high" }) + ); + assert_eq!(agent["effort"]["source"]["layer"], "default"); + + let reads = test.test.harness.link.calls_of("providers.read").len(); + let (changed, logs) = capture::run(false, || test.show(&[], &["gateway-chat"])); + assert!(changed); + assert_eq!( + test.test.harness.link.calls_of("providers.read").len(), + reads, + "Core checks the switch against the models it remembers" + ); + let applied = logs + .iter() + .find(|log| log.event == "agent.providers.change_applied") + .expect("the switch is logged"); + assert_eq!(applied.fields["change"], json!("showModels")); + assert!(test.test.harness.link.calls_of("providers.edit").is_empty()); + assert_eq!( + read_json(&test.test.config_file()), + json!({ "model": "alpha-large" }), + "without setModelMenu only Lithe's pickers change" + ); + assert!( + !test.show(&[], &["gateway-chat"]), + "hiding it again changes nothing" + ); + + // The plugin lists a new model and stops listing the hidden one. + let mut models = catalog(); + let models_list = models.as_array_mut().unwrap(); + models_list.remove(2); + models_list.push(json!({ "id": "alpha-next", "name": "Alpha Next", "provider": "local" })); + test.set_catalog(models); + assert_eq!( + test.shown(), + shown(&[ + ("alpha-large", true), + ("alpha-mini", true), + ("alpha-next", true) + ]), + "a new model is shown, a model no longer listed is not listed" + ); + assert_eq!( + test.settings()["hidden"], + json!(["gateway-chat"]), + "the switch of a model no longer listed is kept" + ); + assert_eq!( + test.show_refused(&["gateway-chat"], &[]), + "agentProviders.unknownModel" + ); + + test.set_catalog(catalog()); + assert_eq!( + test.shown()[2], + ("gateway-chat".to_string(), false), + "a hidden model that comes back stays hidden" + ); + assert!(test.show(&["gateway-chat"], &["alpha-mini"])); + assert_eq!( + test.shown(), + shown(&[ + ("alpha-large", true), + ("alpha-mini", false), + ("gateway-chat", true) + ]) + ); + + for (case, show, hide) in [ + ("nothing to change", &[][..], &[][..]), + ("both at once", &["alpha-mini"][..], &["alpha-mini"][..]), + ("a repeated ID", &[][..], &["alpha-mini", "alpha-mini"][..]), + ] { + assert_eq!( + test.show_refused(show, hide), + "agentProviders.invalidChange", + "{case}" + ); + } + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let background = test.show_refused(&[], &["alpha-large"]); + trace::replace(previous); + assert_eq!(background, "agentLibrary.userActionRequired"); +} + +#[test] +fn the_oldest_switches_of_models_no_longer_listed_go_first() { + let test = ModelsTest::new("models bounded", MODEL_OPERATIONS); + let gone: Vec = (0..1024).map(|i| format!("gone-{i}")).collect(); + fs::create_dir_all(&test.test.library).unwrap(); + fs::write( + test.models_file(), + serde_json::to_vec(&json!({ "version": 0, "agents": { AGENT_KEY: { "hidden": gone } } })) + .unwrap(), + ) + .unwrap(); + assert!(test.show(&[], &["alpha-mini", "gateway-chat"])); + let hidden = test.settings()["hidden"].as_array().unwrap().clone(); + assert_eq!(hidden.len(), 1024); + assert_eq!(hidden[0], "gone-2", "the two oldest records went"); + assert_eq!(hidden[1022..], [json!("alpha-mini"), json!("gateway-chat")]); + + fs::write(test.models_file(), b"{\"version\": 0, \"agents\": 3}").unwrap(); + assert_eq!( + test.test.read()["readError"], + "agentLibrary.unreadable", + "a broken switch file is reported, not guessed" + ); +} + +#[test] +fn a_selection_must_be_in_the_list() { + let test = ModelsTest::new("models selection", MODEL_OPERATIONS); + let expect = |change: Value, code: &str| assert_eq!(test.test.refused(change), code); + expect( + json!({ "op": "setModel", "model": "absent" }), + "agentProviders.unknownModel", + ); + expect( + json!({ "op": "setEffort", "effort": "turbo" }), + "agentProviders.unknownEffort", + ); + expect( + json!({ "op": "setSpeed", "speed": "warp" }), + "agentProviders.unknownSpeed", + ); + expect( + json!({ "op": "setModel", "model": "alpha-large", "effort": "turbo" }), + "agentProviders.unknownEffort", + ); + expect( + json!({ "op": "setEffort", "effort": "very high" }), + "agentProviders.invalidChange", + ); + expect( + json!({ "op": "setModelMenu", "models": ["alpha-large"] }), + "agentProviders.invalidChange", + ); + assert!(test.test.harness.link.calls_of("providers.edit").is_empty()); + + assert!(test + .test + .apply(json!({ "op": "setEffort", "effort": "high" }))); + assert!(test + .test + .apply(json!({ "op": "setSpeed", "speed": "fast" }))); + assert!(test.test.apply( + json!({ "op": "setModel", "model": "alpha-mini", "effort": "low", "speed": "standard" }) + )); + let agent = test.test.read(); + assert_eq!(agent["model"]["id"], "alpha-mini"); + assert_eq!(agent["effort"]["id"], "low"); + assert_eq!(agent["speed"]["id"], "standard"); + assert_eq!(agent["effort"]["source"]["layer"], "user"); + + let only_model = ModelsTest::new("models undeclared", &["setModel"]); + assert_eq!( + only_model + .test + .refused(json!({ "op": "setModel", "model": "alpha-mini", "effort": "low" })), + "agentProviders.unsupportedOperation", + "a model change carries an effort only where setEffort is declared" + ); +} + +#[test] +fn combinations_a_model_does_not_take_are_refused() { + let test = ModelsTest::new("models combinations", MODEL_OPERATIONS); + test.test + .write_config(json!({ "model": "alpha-large", "effort": "xhigh" })); + let expect = |change: Value, code: &str| assert_eq!(test.test.refused(change), code); + expect( + json!({ "op": "setModel", "model": "alpha-mini" }), + "agentProviders.unsupportedCombination", + ); + expect( + json!({ "op": "setModel", "model": "alpha-mini", "effort": "high" }), + "agentProviders.unsupportedCombination", + ); + expect( + json!({ "op": "setModel", "model": "alpha-mini", "effort": "low", "speed": "fast" }), + "agentProviders.unsupportedCombination", + ); + let before = fs::read(test.test.config_file()).unwrap(); + assert!(test.test.harness.link.calls_of("providers.edit").is_empty()); + assert_eq!(fs::read(test.test.config_file()).unwrap(), before); + + assert!( + test.test + .apply(json!({ "op": "setModel", "model": "gateway-chat" })), + "a model that lists no efforts ignores the one kept" + ); + expect( + json!({ "op": "setEffort", "effort": "low" }), + "agentProviders.unsupportedCombination", + ); + expect( + json!({ "op": "setSpeed", "speed": "fast" }), + "agentProviders.unsupportedCombination", + ); + assert!(test + .test + .apply(json!({ "op": "setModel", "model": "alpha-mini", "effort": "medium" }))); + expect( + json!({ "op": "setEffort", "effort": "high" }), + "agentProviders.unsupportedCombination", + ); + + // An effort the CLI's default sets follows the model. + test.test.write_config(json!({ "model": "alpha-large" })); + *test.catalog.lock().unwrap() = { + let mut models = catalog(); + models[1]["efforts"] = json!(["low"]); + models[1]["defaultEffort"] = json!("low"); + models + }; + assert!(test + .test + .apply(json!({ "op": "setModel", "model": "alpha-mini" }))); +} + +#[test] +fn the_cli_menu_follows_only_where_the_plugin_writes_it() { + let test = ModelsTest::new("models menu", MENU_OPERATIONS); + assert!(test.show(&[], &["gateway-chat"])); + let edits = test.test.harness.link.calls_of("providers.edit"); + assert_eq!(edits.len(), 1); + assert_eq!( + edits[0]["change"], + json!({ "op": "setModelMenu", "models": ["alpha-large", "alpha-mini"] }), + "the plugin gets the shown models in the order it listed them" + ); + assert_eq!( + read_json(&test.test.config_file())["menu"], + json!(["alpha-large", "alpha-mini"]) + ); + assert_eq!( + test.test.read()["modelMenu"], + json!(["alpha-large", "alpha-mini"]) + ); + assert!(!test.show(&[], &["gateway-chat"])); + assert_eq!( + test.test.harness.link.calls_of("providers.edit").len(), + 1, + "a menu that already shows the models is left alone" + ); + + *test.failing.lock().unwrap() = true; + assert_eq!( + test.show_refused(&[], &["alpha-mini"]), + "agentProviders.editFailed" + ); + assert_eq!( + test.shown()[1], + ("alpha-mini".to_string(), true), + "the switch goes back when the CLI's menu cannot follow" + ); + *test.failing.lock().unwrap() = false; + + assert!(test.show(&["gateway-chat"], &[])); + assert_eq!( + read_json(&test.test.config_file())["menu"], + json!(["alpha-large", "alpha-mini", "gateway-chat"]) + ); + assert_eq!(test.settings()["hidden"], json!([])); +} + +#[test] +fn settings_are_read_and_applied_as_one_group() { + let test = ModelsTest::new("models settings", MENU_OPERATIONS); + test.test + .write_config(json!({ "model": "alpha-large", "effort": "high", "speed": "fast" })); + assert!(test.show(&[], &["gateway-chat"])); + let plan = test.settings(); + assert_eq!( + plan, + json!({ "hidden": ["gateway-chat"], "model": "alpha-large", "effort": "high", "speed": "fast" }) + ); + + assert!(test.show(&["gateway-chat"], &["alpha-mini"])); + assert!(test.test.apply( + json!({ "op": "setModel", "model": "alpha-mini", "effort": "low", "speed": "standard" }) + )); + assert_ne!(test.settings(), plan); + + let (changed, logs) = capture::run(false, || test.apply_settings(plan.clone())); + assert!(changed); + assert!(logs + .iter() + .any(|log| log.event == "agent.providers.change_applied" + && log.fields["change"] == json!("applyModelSettings"))); + assert_eq!(test.settings(), plan, "the group is back as it was read"); + assert_eq!( + read_json(&test.test.config_file())["menu"], + json!(["alpha-large", "alpha-mini"]), + "the CLI's menu follows the switches written back" + ); + assert!( + !test.apply_settings(plan.clone()), + "the same group changes nothing" + ); + + // A group the list rules out changes nothing at all. + let config = fs::read(test.test.config_file()).unwrap(); + for (case, settings, code) in [ + ( + "a model not listed", + json!({ "hidden": [], "model": "absent" }), + "agentProviders.unknownModel", + ), + ( + "a model with an effort it does not take", + json!({ "hidden": [], "model": "alpha-mini", "effort": "xhigh" }), + "agentProviders.unsupportedCombination", + ), + ( + "a speed the agent does not offer", + json!({ "hidden": [], "effort": "low", "speed": "warp" }), + "agentProviders.unknownSpeed", + ), + ( + "a repeated hidden model", + json!({ "hidden": ["alpha-mini", "alpha-mini"] }), + "agentProviders.invalidChange", + ), + ] { + assert_eq!(test.settings_refused(settings), code, "{case}"); + assert_eq!(fs::read(test.test.config_file()).unwrap(), config, "{case}"); + assert_eq!(test.settings(), plan, "{case}"); + } + assert_eq!( + test.settings_refused(json!({ "model": "alpha-large" })), + "agents.invalidPayload", + "the group always names its hidden models" + ); + + // Hidden records of models no longer listed are written back as given. + assert!(test.apply_settings(json!({ "hidden": ["retired-model"] }))); + assert_eq!(test.settings()["hidden"], json!(["retired-model"])); + assert!(test.shown().iter().all(|(_, shown)| *shown)); +} + +#[test] +fn listed_models_follow_the_saved_provider_in_use() { + let test = ProvidersTest::new( + "models saved provider", + PROVIDER_GRANTS, + &["addProvider", "setModel"], + ); + let mut manifest = providers_manifest(&["addProvider", "setModel"]); + manifest["agents"][0]["configuration"]["providers"]["listKeptBy"] = json!("lithe"); + test.harness.run( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": PROVIDER_GRANTS }] }), + ); + test.harness.link.set_answer(|function, params| match function { + "providers.read" => Ok(json!({ + "format": "litheAgentProviders", + "version": 0, + "provider": { "id": "custom" }, + "providers": [ + { "id": "official", "name": "Official", "builtIn": true }, + { "id": "custom", "name": "Custom endpoint", "baseUrl": "https://work.example.test/v1" } + ], + "models": [ + { "id": "official-model", "provider": "official" }, + { "id": "work-model", "provider": "custom" } + ], + "targets": { "model": "main" } + })), + other => sample_backend(other, params), + }); + assert!(test.apply(json!({ "op": "addProvider", "provider": { + "id": "work", "name": "Work", "baseUrl": "https://work.example.test/v1" + } }))); + let agent = test.read(); + assert_eq!(agent["provider"]["id"], "work"); + assert_eq!(agent["models"][0]["provider"], "official"); + assert_eq!( + agent["models"][1]["provider"], "work", + "a model of the provider in use names the saved provider" + ); +} + +#[test] +fn the_shared_fixture_reads_and_refuses_as_written() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../../../shared/plugins/contract/v1/fixtures/agents/model-catalog.json" + )) + .unwrap(); + let operations: Vec<&str> = fixture["operations"] + .as_array() + .unwrap() + .iter() + .map(|op| op.as_str().unwrap()) + .collect(); + let test = ProvidersTest::new("models fixture", PROVIDER_GRANTS, &operations); + *test.answer.lock().unwrap() = Some(fixture["answer"].clone()); + fs::create_dir_all(&test.library).unwrap(); + fs::write( + test.library.join("models.json"), + serde_json::to_vec( + &json!({ "version": 0, "agents": { AGENT_KEY: { "hidden": fixture["hidden"] } } }), + ) + .unwrap(), + ) + .unwrap(); + let agent = test.read(); + for (field, expected) in fixture["view"].as_object().unwrap() { + assert_eq!(&agent[field.as_str()], expected, "{field}"); + } + for refusal in fixture["refusals"].as_array().unwrap() { + assert_eq!( + test.refused(refusal["change"].clone()), + refusal["code"].as_str().unwrap(), + "{}", + refusal["change"] + ); + } + assert!(test.harness.link.calls_of("providers.edit").is_empty()); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index e7d1fdd6..45cc3444 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -292,6 +292,14 @@ pub enum AgentsCommand { ProvidersApply, /// Puts an agent's configuration back as Lithe backed it up (`agentProviders.restore`). ProvidersRestore, + /// Shows or hides listed models in Lithe's pickers (`agentProviders.showModels`). + ProvidersShowModels, + /// Reads an agent's model switches and selection as one group + /// (`agentProviders.readModelSettings`). + ProvidersReadModelSettings, + /// Applies an agent's model switches and selection as one group + /// (`agentProviders.applyModelSettings`). + ProvidersApplyModelSettings, } impl AgentsCommand { @@ -332,6 +340,9 @@ impl AgentsCommand { Self::ProvidersRead => "agentProviders.read", Self::ProvidersApply => "agentProviders.apply", Self::ProvidersRestore => "agentProviders.restore", + Self::ProvidersShowModels => "agentProviders.showModels", + Self::ProvidersReadModelSettings => "agentProviders.readModelSettings", + Self::ProvidersApplyModelSettings => "agentProviders.applyModelSettings", } } } @@ -1358,6 +1369,13 @@ impl CoreCommand { "agentProviders.read" => Some(Self::Agents(AgentsCommand::ProvidersRead)), "agentProviders.apply" => Some(Self::Agents(AgentsCommand::ProvidersApply)), "agentProviders.restore" => Some(Self::Agents(AgentsCommand::ProvidersRestore)), + "agentProviders.showModels" => Some(Self::Agents(AgentsCommand::ProvidersShowModels)), + "agentProviders.readModelSettings" => { + Some(Self::Agents(AgentsCommand::ProvidersReadModelSettings)) + } + "agentProviders.applyModelSettings" => { + Some(Self::Agents(AgentsCommand::ProvidersApplyModelSettings)) + } "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index a934a6aa..e534f272 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -323,7 +323,7 @@ fn agents_are_reviewed_programs() { "editable": true, "instructions": ["${env:EXAMPLE_HOME}/INSTRUCTIONS.md", "${userHome}/.example/INSTRUCTIONS.md"], "skills": ["${userHome}/.example/skills"], - "providers": {"operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setProvider"]} + "providers": {"operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setEffort", "setSpeed", "setModelMenu", "setProvider"]} }), json!({ "kind": "agentSessions", diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 6c216f86..17195436 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -141,7 +141,7 @@ pub static EVENTS: &[EventMetadata] = &[ 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: "change", field_type: FieldType::Token, required: true, description: "Operation applied, such as addProvider or setModel; showModels when the models Lithe's pickers show changed, applyModelSettings when a group of model settings was written back", 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 }, @@ -157,7 +157,7 @@ pub static EVENTS: &[EventMetadata] = &[ 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: "change", field_type: FieldType::Token, required: true, description: "Operation asked for, such as addProvider or setModel, or showModels or applyModelSettings; 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 }, ], diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index 93435a42..d97356ab 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -95,12 +95,15 @@ 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] = [ +pub const PROVIDER_OPERATIONS: [&str; 10] = [ "addProvider", "updateProvider", "removeProvider", "setProviderEnabled", "setModel", + "setEffort", + "setSpeed", + "setModelMenu", "setProvider", "setProfile", ]; @@ -172,14 +175,16 @@ pub struct ConfigurationDeclaration { } /// The model and model providers of an agent, read and changed by backend -/// functions in the declared configuration files. Keys are write-only: a +/// functions in the declared configuration files. `read` may also list the +/// models the agent offers with the reasoning efforts and speeds each takes; +/// Core keeps which of them Lithe's pickers show. Keys are write-only: a /// change may carry one to `edit`, and `read` reports only whether one is /// set, never a value. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProvidersDeclaration { - /// Backend function that reports the model, providers, profiles and - /// account label. + /// Backend function that reports the model, providers, profiles, + /// account label and the models the agent offers. pub read: String, /// Backend function that applies one change to a staged copy of one /// file. diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 61c20880..ad5027f1 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -535,7 +535,7 @@ "change": { "type": "token", "required": true, - "description": "Operation applied, such as addProvider or setModel" + "description": "Operation applied, such as addProvider or setModel; showModels when the models Lithe's pickers show changed, applyModelSettings when a group of model settings was written back" }, "changed": { "type": "bool", @@ -570,7 +570,7 @@ "change": { "type": "token", "required": true, - "description": "Operation asked for, such as addProvider or setModel; invalid when it is not one" + "description": "Operation asked for, such as addProvider or setModel, or showModels or applyModelSettings; invalid when it is not one" }, "reason": { "type": "token", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 6ff32414..d429a6ec 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -34,7 +34,7 @@ This directory is the cross-platform source of truth: | `fixtures/run/` | Run sessions and console links: `tool-reference-launch` names its runtimes by tool-definition ID and declares output link matchers; `run-start.json` holds what `run.decodeStart` returns for each case, including the rejections, and `output-link-matchers.json` the golden matches and resolutions | | `fixtures/vcs/` | A version control provider | | `fixtures/keymap-import/` | Two independent shortcut import providers sharing one packaged backend | -| `fixtures/agents/` | `agents.plugin.json`: an agent with native, terminal and update forms and a session source, served by its backend; `terminal-agent.plugin.json`: a terminal-only agent without a backend. Their rejections are in `fixtures/manifest/invalid-manifests.json`; `native-session.json` holds golden native-session notifications with the calls each session's handler receives, the reports of failed starts and prompts, and the `agents` host method requests | +| `fixtures/agents/` | `agents.plugin.json`: an agent with native, terminal and update forms and a session source, served by its backend; `terminal-agent.plugin.json`: a terminal-only agent without a backend. Their rejections are in `fixtures/manifest/invalid-manifests.json`; `native-session.json` holds golden native-session notifications with the calls each session's handler receives, the reports of failed starts and prompts, and the `agents` host method requests; `record-read.json` holds session-source `read` requests and answers without and with the opt-in message IDs, tool-call details and commands; `model-catalog.json` holds the models a providers `read` answer lists, the picker view Core makes of them with the user's hidden models, and the changes `agentProviders.apply` refuses against them, with their codes | | `fixtures/project-generators/` | Project generators: template files (`templates/`), a scaffolding command, and an archive download; `project-generator-tool-field.plugin.json` with `templates/tool-field/` picks tool installations with `tool` fields; `project-plans.json` holds golden `project.*` form evaluations, generation plans, and name checks, and a case's optional `manifest` names the fixture it runs against (`project-generator.plugin.json` by default) | | `fixtures/toolchains/` | Production-shape fixtures for tool definitions and a packaged toolchain provider; they require `toolDefinitions` and `toolchainProviders`, which a host advertises only when it implements them | | `fixtures/package-trust/` | `publisher-bundled.plugin.json` and `signature-vectors.json`: public cross-platform vectors for the package publisher signature: the RFC 8032 test key, a fixed package with non-ASCII file names, its canonical payload, RFC 8032 deterministic signature, and content digest. Both platforms must build the same canonical payload and digest and accept the recorded signature; signers that add randomness, such as CryptoKit, check the signature by verification instead of byte comparison | @@ -4655,7 +4655,7 @@ and keeps no name or icon of its own for any agent. | `files` | At most 8 `{id, roots}`: the files in the CLI's own format that hold its MCP servers, hooks, model and model providers. `id` is 1–64 bytes of lowercase ASCII letters, digits and `-`, not starting or ending with `-`, unique in the agent. Only the backend reads their format. | | `read` | Backend function that reports the MCP servers and hooks `files` hold. Required with `files`, unless `providers` is declared, and refused without them. | | `edit` | Backend function that applies one change to a staged copy of one of `files`. Needs `read`. Without it the agent's MCP servers and hooks are shown, never changed. | -| `providers` | `{read, edit?, operations?, listKeptBy?}`: backend functions that report and change the CLI's model, model providers and profiles kept in `files` (see [Models and providers](#models-and-providers)). Needs `files`. `edit` and `operations` come together; `operations` lists each change `edit` makes at most once, from `addProvider`, `updateProvider`, `removeProvider`, `setProviderEnabled`, `setModel`, `setProvider` and `setProfile`. `listKeptBy` is `cli` (the default) when the CLI's configuration holds every custom provider, or `lithe` when it holds one active custom endpoint and Lithe keeps the list the user saved (see [Providers Lithe keeps](#providers-lithe-keeps)). | +| `providers` | `{read, edit?, operations?, listKeptBy?}`: backend functions that report and change the CLI's model, model providers and profiles kept in `files`, and may list the models the agent offers (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`, `setEffort`, `setSpeed`, `setModelMenu`, `setProvider` and `setProfile`. `listKeptBy` is `cli` (the default) when the CLI's configuration holds every custom provider, or `lithe` when it holds one active custom endpoint and Lithe keeps the list the user saved (see [Providers Lithe keeps](#providers-lithe-keeps)). | - A configuration declares at least one of `instructions`, `skills` and `files`. A function ID is dot-separated lowerCamelCase segments. @@ -5071,14 +5071,21 @@ seconds. Any other answer is `agentLibrary.invalidEdit`; a failed call is 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. +The plugin may also list the models the agent offers, with the reasoning +efforts and speeds each takes; the user then picks among them and chooses +which of them Lithe's pickers show (see [Listed models](#listed-models)). +Core knows no CLI, model, variable or file layout: every name comes from +the plugin, and the host draws the views. Without a list from the plugin +there is none: the host and Core keep no model names of their own. | Command | Payload | Result | | --- | --- | --- | | `agentProviders.read` | `{agent?}` | `{agents}` | | `agentProviders.apply` | `{agent, change}` | `{changed}` | | `agentProviders.restore` | `{agent, discardLaterChanges?}` | `{restored: true, unfollowed}` | +| `agentProviders.showModels` | `{agent, show?, hide?}` | `{changed}` | +| `agentProviders.readModelSettings` | `{agent}` | `{settings}` | +| `agentProviders.applyModelSettings` | `{agent, settings}` | `{changed}` | `restore` puts back every file of the agent Lithe changed, for any agent that declares `configuration`, with or without `providers`; see @@ -5115,7 +5122,19 @@ without `providers`): "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"} + "models": [ + {"id": "model-a", "name": "Model A", "provider": "builtin", "efforts": ["low", "medium", "high"], + "defaultEffort": "medium", "speeds": ["standard", "fast"], "defaultSpeed": "standard", + "contextWindow": 400000, "description": "The model for long tasks.", "shown": true}, + {"id": "model-b", "name": "Model B", "provider": "gateway", "efforts": ["low", "medium"], + "speeds": ["standard"], "contextWindow": 128000, "shown": false} + ], + "efforts": [{"id": "low", "name": "Low"}, {"id": "medium", "name": "Medium"}, {"id": "high", "name": "High"}], + "speeds": [{"id": "standard", "name": "Standard"}, {"id": "fast", "name": "Fast"}], + "effort": {"id": "high", "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}}, + "speed": {"id": "standard", "source": {"layer": "default"}}, + "modelMenu": ["model-a"], + "targets": {"providers": "main", "model": "main", "provider": "main", "profile": "main", "modelMenu": "main"} }] } ``` @@ -5137,6 +5156,10 @@ without `providers`): whichever command changed them: when it was kept, in milliseconds since the epoch, and whether a file now differs from what Lithe last wrote. It is the same `backup` that `agentLibrary.read` gives the agent. +- `models` is always there, empty when the plugin lists none. Each listed + model gains `shown`: whether Lithe's pickers show it (see + [Listed models](#listed-models)). `efforts`, `speeds`, `effort`, `speed` + and `modelMenu` are there when the plugin reports them. - A failed read gives `readError` (`agentLibrary.backendUnavailable`, `agentProviders.readFailed` or `agentProviders.invalidSnapshot`) in place of the snapshot; the other agents still answer. @@ -5150,10 +5173,16 @@ without `providers`): | `{op: "updateProvider", provider, key?, clearKey?}` | replaces the provider's `name`, `baseUrl`, `protocol`, `keyVariable` and, when given, `enabled`; a `key` replaces its key, `clearKey: true` removes it, neither keeps it | `providers` | | `{op: "removeProvider", id}` | removes the provider | `providers` | | `{op: "setProviderEnabled", id, enabled}` | turns the provider on or off (`agentProviders.noEnabledState` when its `enabled` was not reported) | `providers` | -| `{op: "setModel", model}` | sets the model the CLI uses | `model` | +| `{op: "setModel", model, effort?, speed?}` | sets the model the CLI uses; `effort` and `speed` set the reasoning effort and speed with it, for an agent that also declares `setEffort` and `setSpeed` (`agentProviders.unsupportedOperation` otherwise) | `model` | +| `{op: "setEffort", effort}` | sets the reasoning effort the CLI uses | `model` | +| `{op: "setSpeed", speed}` | sets the speed the CLI uses, such as a fast mode | `model` | | `{op: "setProvider", id}` | sets the provider the CLI uses | `provider` | | `{op: "setProfile", name}` | sets the profile the CLI uses (`agentProviders.unknownProfile`) | `profile` | +`setModelMenu` is a change only Core makes, when the models Lithe shows +change (see [Listed models](#listed-models)); `apply` refuses it as +`agentProviders.invalidChange`. + `provider` in a change is `{id, name, baseUrl?, protocol?, keyVariable?, enabled?, model?}`; the provider's header and query parameter names stay as the plugin keeps them. With `listKeptBy: "lithe"` it is `{id, name, @@ -5180,10 +5209,12 @@ whether there is one. Core checks, in this order: 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. With `listKeptBy: "lithe"`, the + one (`agentProviders.builtInProvider`). `setModel`, `setEffort`, + `setSpeed`, `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. `setModel`, + `setEffort` and `setSpeed` follow the plugin's list of models (see + [Listed models](#listed-models)). With `listKeptBy: "lithe"`, the provider changes check the saved list instead, as [Providers Lithe keeps](#providers-lithe-keeps) describes. 4. The snapshot's `targets` names the file for the change @@ -5191,7 +5222,8 @@ whether there is one. Core checks, in this order: 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`; a `key` shows as `keySet: true`, - `clearKey` as `keySet: false`); the file is replaced only if it still + `clearKey` as `keySet: false`, an effort or speed as `effort` or `speed` + in use); 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. @@ -5201,6 +5233,84 @@ whether there is one. Core checks, in this order: `apply` answers `changed: false` when the file already held the change. +##### Listed models + +A plugin lists the models an agent offers in its `read` answer: `models`, +with the `efforts` and `speeds` the CLI offers (see +[Provider functions](#provider-functions)). Core keeps no model list of its +own; an agent whose plugin lists none has an empty `models`, nothing to +show or hide, and Core checks a `setModel` only for its form. + +**Picking.** With a list, the model, effort and speed a change sets must be +listed: a `setModel` model the plugin does not list is +`agentProviders.unknownModel`, and an effort or speed the agent does not +offer in `efforts` or `speeds` is `agentProviders.unknownEffort` or +`agentProviders.unknownSpeed`. When the plugin lists the model in use after +the change, the effort and speed the change sets must be ones that model +takes; a model that lists no efforts (or speeds) takes none, and Core +refuses a `setEffort` (or `setSpeed`) for it. A `setModel` must also leave +an effort and speed the new model takes: the current ones it keeps are +checked against the new model too, except a value whose `source.layer` is +`default`, which follows the model, and a kind the new model lists none +of. Every one of these refusals is `agentProviders.unsupportedCombination` +and happens before the plugin is called; to change both, a `setModel` +carries the `effort` or `speed` the new model takes. + +**Showing.** Core keeps, for each agent, the listed models the user hid in +Lithe's pickers, in `models.json` in the library directory (owner-only, +no secrets): the IDs in the order they were hidden. `read` gives each +listed model `shown`. A listed model the user has not hidden is shown, so +every model is shown at first and a model the plugin adds later is shown. +A hidden model the plugin stops listing is no longer in `models`, but its +record is kept, and the model is hidden again when the plugin lists it +again. An agent keeps at most 1024 records; a change that would keep more +drops the oldest records of models the plugin no longer lists. + +`agentProviders.showModels {agent, show?, hide?}` runs only for a request +whose origin is the user (`agentLibrary.userActionRequired`). `show` and +`hide` are each at most 512 distinct model IDs, together at least one and +no ID in both (`agentProviders.invalidChange`), each a model the plugin +lists (`agentProviders.unknownModel`). Core checks them against the models +the plugin listed when Core last read the agent, and reads the agent when +it has not yet. It answers `{changed}`, `false` when every model already +was as asked. + +The switches change Lithe's pickers. A plugin that declares +`setModelMenu` also has the CLI's own model menu follow them: Core reads +the agent, saves the switches, and when the shown models differ from the +snapshot's `modelMenu`, calls `edit` with `{op: "setModelMenu", models}`, +the shown models in the order the plugin lists them (possibly none), on a +staged copy of the file `targets.modelMenu` names +(`agentProviders.noTarget` without one), backed up first like any change. +The re-read copy must report exactly those models as `modelMenu` +(`agentProviders.editNotApplied`). When the edit fails, Core puts the +switches back and answers the edit's refusal. A plugin without +`setModelMenu` leaves the CLI's menu as it is. + +**Settings as one group.** `agentProviders.readModelSettings {agent}` +answers `{settings: {hidden, model?, effort?, speed?}}`: every record of +the agent's hidden models, including models the plugin no longer lists, +and the model, effort and speed in use, as the plugin read them now. +`agentProviders.applyModelSettings {agent, settings}`, only for a request +whose origin is the user, takes the same shape back: `hidden` is required +(at most 1024 distinct model IDs, which need not be listed now), the +others optional. Core reads the agent and turns each of `model`, `effort` +and `speed` that differs from the one in use into changes: one `setModel` +carrying the effort and speed that change with it, or else a `setEffort` +and a `setSpeed`. It checks every change as `apply` would before making the +first, so a refused one changes nothing; then it makes them, replaces the +hidden records with `hidden` and has the CLI's menu follow as above. It +answers `{changed}`. A value left out stays as it is. A malformed +`settings` is `agentProviders.invalidChange`, and a payload without +`hidden` is `agents.invalidPayload`. + +```json +{ + "agent": "dev.example.agents/alpha", + "settings": {"hidden": ["model-b"], "model": "model-a", "effort": "high", "speed": "standard"} +} +``` + ##### Providers Lithe keeps Some CLIs keep one custom endpoint in their configuration, not a list. A @@ -5267,8 +5377,29 @@ configuration `read`, and answers within 10 seconds exactly: - `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. +- `models`: at most 512 `{id, name?, provider?, efforts?, defaultEffort?, + speeds?, defaultSpeed?, contextWindow?, description?}`, the models the + agent offers, IDs unique; empty when the plugin lists none. `id` is the + model as the CLI names it. `provider` is the `id` of an entry of + `providers` that serves it. `efforts` and `speeds` are the IDs of the + agent's `efforts` and `speeds` the model takes, each once, and none when + it takes no such setting; `defaultEffort` and `defaultSpeed` are among + them, the ones the CLI uses with the model when none is set. + `contextWindow` is how many tokens a prompt may hold, 1–1000000000. + `description` is at most 1024 characters without NUL. List the CLI's + normal speed among a model's `speeds` when the model runs at it; +- `efforts`: at most 16 `{id, name?}`, the reasoning efforts the CLI + offers, lowest first, IDs unique; +- `speeds`: at most 16 `{id, name?}`, the speeds the CLI offers, such as + a normal speed and a fast mode, IDs unique; +- `effort?` and `speed?`: `{id, source?}`, the effort and speed in use; +- `modelMenu?`: the IDs of the listed models the CLI's own model menu + shows now, each once. A plugin that declares `setModelMenu` reports it, + every listed model when the CLI's configuration keeps no menu of its + own; +- `targets`: `{providers?, model?, provider?, profile?, modelMenu?}`, the + declared file `id` each kind of change goes to: `setModel`, `setEffort` + and `setSpeed` go to `model`. A `source` is `{layer, file?, path?, variable?, profile?}`: `layer` is `user`, `profile`, `default` or `environment`; `file` is a declared file's @@ -5294,10 +5425,10 @@ an unknown field, is `agentProviders.invalidSnapshot`; a failed call is - **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. + and `_`, at most 128 bytes; `protocol`, `cliVersion` and an effort or + speed `id` 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 of @@ -5318,7 +5449,11 @@ field for it, or, with `listKeptBy: "lithe"`, stored in the plugin's credentials and written when the provider is in use; `clearKey: true` removes it. With `listKeptBy: "lithe"`, `change` carries the extra fields [Providers Lithe keeps](#providers-lithe-keeps) lists. A plugin never puts -a key in its answer, an error message or a log. +a key in its answer, an error message or a log. `setModel` writes the +`effort` and `speed` it carries with the model; `setModelMenu` makes the +CLI's own model menu show exactly `models`, which the plugin may write as +the CLI's allow list, as a list of hidden models, or by removing the CLI's +restriction when `models` holds every listed model. #### Backups and restore diff --git a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json index e202933d..7e98b547 100644 --- a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -94,6 +94,9 @@ "updateProvider", "removeProvider", "setModel", + "setEffort", + "setSpeed", + "setModelMenu", "setProvider" ] } diff --git a/shared/plugins/contract/v1/fixtures/agents/model-catalog.json b/shared/plugins/contract/v1/fixtures/agents/model-catalog.json new file mode 100644 index 00000000..f3c84442 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/agents/model-catalog.json @@ -0,0 +1,95 @@ +{ + "description": "The models a plugin lists for an agent in its providers read answer (configuration.providers, plan API-45). `answer` is what the plugin's read function returns; `hidden` the models the user hid in Lithe's pickers; `view` the model fields of the agent's entry in agentProviders.read, each listed model with `shown`; `refusals` changes agentProviders.apply refuses against this answer, with their codes. The agent declares setModel, setEffort and setSpeed.", + "operations": ["setModel", "setEffort", "setSpeed"], + "answer": { + "format": "litheAgentProviders", + "version": 0, + "model": { "id": "model-a", "source": { "layer": "user", "file": "main" } }, + "providers": [ + { "id": "builtin", "name": "Built-in", "builtIn": true }, + { "id": "gateway", "name": "Gateway", "baseUrl": "https://gateway.example.com/v1" } + ], + "models": [ + { + "id": "model-a", + "name": "Model A", + "provider": "builtin", + "efforts": ["low", "medium", "high"], + "defaultEffort": "medium", + "speeds": ["standard", "fast"], + "defaultSpeed": "standard", + "contextWindow": 400000, + "description": "The model for long tasks." + }, + { + "id": "model-b", + "name": "Model B", + "provider": "builtin", + "efforts": ["low", "medium"], + "defaultEffort": "low", + "speeds": ["standard"], + "contextWindow": 128000 + }, + { "id": "model-c", "provider": "gateway", "contextWindow": 200000 } + ], + "efforts": [ + { "id": "low", "name": "Low" }, + { "id": "medium", "name": "Medium" }, + { "id": "high", "name": "High" } + ], + "speeds": [ + { "id": "standard", "name": "Standard" }, + { "id": "fast", "name": "Fast" } + ], + "effort": { "id": "high", "source": { "layer": "user" } }, + "speed": { "id": "standard", "source": { "layer": "default" } }, + "targets": { "model": "main" } + }, + "hidden": ["model-c", "retired-model"], + "view": { + "models": [ + { + "id": "model-a", + "name": "Model A", + "provider": "builtin", + "efforts": ["low", "medium", "high"], + "defaultEffort": "medium", + "speeds": ["standard", "fast"], + "defaultSpeed": "standard", + "contextWindow": 400000, + "description": "The model for long tasks.", + "shown": true + }, + { + "id": "model-b", + "name": "Model B", + "provider": "builtin", + "efforts": ["low", "medium"], + "defaultEffort": "low", + "speeds": ["standard"], + "contextWindow": 128000, + "shown": true + }, + { "id": "model-c", "provider": "gateway", "contextWindow": 200000, "shown": false } + ], + "efforts": [ + { "id": "low", "name": "Low" }, + { "id": "medium", "name": "Medium" }, + { "id": "high", "name": "High" } + ], + "speeds": [ + { "id": "standard", "name": "Standard" }, + { "id": "fast", "name": "Fast" } + ], + "effort": { "id": "high", "source": { "layer": "user" } }, + "speed": { "id": "standard", "source": { "layer": "default" } } + }, + "refusals": [ + { "change": { "op": "setModel", "model": "model-d" }, "code": "agentProviders.unknownModel" }, + { "change": { "op": "setEffort", "effort": "max" }, "code": "agentProviders.unknownEffort" }, + { "change": { "op": "setSpeed", "speed": "turbo" }, "code": "agentProviders.unknownSpeed" }, + { "change": { "op": "setModel", "model": "model-b" }, "code": "agentProviders.unsupportedCombination" }, + { "change": { "op": "setModel", "model": "model-b", "effort": "low", "speed": "fast" }, "code": "agentProviders.unsupportedCombination" }, + { "change": { "op": "setModelMenu", "models": ["model-a"] }, "code": "agentProviders.invalidChange" } + ] +} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 2fb0c0a5..327bed37 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -554,7 +554,7 @@ "$ref": "#/$defs/pluginFunctionID" }, "providers": { - "description": "Added within agents 0. Backend functions that report and change the CLI's model, model providers and profiles kept in files. Needs files. Keys are write-only: a change may carry one to the edit function, and answers report only whether one is set (keySet), never a key, token, header or query value; endpoints have no user, password, query or fragment; plugins never read credential files or the keychain.", + "description": "Added within agents 0. Backend functions that report and change the CLI's model, model providers and profiles kept in files, and may list the models the agent offers with the reasoning efforts and speeds each takes. Needs files. Keys are write-only: a change may carry one to the edit function, and answers report only whether one is set (keySet), never a key, token, header or query value; endpoints have no user, password, query or fragment; plugins never read credential files or the keychain.", "type": "object", "additionalProperties": false, "required": ["read"], @@ -572,12 +572,12 @@ "$ref": "#/$defs/pluginFunctionID" }, "operations": { - "description": "The changes edit makes; Core refuses any other with agentProviders.unsupportedOperation.", + "description": "The changes edit makes; Core refuses any other with agentProviders.unsupportedOperation. setModelMenu means the plugin writes the listed models Lithe shows into the CLI's own model menu; the host never sends it.", "type": "array", "minItems": 1, "uniqueItems": true, "items": { - "enum": ["addProvider", "updateProvider", "removeProvider", "setProviderEnabled", "setModel", "setProvider", "setProfile"] + "enum": ["addProvider", "updateProvider", "removeProvider", "setProviderEnabled", "setModel", "setEffort", "setSpeed", "setModelMenu", "setProvider", "setProfile"] } }, "listKeptBy": { diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index ec09c739..fd00d60f 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 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充);插件可在 `providers` 快照里[列出模型](../contract/v1/README.md#listed-models)及其推理强度、速度档和上下文窗口,Core 检查选择在清单里、组合是插件允许的,用户在 Lithe 选择器里显示或隐藏模型的开关由 Core 记住(`agentProviders.showModels`),插件声明 `setModelMenu` 时 CLI 自己的模型菜单跟着变,开关和选择可整组读出、写回(`agentProviders.readModelSettings`、`agentProviders.applyModelSettings`)(`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. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | +| 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. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0); the plugin may [list models](../contract/v1/README.md#listed-models) in the `providers` snapshot with their reasoning efforts, speeds, and context windows, Core checks that a pick is listed and a combination the plugin allows, Core keeps the switches with which the user shows or hides models in Lithe's pickers (`agentProviders.showModels`), the CLI's own model menu follows them when the plugin declares `setModelMenu`, and the switches and picks are read and written back as one group (`agentProviders.readModelSettings`, `agentProviders.applyModelSettings`) (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces, saving and switching model plans; 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 48e4623d..00e29abf 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -67,7 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令;插件在 `providers` 快照里列出的模型(`models`、`efforts`、`speeds`、`effort`、`speed`、`modelMenu`、`targets.modelMenu`)、操作 `setEffort`、`setSpeed`、`setModelMenu` 和 `setModel` 的 `effort`、`speed`,以及命令 `agentProviders.showModels`、`agentProviders.readModelSettings`、`agentProviders.applyModelSettings` 是最后的补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -188,7 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands | ✅ | Pending host integration | [Agents](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands; the models a plugin lists in the `providers` snapshot (`models`, `efforts`, `speeds`, `effort`, `speed`, `modelMenu`, `targets.modelMenu`), the operations `setEffort`, `setSpeed` and `setModelMenu` with the `effort` and `speed` of `setModel`, and the commands `agentProviders.showModels`, `agentProviders.readModelSettings` and `agentProviders.applyModelSettings` were added last | ✅ | 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 7f10c237..55dfd42d 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -85,15 +85,20 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 `configuration` 里再声明 `providers: {read, edit?, operations?, listKeptBy?}`,宿主就能显示 CLI 当前用的模型、可用的模型供应商、配置档和登录账号标签,并让用户修改。它和 MCP 服务器、Hooks 共用 `files`、`agents.configuration` 授权和暂存副本流程: - `read` 报告 `litheAgentProviders` 快照,每个值带来源层(`user`、`profile`、`default`、`environment`)和来源文件或变量名;`edit` 只改 Core 给的暂存副本,Core 再读一遍副本确认改动生效后原子替换。 -- `operations` 列出 `edit` 支持的操作(`addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setProvider`、`setProfile`);没列出的操作 Core 在调用插件前就以 `agentProviders.unsupportedOperation` 拒绝。 +- `operations` 列出 `edit` 支持的操作(`addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setEffort`、`setSpeed`、`setModelMenu`、`setProvider`、`setProfile`);没列出的操作 Core 在调用插件前就以 `agentProviders.unsupportedOperation` 拒绝。 - **密钥只写不读**:`addProvider`、`updateProvider` 可以带 `key`(1–1024 字节,不含控制字符和换行,否则 `agentProviders.invalidKey`),`updateProvider` 可以带 `clearKey: true`,两者同时给是 `agentProviders.invalidChange`,都不给就保留原来的密钥。Core 只在内存里把密钥交给插件的 `edit`,任何回答、日志、事件和错误都不带它;读取只回答 `keySet` 表示有没有密钥。密钥的环境变量名 `keyVariable`、请求头和查询参数只给名字,快照里没有能放值的字段,多一个字段整份拒绝。CLI 把端点写在设置文件的环境变量块里时,插件把它报成该供应商的 `baseUrl`,块里其他变量只把名字放进 `environmentNames`。 - 端点只能是不带用户名、密码、查询和片段的 `http`/`https` 地址;名称、列表都有上限。 - 插件不得读取 CLI 的凭据文件(如 `auth.json`、`.credentials.json`)和系统钥匙串,账号标签只来自不含凭据的设置或 CLI 命令。 - 被环境变量覆盖的当前模型、供应商或配置档改文件不会生效,Core 以 `agentProviders.overridden` 拒绝;CLI 内置的供应商只显示,不能改或删。 - **由 Lithe 保存供应商列表**:配置里只能放一个自定义端点的 CLI,插件声明 `listKeptBy: "lithe"`。Core 把用户保存的供应商 `{id, name, baseUrl, protocol?, model?}` 和“插件是否存了密钥”记在资源库目录的 `saved-providers.json`(仅所有者可读写,不含密钥);密钥由插件用 `lithe/host/credentials/set|get|delete`(`credentials.store` 权限)存在自己的命名空间。读取时正在用的自定义供应商按 `baseUrl` 对上已保存的供应商,没在用的已保存供应商以 `origin: "lithe"` 追加。重复的 ID 是 `agentProviders.providerExists`,重复的端点是 `agentProviders.endpointExists`,删正在用的供应商是 `agentProviders.activeProvider`。Core 先存列表再调用插件,插件失败就把列表恢复原样。 - **备份与恢复**:`apply` 替换文件前先备份,和资源库的改动共用同一份备份,见下面的“修改前备份与恢复”。 +- **模型清单**(`agents` 0 内的补充):插件可以在 `read` 的快照里列出这个 Agent 能用的模型 `models`(每项 `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`,最多 512 个),以及 CLI 提供的推理强度 `efforts`、速度档 `speeds`(如普通速度和快速模式,各最多 16 个)和正在用的 `effort`、`speed`。插件不列,就什么都没有:宿主和 Core 不内置任何模型名单。 + - **选择**:`setModel` 可以同时带 `effort`、`speed`(插件也声明了 `setEffort`、`setSpeed` 时),另有 `setEffort`、`setSpeed`,都写进 `targets.model` 那个文件。有清单时,Core 先检查值在清单里(`agentProviders.unknownModel`、`unknownEffort`、`unknownSpeed`),再按插件给的组合规则检查:模型列出的 `efforts`、`speeds` 才能用,换模型时保留下来的强度和速度也要新模型支持(来源层是 `default` 的跟着模型走,不检查),否则 `agentProviders.unsupportedCombination`,都不调用插件。 + - **显示开关**:`agentProviders.showModels {agent, show?, hide?}`(只接受用户发起的请求)切换某些模型在 Lithe 选择器里是否显示。Core 把隐藏的模型按隐藏顺序记在资源库目录的 `models.json`(仅所有者可读写,不含机密),`read` 给每个列出的模型加 `shown`。默认全部显示,插件新加的模型也显示;插件去掉的模型不再列出,但它的隐藏记录保留,再出现时仍隐藏;每个 Agent 最多 1024 条记录,超出时先丢最早的、已不在清单里的。Core 用最近一次读到的清单检查开关,不必每次问插件。 + - **CLI 自己的模型菜单**:插件声明 `setModelMenu` 时,开关变化后 Core 把显示的模型(按插件的顺序)用 `{op: "setModelMenu", models}` 经暂存副本交给插件写进 `targets.modelMenu` 那个文件,重读的 `modelMenu` 必须正好是这些模型,插件写失败就把开关恢复原样;不声明时开关只影响 Lithe 自己的选择器。宿主不能直接发 `setModelMenu`(`agentProviders.invalidChange`)。 + - **整组读出与写回**:`agentProviders.readModelSettings {agent}` 回答 `{settings: {hidden, model?, effort?, speed?}}`,`agentProviders.applyModelSettings {agent, settings}`(只接受用户发起的请求)原样写回:先把要改的模型、强度、速度全部按 `apply` 的规则检查一遍,有一个不行就什么都不改,再依次修改、替换隐藏记录并让 CLI 菜单跟上。以后的“方案”保存和切换的就是这一组。 -命令是 `agentProviders.read {agent?}`、`agentProviders.apply {agent, change}` 和 `agentProviders.restore {agent, discardLaterChanges?}`,字段、拒绝码和完整示例见[契约](../../contract/v1/README.md#models-and-providers)。 +命令是 `agentProviders.read {agent?}`、`agentProviders.apply {agent, change}`、`agentProviders.restore {agent, discardLaterChanges?}`、`agentProviders.showModels {agent, show?, hide?}`、`agentProviders.readModelSettings {agent}` 和 `agentProviders.applyModelSettings {agent, settings}`,字段、拒绝码和完整示例见[契约](../../contract/v1/README.md#models-and-providers),模型清单的规则见[契约的 Listed models](../../contract/v1/README.md#listed-models),示例数据见 `fixtures/agents/model-catalog.json`。 ### 修改前备份与恢复 @@ -236,15 +241,20 @@ See the [contract](../../contract/v1/README.md#instruction-files). An agent whose `configuration` also declares `providers: {read, edit?, operations?, listKeptBy?}` lets the host show the model the CLI uses, its model providers, profiles and signed-in account label, and lets the user change them. It shares `files`, the `agents.configuration` grant and the staged-copy flow with MCP servers and hooks: - `read` reports a `litheAgentProviders` snapshot, each value with its layer (`user`, `profile`, `default`, `environment`) and its source file or variable name; `edit` changes only the staged copy Core gives it, and Core reads the copy back to see the change before replacing the file atomically. -- `operations` lists what `edit` does (`addProvider`, `updateProvider`, `removeProvider`, `setProviderEnabled`, `setModel`, `setProvider`, `setProfile`); Core refuses any other with `agentProviders.unsupportedOperation` before calling the plugin. +- `operations` lists what `edit` does (`addProvider`, `updateProvider`, `removeProvider`, `setProviderEnabled`, `setModel`, `setEffort`, `setSpeed`, `setModelMenu`, `setProvider`, `setProfile`); Core refuses any other with `agentProviders.unsupportedOperation` before calling the plugin. - **Keys are write-only**: `addProvider` and `updateProvider` may carry a `key` (1–1024 bytes without control characters or line breaks, else `agentProviders.invalidKey`), and `updateProvider` may carry `clearKey: true`; both together are `agentProviders.invalidChange`, and neither keeps the key. Core hands the key in memory to the plugin's `edit` only; no answer, log, event or error carries it, and a read answers only `keySet`, whether there is one. The key's environment variable `keyVariable`, headers and query parameters are names only; the snapshot has no field that could hold a value, and an extra field refuses the whole answer. When the CLI keeps an endpoint in its settings' environment block, the plugin reports it as that provider's `baseUrl` and every other variable of the block by name only, in `environmentNames`. - An endpoint is an `http` or `https` URL without a user, password, query or fragment; names and lists have upper limits. - Plugins never read the CLI's credential files (such as `auth.json` or `.credentials.json`) or the system keychain; the account label comes only from settings or CLI commands that carry no credentials. - A current model, provider or profile an environment variable sets would not change by editing the file, so Core refuses it with `agentProviders.overridden`; providers built into the CLI are shown, never changed or removed. - **Providers Lithe keeps**: a plugin for a CLI whose configuration holds one custom endpoint declares `listKeptBy: "lithe"`. Core keeps the providers the user saved, `{id, name, baseUrl, protocol?, model?}` and whether the plugin stored a key, in `saved-providers.json` in the library directory (owner-only, never a key); the plugin keeps each key in its own namespace with `lithe/host/credentials/set|get|delete` (the `credentials.store` permission). A read matches the custom provider in use to a saved one by `baseUrl` and appends the saved providers not in use with `origin: "lithe"`. A taken ID is `agentProviders.providerExists`, a taken endpoint `agentProviders.endpointExists`, and removing the provider in use `agentProviders.activeProvider`. Core saves the list before calling the plugin and puts it back when the plugin fails. - **Backups and restore**: `apply` backs a file up before replacing it, in the same backup the library's changes use; see "Backups before a change, and restore" below. +- **Listed models** (added within `agents` 0): the plugin may list the models the agent offers in the `read` snapshot, `models` (each `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`, at most 512), with the reasoning efforts `efforts` and speeds `speeds` the CLI offers (such as a normal speed and a fast mode, at most 16 each) and the `effort` and `speed` in use. Without a list from the plugin there is none: neither the host nor Core keeps model names of its own. + - **Picking**: `setModel` may carry `effort` and `speed` (when the plugin also declares `setEffort` and `setSpeed`), beside `setEffort` and `setSpeed`; all go to the file `targets.model` names. With a list, Core checks that a value is listed (`agentProviders.unknownModel`, `unknownEffort`, `unknownSpeed`) and then the combination rules the plugin gives: only the `efforts` and `speeds` a model lists, and on a model change the effort and speed it keeps must suit the new model too (a value whose layer is `default` follows the model and is not checked); otherwise `agentProviders.unsupportedCombination`, all before the plugin is called. + - **Show switches**: `agentProviders.showModels {agent, show?, hide?}` (user requests only) shows or hides models in Lithe's pickers. Core records the hidden models, in the order hidden, in `models.json` in the library directory (owner-only, no secrets), and `read` gives each listed model `shown`. Every model is shown by default, including one the plugin adds later; a model the plugin drops is no longer listed but keeps its record, and is hidden again when it comes back; an agent keeps at most 1024 records, dropping the oldest of models no longer listed first. Core checks a switch against the list it read last, without asking the plugin each time. + - **The CLI's own model menu**: when the plugin declares `setModelMenu`, Core hands the shown models (in the plugin's order) to the plugin as `{op: "setModelMenu", models}` on a staged copy of the file `targets.modelMenu` names after a switch changes; the re-read `modelMenu` must be exactly those models, and when the plugin fails the switches go back. Without it the switches affect only Lithe's pickers. The host cannot send `setModelMenu` itself (`agentProviders.invalidChange`). + - **Settings as one group**: `agentProviders.readModelSettings {agent}` answers `{settings: {hidden, model?, effort?, speed?}}`, and `agentProviders.applyModelSettings {agent, settings}` (user requests only) writes it back: it checks every model, effort and speed change by the rules of `apply` first, changes nothing when one is refused, then makes them, replaces the hidden records and has the CLI's menu follow. Model plans will save and switch this group. -The commands are `agentProviders.read {agent?}`, `agentProviders.apply {agent, change}` and `agentProviders.restore {agent, discardLaterChanges?}`; fields, refusal codes and a full example are in the [contract](../../contract/v1/README.md#models-and-providers). +The commands are `agentProviders.read {agent?}`, `agentProviders.apply {agent, change}`, `agentProviders.restore {agent, discardLaterChanges?}`, `agentProviders.showModels {agent, show?, hide?}`, `agentProviders.readModelSettings {agent}` and `agentProviders.applyModelSettings {agent, settings}`; fields, refusal codes and a full example are in the [contract](../../contract/v1/README.md#models-and-providers), the rules of listed models in its [Listed models](../../contract/v1/README.md#listed-models), and sample data in `fixtures/agents/model-catalog.json`. ### Backups before a change, and restore diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 76e2a505..1139c36a 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#262](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/262)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 已记录会话的五项补充,对 Agent 的会话文件都只读。**恢复命令**:清单 `agents[].terminal` 新增可选 `resumeArguments`(1–64 个参数,至少含一次 `${sessionID}`,不得有其他 `${`),安装审查的终端程序随之列出模板;宿主命令 `agentSessions.resume {agent, sessionID, toolPath, shell?}` 回答 `{pluginID, agentID, sessionID, executable, arguments, shell, cwd?, commandLine?}`,`commandLine` 按 `posix` 或 `powershell`(默认随宿主平台)转义;Core 只接受由字母、数字、`.`、`_`、`:`、`-` 组成、不以 `-` 开头、最长 256 字节的会话 ID;需要 `agents.run`,宿主用已有终端形式运行,不新增执行通道。`agentSessions.list` 的会话新增 `resumable`。**导出**:宿主命令 `agentSessions.export {agent, sessionID, labels, maxBytes?, keep?, utcOffsetSeconds?}` 回答 `{changed, markdown, messages, truncated}`,含用户消息、回复、每次工具调用一行和时间,不含思考和工具输出;`maxBytes` 4 KiB–4 MiB(默认 1 MiB),`keep` 为 `start` 或 `end`,最多读源文件 64 MiB。导出里的文字全部来自必填的 `labels`(`untitled`、`agent`、`session`、`directory`、`started`、`lastActive`、`timeZone`、`user`、`assistant`、`tool`、`failed`、`earlierOmitted`、`laterOmitted`,各 1–256 字节、不含控制字符),宿主按界面语言传入,Core 不带默认文字;缺少、多出或不合法的标签以 `agentSessions.invalidExport` 拒绝。**子代理**:`scan` 请求新增可选 `threads: true`,只有这时后端才可回答 `threads`(`{sessionID, threadID, parentThreadID?, kind?, startedAtMs?, updatedAtMs?, titleRange?}`);宿主命令 `agentSessions.subagents {agent, sessionID}` 合并线程描述和带 `threadID` 的调用,回答每个子代理的调用行与用量汇总,插件不报告时为空列表。**其他文件夹**:`agentSessions.list` 的 `groups` 新增 `category`(`root`、`temporary`、`hidden`),按路径形式套用 macOS、Linux、Windows 规则,共享用例 `rust/fixtures/agents/folder-categories-v1.json`。**搜索片段**:`agentSessions.search` 新增可选 `snippets: true`,命中带 `snippet`(第一个命中词前 36 个字符到其后 120 个字符,截断处加 `…`)和 `snippetMatches`(片段内的 UTF-8 字节区间,多词、不分大小写、重叠或相接的合并),匹配规则与搜索索引相同;单个命中超过 256 KiB 或一次搜索累计超过 4 MiB 时不给片段、不报错。`agentSessions.read`、`agentSessions.page` 对拆不开的 `agent` 键也回答 `agentSessions.unknownAgent` 和 `entry_not_found`(此前 `read` 回答 `invalid_request`,`page` 回答 `agentSessions.invalidPage`),与新命令一致,一个错误码只对应一个数字码。新增错误码 `agentSessions.unknownSession`、`agentSessions.runNotGranted`、`agentSessions.toolNotFound`、`agentSessions.noResume`、`agentSessions.unsafeResume`、`agentSessions.invalidExport`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明 `resumeArguments` 的清单,不发送 `threads`、严格拒绝回答里的 `threads`,把三个新命令当未知命令、把 `snippets` 当未知字段拒绝。`scan`、`read` 仍是普通 JSON 函数,四语 SDK 无类型或版本变化;新增日志事件 `agent.session.cleanup_failed`(启动失败或会话结束后停不掉的 Agent CLI,带 Core 错误码,不带参数或输出)和 `agent.records.rate_limits_save_failed`(额度快照写入或换名失败,只带步骤和文件系统错误类别,不带路径);`agents/didExit` 通知发不出去时记 `agent.interaction.failed`。没有新增插件可调用的宿主方法、通知或能力版本。样例见 `fixtures/agents/agents.plugin.json` 与 `fixtures/manifest/invalid-manifests.json`。 | +| [#263](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/263)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 插件可在 `configuration.providers` 的 `read` 快照里列出 Agent 能用的模型 `models`(每项 `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`,最多 512 个),以及 CLI 提供的推理强度 `efforts`、速度档 `speeds`(各最多 16 个,每项 `{id, name?}`)、正在用的 `effort`、`speed`(`{id, source?}`)、CLI 自己的模型菜单 `modelMenu` 和写它的文件 `targets.modelMenu`;插件不列就没有,宿主和 Core 不内置任何模型名单。`configuration.providers.operations` 新增 `setEffort`、`setSpeed`、`setModelMenu`,`setModel` 可带 `effort`、`speed`(插件也声明了 `setEffort`、`setSpeed` 时);有清单时 Core 在调用插件前检查选择在清单里、组合是模型支持的,换模型时保留的强度和速度也要新模型支持(来源层是 `default` 的不查),新增错误码 `agentProviders.unknownModel`、`agentProviders.unknownEffort`、`agentProviders.unknownSpeed`、`agentProviders.unsupportedCombination`。`setModelMenu` 只由 Core 发给插件,宿主经 `agentProviders.apply` 发它以 `agentProviders.invalidChange` 拒绝。`agentProviders.read` 总是回答 `models`,每项带 `shown`。新增宿主命令 `agentProviders.showModels {agent, show?, hide?}`:用户隐藏的模型按隐藏顺序记在资源库目录的 `models.json`(仅所有者可读写),默认全部显示,插件新加的模型也显示,插件去掉的模型保留记录,每个 Agent 最多 1024 条,超出先丢最早的、已不在清单里的;插件声明 `setModelMenu` 时 Core 经暂存副本让插件把显示的模型写进 CLI 的菜单,写失败把开关放回,不声明时开关只影响 Lithe 的选择器。新增 `agentProviders.readModelSettings {agent}` 和 `agentProviders.applyModelSettings {agent, settings}`,把开关和模型、强度、速度作为一组读出和写回(写回先全部检查,一个被拒就都不改),供以后的模型方案使用。日志 `agent.providers.change_applied`、`agent.providers.change_failed` 的 `change` 新增取值 `showModels`、`applyModelSettings`。样例见 `contract/v1/fixtures/agents/model-catalog.json`。插件函数 `edit` 新增上述操作,`read` 回答新增上述字段;没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码,只更新说明。 | ## 按协议查首次出现 @@ -241,6 +241,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#262](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/262) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 已记录会话的五项补充,对 Agent 的会话文件都只读。**恢复命令**:清单 `agents[].terminal` 新增可选 `resumeArguments`(1–64 个参数,至少含一次 `${sessionID}`,不得有其他 `${`),安装审查的终端程序随之列出模板;宿主命令 `agentSessions.resume {agent, sessionID, toolPath, shell?}` 回答 `{pluginID, agentID, sessionID, executable, arguments, shell, cwd?, commandLine?}`,`commandLine` 按 `posix` 或 `powershell`(默认随宿主平台)转义;Core 只接受由字母、数字、`.`、`_`、`:`、`-` 组成、不以 `-` 开头、最长 256 字节的会话 ID;需要 `agents.run`,宿主用已有终端形式运行,不新增执行通道。`agentSessions.list` 的会话新增 `resumable`。**导出**:宿主命令 `agentSessions.export {agent, sessionID, labels, maxBytes?, keep?, utcOffsetSeconds?}` 回答 `{changed, markdown, messages, truncated}`,含用户消息、回复、每次工具调用一行和时间,不含思考和工具输出;`maxBytes` 4 KiB–4 MiB(默认 1 MiB),`keep` 为 `start` 或 `end`,最多读源文件 64 MiB。导出里的文字全部来自必填的 `labels`(`untitled`、`agent`、`session`、`directory`、`started`、`lastActive`、`timeZone`、`user`、`assistant`、`tool`、`failed`、`earlierOmitted`、`laterOmitted`,各 1–256 字节、不含控制字符),宿主按界面语言传入,Core 不带默认文字;缺少、多出或不合法的标签以 `agentSessions.invalidExport` 拒绝。**子代理**:`scan` 请求新增可选 `threads: true`,只有这时后端才可回答 `threads`(`{sessionID, threadID, parentThreadID?, kind?, startedAtMs?, updatedAtMs?, titleRange?}`);宿主命令 `agentSessions.subagents {agent, sessionID}` 合并线程描述和带 `threadID` 的调用,回答每个子代理的调用行与用量汇总,插件不报告时为空列表。**其他文件夹**:`agentSessions.list` 的 `groups` 新增 `category`(`root`、`temporary`、`hidden`),按路径形式套用 macOS、Linux、Windows 规则,共享用例 `rust/fixtures/agents/folder-categories-v1.json`。**搜索片段**:`agentSessions.search` 新增可选 `snippets: true`,命中带 `snippet`(第一个命中词前 36 个字符到其后 120 个字符,截断处加 `…`)和 `snippetMatches`(片段内的 UTF-8 字节区间,多词、不分大小写、重叠或相接的合并),匹配规则与搜索索引相同;单个命中超过 256 KiB 或一次搜索累计超过 4 MiB 时不给片段、不报错。`agentSessions.read`、`agentSessions.page` 对拆不开的 `agent` 键也回答 `agentSessions.unknownAgent` 和 `entry_not_found`(此前 `read` 回答 `invalid_request`,`page` 回答 `agentSessions.invalidPage`),与新命令一致,一个错误码只对应一个数字码。新增错误码 `agentSessions.unknownSession`、`agentSessions.runNotGranted`、`agentSessions.toolNotFound`、`agentSessions.noResume`、`agentSessions.unsafeResume`、`agentSessions.invalidExport`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明 `resumeArguments` 的清单,不发送 `threads`、严格拒绝回答里的 `threads`,把三个新命令当未知命令、把 `snippets` 当未知字段拒绝。`scan`、`read` 仍是普通 JSON 函数,四语 SDK 无类型或版本变化;新增日志事件 `agent.session.cleanup_failed`(启动失败或会话结束后停不掉的 Agent CLI,带 Core 错误码,不带参数或输出)和 `agent.records.rate_limits_save_failed`(额度快照写入或换名失败,只带步骤和文件系统错误类别,不带路径);`agents/didExit` 通知发不出去时记 `agent.interaction.failed`。没有新增插件可调用的宿主方法、通知或能力版本。样例见 `fixtures/agents/agents.plugin.json` 与 `fixtures/manifest/invalid-manifests.json`。 | | [#261](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/261) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的指令改为只写指令文件里 Lithe 标记的一块(`` 到 ``):块外用户文字逐字节保留,新块追加在用户文字之后,资源库文字里的标记行写成失效形式,多余的块和落单的标记行被清掉,指令为空时去掉整块,重复写入不变大;`state.json` 改记块内文字的哈希,旧 Core 整份写过且哈希一致的文件下次写成只有块,其他没有块的文件当作用户文字直接追加,不需确认。指令集新增可选 `on`、`agents`(空为所有 Agent),按 `sets` 顺序拼接后加 Agent 的 `extra`;去掉 `active`:读取带 `active` 的旧 `library.json` 时换成“该套开、其余关”,拼接结果逐字节不变,`save` 带 `active` 以 `agentLibrary.invalidLibrary` 拒绝。宿主命令 `agentLibrary.read` 的 `instructions.state` 改为 `absent`、`noBlock`、`current`、`stale`、`edited`、`tooLarge`、`unreadable`,新增 `ownLines`(块外用户文字行数);`agentLibrary.save` 回答新增 `instructions`:保存后 Core 给每个跟随的 Agent 写块,逐个回答 `written`、`unchanged`、`skipped`(带 `reason`)或 `failed`(带 `reason`),不覆盖用户改过的块;`agentLibrary.apply` 新增 `{category: "instructions", op: "import", id, name?, revision, replace?}`,把块外用户文字并入新建或已有的一套,先备份,文件只剩块,回答 `{changed, revision, instructions}`;`agentLibrary.otherInstructions` 收窄为“块里有不是 Lithe 写的内容”。`agentProviders.restore` 放回指令文件时关掉该 Agent 的跟随,回答新增 `unfollowed`,日志 `agent.providers.restore_applied` 新增字段 `unfollowed`。新增错误码 `agentLibrary.setExists`(并入时新建的一套 `id` 已存在)。新增日志事件 `agent.library.cleanup_failed`:资源库删不掉不再需要的文件(写入失败留下的临时文件、暂存副本、导入一半的技能、备份基线或历史),或失败后放不回备份记录时记录,只带对象种类和文件系统错误类别,不带路径。样例见 `rust/fixtures/agents/library-instructions-v1.json`。没有新增插件可调用的宿主方法、通知、插件函数参数或能力版本,插件后端协议和四语 SDK 不变。 | | [#260](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/260) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的修改替换 Agent 的文件前也先备份,和 `agentProviders.apply` 共用同一份备份。`agentLibrary.apply` 为 MCP 服务器、Hooks 改声明文件,以及整份写入指令文件(包括 `replace: true` 覆盖不是 Lithe 写的内容)之前先备份,备份不成功就不写文件,复用已有错误码 `agentProviders.backupFailed`;技能的符号链接不覆盖内容,不备份。同一个文件无论资源库还是供应商先改,都只存一份“自上次恢复以来 Lithe 第一次修改前的原样”(按第一个解析到该路径的声明文件归并,指令文件不是声明文件时单独一项)。宿主命令 `agentLibrary.read` 的每个 Agent 新增可选 `backup {savedAtMs, modifiedSince}`,和 `agentProviders.read` 的 `backup` 相同;后者现在也覆盖指令文件和资源库的修改。`agentProviders.restore` 不再要求 Agent 声明 `providers`(原来以 `agentProviders.notDeclared` 拒绝),恢复该 Agent 所有备份过的文件;放回指令文件前先忘掉 Core 最后写入的指令哈希,恢复后 `instructions.state` 按文件实际内容显示、不会是 `written`,再写入要重新确认 `replace: true`。旧 Core 只备份 `agentProviders.apply` 的修改,`agentLibrary.read` 不带 `backup`,对不声明 `providers` 的 Agent 的恢复回答 `agentProviders.notDeclared`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 | | [#251](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/251) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 内的补充 | 宿主 `agentSessions.stats` 增加可选 `overview`,在同一快照中返回总计、分组、按日或小时的序列。按日分桶使用概览日历。缺少分组维度沿用 `agentSessions.invalidSplit`;概览的分组、明细开关和日历错误分别返回 `agentSessions.invalidOverviewGroup`、`agentSessions.invalidOverviewDetail`、`agentSessions.invalidCalendar`。插件的 `agents/usage` 和四语 SDK 接口沿用原状。 | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index 36ab1444..cd210919 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -706,10 +706,18 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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. + It may list the models the agent offers (`models`, each with the efforts and + speeds it takes and its context window), the `efforts` and `speeds` the CLI + offers, the `effort` and `speed` in use and the CLI's own model menu + (`modelMenu`); Core checks a pick against them before calling `edit`. - `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}`. +- `setModel` may carry `effort` and `speed`, beside `setEffort` and + `setSpeed`. A plugin that declares `setModelMenu` receives + `{op: "setModelMenu", models}` from Core, never from the host, with the + listed models Lithe shows, and writes them into the CLI's own menu. - Keys are write-only: a `change` may carry a `key` (or `clearKey`) for `edit` to write, and `read` reports only `keySet`, never the value; no answer, error or log carries a key. Headers and query parameters are diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 6491daae..6d3b2a71 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -673,10 +673,18 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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. + It may list the models the agent offers (`models`, each with the efforts and + speeds it takes and its context window), the `efforts` and `speeds` the CLI + offers, the `effort` and `speed` in use and the CLI's own model menu + (`modelMenu`); Core checks a pick against them before calling `edit`. - `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}`. +- `setModel` may carry `effort` and `speed`, beside `setEffort` and + `setSpeed`. A plugin that declares `setModelMenu` receives + `{op: "setModelMenu", models}` from Core, never from the host, with the + listed models Lithe shows, and writes them into the CLI's own menu. - Keys are write-only: a `change` may carry a `key` (or `clearKey`) for `edit` to write, and `read` reports only `keySet`, never the value; no answer, error or log carries a key. Headers and query parameters are diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index e57ef4dd..28da19fd 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -686,10 +686,18 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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. + It may list the models the agent offers (`models`, each with the efforts and + speeds it takes and its context window), the `efforts` and `speeds` the CLI + offers, the `effort` and `speed` in use and the CLI's own model menu + (`modelMenu`); Core checks a pick against them before calling `edit`. - `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}`. +- `setModel` may carry `effort` and `speed`, beside `setEffort` and + `setSpeed`. A plugin that declares `setModelMenu` receives + `{op: "setModelMenu", models}` from Core, never from the host, with the + listed models Lithe shows, and writes them into the CLI's own menu. - Keys are write-only: a `change` may carry a `key` (or `clearKey`) for `edit` to write, and `read` reports only `keySet`, never the value; no answer, error or log carries a key. Headers and query parameters are diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 85b94634..b9ac12ce 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -883,10 +883,18 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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. + It may list the models the agent offers (`models`, each with the efforts and + speeds it takes and its context window), the `efforts` and `speeds` the CLI + offers, the `effort` and `speed` in use and the CLI's own model menu + (`modelMenu`); Core checks a pick against them before calling `edit`. - `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}`. +- `setModel` may carry `effort` and `speed`, beside `setEffort` and + `setSpeed`. A plugin that declares `setModelMenu` receives + `{op: "setModelMenu", models}` from Core, never from the host, with the + listed models Lithe shows, and writes them into the CLI's own menu. - Keys are write-only: a `change` may carry a `key` (or `clearKey`) for `edit` to write, and `read` reports only `keySet`, never the value; no answer, error or log carries a key. Headers and query parameters are