From fdf234f52a5ebbb6755196b0f30d16dbed2f08df Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Fri, 4 Dec 2026 00:36:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(agents):=20=E6=8F=92=E4=BB=B6=E6=8F=90?= =?UTF-8?q?=E4=BE=9B=E4=BE=9B=E5=BA=94=E5=95=86=E9=A2=84=E8=AE=BE=E3=80=81?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E6=A8=A1=E5=9E=8B=E5=88=97=E8=A1=A8=E5=92=8C?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E8=BF=9E=E6=8E=A5=EF=BC=8C=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86=E5=8F=AF=E5=B8=A6=E5=8F=AA=E5=86=99=E7=9A=84=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=A4=B4=EF=BC=8C=E6=8F=92=E4=BB=B6=E8=AF=B4=E6=B2=A1?= =?UTF-8?q?=E6=94=B9=E5=8A=A8=E6=97=B6=20Core=20=E4=B9=9F=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 8 +- rust/crates/agent-runtime/src/lib.rs | 6 +- rust/crates/agent-runtime/src/library.rs | 22 +- .../agent-runtime/src/library/providers.rs | 161 +++- .../src/library/providers/headers.rs | 186 +++++ .../src/library/providers/presets.rs | 135 ++++ .../src/library/providers/probe.rs | 681 +++++++++++++++++ .../crates/agent-runtime/src/tests/library.rs | 29 +- .../agent-runtime/src/tests/providers.rs | 43 +- .../src/tests/providers/headers.rs | 376 ++++++++++ .../agent-runtime/src/tests/providers/keys.rs | 4 +- .../src/tests/providers/presets.rs | 152 ++++ .../src/tests/providers/probes.rs | 707 ++++++++++++++++++ .../src/tests/providers/saved.rs | 67 ++ rust/crates/core/src/protocol/command.rs | 12 + .../core/src/tests/declarative_plugins.rs | 6 +- .../diagnostics/src/catalog_generated.rs | 35 + rust/crates/plugin-agents/src/lib.rs | 89 ++- rust/crates/plugin-agents/src/tests.rs | 96 +++ rust/logging/events/agent.json | 85 +++ shared/plugins/contract/v1/README.md | 334 ++++++++- .../v1/fixtures/agents/agents.plugin.json | 6 + .../v1/fixtures/agents/provider-probes.json | 344 +++++++++ .../fixtures/manifest/invalid-manifests.json | 4 + .../contract/v1/plugin-manifest.schema.json | 23 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 22 +- .../plugins/reference/protocol-changelog.md | 3 +- shared/plugins/sdk/go/README.md | 38 +- shared/plugins/sdk/java/README.md | 38 +- shared/plugins/sdk/node/README.md | 38 +- shared/plugins/sdk/rust/README.md | 38 +- 33 files changed, 3680 insertions(+), 116 deletions(-) create mode 100644 rust/crates/agent-runtime/src/library/providers/headers.rs create mode 100644 rust/crates/agent-runtime/src/library/providers/presets.rs create mode 100644 rust/crates/agent-runtime/src/library/providers/probe.rs create mode 100644 rust/crates/agent-runtime/src/tests/providers/headers.rs create mode 100644 rust/crates/agent-runtime/src/tests/providers/presets.rs create mode 100644 rust/crates/agent-runtime/src/tests/providers/probes.rs create mode 100644 shared/plugins/contract/v1/fixtures/agents/provider-probes.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index bfec6cc5..6a77f0ca 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -506,15 +506,17 @@ or removing a command fails until the table changes in the same commit. | `agentLibrary.configure` | Open the agent library in the platform's application data | | `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold, with the agent's `backup: {savedAtMs, modifiedSince}` while Core keeps one; an agent's `instructions` is `{path, state, ownLines?}`, `state` comparing Lithe's block in the file with the library (`absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge`, `unreadable`) and `ownLines` counting the user's own lines outside it; a library saved with `active` reads as that set `on`; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | | `agentLibrary.save` | Replace the library the user edited if it is still at the revision read (instruction sets each with `on` and `agents`; `active` is refused), then write Lithe's block in the instruction file of every agent that follows the library, never over a block edited outside Lithe, and answer each agent's `written`, `unchanged`, `skipped` or `failed` with its reason in `instructions` | -| `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.apply` | Apply one library change the user chose to one agent's configuration, backing up the configuration or instruction file it replaces first; a server or hook goes through the plugin's `edit` on a checked staged copy, and an edit that reports no change is checked against the file as it is (`editNotApplied` when the change is not there); 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}`; 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.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; always answers `presets`, the providers the plugin offers to add (none when it lists none), and the manifest's `editsHeaders` and `probes`; a provider reported with `headers` (names with `valueSet`, never values) also has `headerNames` | +| `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 (an edit that reports no change is checked against the file as it is, `editNotApplied` when the change is not there); `addProvider`/`updateProvider` may carry a write-only `key` (or `clearKey`) and, for a plugin that declares `editsHeaders`, the provider's whole list of `headers` `{name, value?}` (a header without a value keeps the provider's), all 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}` | +| `agentProviders.fetchModels` | List the models one provider serves (user requests only), through the plugin's declared `probe` function, which makes the request with its own HTTP client: Core checks the provider, fills in what the agent has, hands a key and headers the user typed only to the plugin with a 20-second budget and an 8 MiB answer limit, waits at most 30 seconds, and answers `{agent, result: {category, status?, code?, durationMs}, models?}` with a closed category and no text; nothing is kept | +| `agentProviders.testConnection` | Send one provider the smallest request of its protocol (user requests only) through the plugin's declared `probe` function, as `agentProviders.fetchModels` does, with a 64 KiB answer limit; answers `{agent, result: {category, status?, code?, durationMs, model?}}`, a failed connection being a result and not a refusal | | `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 2ae3836b..a674cda1 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -16,7 +16,9 @@ //! covers Lithe's library of MCP servers, hooks, skills and instructions and //! applies them to the agents' own configuration (the `library` module); //! `agentProviders.*` reads and changes an agent's model, model providers -//! and profiles through the same staged copy. Backends reach it with +//! and profiles through the same staged copy, and has the agent's plugin +//! reach a provider over the network when the user asks for its models or a +//! connection test. Backends reach it with //! `lithe/host/agents/*` requests, which the engine hands to the installed //! [`AgentHost`] and which never reach the host application. //! @@ -141,6 +143,8 @@ impl Runtime { "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), + "agentProviders.fetchModels" => self.library.fetch_models(self, payload), + "agentProviders.testConnection" => self.library.test_connection(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 9f416ad3..a3452a44 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -2330,10 +2330,14 @@ impl Library { /// `staging/`, lets `edit` change only the copy and report whether it /// changed, lets `shows_change` confirm the copy holds the change, and /// replaces the file with the copy if the file is unchanged meanwhile. - /// The staged copy is removed whatever happens. Before the file is - /// replaced its bytes are backed up under `backup` (the agent's record - /// key and the file's backup ID), and the change fails, unwritten, if - /// they cannot be. Answers whether the file changed. + /// When `edit` reports no change, or leaves the copy as the file was, + /// nothing is written, but `shows_change` must still confirm that the + /// file as it is holds the change: a plugin that ignores part of a + /// change cannot pass it off as already made. The staged copies are + /// removed whatever happens. Before the file is replaced its bytes are + /// backed up under `backup` (the agent's record key and the file's + /// backup ID), and the change fails, unwritten, if they cannot be. + /// Answers whether the file changed. fn edit_staged( &self, config: &Config, @@ -2347,12 +2351,20 @@ impl Library { let staging = self.stage(config, &real, original.as_deref())?; let outcome = (|| { if !edit(&staging, original.is_some())? { - return Ok(false); + // Whatever the plugin left in its copy is dropped: the + // plugin reads a fresh copy of the file, which must already + // hold the change. + let fresh = self.stage(config, &real, original.as_deref())?; + let shown = shows_change(&fresh); + remove_leftover(&fresh, Leftover::Staging); + return shown.map(|()| false); } let edited = read_bounded(&staging, MAX_CONFIGURATION_FILE_BYTES) .map_err(read_failure)? .unwrap_or_default(); if original.as_deref() == Some(edited.as_slice()) { + // The copy is the file byte for byte. + shows_change(&staging)?; return Ok(false); } shows_change(&staging)?; diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs index dca8a641..ca600991 100644 --- a/rust/crates/agent-runtime/src/library/providers.rs +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -30,11 +30,21 @@ //! 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). +//! +//! A plugin may offer presets of providers its CLI can reach (`presets` +//! module), save a provider's request headers, whose values are write-only +//! like keys (`headers` module), and reach a provider over the network when +//! the user asks for its models or a connection test (`probe` module). +mod headers; mod models; +mod presets; +mod probe; pub(super) use models::Catalogs; +use headers::HeaderInput; + use super::backups; use super::saved::{self, SavedProvider}; use super::{ @@ -194,8 +204,15 @@ struct Provider { /// The model the configuration pairs with this provider, if any. #[serde(default, skip_serializing_if = "Option::is_none")] model: Option, + /// The provider's request headers by name, from a plugin that does not + /// report `headers`. The read answer has it for every provider with a + /// header, however the plugin reported it. #[serde(default, skip_serializing_if = "Vec::is_empty")] header_names: Vec, + /// The provider's request headers with whether each value is set, from + /// a plugin that reports them; never with `headerNames`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + headers: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] query_parameter_names: Vec, /// Absent when the CLI has no on/off switch for providers. @@ -346,6 +363,9 @@ struct ProvidersSnapshot { /// writes that menu. #[serde(default, skip_serializing_if = "Option::is_none")] model_menu: Option>, + /// Providers the plugin offers to add; empty when it offers none. + #[serde(default)] + presets: Vec, #[serde(default)] targets: ProviderTargets, } @@ -583,6 +603,10 @@ impl ProvidersSnapshot { &format!("{field}.headerNames"), is_parameter_name, )?; + if !provider.headers.is_empty() && !provider.header_names.is_empty() { + return Err(format!("{field}.headers")); + } + headers::check_reported(&provider.headers, &format!("{field}.headers"))?; check_names( &provider.query_parameter_names, &format!("{field}.queryParameterNames"), @@ -812,9 +836,9 @@ impl ProvidersSnapshot { // --------------------------------------------------------------------------- // Changes. -/// A provider as a change gives it: no headers or query parameters, which -/// the plugin keeps as they are, and no key, which the change carries -/// beside it. +/// A provider as a change gives it: no query parameters, which the plugin +/// keeps as they are, and no key or headers, which the change carries beside +/// it. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ProviderInput { @@ -866,6 +890,10 @@ enum ProviderChange { provider: ProviderInput, #[serde(default, skip_serializing_if = "Option::is_none")] key: Option, + /// The provider's request headers; only for an agent that declares + /// `editsHeaders`. + #[serde(default, skip_serializing_if = "Option::is_none")] + headers: Option>, }, UpdateProvider { provider: ProviderInput, @@ -875,6 +903,11 @@ enum ProviderChange { /// Removes the key. #[serde(default, rename = "clearKey", skip_serializing_if = "is_false")] clear_key: bool, + /// The provider's whole list of request headers after the change; + /// none keeps them all. Only for an agent that declares + /// `editsHeaders`. + #[serde(default, skip_serializing_if = "Option::is_none")] + headers: Option>, }, RemoveProvider { id: String, @@ -937,9 +970,19 @@ impl ProviderChange { } } - /// Checks the change's own fields; a bad endpoint and a bad key have - /// their own codes. Where Lithe keeps the list, a provider has an - /// endpoint and may name a model; elsewhere it names none. + /// The request headers an `addProvider` or `updateProvider` carries. + fn headers(&self) -> Option<&[HeaderInput]> { + match self { + Self::AddProvider { headers, .. } | Self::UpdateProvider { headers, .. } => { + headers.as_deref() + } + _ => None, + } + } + + /// Checks the change's own fields; a bad endpoint, a bad key and bad + /// headers have their own codes. Where Lithe keeps the list, a provider + /// has an endpoint and may name a model; elsewhere it names none. fn check(&self, kept_by: ListKeptBy) -> Result<(), CoreError> { let (key, clear_key) = match self { Self::AddProvider { key, .. } => (key.as_ref(), false), @@ -949,6 +992,9 @@ impl ProviderChange { if key.is_some_and(|key| !key.is_valid()) { return Err(invalid_key()); } + if let Some(headers) = self.headers() { + headers::check_inputs(headers)?; + } if key.is_some() && clear_key { return Err(invalid_change( "A change sets a key or clears it, not both.", @@ -1055,13 +1101,24 @@ impl ProviderChange { } } match self { - Self::AddProvider { provider, .. } => { + Self::AddProvider { + provider, headers, .. + } => { if snapshot.find(&provider.id).is_some() { return Err(provider_exists()); } + // A new provider has no value to keep. + if let Some(headers) = headers { + headers::check_kept(headers, std::iter::empty())?; + } } - Self::UpdateProvider { provider, .. } => { - changeable(&provider.id)?; + Self::UpdateProvider { + provider, headers, .. + } => { + let found = changeable(&provider.id)?; + if let Some(headers) = headers { + headers::check_kept(headers, headers::names(found))?; + } } Self::RemoveProvider { id } => { changeable(id)?; @@ -1179,11 +1236,12 @@ impl ProviderChange { fn saved_after(&self, saved: &[SavedProvider]) -> Vec { let mut after = saved.to_vec(); match self { - Self::AddProvider { provider, key } => after.push(provider.saved(key.is_some())), + Self::AddProvider { provider, key, .. } => after.push(provider.saved(key.is_some())), Self::UpdateProvider { provider, key, clear_key, + .. } => { if let Some(entry) = after.iter_mut().find(|entry| entry.id == provider.id) { let key_set = key.is_some() || (entry.key_set && !*clear_key); @@ -1196,21 +1254,24 @@ impl ProviderChange { after } - /// Whether a re-read staged copy holds the change. `saved` is the list - /// Lithe keeps after the change, none where the CLI keeps it. - fn shows_in(&self, snapshot: &ProvidersSnapshot, saved: Option<&[SavedProvider]>) -> bool { + /// Whether a re-read staged copy holds the change. `kept` is what Lithe + /// keeps after the change, none where the CLI keeps the list. + fn shows_in(&self, snapshot: &ProvidersSnapshot, kept: Option>) -> bool { let key_shows = |found: &Provider, key: &Option, clear_key: bool| { (key.is_none() || found.key_set) && (!clear_key || !found.key_set) }; - if let Some(saved) = saved { + if let Some(Kept { saved, in_use }) = kept { return match self { // A saved provider that is not in use has nothing in the - // configuration to show. + // configuration to show: the plugin keeps its key in its + // own credentials. Self::AddProvider { .. } | Self::RemoveProvider { .. } => true, + Self::UpdateProvider { .. } if !in_use => true, Self::UpdateProvider { provider, key, clear_key, + .. } => active_saved(snapshot, saved).is_some_and(|active| { active.id == provider.id && current_provider(snapshot) @@ -1222,17 +1283,25 @@ impl ProviderChange { _ => self.shows_in(snapshot, None), }; } + // Headers a change gives must show by name, each value it set as set. + let headers_show = |found: &Provider| { + self.headers() + .is_none_or(|headers| headers::show_in(headers, found)) + }; match self { - Self::AddProvider { provider, key } => snapshot - .find(&provider.id) - .is_some_and(|found| provider.is_in(found) && key_shows(found, key, false)), + Self::AddProvider { provider, key, .. } => { + snapshot.find(&provider.id).is_some_and(|found| { + provider.is_in(found) && key_shows(found, key, false) && headers_show(found) + }) + } Self::UpdateProvider { provider, key, clear_key, - } => snapshot - .find(&provider.id) - .is_some_and(|found| provider.is_in(found) && key_shows(found, key, *clear_key)), + .. + } => snapshot.find(&provider.id).is_some_and(|found| { + provider.is_in(found) && key_shows(found, key, *clear_key) && headers_show(found) + }), Self::RemoveProvider { id } => snapshot.find(id).is_none(), Self::SetProviderEnabled { id, enabled } => snapshot .find(id) @@ -1294,6 +1363,17 @@ fn current_provider(snapshot: &ProvidersSnapshot) -> Option<&Provider> { .and_then(|current| snapshot.find(¤t.id)) } +/// What a change where Lithe keeps the list of providers is checked +/// against once the plugin has made it. +#[derive(Clone, Copy)] +struct Kept<'a> { + /// The saved providers after the change. + saved: &'a [SavedProvider], + /// Whether the provider an `updateProvider` changes is the one in use, + /// which the plugin then writes into the configuration too. + in_use: bool, +} + /// The saved provider the configuration currently uses: the one whose /// endpoint the active custom provider has. fn active_saved<'a>( @@ -1439,6 +1519,7 @@ fn read_providers( let snapshot: ProvidersSnapshot = serde_json::from_value(answer).map_err(|_| invalid())?; let ids: BTreeSet<&str> = configuration.files.iter().map(|f| f.id.as_str()).collect(); snapshot.check(&ids).map_err(|_| invalid())?; + presets::check(&snapshot.presets, declared.list_kept_by).map_err(|_| invalid())?; Ok(snapshot) } @@ -1470,6 +1551,15 @@ fn snapshot_view(snapshot: &ProvidersSnapshot, files: &[(String, PathBuf)]) -> V } let mut view = json!(snapshot); add_path(&mut view, files); + // A provider reported with `headers` gets `headerNames` too, so the host + // finds the names in one field whichever form the plugin reports. + if let Some(Value::Array(providers)) = view.get_mut("providers") { + for (entry, provider) in providers.iter_mut().zip(&snapshot.providers) { + if !provider.headers.is_empty() { + entry["headerNames"] = json!(headers::names(provider).collect::>()); + } + } + } if let Some(current) = &snapshot.provider { if current.name.is_none() { if let Some(found) = snapshot.find(¤t.id) { @@ -1575,6 +1665,10 @@ fn prepared_change( return Err(unsupported_operation()); } } + // Headers are a part of the change only a plugin that saves them takes. + if change.headers().is_some() && !declared.edits_headers { + return Err(unsupported_operation()); + } change.check(declared.list_kept_by)?; Ok(change) } @@ -1692,6 +1786,8 @@ impl Library { "mayConfigure": agent.may_configure, "operations": declared.operations, "listKeptBy": declared.list_kept_by, + "editsHeaders": declared.edits_headers, + "probes": declared.probes, }); if !agent.may_configure { return entry; @@ -1816,17 +1912,19 @@ impl Library { // back as they were when the plugin's part fails. let saved_after = change.saved_after(&saved_before); let mut params = json!(change); + let mut in_use = false; let calls_plugin = match &change { ProviderChange::AddProvider { key, .. } => key.is_some(), ProviderChange::UpdateProvider { provider, key, clear_key, + .. } => { - let active = active_saved(&snapshot, &saved_before) + in_use = active_saved(&snapshot, &saved_before) .is_some_and(|active| active.id == provider.id); - params["active"] = json!(active); - key.is_some() || *clear_key || active + params["active"] = json!(in_use); + key.is_some() || *clear_key || in_use } ProviderChange::SetProvider { id } => { if let Some(chosen) = saved_before.iter().find(|provider| provider.id == *id) { @@ -1854,7 +1952,10 @@ impl Library { &snapshot, &change, params, - Some(&saved_after), + Some(Kept { + saved: &saved_after, + in_use, + }), ) } else { Ok(false) @@ -1871,8 +1972,10 @@ impl Library { /// Hands `change` (as `params`, which may carry more than the change) /// to the plugin's `edit` on a staged copy of the change's target file, - /// and writes the copy when a re-read shows the change. `saved` is the - /// list Lithe keeps after the change, none where the CLI keeps it. + /// and writes the copy when a re-read shows the change; when the plugin + /// reports no change, a re-read of the file must show it already. + /// `kept` is what Lithe keeps after the change, none where the CLI + /// keeps the list. #[allow(clippy::too_many_arguments)] fn edit_providers( &self, @@ -1883,7 +1986,7 @@ impl Library { snapshot: &ProvidersSnapshot, change: &ProviderChange, params: Value, - saved: Option<&[SavedProvider]>, + kept: Option>, ) -> Result { let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; let edit = declared.edit.as_deref().ok_or_else(not_declared)?; @@ -1941,7 +2044,7 @@ impl Library { let shows_change = |staging: &Path| -> Result<(), CoreError> { let staged_files = with_staged(&paths.files, &target_id, staging); let staged = read_providers(link, agent, configuration, declared, &staged_files)?; - if change.shows_in(&staged, saved) { + if change.shows_in(&staged, kept) { Ok(()) } else { Err(refusal( diff --git a/rust/crates/agent-runtime/src/library/providers/headers.rs b/rust/crates/agent-runtime/src/library/providers/headers.rs new file mode 100644 index 00000000..e015954a --- /dev/null +++ b/rust/crates/agent-runtime/src/library/providers/headers.rs @@ -0,0 +1,186 @@ +//! A provider's request headers: names a plugin reports, values only a +//! change or a probe carries. +//! +//! A header value is a secret, like a key. A plugin reports each header of +//! a provider by name, with whether the configuration holds its value +//! (`valueSet`) and the environment variable the CLI reads it from +//! (`variable`), never the value. A change of an agent whose plugin +//! declares `editsHeaders`, and a probe, carry the provider's whole list of +//! headers as `{name, value?}`, the same shape the library takes for an MCP +//! server's variables: a header with `value` takes it, one without keeps the +//! value the provider has for that name (ASCII case ignored), and a header +//! left out is dropped. Core hands values to the plugin in memory and to +//! nothing else; no answer, refusal, log or debug output carries one. + +use super::{is_environment_name, is_parameter_name, refusal, Check, Provider, Secret}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Most headers one provider has. +const MAX_HEADERS: usize = 64; +/// Longest header value, in bytes, as HTTP clients commonly take one. +const MAX_HEADER_VALUE_BYTES: usize = 8192; + +/// Header names a CLI's HTTP client sets itself; a provider never carries +/// them. Lowercase. +const RESERVED_HEADERS: [&str; 9] = [ + "host", + "connection", + "content-length", + "transfer-encoding", + "proxy-authorization", + "proxy-connection", + "upgrade", + "trailer", + "te", +]; + +/// One header of a provider as a plugin reports it. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ReportedHeader { + pub name: String, + /// Whether the configuration holds a value for the header. + #[serde(default)] + pub value_set: bool, + /// The environment variable the CLI reads the value from. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variable: Option, +} + +/// One header as a change or a probe gives it. `valueSet` is what a read +/// answered and is ignored, so the host can send back what it read. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct HeaderInput { + pub name: String, + /// The new value; none keeps the provider's value. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, + #[serde(default, rename = "valueSet", skip_serializing)] + value_set: Option, +} + +/// A header name a provider may carry: a header name of the snapshot rules, +/// not one the HTTP client sets itself. +pub(super) fn is_header_name(name: &str) -> bool { + is_parameter_name(name) && !RESERVED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) +} + +/// The names of `names`, lowercased, each once; `None` when two differ only +/// in ASCII case. +fn folded<'a>(names: impl Iterator) -> Option> { + let mut seen = BTreeSet::new(); + for name in names { + if !seen.insert(name.to_ascii_lowercase()) { + return None; + } + } + Some(seen) +} + +/// The headers a plugin reports for one provider. +pub(super) fn check_reported(headers: &[ReportedHeader], field: &str) -> Check { + if headers.len() > MAX_HEADERS { + return Err(field.to_string()); + } + for (index, header) in headers.iter().enumerate() { + if !is_header_name(&header.name) { + return Err(format!("{field}[{index}].name")); + } + if header + .variable + .as_deref() + .is_some_and(|name| !is_environment_name(name)) + { + return Err(format!("{field}[{index}].variable")); + } + } + folded(headers.iter().map(|header| header.name.as_str())) + .map(|_| ()) + .ok_or_else(|| field.to_string()) +} + +pub(super) fn invalid_headers() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentProviders.invalidHeaders", + "Headers are at most 64 {name, value?}: names of ASCII letters, digits, '-', '_' and '.', unique ignoring case and not set by the HTTP client; values 1 to 8192 bytes without control characters.", + ) +} + +fn unknown_header() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentProviders.unknownHeader", + "A header without a value keeps the provider's value, but the provider has no header of this name.", + ) +} + +/// The headers a change or a probe carries, by their own rules. A value is +/// checked without being shown in the refusal. +pub(super) fn check_inputs(headers: &[HeaderInput]) -> Result<(), CoreError> { + let valid = headers.len() <= MAX_HEADERS + && headers.iter().all(|header| { + is_header_name(&header.name) + && header.value.as_ref().is_none_or(|value| { + !value.0.is_empty() + && value.0.len() <= MAX_HEADER_VALUE_BYTES + && !value.0.chars().any(char::is_control) + }) + }) + && folded(headers.iter().map(|header| header.name.as_str())).is_some(); + if valid { + Ok(()) + } else { + Err(invalid_headers()) + } +} + +/// Refuses a header without a value whose name `kept` (the provider's +/// header names, none for a new provider) does not hold. +pub(super) fn check_kept<'a>( + headers: &[HeaderInput], + kept: impl Iterator, +) -> Result<(), CoreError> { + let kept: BTreeSet = kept.map(str::to_ascii_lowercase).collect(); + if headers + .iter() + .any(|header| header.value.is_none() && !kept.contains(&header.name.to_ascii_lowercase())) + { + return Err(unknown_header()); + } + Ok(()) +} + +/// The header names of a reported provider, from `headers` or, for a +/// plugin that reports names only, `headerNames`. +pub(super) fn names(provider: &Provider) -> impl Iterator { + provider + .headers + .iter() + .map(|header| header.name.as_str()) + .chain(provider.header_names.iter().map(String::as_str)) +} + +/// Whether a re-read provider holds the headers a change gave: the same +/// names, ASCII case ignored, and a set value for each header given one, +/// where the plugin reports values. +pub(super) fn show_in(headers: &[HeaderInput], provider: &Provider) -> bool { + let wanted = folded(headers.iter().map(|header| header.name.as_str())); + let found = folded(names(provider)); + if wanted.is_none() || wanted != found { + return false; + } + headers + .iter() + .filter(|header| header.value.is_some()) + .all(|header| { + provider.headers.is_empty() + || provider + .headers + .iter() + .any(|found| found.name.eq_ignore_ascii_case(&header.name) && found.value_set) + }) +} diff --git a/rust/crates/agent-runtime/src/library/providers/presets.rs b/rust/crates/agent-runtime/src/library/providers/presets.rs new file mode 100644 index 00000000..dfc9d0c6 --- /dev/null +++ b/rust/crates/agent-runtime/src/library/providers/presets.rs @@ -0,0 +1,135 @@ +//! The provider presets a plugin offers for its CLI. +//! +//! A plugin may list, in its providers `read` answer, the providers its CLI +//! can reach that it already knows: a name, an endpoint, the wire protocol +//! as the CLI names it, a default model, where the CLI reads the key from, +//! and the optional headers the vendor documents. The host shows them and +//! adds the one the user picks with an ordinary `addProvider`, the key and +//! header values the user types going with it. Core keeps no preset of its +//! own and no record of which provider came from which preset: without a +//! list from the plugin there is none. + +use super::{ + check_description, check_name, is_endpoint, is_environment_name, is_provider_id, is_token, + Check, +}; +use lithe_plugin_agents::ListKeptBy; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Most presets a plugin offers for one agent. +const MAX_PRESETS: usize = 128; +/// Most optional headers one preset names. +const MAX_PRESET_HEADERS: usize = 16; + +/// How the host groups a preset in its picker. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +enum PresetKind { + /// The models' own maker. + Vendor, + /// A service that resells the models of many makers. + Relay, + /// A server running on the user's machine. + Local, +} + +/// One provider the plugin offers to add. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Preset { + /// Follows the provider ID rules; the host offers it as the new + /// provider's ID. + id: String, + name: String, + /// One line about the provider, as the plugin words it. + #[serde(default, skip_serializing_if = "Option::is_none")] + description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + kind: Option, + /// Absent for a provider reached at the user's own address, which the + /// host then asks for. + #[serde(default, skip_serializing_if = "Option::is_none")] + base_url: Option, + /// The wire protocol, as the CLI names it. + #[serde(default, skip_serializing_if = "Option::is_none")] + protocol: Option, + /// The model to use with the provider. + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, + /// The environment variable the CLI reads the key from; only where the + /// CLI keeps the list of providers. + #[serde(default, skip_serializing_if = "Option::is_none")] + key_variable: Option, + /// The provider takes no key, or an optional one, such as a local + /// server. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + key_optional: bool, + /// Optional request headers the vendor documents, by name; their values + /// are the user's to type. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + header_names: Vec, + /// Where the user makes a key, opened in the browser on the user's + /// click. + #[serde(default, skip_serializing_if = "Option::is_none")] + keys_url: Option, +} + +/// The presets of a providers `read` answer: at most [`MAX_PRESETS`], IDs +/// unique, each by the snapshot's rules. Where Lithe keeps the list, a +/// provider names no key variable, so a preset names none either. +pub(super) fn check(presets: &[Preset], kept_by: ListKeptBy) -> Check { + if presets.len() > MAX_PRESETS { + return Err("presets".into()); + } + let mut ids = BTreeSet::new(); + for (index, preset) in presets.iter().enumerate() { + let field = format!("presets[{index}]"); + let invalid = |name: &str| Err(format!("{field}.{name}")); + if !is_provider_id(&preset.id) || !ids.insert(preset.id.as_str()) { + return invalid("id"); + } + check_name(&preset.name, &format!("{field}.name"))?; + check_description( + preset.description.as_deref(), + &format!("{field}.description"), + )?; + if preset + .base_url + .as_deref() + .is_some_and(|url| !is_endpoint(url)) + { + return invalid("baseUrl"); + } + if preset.protocol.as_deref().is_some_and(|p| !is_token(p)) { + return invalid("protocol"); + } + if let Some(model) = &preset.model { + check_name(model, &format!("{field}.model"))?; + } + match (&preset.key_variable, kept_by) { + (Some(_), ListKeptBy::Lithe) => return invalid("keyVariable"), + (Some(name), ListKeptBy::Cli) if !is_environment_name(name) => { + return invalid("keyVariable") + } + _ => {} + } + if preset.header_names.len() > MAX_PRESET_HEADERS { + return invalid("headerNames"); + } + let mut names = BTreeSet::new(); + for (header, name) in preset.header_names.iter().enumerate() { + if !super::headers::is_header_name(name) || !names.insert(name.to_ascii_lowercase()) { + return invalid(&format!("headerNames[{header}]")); + } + } + if preset + .keys_url + .as_deref() + .is_some_and(|url| !is_endpoint(url)) + { + return invalid("keysUrl"); + } + } + Ok(()) +} diff --git a/rust/crates/agent-runtime/src/library/providers/probe.rs b/rust/crates/agent-runtime/src/library/providers/probe.rs new file mode 100644 index 00000000..3e8935fb --- /dev/null +++ b/rust/crates/agent-runtime/src/library/providers/probe.rs @@ -0,0 +1,681 @@ +//! Reaching a provider over the network for the user +//! (`agentProviders.fetchModels` and `agentProviders.testConnection`). +//! +//! The plugin's `probe` function makes the request, not Core: the key is in +//! the CLI's configuration or the plugin's own credentials, and only the +//! plugin knows the wire protocol, its paths, how it carries the key and +//! what its answer looks like. Core has no HTTP client, and handing it the +//! key would read the key back out of the plugin. Core decides when a probe +//! happens and what it may reach, and checks what comes back: +//! +//! - Only a request the user started probes, only for a plugin granted +//! `agents.configuration`, and only the probes its manifest declares. +//! Nothing probes in the background. +//! - The provider is one the agent has, or one the user is adding; either +//! way it has an `http` or `https` endpoint without a user, password, +//! query or fragment, which is all the plugin may reach. A key and header +//! values the user typed go to the plugin in memory and nowhere else. +//! - Core gives the plugin a time budget and a response size limit for the +//! exchange, waits a little longer for the answer, and accepts only a +//! result of the closed set of categories, an HTTP status that agrees +//! with it, a server error code and the models listed. The answer has no +//! field for text, so a server's message, which may quote a key, never +//! reaches the host. +//! - Logs carry plugin and agent IDs, the probe, the category, the status, +//! counts and codes, never an endpoint, a model, a header or a key. + +use super::super::{agent_paths, configurable_agent, files_param, require_user}; +use super::headers::{self, HeaderInput}; +use super::{ + backend_unavailable, check_name, declaration, invalid_key, is_endpoint, is_environment_name, + is_provider_id, is_token, not_declared, refusal, saved, ListKeptBy, Provider, + ProvidersSnapshot, Secret, MAX_CONTEXT_WINDOW, +}; +use crate::catalog::CatalogAgent; +use crate::{log_fields, Runtime}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + +const PROBE_FORMAT: &str = "litheAgentProvidersProbe"; + +/// The plugin's budget for its whole exchange with the provider: resolving +/// the name, connecting, sending and reading the answer. +const EXCHANGE_MILLISECONDS: u64 = 20_000; +/// How long Core waits for the probe function, in milliseconds: the +/// exchange plus time to find the key and decode the answer. +const PROBE_TIMEOUT_MILLISECONDS: u64 = 30_000; +const PROBE_TIMEOUT: Duration = Duration::from_millis(PROBE_TIMEOUT_MILLISECONDS); +/// Largest answer body the plugin reads for a list of models. Some relays +/// describe every model they resell in it. +const MODELS_RESPONSE_BYTES: u64 = 8 * 1024 * 1024; +/// Largest answer body the plugin reads for a connection test, which needs +/// only the status and the server's error code. +const TEST_RESPONSE_BYTES: u64 = 64 * 1024; +/// Most models a list of models may hold. +const MAX_FETCHED_MODELS: usize = 2048; + +/// One of the requests a `probe` function answers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Probe { + /// Lists the models the provider serves. + FetchModels, + /// Sends the provider the smallest request its protocol takes. + TestConnection, +} + +impl Probe { + /// The name the manifest declares and the plugin receives. + fn name(self) -> &'static str { + match self { + Self::FetchModels => "fetchModels", + Self::TestConnection => "testConnection", + } + } + + fn response_bytes(self) -> u64 { + match self { + Self::FetchModels => MODELS_RESPONSE_BYTES, + Self::TestConnection => TEST_RESPONSE_BYTES, + } + } +} + +// --------------------------------------------------------------------------- +// The request. + +/// The provider a probe reaches, as the host names it: one the agent has, +/// by `id`, with any field the user changed, or one the user is adding. +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProbeProvider { + #[serde(default)] + id: Option, + #[serde(default)] + base_url: Option, + #[serde(default)] + protocol: Option, + #[serde(default)] + key_variable: Option, + /// The model to ask for in a connection test. + #[serde(default)] + model: Option, +} + +/// No `Debug`: it may carry a key and header values. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProbeRequest { + agent: String, + provider: ProbeProvider, + /// A key the user typed; none uses the key the plugin keeps for an + /// existing provider. + #[serde(default)] + key: Option, + /// The headers to send in place of the provider's. + #[serde(default)] + headers: Option>, +} + +impl ProbeRequest { + /// Whether the request carries anything of its own beyond naming a + /// provider: changed fields, a key or headers. + fn is_draft(&self) -> bool { + let provider = &self.provider; + provider.base_url.is_some() + || provider.protocol.is_some() + || provider.key_variable.is_some() + || provider.model.is_some() + || self.key.is_some() + || self.headers.is_some() + } + + /// The request's own fields; a bad endpoint, key and headers have their + /// own codes. + fn check(&self) -> Result<(), CoreError> { + let provider = &self.provider; + let invalid = provider.id.as_deref().is_some_and(|id| !is_provider_id(id)) + || provider.protocol.as_deref().is_some_and(|p| !is_token(p)) + || provider + .key_variable + .as_deref() + .is_some_and(|name| !is_environment_name(name)) + || provider + .model + .as_deref() + .is_some_and(|model| check_name(model, "model").is_err()); + if invalid { + return Err(invalid_probe()); + } + if provider + .base_url + .as_deref() + .is_some_and(|url| !is_endpoint(url)) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentProviders.invalidEndpoint", + "An endpoint is an http or https URL without a user, password, query or fragment.", + )); + } + if self.key.as_ref().is_some_and(|key| !key.is_valid()) { + return Err(invalid_key()); + } + if let Some(headers) = &self.headers { + headers::check_inputs(headers)?; + } + Ok(()) + } +} + +/// The provider as the plugin receives it, after Core filled in what the +/// agent has: an endpoint always. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Target { + #[serde(skip_serializing_if = "Option::is_none")] + id: Option, + base_url: String, + #[serde(skip_serializing_if = "Option::is_none")] + protocol: Option, + #[serde(skip_serializing_if = "Option::is_none")] + key_variable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + model: Option, +} + +/// What the agent has for a provider ID: its fields and header names. +struct Existing { + base_url: Option, + protocol: Option, + key_variable: Option, + model: Option, + header_names: Vec, +} + +impl Existing { + fn reported(provider: &Provider) -> Self { + Self { + base_url: provider.base_url.clone(), + protocol: provider.protocol.clone(), + key_variable: provider.key_variable.clone(), + model: provider.model.clone(), + header_names: headers::names(provider).map(str::to_string).collect(), + } + } +} + +/// Finds the provider `id` names: where Lithe keeps the list, a saved +/// provider first (the host knows the one in use by its saved ID), then a +/// provider the configuration holds. +fn existing( + snapshot: &ProvidersSnapshot, + saved: &[saved::SavedProvider], + id: &str, +) -> Option { + if let Some(provider) = saved.iter().find(|provider| provider.id == id) { + return Some(Existing { + base_url: Some(provider.base_url.clone()), + protocol: provider.protocol.clone(), + key_variable: None, + model: provider.model.clone(), + header_names: Vec::new(), + }); + } + snapshot.find(id).map(Existing::reported) +} + +/// The provider the plugin reaches and whether the agent has it. Refuses an +/// ID the agent does not have without an endpoint to reach instead, a +/// provider without an endpoint, and a header without a value the provider +/// does not have. +fn target( + request: &ProbeRequest, + snapshot: &ProvidersSnapshot, + saved: &[saved::SavedProvider], +) -> Result<(Target, bool), CoreError> { + let asked = &request.provider; + let found = asked + .id + .as_deref() + .and_then(|id| existing(snapshot, saved, id)); + if asked.id.is_some() && found.is_none() && asked.base_url.is_none() { + return Err(refusal( + ErrorCode::EntryNotFound, + "agentProviders.unknownProvider", + "The agent has no provider with this ID.", + )); + } + let kept = found.as_ref(); + let pick = |given: &Option, had: fn(&Existing) -> &Option| { + given.clone().or_else(|| kept.and_then(|e| had(e).clone())) + }; + let Some(base_url) = pick(&asked.base_url, |e| &e.base_url) else { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentProviders.noEndpoint", + "The provider has no endpoint to reach; give a baseUrl.", + )); + }; + if let Some(headers) = &request.headers { + headers::check_kept( + headers, + kept.into_iter() + .flat_map(|e| e.header_names.iter().map(String::as_str)), + )?; + } + let target = Target { + id: asked.id.clone(), + base_url, + protocol: pick(&asked.protocol, |e| &e.protocol), + key_variable: pick(&asked.key_variable, |e| &e.key_variable), + model: pick(&asked.model, |e| &e.model), + }; + Ok((target, found.is_some())) +} + +// --------------------------------------------------------------------------- +// The answer. + +/// What came of the exchange, one closed set for both probes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Category { + /// The provider answered as its protocol does. + Ok, + /// HTTP 401 or 403: the key was refused or has no access. + Unauthorized, + /// HTTP 404: nothing at that address, usually a wrong endpoint. + NotFound, + /// HTTP 429. + RateLimited, + /// Another HTTP 4xx, such as a model the provider does not serve. + RequestRejected, + /// HTTP 5xx. + ServerError, + /// HTTP 3xx, which the plugin does not follow. + Redirected, + /// A 2xx answer that is not what the protocol answers. + InvalidResponse, + /// The answer was larger than the plugin may read. + ResponseTooLarge, + /// No whole answer within the time budget. + Timeout, + /// The endpoint's host name did not resolve. + DnsFailed, + /// No connection could be made, directly or through a proxy. + ConnectFailed, + /// The TLS handshake or the certificate check failed. + TlsFailed, + /// The provider needs a key and the plugin has none; nothing was sent. + NoKey, + /// The plugin cannot make this probe for this provider, such as a + /// protocol without a list of models; nothing was sent. + Unsupported, +} + +impl Category { + fn name(self) -> &'static str { + match self { + Self::Ok => "ok", + Self::Unauthorized => "unauthorized", + Self::NotFound => "notFound", + Self::RateLimited => "rateLimited", + Self::RequestRejected => "requestRejected", + Self::ServerError => "serverError", + Self::Redirected => "redirected", + Self::InvalidResponse => "invalidResponse", + Self::ResponseTooLarge => "responseTooLarge", + Self::Timeout => "timeout", + Self::DnsFailed => "dnsFailed", + Self::ConnectFailed => "connectFailed", + Self::TlsFailed => "tlsFailed", + Self::NoKey => "noKey", + Self::Unsupported => "unsupported", + } + } + + /// Whether `status` agrees with the category: the categories of an HTTP + /// answer need its status in their range, `responseTooLarge` may have + /// one, and the others have none. + fn takes(self, status: Option) -> bool { + match (self, status) { + (Self::Ok | Self::InvalidResponse, Some(status)) => (200..300).contains(&status), + (Self::Unauthorized, Some(status)) => status == 401 || status == 403, + (Self::NotFound, Some(status)) => status == 404, + (Self::RateLimited, Some(status)) => status == 429, + (Self::RequestRejected, Some(status)) => { + (400..500).contains(&status) && ![401, 403, 404, 429].contains(&status) + } + (Self::ServerError, Some(status)) => (500..600).contains(&status), + (Self::Redirected, Some(status)) => (300..400).contains(&status), + (Self::ResponseTooLarge, status) => { + status.is_none_or(|status| (100..600).contains(&status)) + } + ( + Self::Timeout + | Self::DnsFailed + | Self::ConnectFailed + | Self::TlsFailed + | Self::NoKey + | Self::Unsupported, + None, + ) => true, + _ => false, + } + } +} + +/// The result of one probe as the plugin reports it. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProbeResult { + category: Category, + /// The HTTP status of the provider's answer, when one came back. + #[serde(default, skip_serializing_if = "Option::is_none")] + status: Option, + /// The provider's own error code from its answer, such as + /// `invalid_api_key`; only with a status of 400 or more. + #[serde(default, skip_serializing_if = "Option::is_none")] + code: Option, + /// Milliseconds from sending the request to the answer or the failure; + /// 0 when nothing was sent. + duration_ms: u64, + /// The model a connection test asked for. + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, +} + +/// One model a provider lists. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FetchedModel { + /// The model as the provider names it in a request. + id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, + /// How many tokens a prompt may hold, when the provider says. + #[serde(default, skip_serializing_if = "Option::is_none")] + context_window: Option, +} + +/// The answer of a `probe` function. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProbeAnswer { + format: String, + version: u32, + result: ProbeResult, + /// The models the provider lists; only for `fetchModels` that went + /// `ok`, and then always. + #[serde(default)] + models: Option>, +} + +impl ProbeAnswer { + fn check(&self, probe: Probe) -> Check { + if self.format != PROBE_FORMAT || self.version != 0 { + return Err("format".into()); + } + let result = &self.result; + if !result.category.takes(result.status) { + return Err("result.status".into()); + } + if result + .code + .as_deref() + .is_some_and(|code| !is_token(code) || result.status.is_none_or(|status| status < 400)) + { + return Err("result.code".into()); + } + if result.duration_ms > PROBE_TIMEOUT_MILLISECONDS { + return Err("result.durationMs".into()); + } + if let Some(model) = &result.model { + if probe != Probe::TestConnection { + return Err("result.model".into()); + } + check_name(model, "result.model")?; + } + let lists = probe == Probe::FetchModels && result.category == Category::Ok; + match (&self.models, lists) { + (None, false) => Ok(()), + (Some(models), true) => check_fetched(models), + _ => Err("models".into()), + } + } +} + +type Check = Result<(), String>; + +fn check_fetched(models: &[FetchedModel]) -> Check { + if models.len() > MAX_FETCHED_MODELS { + return Err("models".into()); + } + let mut ids = BTreeSet::new(); + for (index, model) in 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 + .context_window + .is_some_and(|tokens| tokens == 0 || tokens > MAX_CONTEXT_WINDOW) + { + return Err(format!("{field}.contextWindow")); + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Refusals. + +fn invalid_probe() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentProviders.invalidProbe", + "The probe's provider fields break the rules of a provider.", + ) +} + +fn unsupported_probe() -> CoreError { + refusal( + ErrorCode::NotSupported, + "agentProviders.unsupportedProbe", + "The agent plugin does not declare this probe.", + ) +} + +/// A refusal and, when the plugin's function call failed, the call's own +/// failure code for the log. +struct Refused { + error: CoreError, + call_code: Option, +} + +impl From for Refused { + fn from(error: CoreError) -> Self { + Self { + error, + call_code: None, + } + } +} + +/// What a log token may hold: at most 64 bytes of ASCII letters, digits +/// and `._:/-$`. A call code that is not one is left out of the log. +fn log_token(code: &str) -> Option<&str> { + (!code.is_empty() + && code.len() <= 64 + && code + .chars() + .all(|c| c.is_ascii_alphanumeric() || "._:/-$".contains(c))) + .then_some(code) +} + +// --------------------------------------------------------------------------- +// The commands. + +/// The success of a probe, for the log. +struct Finished { + category: Category, + status: Option, + models: Option, + draft: bool, +} + +fn elapsed_ms(started: Instant) -> u64 { + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +impl super::super::Library { + /// `agentProviders.fetchModels`: the models one provider serves, as the + /// agent's plugin lists them from the provider for the user. + pub fn fetch_models(&self, runtime: &Runtime, payload: Value) -> Result { + self.probe_provider(runtime, Probe::FetchModels, payload) + } + + /// `agentProviders.testConnection`: whether one provider answers the + /// smallest request of its protocol, as the agent's plugin sends it for + /// the user. + pub fn test_connection(&self, runtime: &Runtime, payload: Value) -> Result { + self.probe_provider(runtime, Probe::TestConnection, payload) + } + + /// Asks the agent's plugin to reach one provider for the user. + fn probe_provider( + &self, + runtime: &Runtime, + probe: Probe, + payload: Value, + ) -> Result { + require_user()?; + // The decoder's text could quote a key or a header value. + let request: ProbeRequest = serde_json::from_value(payload).map_err(|_| { + refusal( + ErrorCode::InvalidRequest, + "agents.invalidPayload", + "The probe payload is not {agent, provider, key?, headers?}.", + ) + })?; + let started = Instant::now(); + let agent = configurable_agent(runtime, &request.agent)?; + let outcome = self.probe_checked(runtime, &agent, probe, &request); + let mut fields = vec![ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("probe", json!(probe.name())), + ]; + match outcome { + Ok((answer, finished)) => { + fields.push(("category", json!(finished.category.name()))); + fields.push(("draft", json!(finished.draft))); + fields.push(("duration_ms", json!(elapsed_ms(started)))); + if let Some(status) = finished.status { + fields.push(("status", json!(status))); + } + if let Some(models) = finished.models { + fields.push(("models", json!(models))); + } + log_fields("agent.providers.probe_finished", fields.into_iter()); + Ok(answer) + } + Err(refused) => { + let reason = refused + .error + .details + .clone() + .unwrap_or_else(|| "agentProviders.probeFailed".into()); + fields.push(("reason", json!(reason))); + if let Some(code) = refused.call_code.as_deref().and_then(log_token) { + fields.push(("call_code", json!(code))); + } + log_fields("agent.providers.probe_failed", fields.into_iter()); + Err(refused.error) + } + } + } + + fn probe_checked( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + probe: Probe, + request: &ProbeRequest, + ) -> Result<(Value, Finished), Refused> { + let (configuration, declared) = declaration(agent).ok_or_else(not_declared)?; + let function = declared + .probe + .as_deref() + .filter(|_| declared.probes.iter().any(|name| name == probe.name())) + .ok_or_else(unsupported_probe)?; + request.check()?; + + let config = self.config()?; + let paths = agent_paths(&config, configuration); + let snapshot = self.read_and_remember(runtime, agent, &paths)?; + let saved = match declared.list_kept_by { + ListKeptBy::Lithe => saved::load(&config, &agent.record_key())?, + ListKeptBy::Cli => Vec::new(), + }; + let (target, existing) = target(request, &snapshot, &saved)?; + + let mut params = json!({ + "agentID": agent.agent.id, + "files": files_param(&paths.files), + "probe": probe.name(), + "provider": target, + "existing": existing, + "timeoutMilliseconds": EXCHANGE_MILLISECONDS, + "maximumResponseBytes": probe.response_bytes(), + }); + if let Some(key) = &request.key { + params["key"] = json!(key); + } + if let Some(headers) = &request.headers { + params["headers"] = json!(headers); + } + let link = &*runtime.link; + let backend = link + .session_for(&agent.plugin_id, function, None) + .ok_or_else(backend_unavailable)?; + let answer = link + .call(&backend, &agent.plugin_id, function, params, PROBE_TIMEOUT) + .map_err(|failure| Refused { + error: refusal( + ErrorCode::ProcessFailed, + "agentProviders.probeFailed", + "The agent plugin could not reach the provider for this probe.", + ), + call_code: Some(failure.code), + })?; + let invalid = || { + refusal( + ErrorCode::ParseFailed, + "agentProviders.invalidProbeAnswer", + "The agent plugin returned an invalid probe answer.", + ) + }; + let answer: ProbeAnswer = serde_json::from_value(answer).map_err(|_| invalid())?; + answer.check(probe).map_err(|_| invalid())?; + + let mut view = json!({ "agent": agent.record_key(), "result": answer.result }); + if let Some(models) = &answer.models { + view["models"] = json!(models); + } + let finished = Finished { + category: answer.result.category, + status: answer.result.status, + models: answer.models.as_ref().map(Vec::len), + draft: request.is_draft(), + }; + Ok((view, finished)) + } +} diff --git a/rust/crates/agent-runtime/src/tests/library.rs b/rust/crates/agent-runtime/src/tests/library.rs index 89ed48d2..621ba9c1 100644 --- a/rust/crates/agent-runtime/src/tests/library.rs +++ b/rust/crates/agent-runtime/src/tests/library.rs @@ -21,6 +21,10 @@ enum Edit { /// Applies the change, and something else changes the real file /// meanwhile. Race(PathBuf), + /// Leaves the copy as it is and reports no change. + Ignore, + /// Makes the change in the copy but reports no change. + Unreported, } /// The synthetic plugin with configuration declared for its agent. @@ -132,15 +136,17 @@ fn configuration_edit(params: &Value, edit: &Edit) -> Result return Err(failure("plugin.params.invalid")), } match edit { - Edit::Apply => {} + Edit::Apply | Edit::Unreported => {} Edit::Wrong => config = json!({ "servers": before["servers"], "noise": true }), Edit::Race(real) => fs::write(real, br#"{"servers":{}}"#).unwrap(), + Edit::Ignore => config = before.clone(), } let changed = config != before; if changed { fs::write(&staging, serde_json::to_vec(&config).unwrap()).unwrap(); } - Ok(json!({ "format": "litheAgentConfigurationEdit", "version": 0, "changed": changed })) + let reported = changed && !matches!(edit, Edit::Unreported); + Ok(json!({ "format": "litheAgentConfigurationEdit", "version": 0, "changed": reported })) } /// A harness with the configuration plugin granted `grants` and the library @@ -413,6 +419,25 @@ fn servers_and_hooks_change_only_through_a_checked_staged_copy() { before, "a wrong edit never reaches the file" ); + // A plugin that ignores a change and says nothing changed cannot pass + // it off as made, nor can one that makes it in its copy and says it + // did not: the file as it is must hold the change. + for edit in [Edit::Ignore, Edit::Unreported] { + *test.edit.lock().unwrap() = edit; + assert_eq!( + test.refused_change( + json!({ "category": "mcpServers", "op": "remove", "name": "docs" }) + ), + "agentLibrary.editNotApplied" + ); + assert_eq!(fs::read(&file).unwrap(), before); + } + *test.edit.lock().unwrap() = Edit::Ignore; + assert!( + !test.apply(json!({ "category": "mcpServers", "op": "put", "name": "docs" })), + "what the file already holds needs no edit" + ); + assert_eq!(test.staged_files(), 0, "every staged copy is removed"); *test.edit.lock().unwrap() = Edit::Race(file.clone()); assert_eq!( test.refused_change(json!({ "category": "mcpServers", "op": "remove", "name": "docs" })), diff --git a/rust/crates/agent-runtime/src/tests/providers.rs b/rust/crates/agent-runtime/src/tests/providers.rs index 9524ef36..847d792f 100644 --- a/rust/crates/agent-runtime/src/tests/providers.rs +++ b/rust/crates/agent-runtime/src/tests/providers.rs @@ -126,6 +126,10 @@ enum Edit { Apply, /// Reports a change but writes something else. Wrong, + /// Leaves the copy as it is and reports no change. + Ignore, + /// Makes the change in the copy but reports no change. + Unreported, } fn providers_edit(params: &Value, edit: Edit) -> Result { @@ -161,14 +165,17 @@ fn providers_edit(params: &Value, edit: Edit) -> Result "setProfile" => config["profile"] = change["name"].clone(), _ => return Err(failure("plugin.params.invalid")), } - if let Edit::Wrong = edit { - config = json!({ "noise": true }); + match edit { + Edit::Wrong => config = json!({ "noise": true }), + Edit::Ignore => config = before.clone(), + Edit::Apply | Edit::Unreported => {} } let changed = config != before; if changed { fs::write(&staging, serde_json::to_vec(&config).unwrap()).unwrap(); } - Ok(json!({ "format": "litheAgentProvidersEdit", "version": 0, "changed": changed })) + let reported = changed && !matches!(edit, Edit::Unreported); + Ok(json!({ "format": "litheAgentProvidersEdit", "version": 0, "changed": reported })) } struct ProvidersTest { @@ -182,10 +189,16 @@ struct ProvidersTest { impl ProvidersTest { fn new(name: &str, grants: &[&str], operations: &[&str]) -> Self { + Self::with_manifest(name, grants, providers_manifest(operations)) + } + + /// A test whose plugin has `manifest`, such as [`providers_manifest`] + /// with more declared. + fn with_manifest(name: &str, grants: &[&str], manifest: Value) -> Self { let harness = Harness::new(name, ALL_GRANTS); harness.run( "agents.configure", - json!({ "plugins": [{ "manifest": providers_manifest(operations), "grantedPermissions": grants }] }), + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": grants }] }), ); let home = harness.dir.path().join("home"); let library = harness.dir.path().join("library"); @@ -560,6 +573,25 @@ fn changes_go_through_a_checked_staged_copy() { ); assert_eq!(test.staged_files(), 0); + // A plugin that ignores a change and says nothing changed cannot pass + // it off as made, nor can one that makes it in its copy and says it + // did not: the file as it is must hold the change. + for edit in [Edit::Ignore, Edit::Unreported] { + *test.edit.lock().unwrap() = edit; + expect( + json!({ "op": "setProvider", "id": "alpha" }), + "agentProviders.editNotApplied", + ); + assert_eq!(fs::read(&file).unwrap(), before); + } + *test.edit.lock().unwrap() = Edit::Ignore; + assert!( + !test.apply(json!({ "op": "setProfile", "name": "work" })), + "what the file already holds needs no edit" + ); + assert_eq!(test.staged_files(), 0, "every staged copy is removed"); + *test.edit.lock().unwrap() = Edit::Apply; + let previous = trace::replace(trace::Context { op: None, source: Source::Background, @@ -648,6 +680,9 @@ impl LibraryHarness { } mod backups; +mod headers; mod keys; mod models; +mod presets; +mod probes; mod saved; diff --git a/rust/crates/agent-runtime/src/tests/providers/headers.rs b/rust/crates/agent-runtime/src/tests/providers/headers.rs new file mode 100644 index 00000000..201a9532 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers/headers.rs @@ -0,0 +1,376 @@ +//! Request headers a change carries where the plugin declares +//! `editsHeaders`: values reach the plugin's `edit` and nothing else, and a +//! header without a value keeps the one the provider has. + +use super::*; + +/// A synthetic header value; no real service accepts it. +const VALUE: &str = "test-header-not-real"; + +fn assert_value_hidden(text: &str, place: &str) { + assert!(!text.contains(VALUE), "a header value shows in {place}"); +} + +/// [`providers_manifest`] with every operation and `editsHeaders`. +fn headers_manifest() -> Value { + let mut manifest = providers_manifest(ALL_OPERATIONS); + manifest["agents"][0]["configuration"]["providers"]["editsHeaders"] = json!(true); + manifest +} + +/// [`providers_read`] of a file that keeps a provider's headers as a table +/// of values, reported by name with whether each has a value. +fn headers_read(params: &Value) -> Result { + let mut answer = providers_read(params)?; + for provider in answer["providers"].as_array_mut().unwrap() { + if let Some(table) = provider.as_object_mut().unwrap().remove("headers") { + let headers: Vec = table + .as_object() + .unwrap() + .iter() + .map(|(name, value)| json!({ "name": name, "valueSet": !value.is_null() })) + .collect(); + provider["headers"] = json!(headers); + } + } + Ok(answer) +} + +/// [`providers_edit`] that also writes the headers a change carries: a +/// header with a value takes it, one without keeps the provider's value +/// for that name (case ignored), and a change without headers keeps them +/// all. With `dropping`, it writes the provider without its headers. +fn headers_edit(params: &Value, dropping: bool) -> Result { + let staging = PathBuf::from(params["file"]["staging"].as_str().unwrap()); + let before = read_json(&staging); + let change = ¶ms["change"]; + let edited = providers_edit(params, Edit::Apply)?; + let Some(id) = change["provider"]["id"].as_str() else { + return Ok(edited); + }; + let old = before["providers"][id]["headers"].clone(); + let headers = match change.get("headers") { + None => old, + Some(given) => { + let mut table = serde_json::Map::new(); + for header in given.as_array().unwrap() { + let name = header["name"].as_str().unwrap(); + let value = header.get("value").cloned().unwrap_or_else(|| { + old.as_object() + .and_then(|old| { + old.iter() + .find(|(kept, _)| kept.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.clone()) + }) + .unwrap_or(Value::Null) + }); + table.insert(name.to_string(), value); + } + Value::Object(table) + } + }; + let mut config = read_json(&staging); + let row = config["providers"][id].as_object_mut().unwrap(); + match headers { + Value::Object(table) if !table.is_empty() && !dropping => { + row.insert("headers".into(), Value::Object(table)); + } + _ => { + row.remove("headers"); + } + } + let changed = config != before; + fs::write(&staging, serde_json::to_vec(&config).unwrap()).unwrap(); + Ok(json!({ "format": "litheAgentProvidersEdit", "version": 0, "changed": changed })) +} + +struct HeadersTest { + test: ProvidersTest, + /// Whether `providers.edit` loses the headers. + dropping: Arc>, +} + +impl HeadersTest { + fn new(name: &str) -> Self { + let test = ProvidersTest::with_manifest(name, PROVIDER_GRANTS, headers_manifest()); + let dropping = Arc::new(Mutex::new(false)); + let (drops, answer) = (dropping.clone(), test.answer.clone()); + test.harness + .link + .set_answer(move |function, params| match function { + "providers.read" => match answer.lock().unwrap().clone() { + Some(answer) => Ok(answer), + None => headers_read(params), + }, + "providers.edit" => headers_edit(params, *drops.lock().unwrap()), + other => sample_backend(other, params), + }); + Self { test, dropping } + } + + /// The headers of the provider `id` in the configuration file. + fn kept(&self, id: &str) -> Value { + read_json(&self.test.config_file())["providers"][id]["headers"].clone() + } +} + +/// The header names of a provider in the read answer, sorted. +fn header_names(provider: &Value) -> Vec { + let mut names: Vec = provider["headerNames"] + .as_array() + .unwrap() + .iter() + .map(|name| name.as_str().unwrap().to_string()) + .collect(); + names.sort(); + names +} + +fn gamma() -> Value { + json!({ "id": "gamma", "name": "Gamma", "baseUrl": "https://gamma.example.test/v1" }) +} + +#[test] +fn header_values_reach_only_the_plugin_edit() { + let headers = HeadersTest::new("providers headers"); + let test = &headers.test; + test.write_config(sample_config()); + + let ((), logs) = capture::run(false, || { + assert_eq!(test.read()["editsHeaders"], true); + assert!(test.apply( + json!({ "op": "addProvider", "provider": gamma(), "headers": [ + { "name": "X-Team", "value": VALUE }, { "name": "X-Region", "value": "eu" } + ] }) + )); + let edits = test.harness.link.calls_of("providers.edit"); + assert_eq!( + edits[0]["change"]["headers"], + json!([{ "name": "X-Team", "value": VALUE }, { "name": "X-Region", "value": "eu" }]), + "the plugin gets the values" + ); + let read = test.read(); + assert_value_hidden(&read.to_string(), "the read answer"); + let found = test.provider("gamma"); + assert_eq!(header_names(&found), ["X-Region", "X-Team"]); + assert!(found["headers"] + .as_array() + .unwrap() + .iter() + .all(|header| header["valueSet"] == true && header.get("value").is_none())); + + // A header the host read back, `valueSet` and all, keeps its value + // by name, case ignored; one left out goes. + assert!(test.apply( + json!({ "op": "updateProvider", "provider": gamma(), "headers": [ + { "name": "x-team", "valueSet": true }, { "name": "X-Trace", "value": "on" } + ] }) + )); + let change = &test.harness.link.calls_of("providers.edit")[1]["change"]; + assert_eq!( + change["headers"], + json!([{ "name": "x-team" }, { "name": "X-Trace", "value": "on" }]), + "Core passes on no valueSet" + ); + assert_eq!( + headers.kept("gamma"), + json!({ "x-team": VALUE, "X-Trace": "on" }) + ); + + assert!(test.apply(json!({ "op": "updateProvider", "provider": { + "id": "gamma", "name": "Gamma Two", "baseUrl": "https://gamma.example.test/v1" + } }))); + assert_eq!( + headers.kept("gamma"), + json!({ "x-team": VALUE, "X-Trace": "on" }), + "a change without headers keeps them" + ); + + assert!(test.apply(json!({ "op": "updateProvider", "provider": gamma(), "headers": [] }))); + assert!(headers.kept("gamma").is_null(), "an empty list drops them"); + assert!(test.provider("gamma").get("headerNames").is_none()); + + // An edit that does not show the headers is refused without the + // value: one that writes the rest, and one that leaves the file as + // it was and says nothing changed. + *headers.dropping.lock().unwrap() = true; + let renamed = json!({ + "id": "gamma", "name": "Gamma Three", "baseUrl": "https://gamma.example.test/v1" + }); + for provider in [renamed, gamma()] { + let text = test.refusal_text(json!({ "op": "updateProvider", "provider": provider, + "headers": [{ "name": "X-Team", "value": VALUE }] })); + assert!(text.contains("agentProviders.editNotApplied"), "{text}"); + assert_value_hidden(&text, "an edit refusal"); + } + *headers.dropping.lock().unwrap() = false; + }); + for log in &logs { + assert_value_hidden(&format!("{:?}", log.fields), &log.event); + } + assert!(logs + .iter() + .any(|log| log.event == "agent.providers.change_applied")); +} + +#[test] +fn header_changes_are_checked_without_showing_values() { + let headers = HeadersTest::new("providers header rules"); + let test = &headers.test; + let mut config = sample_config(); + config["providers"]["alpha"]["headers"] = json!({ "X-Team": VALUE }); + test.write_config(config); + let alpha = json!({ + "id": "alpha", "name": "Alpha", "baseUrl": "https://alpha.example.test/v1", + "protocol": "responses", "keyVariable": "ALPHA_API_KEY", "enabled": true + }); + let update = + |headers: Value| json!({ "op": "updateProvider", "provider": alpha, "headers": headers }); + let many: Vec = (0..65) + .map(|i| json!({ "name": format!("X-H{i}"), "value": VALUE })) + .collect(); + for (case, change, code) in [ + ( + "a kept header the provider does not have", + update(json!([{ "name": "X-Missing" }])), + "agentProviders.unknownHeader", + ), + ( + "a kept header on a new provider", + json!({ "op": "addProvider", "provider": gamma(), "headers": [{ "name": "X-Team" }] }), + "agentProviders.unknownHeader", + ), + ( + "a header the HTTP client sets", + update(json!([{ "name": "Host", "value": VALUE }])), + "agentProviders.invalidHeaders", + ), + ( + "a name twice, case ignored", + update( + json!([{ "name": "X-Team", "value": VALUE }, { "name": "x-team", "value": VALUE }]), + ), + "agentProviders.invalidHeaders", + ), + ( + "a name with a space", + update(json!([{ "name": "X Team", "value": VALUE }])), + "agentProviders.invalidHeaders", + ), + ( + "an empty value", + update(json!([{ "name": "X-Team", "value": "" }])), + "agentProviders.invalidHeaders", + ), + ( + "a value with a line break", + update(json!([{ "name": "X-Team", "value": format!("{VALUE}\r\nX-Other: 1") }])), + "agentProviders.invalidHeaders", + ), + ( + "a long value", + update(json!([{ "name": "X-Team", "value": format!("{VALUE}{}", "a".repeat(8192)) }])), + "agentProviders.invalidHeaders", + ), + ( + "too many headers", + update(json!(many)), + "agentProviders.invalidHeaders", + ), + ( + "an unknown field", + update(json!([{ "name": "X-Team", "value": VALUE, "secret": VALUE }])), + "agentProviders.invalidChange", + ), + ] { + let text = test.refusal_text(change); + assert!(text.contains(code), "{case}: {text}"); + assert_value_hidden(&text, case); + } + assert!( + test.harness.link.calls_of("providers.edit").is_empty(), + "a refused change never reaches the plugin" + ); + assert!(test.apply(update(json!([{ "name": "X-TEAM" }])))); + assert_eq!(headers.kept("alpha"), json!({ "X-TEAM": VALUE })); + + let plain = ProvidersTest::new( + "providers headers undeclared", + PROVIDER_GRANTS, + ALL_OPERATIONS, + ); + plain.write_config(sample_config()); + assert_eq!(plain.read()["editsHeaders"], false); + assert_eq!( + plain.refused(json!({ "op": "addProvider", "provider": gamma(), + "headers": [{ "name": "X-Team", "value": VALUE }] })), + "agentProviders.unsupportedOperation", + "only a plugin that declares editsHeaders takes headers" + ); +} + +#[test] +fn reported_headers_carry_names_and_whether_set_only() { + let test = ProvidersTest::new( + "providers reported headers", + PROVIDER_GRANTS, + ALL_OPERATIONS, + ); + let invalid = json!("agentProviders.invalidSnapshot"); + let provider = |headers: Value| { + snapshot(json!({ "providers": [{ "id": "alpha", "name": "Alpha", "headers": headers }] })) + }; + for (case, answer) in [ + ( + "a header value", + provider(json!([{ "name": "X-Team", "value": VALUE }])), + ), + ( + "headers and headerNames together", + snapshot(json!({ "providers": [{ + "id": "alpha", "name": "Alpha", + "headers": [{ "name": "X-Team", "valueSet": true }], "headerNames": ["X-Team"] + }] })), + ), + ( + "a header the HTTP client sets", + provider(json!([{ "name": "Content-Length", "valueSet": true }])), + ), + ( + "a name twice, case ignored", + provider(json!([{ "name": "X-Team" }, { "name": "x-team" }])), + ), + ( + "a variable that is not a name", + provider(json!([{ "name": "X-Team", "variable": "Bearer token" }])), + ), + ( + "too many headers", + provider(json!((0..65) + .map(|i| json!({ "name": format!("X-H{i}") })) + .collect::>())), + ), + ] { + let error = test.read_error(answer); + assert_eq!(error, invalid, "{case}"); + assert_value_hidden(&error.to_string(), case); + } + *test.answer.lock().unwrap() = Some(provider(json!([ + { "name": "X-Team", "valueSet": true, "variable": "TEAM_HEADER" }, + { "name": "X-Region" } + ]))); + let alpha = test.read()["providers"][0].clone(); + assert!(alpha.get("readError").is_none()); + assert_eq!( + alpha["headers"], + json!([ + { "name": "X-Team", "valueSet": true, "variable": "TEAM_HEADER" }, + { "name": "X-Region", "valueSet": false } + ]) + ); + assert_eq!( + alpha["headerNames"], + json!(["X-Team", "X-Region"]), + "a host that reads names only sees every header" + ); +} diff --git a/rust/crates/agent-runtime/src/tests/providers/keys.rs b/rust/crates/agent-runtime/src/tests/providers/keys.rs index dc5de488..becbcd54 100644 --- a/rust/crates/agent-runtime/src/tests/providers/keys.rs +++ b/rust/crates/agent-runtime/src/tests/providers/keys.rs @@ -8,7 +8,7 @@ const KEY: &str = "test-key-not-real"; impl ProvidersTest { /// The whole error of a refused change, as Core would format it. - fn refusal_text(&self, change: Value) -> String { + pub(super) fn refusal_text(&self, change: Value) -> String { match self.harness.runtime.execute( "agentProviders.apply", json!({ "agent": AGENT_KEY, "change": change }), @@ -18,7 +18,7 @@ impl ProvidersTest { } } - fn provider(&self, id: &str) -> Value { + pub(super) fn provider(&self, id: &str) -> Value { self.read()["providers"] .as_array() .unwrap() diff --git a/rust/crates/agent-runtime/src/tests/providers/presets.rs b/rust/crates/agent-runtime/src/tests/providers/presets.rs new file mode 100644 index 00000000..a93abae8 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers/presets.rs @@ -0,0 +1,152 @@ +//! The provider presets a plugin lists in its read answer: shown as the +//! plugin gives them, checked by Core, and added with an ordinary +//! `addProvider`. Core has none of its own. + +use super::*; + +fn presets() -> Value { + json!([ + { + "id": "vendor", "name": "Vendor", "description": "The models' own maker.", + "kind": "vendor", "baseUrl": "https://api.vendor.example.test/v1", + "protocol": "responses", "model": "vendor-large", "keyVariable": "VENDOR_API_KEY", + "headerNames": ["X-Vendor-Project"], "keysUrl": "https://vendor.example.test/keys" + }, + { + "id": "on-device", "name": "On-device server", "kind": "local", + "baseUrl": "http://127.0.0.1:11434/v1", "protocol": "chat", "keyOptional": true + }, + { "id": "own", "name": "Your own endpoint", "protocol": "chat" } + ]) +} + +/// [`providers_read`] with `presets` added to its answer. +fn listing(test: &ProvidersTest, presets: Value) { + test.harness + .link + .set_answer(move |function, params| match function { + "providers.read" => providers_read(params).map(|mut answer| { + answer["presets"] = presets.clone(); + answer + }), + "providers.edit" => providers_edit(params, Edit::Apply), + other => sample_backend(other, params), + }); +} + +#[test] +fn presets_are_shown_as_listed_and_added_as_providers() { + let test = ProvidersTest::new("providers presets", PROVIDER_GRANTS, ALL_OPERATIONS); + test.write_config(sample_config()); + assert_eq!( + test.read()["presets"], + json!([]), + "without a list from the plugin there is none" + ); + + listing(&test, presets()); + let agent = test.read(); + assert!(agent.get("readError").is_none(), "{agent}"); + assert_eq!(agent["presets"], presets()); + + let vendor = json!({ + "id": "vendor", "name": "Vendor", "baseUrl": "https://api.vendor.example.test/v1", + "protocol": "responses", "keyVariable": "VENDOR_API_KEY" + }); + assert!(test.apply(json!({ "op": "addProvider", "provider": vendor }))); + let change = &test.harness.link.calls_of("providers.edit")[0]["change"]; + assert_eq!( + change, + &json!({ "op": "addProvider", "provider": vendor }), + "a provider from a preset is an ordinary addProvider" + ); + let providers = test.read()["providers"].clone(); + assert!(providers + .as_array() + .unwrap() + .iter() + .any(|provider| provider["id"] == "vendor")); +} + +#[test] +fn presets_follow_the_limits() { + let test = ProvidersTest::new("providers preset rules", PROVIDER_GRANTS, ALL_OPERATIONS); + let invalid = json!("agentProviders.invalidSnapshot"); + let preset = |extra: Value| { + let mut row = json!({ "id": "vendor", "name": "Vendor" }); + for (key, value) in extra.as_object().unwrap() { + row[key.as_str()] = value.clone(); + } + snapshot(json!({ "presets": [row] })) + }; + for (case, answer) in [ + ( + "too many presets", + snapshot(json!({ "presets": (0..129) + .map(|i| json!({ "id": format!("p{i}"), "name": "P" })) + .collect::>() })), + ), + ( + "a repeated ID", + snapshot( + json!({ "presets": [{ "id": "vendor", "name": "A" }, { "id": "vendor", "name": "B" }] }), + ), + ), + ("an ID with a space", preset(json!({ "id": "a vendor" }))), + ("a long name", preset(json!({ "name": "a".repeat(129) }))), + ( + "an endpoint with a query", + preset(json!({ "baseUrl": "https://api.vendor.example.test/v1?key=secret" })), + ), + ( + "an endpoint of another scheme", + preset(json!({ "baseUrl": "file:///etc/vendor" })), + ), + ( + "a keys page of another scheme", + preset(json!({ "keysUrl": "javascript:alert(1)" })), + ), + ( + "a protocol of two words", + preset(json!({ "protocol": "two words" })), + ), + ("an empty model", preset(json!({ "model": "" }))), + ( + "a key value as a variable", + preset(json!({ "keyVariable": "sk-vendor-secret" })), + ), + ( + "a header the HTTP client sets", + preset(json!({ "headerNames": ["Host"] })), + ), + ( + "a header name twice, case ignored", + preset(json!({ "headerNames": ["X-Team", "x-team"] })), + ), + ( + "too many header names", + preset( + json!({ "headerNames": (0..17).map(|i| format!("X-H{i}")).collect::>() }), + ), + ), + ("another kind", preset(json!({ "kind": "gateway" }))), + ("a key value", preset(json!({ "apiKey": "vendor-secret" }))), + ] { + assert_eq!(test.read_error(answer), invalid, "{case}"); + } + + let mut manifest = providers_manifest(&["addProvider", "setProvider"]); + manifest["agents"][0]["configuration"]["providers"]["listKeptBy"] = json!("lithe"); + let lithe = ProvidersTest::with_manifest("providers preset lithe", PROVIDER_GRANTS, manifest); + assert_eq!( + lithe.read_error(preset(json!({ "keyVariable": "VENDOR_API_KEY" }))), + invalid, + "where Lithe keeps the list, a preset names no key variable" + ); + *lithe.answer.lock().unwrap() = Some(preset( + json!({ "baseUrl": "https://api.vendor.example.test" }), + )); + let agent = lithe.read(); + assert!(agent.get("readError").is_none(), "{agent}"); + assert_eq!(agent["presets"][0]["id"], "vendor"); +} diff --git a/rust/crates/agent-runtime/src/tests/providers/probes.rs b/rust/crates/agent-runtime/src/tests/providers/probes.rs new file mode 100644 index 00000000..62e4f8fe --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/providers/probes.rs @@ -0,0 +1,707 @@ +//! Reaching a provider for the user (`agentProviders.fetchModels` and +//! `agentProviders.testConnection`): the plugin's `probe` function makes +//! the request; Core decides when it happens and what it may reach, and +//! checks what comes back. + +use super::*; + +/// Synthetic secrets; no real service accepts them. +const KEY: &str = "test-key-not-real"; +const HEADER_VALUE: &str = "test-header-not-real"; + +fn assert_secrets_hidden(text: &str, place: &str) { + assert!(!text.contains(KEY), "the key shows in {place}"); + assert!( + !text.contains(HEADER_VALUE), + "a header value shows in {place}" + ); +} + +/// [`providers_manifest`] with every operation and a probe function that +/// answers `probes`. +fn probes_manifest(probes: &[&str]) -> Value { + let mut manifest = providers_manifest(ALL_OPERATIONS); + let providers = &mut manifest["agents"][0]["configuration"]["providers"]; + providers["probe"] = json!("providers.probe"); + providers["probes"] = json!(probes); + manifest +} + +fn probe_answer(result: Value) -> Value { + json!({ "format": "litheAgentProvidersProbe", "version": 0, "result": result }) +} + +fn listed() -> Value { + let mut answer = probe_answer(json!({ "category": "ok", "status": 200, "durationMs": 120 })); + answer["models"] = json!([ + { "id": "alpha-large", "name": "Alpha Large", "contextWindow": 200000 }, + { "id": "alpha-small" } + ]); + answer +} + +struct ProbeTest { + test: ProvidersTest, + /// What `providers.probe` answers; none fails the call. + answer: Arc>>, +} + +impl ProbeTest { + fn new(name: &str, probes: &[&str]) -> Self { + let test = Self::with_manifest(name, probes_manifest(probes)); + test.test.write_config(sample_config()); + test + } + + fn with_manifest(name: &str, manifest: Value) -> Self { + let test = ProvidersTest::with_manifest(name, PROVIDER_GRANTS, manifest); + let answer = Arc::new(Mutex::new(Some(listed()))); + let (probe, read, edit) = (answer.clone(), test.answer.clone(), test.edit.clone()); + test.harness + .link + .set_answer(move |function, params| match function { + "providers.read" => match read.lock().unwrap().clone() { + Some(answer) => Ok(answer), + None => providers_read(params), + }, + "providers.edit" => providers_edit(params, *edit.lock().unwrap()), + "providers.probe" | "example.providers.probe" => probe + .lock() + .unwrap() + .clone() + .ok_or_else(|| failure("backend.timeout")), + other => sample_backend(other, params), + }); + Self { test, answer } + } + + fn answer(&self, answer: Option) { + *self.answer.lock().unwrap() = answer; + } + + fn run(&self, command: &str, mut request: Value) -> Value { + request["agent"] = json!(AGENT_KEY); + self.test.harness.run(command, request) + } + + /// The whole error of a refused probe, as Core would format it. + fn refusal(&self, command: &str, mut request: Value) -> String { + request["agent"] = json!(AGENT_KEY); + match self.test.harness.runtime.execute(command, request) { + Ok(answer) => panic!("{command} was not refused: {answer}"), + Err(error) => format!("{error:?}"), + } + } + + /// The calls of the probe function, by either name a test declares. + fn calls(&self) -> Vec { + let link = &self.test.harness.link; + let mut calls = link.calls_of("providers.probe"); + calls.extend(link.calls_of("example.providers.probe")); + calls + } +} + +#[test] +fn fetch_models_asks_the_plugin_about_a_provider_the_agent_has() { + let probe = ProbeTest::new("probe models", &["fetchModels", "testConnection"]); + let read = probe.test.read(); + assert_eq!(read["probes"], json!(["fetchModels", "testConnection"])); + assert_eq!(read["editsHeaders"], false); + let before = fs::read(probe.test.config_file()).unwrap(); + + let (answer, logs) = capture::run(false, || { + probe.run( + "agentProviders.fetchModels", + json!({ "provider": { "id": "alpha" } }), + ) + }); + assert_eq!( + answer, + json!({ + "agent": AGENT_KEY, + "result": { "category": "ok", "status": 200, "durationMs": 120 }, + "models": [ + { "id": "alpha-large", "name": "Alpha Large", "contextWindow": 200000 }, + { "id": "alpha-small" } + ] + }) + ); + let calls = probe.calls(); + assert_eq!(calls.len(), 1); + let params = &calls[0]; + assert_eq!(params["agentID"], AGENT); + assert_eq!(params["probe"], "fetchModels"); + assert_eq!( + params["provider"], + json!({ + "id": "alpha", "baseUrl": "https://alpha.example.test/v1", + "protocol": "responses", "keyVariable": "ALPHA_API_KEY" + }), + "Core fills in what the agent has for the provider" + ); + assert_eq!(params["existing"], true); + assert_eq!(params["timeoutMilliseconds"], 20000); + assert_eq!(params["maximumResponseBytes"], 8 * 1024 * 1024); + assert_eq!( + params["files"][0]["path"], + path_text(&probe.test.config_file()) + ); + assert!(params.get("key").is_none() && params.get("headers").is_none()); + + let finished = logs + .iter() + .find(|log| log.event == "agent.providers.probe_finished") + .expect("the probe is logged"); + assert_eq!(finished.fields["probe"], json!("fetchModels")); + assert_eq!(finished.fields["category"], json!("ok")); + assert_eq!(finished.fields["status"], json!(200)); + assert_eq!(finished.fields["models"], json!(2)); + assert_eq!(finished.fields["draft"], json!(false)); + let fields = format!("{:?}", finished.fields); + assert!( + !fields.contains("alpha.example.test") && !fields.contains("alpha-large"), + "the log has no endpoint and no model" + ); + + assert_eq!( + fs::read(probe.test.config_file()).unwrap(), + before, + "a probe changes nothing" + ); + assert!(probe + .test + .harness + .link + .calls_of("providers.edit") + .is_empty()); + assert_eq!( + probe.test.read()["models"], + read["models"], + "fetched models are not kept" + ); + + // A provider whose endpoint the environment holds. + probe.run( + "agentProviders.fetchModels", + json!({ "provider": { "id": "beta" } }), + ); + assert_eq!( + probe.calls()[1]["provider"], + json!({ "id": "beta", "baseUrl": "https://beta.example.test", "keyVariable": "BETA_TOKEN" }) + ); +} + +#[test] +fn test_connection_hands_what_the_user_typed_to_the_plugin_only() { + let probe = ProbeTest::new("probe connection", &["testConnection"]); + probe.answer(Some(probe_answer(json!({ + "category": "unauthorized", "status": 401, "code": "invalid_api_key", + "durationMs": 80, "model": "draft-model" + })))); + let request = json!({ + "provider": { "baseUrl": "https://draft.example.test/v1", "protocol": "chat", "model": "draft-model" }, + "key": KEY, + "headers": [{ "name": "X-Team", "value": HEADER_VALUE }] + }); + let (answer, logs) = capture::run(false, || { + let answer = probe.run("agentProviders.testConnection", request.clone()); + assert_secrets_hidden(&probe.test.read().to_string(), "the read answer"); + answer + }); + assert_eq!( + answer, + json!({ "agent": AGENT_KEY, "result": { + "category": "unauthorized", "status": 401, "code": "invalid_api_key", + "durationMs": 80, "model": "draft-model" + } }) + ); + assert_secrets_hidden(&answer.to_string(), "the probe answer"); + let params = &probe.calls()[0]; + assert_eq!(params["probe"], "testConnection"); + assert_eq!(params["key"], KEY, "the plugin gets the key"); + assert_eq!( + params["headers"], + json!([{ "name": "X-Team", "value": HEADER_VALUE }]) + ); + assert_eq!(params["existing"], false); + assert_eq!(params["maximumResponseBytes"], 64 * 1024); + assert_eq!( + params["provider"], + json!({ "baseUrl": "https://draft.example.test/v1", "protocol": "chat", "model": "draft-model" }) + ); + for log in &logs { + assert_secrets_hidden(&format!("{:?}", log.fields), &log.event); + } + let finished = logs + .iter() + .find(|log| log.event == "agent.providers.probe_finished") + .expect("the probe is logged"); + assert_eq!(finished.fields["category"], json!("unauthorized")); + assert_eq!(finished.fields["status"], json!(401)); + assert_eq!(finished.fields["draft"], json!(true)); + assert!(!finished.fields.contains_key("models")); + assert_eq!( + read_json(&probe.test.config_file()), + sample_config(), + "a draft is not saved" + ); + + // The user's fields win over the provider's; the rest are the agent's. + probe.answer(Some(probe_answer( + json!({ "category": "ok", "status": 200, "durationMs": 40 }), + ))); + let ok = probe.run( + "agentProviders.testConnection", + json!({ "provider": { "id": "alpha", "model": "alpha-small" } }), + ); + assert_eq!(ok["result"]["category"], "ok"); + assert_eq!( + probe.calls()[1]["provider"], + json!({ + "id": "alpha", "baseUrl": "https://alpha.example.test/v1", "protocol": "responses", + "keyVariable": "ALPHA_API_KEY", "model": "alpha-small" + }) + ); + assert_eq!(probe.calls()[1]["existing"], true); + + assert!(probe + .refusal( + "agentProviders.fetchModels", + json!({ "provider": { "id": "alpha" } }) + ) + .contains("agentProviders.unsupportedProbe")); + assert_eq!(probe.calls().len(), 2, "an undeclared probe is never sent"); +} + +#[test] +fn probes_are_refused_before_the_plugin_is_called() { + let probe = ProbeTest::new("probe checks", &["fetchModels", "testConnection"]); + let header = |name: &str| json!({ "name": name, "value": HEADER_VALUE }); + for (case, request, code) in [ + ( + "an ID the agent does not have", + json!({ "provider": { "id": "missing" } }), + "agentProviders.unknownProvider", + ), + ( + "no provider at all", + json!({ "provider": {} }), + "agentProviders.noEndpoint", + ), + ( + "a provider without an endpoint", + json!({ "provider": { "id": "local" } }), + "agentProviders.noEndpoint", + ), + ( + "an endpoint with a user and password", + json!({ "provider": { "baseUrl": format!("https://user:{KEY}@draft.example.test") } }), + "agentProviders.invalidEndpoint", + ), + ( + "an endpoint with a query", + json!({ "provider": { "baseUrl": format!("https://draft.example.test/v1?key={KEY}") } }), + "agentProviders.invalidEndpoint", + ), + ( + "an endpoint of another scheme", + json!({ "provider": { "baseUrl": "file:///etc/draft" } }), + "agentProviders.invalidEndpoint", + ), + ( + "an ID with a space", + json!({ "provider": { "id": "a draft", "baseUrl": "https://draft.example.test" } }), + "agentProviders.invalidProbe", + ), + ( + "a protocol of two words", + json!({ "provider": { "id": "alpha", "protocol": "two words" } }), + "agentProviders.invalidProbe", + ), + ( + "a key as a variable", + json!({ "provider": { "id": "alpha", "keyVariable": KEY } }), + "agentProviders.invalidProbe", + ), + ( + "an empty model", + json!({ "provider": { "id": "alpha", "model": "" } }), + "agentProviders.invalidProbe", + ), + ( + "an empty key", + json!({ "provider": { "id": "alpha" }, "key": "" }), + "agentProviders.invalidKey", + ), + ( + "a key with a line break", + json!({ "provider": { "id": "alpha" }, "key": format!("{KEY}\n") }), + "agentProviders.invalidKey", + ), + ( + "a header the HTTP client sets", + json!({ "provider": { "id": "alpha" }, "headers": [header("Host")] }), + "agentProviders.invalidHeaders", + ), + ( + "a header value with a line break", + json!({ "provider": { "id": "alpha" }, "headers": [ + { "name": "X-Team", "value": format!("{HEADER_VALUE}\r\nX-Other: 1") } + ] }), + "agentProviders.invalidHeaders", + ), + ( + "a kept header the provider does not have", + json!({ "provider": { "id": "alpha" }, "headers": [{ "name": "X-Team" }] }), + "agentProviders.unknownHeader", + ), + ( + "a field the payload does not have", + json!({ "provider": { "id": "alpha" }, "key": KEY, "apiKey": KEY }), + "agents.invalidPayload", + ), + ( + "a field a provider does not have", + json!({ "provider": { "id": "alpha", "apiKey": KEY }, "headers": [header("X-Team")] }), + "agents.invalidPayload", + ), + ( + "a header field it does not have", + json!({ "provider": { "id": "alpha" }, "headers": [ + { "name": "X-Team", "value": HEADER_VALUE, "secret": HEADER_VALUE } + ] }), + "agents.invalidPayload", + ), + ] { + let ((), logs) = capture::run(false, || { + let text = probe.refusal("agentProviders.testConnection", request.clone()); + assert!(text.contains(code), "{case}: {text}"); + assert_secrets_hidden(&text, case); + }); + for log in &logs { + assert_secrets_hidden(&format!("{:?}", log.fields), case); + } + } + assert!( + probe.calls().is_empty(), + "a refused probe never reaches the plugin" + ); + assert_eq!( + probe.test.harness.refused( + "agentProviders.fetchModels", + json!({ "agent": "other/agent", "provider": { "id": "alpha" } }) + ), + "agentLibrary.unknownAgent" + ); + + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let background = probe.refusal( + "agentProviders.fetchModels", + json!({ "provider": { "id": "alpha" } }), + ); + trace::replace(previous); + assert!(background.contains("agentLibrary.userActionRequired")); + assert!(probe.calls().is_empty(), "nothing probes in the background"); + + let undeclared = + ProbeTest::with_manifest("probe undeclared", providers_manifest(ALL_OPERATIONS)); + undeclared.test.write_config(sample_config()); + assert_eq!(undeclared.test.read()["probes"], json!([])); + for command in [ + "agentProviders.fetchModels", + "agentProviders.testConnection", + ] { + assert!(undeclared + .refusal(command, json!({ "provider": { "id": "alpha" } })) + .contains("agentProviders.unsupportedProbe")); + } + + let library = LibraryHarness::without_providers(); + assert_eq!( + library.refused( + "agentProviders.fetchModels", + json!({ "agent": AGENT_KEY, "provider": { "id": "alpha" } }) + ), + "agentProviders.notDeclared" + ); +} + +#[test] +fn probe_answers_are_checked_and_failures_logged() { + let probe = ProbeTest::new("probe answers", &["fetchModels", "testConnection"]); + let fetch = "agentProviders.fetchModels"; + let test = "agentProviders.testConnection"; + let with_models = |result: Value, models: Value| { + let mut answer = probe_answer(result); + answer["models"] = models; + answer + }; + let ok = json!({ "category": "ok", "status": 200, "durationMs": 5 }); + for (case, command, answer) in [ + ( + "another format", + fetch, + json!({ "format": "litheAgentProviders", "version": 0, "result": ok, "models": [] }), + ), + ( + "another version", + fetch, + json!({ "format": "litheAgentProvidersProbe", "version": 1, "result": ok, "models": [] }), + ), + ( + "a category of its own", + test, + probe_answer(json!({ "category": "refused", "durationMs": 5 })), + ), + ( + "an HTTP category without a status", + test, + probe_answer(json!({ "category": "notFound", "durationMs": 5 })), + ), + ( + "a status that disagrees", + test, + probe_answer(json!({ "category": "unauthorized", "status": 404, "durationMs": 5 })), + ), + ( + "a failure before any answer with a status", + test, + probe_answer(json!({ "category": "timeout", "status": 504, "durationMs": 5 })), + ), + ( + "a server code without an error status", + test, + probe_answer( + json!({ "category": "ok", "status": 200, "code": "fine", "durationMs": 5 }), + ), + ), + ( + "a server code that is a message", + test, + probe_answer(json!({ + "category": "unauthorized", "status": 401, "durationMs": 5, + "code": format!("Incorrect API key provided: {KEY}") + })), + ), + ( + "a server message", + test, + probe_answer(json!({ + "category": "unauthorized", "status": 401, "durationMs": 5, + "message": format!("Incorrect API key provided: {KEY}") + })), + ), + ( + "an error text beside the result", + test, + json!({ + "format": "litheAgentProvidersProbe", "version": 0, "result": ok, + "error": format!("echo {HEADER_VALUE}") + }), + ), + ( + "longer than Core waits", + test, + probe_answer(json!({ "category": "timeout", "durationMs": 30001 })), + ), + ( + "a model on a listing", + fetch, + with_models( + json!({ "category": "ok", "status": 200, "durationMs": 5, "model": "alpha-large" }), + json!([]), + ), + ), + ("a listing without models", fetch, probe_answer(ok.clone())), + ( + "models of a failed listing", + fetch, + with_models( + json!({ "category": "unauthorized", "status": 401, "durationMs": 5 }), + json!([]), + ), + ), + ( + "models of a connection test", + test, + with_models(ok.clone(), json!([])), + ), + ( + "a model listed twice", + fetch, + with_models( + ok.clone(), + json!([{ "id": "alpha-large" }, { "id": "alpha-large" }]), + ), + ), + ( + "a model without context", + fetch, + with_models( + ok.clone(), + json!([{ "id": "alpha-large", "contextWindow": 0 }]), + ), + ), + ( + "too many models", + fetch, + with_models( + ok.clone(), + json!((0..2049) + .map(|i| json!({ "id": format!("m{i}") })) + .collect::>()), + ), + ), + ] { + probe.answer(Some(answer)); + let (text, logs) = capture::run(false, || { + probe.refusal(command, json!({ "provider": { "id": "alpha" } })) + }); + assert!( + text.contains("agentProviders.invalidProbeAnswer"), + "{case}: {text}" + ); + assert_secrets_hidden(&text, case); + let failed = logs + .iter() + .find(|log| log.event == "agent.providers.probe_failed") + .unwrap_or_else(|| panic!("{case} is logged")); + assert_eq!( + failed.fields["reason"], + json!("agentProviders.invalidProbeAnswer") + ); + assert_secrets_hidden(&format!("{:?}", failed.fields), case); + } + + for (command, result) in [ + ( + fetch, + json!({ "category": "unauthorized", "status": 403, "code": "invalid_api_key", "durationMs": 12 }), + ), + ( + fetch, + json!({ "category": "responseTooLarge", "status": 200, "durationMs": 900 }), + ), + ( + test, + json!({ "category": "responseTooLarge", "durationMs": 900 }), + ), + (test, json!({ "category": "noKey", "durationMs": 0 })), + (fetch, json!({ "category": "unsupported", "durationMs": 0 })), + ( + test, + json!({ "category": "redirected", "status": 307, "durationMs": 30 }), + ), + ( + test, + json!({ "category": "requestRejected", "status": 400, "code": "model_not_found", "durationMs": 30 }), + ), + (test, json!({ "category": "tlsFailed", "durationMs": 30 })), + ] { + probe.answer(Some(probe_answer(result.clone()))); + let answer = probe.run(command, json!({ "provider": { "id": "alpha" } })); + assert_eq!(answer["result"], result); + assert!(answer.get("models").is_none()); + } + + probe.answer(None); + let (text, logs) = capture::run(false, || { + probe.refusal(test, json!({ "provider": { "id": "alpha" }, "key": KEY })) + }); + assert!(text.contains("agentProviders.probeFailed"), "{text}"); + assert_secrets_hidden(&text, "a failed call"); + let failed = logs + .iter() + .find(|log| log.event == "agent.providers.probe_failed") + .expect("the failure is logged"); + assert_eq!(failed.fields["reason"], json!("agentProviders.probeFailed")); + assert_eq!(failed.fields["call_code"], json!("backend.timeout")); + assert_eq!(failed.fields["probe"], json!("testConnection")); +} + +#[test] +fn the_shared_fixture_probes_as_written() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../../../shared/plugins/contract/v1/fixtures/agents/provider-probes.json" + )) + .unwrap(); + let mut manifest = providers_manifest(&[]); + let declared = &mut manifest["agents"][0]["configuration"]["providers"]; + for (key, value) in fixture["providers"].as_object().unwrap() { + declared[key.as_str()] = value.clone(); + } + let probe = ProbeTest::with_manifest("probe fixture", manifest); + *probe.test.answer.lock().unwrap() = Some(fixture["answer"].clone()); + let agent = probe.test.read(); + for (field, expected) in fixture["view"].as_object().unwrap() { + assert_eq!(&agent[field.as_str()], expected, "{field}"); + } + for case in fixture["probes"].as_array().unwrap() { + let command = case["command"].as_str().unwrap(); + probe.answer(Some(case["answer"].clone())); + let mut view = case["view"].clone(); + view["agent"] = json!(AGENT_KEY); + assert_eq!( + probe.run(command, case["request"].clone()), + view, + "{command}" + ); + let params = probe.calls().pop().unwrap(); + for (field, expected) in case["params"].as_object().unwrap() { + assert_eq!(¶ms[field.as_str()], expected, "{command} {field}"); + } + let mut given: Vec<&str> = params + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + let mut wanted: Vec<&str> = case["params"] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + wanted.extend(["agentID", "files"]); + given.sort_unstable(); + wanted.sort_unstable(); + assert_eq!( + given, wanted, + "{command}: the plugin gets these fields only" + ); + } + let calls = probe.calls().len(); + for refusal in fixture["refusals"].as_array().unwrap() { + let text = probe.refusal( + refusal["command"].as_str().unwrap(), + refusal["request"].clone(), + ); + assert!( + text.contains(refusal["code"].as_str().unwrap()), + "{}: {text}", + refusal["request"] + ); + } + assert_eq!( + probe.calls().len(), + calls, + "a refusal never reaches the plugin" + ); + for invalid in fixture["invalidAnswers"].as_array().unwrap() { + probe.answer(Some(invalid["answer"].clone())); + let text = probe.refusal( + invalid["command"].as_str().unwrap(), + json!({ "provider": { "id": "gateway" } }), + ); + assert!( + text.contains("agentProviders.invalidProbeAnswer"), + "{}: {text}", + invalid["case"] + ); + assert!(!text.contains("fixture-key-not-real")); + } +} diff --git a/rust/crates/agent-runtime/src/tests/providers/saved.rs b/rust/crates/agent-runtime/src/tests/providers/saved.rs index 3a97c5da..caad098d 100644 --- a/rust/crates/agent-runtime/src/tests/providers/saved.rs +++ b/rust/crates/agent-runtime/src/tests/providers/saved.rs @@ -192,6 +192,15 @@ fn saved_providers_are_listed_and_switched_with_their_keys() { let edits = lithe.edits(); assert!(test.apply(json!({ "op": "addProvider", "provider": spare() }))); assert_eq!(lithe.edits(), edits, "no key, nothing for the plugin"); + // A key for a saved provider not in use goes only into the plugin's + // credentials, and the configuration has nothing to show for it. + let keyed = json!({ "op": "updateProvider", "provider": spare(), "key": KEY }); + assert!(test.apply(keyed)); + assert_eq!(lithe.credentials.lock().unwrap()["spare"], KEY); + let cleared = json!({ "op": "updateProvider", "provider": spare(), "clearKey": true }); + assert!(test.apply(cleared)); + assert!(!lithe.credentials.lock().unwrap().contains_key("spare")); + assert_eq!(lithe.env(), json!({ "OTHER": "kept" })); let listed = test.read(); assert_hidden(&listed.to_string(), "the read answer"); assert_eq!(listed["providers"][1]["id"], "relay"); @@ -356,3 +365,61 @@ fn saved_providers_are_checked_and_put_back_when_the_plugin_fails() { assert_eq!(ids, vec![json!("official"), json!("relay")]); assert!(!lithe.credentials.lock().unwrap().contains_key("spare")); } + +#[test] +fn a_saved_provider_is_probed_with_the_key_the_plugin_keeps() { + let lithe = LitheTest::new("providers saved probe"); + let test = &lithe.test; + let mut manifest = providers_manifest(LITHE_OPERATIONS); + let providers = &mut manifest["agents"][0]["configuration"]["providers"]; + providers["listKeptBy"] = json!("lithe"); + providers["probe"] = json!("providers.probe"); + providers["probes"] = json!(["fetchModels", "testConnection"]); + test.harness.run( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": PROVIDER_GRANTS }] }), + ); + let kept = lithe.credentials.clone(); + test.harness + .link + .set_answer(move |function, params| match function { + "providers.read" => lithe_read(params), + "providers.edit" => lithe_edit(params, &kept), + "providers.probe" => Ok(json!({ + "format": "litheAgentProvidersProbe", "version": 0, + "result": { "category": "ok", "status": 200, "durationMs": 3 }, + "models": [{ "id": "relay-large" }] + })), + other => sample_backend(other, params), + }); + assert!(test.apply(json!({ "op": "addProvider", "provider": relay(), "key": KEY }))); + + let answer = test.harness.run( + "agentProviders.fetchModels", + json!({ "agent": AGENT_KEY, "provider": { "id": "relay" } }), + ); + assert_eq!(answer["models"], json!([{ "id": "relay-large" }])); + let params = &test.harness.link.calls_of("providers.probe")[0]; + assert_eq!( + params["provider"], + json!({ + "id": "relay", "baseUrl": "https://relay.example.test", + "protocol": "messages", "model": "relay-large" + }), + "a saved provider is found by its saved ID" + ); + assert_eq!(params["existing"], true); + assert!( + params.get("key").is_none(), + "the plugin uses the key it keeps" + ); + assert_hidden(&answer.to_string(), "the probe answer"); + assert_eq!( + test.harness.refused( + "agentProviders.testConnection", + json!({ "agent": AGENT_KEY, "provider": { "id": "relay" }, "headers": [{ "name": "X-Team" }] }), + ), + "agentProviders.unknownHeader", + "Lithe keeps no header values for a saved provider" + ); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 45cc3444..56609a2c 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -300,6 +300,12 @@ pub enum AgentsCommand { /// Applies an agent's model switches and selection as one group /// (`agentProviders.applyModelSettings`). ProvidersApplyModelSettings, + /// Lists the models one provider serves, through the agent's plugin + /// (`agentProviders.fetchModels`). + ProvidersFetchModels, + /// Sends one provider the smallest request of its protocol, through the + /// agent's plugin (`agentProviders.testConnection`). + ProvidersTestConnection, } impl AgentsCommand { @@ -343,6 +349,8 @@ impl AgentsCommand { Self::ProvidersShowModels => "agentProviders.showModels", Self::ProvidersReadModelSettings => "agentProviders.readModelSettings", Self::ProvidersApplyModelSettings => "agentProviders.applyModelSettings", + Self::ProvidersFetchModels => "agentProviders.fetchModels", + Self::ProvidersTestConnection => "agentProviders.testConnection", } } } @@ -1376,6 +1384,10 @@ impl CoreCommand { "agentProviders.applyModelSettings" => { Some(Self::Agents(AgentsCommand::ProvidersApplyModelSettings)) } + "agentProviders.fetchModels" => Some(Self::Agents(AgentsCommand::ProvidersFetchModels)), + "agentProviders.testConnection" => { + Some(Self::Agents(AgentsCommand::ProvidersTestConnection)) + } "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 e534f272..e93e76d0 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -323,7 +323,11 @@ 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", "setEffort", "setSpeed", "setModelMenu", "setProvider"]} + "providers": { + "operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setEffort", "setSpeed", "setModelMenu", "setProvider"], + "probes": ["fetchModels", "testConnection"], + "editsHeaders": true + } }), json!({ "kind": "agentSessions", diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 17195436..bd4e034b 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -165,6 +165,41 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.providers.probe_failed", + channel: "agent", + level: LogLevel::Warn, + message: "A probe of a model provider was refused or the agent plugin could not answer it", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "call_code", field_type: FieldType::Token, required: false, description: "Failure code of the plugin function call behind agentProviders.probeFailed, such as plugin.function.timeout", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "probe", field_type: FieldType::Token, required: true, description: "Probe the user asked for: fetchModels or testConnection", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code such as agentProviders.noEndpoint or agentProviders.probeFailed; never endpoints, keys, headers or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.providers.probe_finished", + channel: "agent", + level: LogLevel::Info, + message: "An agent plugin reached a model provider for the user and reported what came back", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "category", field_type: FieldType::Token, required: true, description: "What came of the exchange, such as ok, unauthorized, timeout or tlsFailed; never the server's message", reason: None }, + FieldMetadata { name: "draft", field_type: FieldType::Bool, required: true, description: "Whether the request carried fields, a key or headers the user typed rather than only a saved provider's ID", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took, including reading the agent and the plugin's exchange", reason: None }, + FieldMetadata { name: "models", field_type: FieldType::Int, required: false, description: "Models the provider listed, for a fetchModels probe that went ok", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "probe", field_type: FieldType::Token, required: true, description: "Probe the user asked for: fetchModels or testConnection", reason: None }, + FieldMetadata { name: "status", field_type: FieldType::Int, required: false, description: "HTTP status of the provider's answer when one came back, such as 200 or 401", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.providers.read_failed", channel: "agent", diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index d97356ab..0c94d976 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -25,7 +25,9 @@ //! that read and edit those files. Core writes them only when the user //! applies a change, and only through a staged copy it checks first. //! `configuration.providers` names the backend functions that report and -//! change the CLI's model, model providers and profiles in those files. +//! change the CLI's model, model providers and profiles in those files, +//! and the one that reaches a provider over the network when the user +//! asks for its models or a connection test. //! //! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-25-agent-native-cli-and-local-session-records.md @@ -108,6 +110,12 @@ pub const PROVIDER_OPERATIONS: [&str; 10] = [ "setProfile", ]; +/// The requests a providers `probe` function answers, in the order the +/// contract lists them: list the models a provider serves, and send it the +/// smallest request its protocol takes. Each reaches the network, and Core +/// asks for one only for a request the user started. +pub const PROVIDER_PROBES: [&str; 2] = ["fetchModels", "testConnection"]; + /// Template variable of the user's home directory in a session root. const USER_HOME_VARIABLE: &str = "${userHome}"; @@ -197,6 +205,40 @@ pub struct ProvidersDeclaration { /// Who keeps the list of custom providers. #[serde(default, skip_serializing_if = "ListKeptBy::is_cli")] pub list_kept_by: ListKeptBy, + /// Whether `edit` saves the request headers that `addProvider` and + /// `updateProvider` carry. Header values are write-only, like keys. + #[serde(default, skip_serializing_if = "is_false")] + pub edits_headers: bool, + /// Backend function that reaches a provider over the network for the + /// user: it lists the models the provider serves, or sends it the + /// smallest request its protocol takes, with the key and headers the + /// plugin keeps for it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub probe: Option, + /// The requests `probe` answers, from [`PROVIDER_PROBES`]; Core refuses + /// any other before calling the plugin. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub probes: Vec, +} + +fn is_false(value: &bool) -> bool { + !*value +} + +impl ProvidersDeclaration { + /// What the catalog and the install review show of the declaration: the + /// changes `edit` makes and, when declared, the probes and whether + /// headers are saved. Function IDs stay inside Core. + pub fn summary(&self) -> Value { + let mut summary = json!({ "operations": self.operations }); + if !self.probes.is_empty() { + summary["probes"] = json!(self.probes); + } + if self.edits_headers { + summary["editsHeaders"] = json!(true); + } + summary + } } /// Who keeps an agent's list of custom providers. @@ -746,6 +788,7 @@ fn check_providers( for (name, function) in [ ("read", Some(&providers.read)), ("edit", providers.edit.as_ref()), + ("probe", providers.probe.as_ref()), ] { if function.is_some_and(|function| !is_function_id(function)) { return Err(invalid( @@ -778,6 +821,44 @@ fn check_providers( )); } } + match (&providers.probe, providers.probes.is_empty()) { + (Some(_), true) => { + return Err(invalid( + format!("{field}.probes"), + "A providers probe function declares the requests it answers.", + )) + } + (None, false) => { + return Err(invalid( + format!("{field}.probe"), + "Provider probes need a probe function.", + )) + } + _ => {} + } + let mut seen = BTreeSet::new(); + for (index, probe) in providers.probes.iter().enumerate() { + if !PROVIDER_PROBES.contains(&probe.as_str()) || !seen.insert(probe.as_str()) { + return Err(invalid( + format!("{field}.probes[{index}]"), + "A provider probe is one of the contract's probes, listed once.", + )); + } + } + if providers.edits_headers { + // Core keeps no header value, so a list Lithe keeps could not hand + // the plugin a saved provider's headers when it is chosen. + let saves_providers = providers + .operations + .iter() + .any(|op| op == "addProvider" || op == "updateProvider"); + if !saves_providers || providers.list_kept_by == ListKeptBy::Lithe { + return Err(invalid( + format!("{field}.editsHeaders"), + "Headers are saved by addProvider or updateProvider where the CLI keeps the list of providers.", + )); + } + } Ok(()) } @@ -968,7 +1049,7 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { "editable": configuration.edit.is_some(), }); if let Some(providers) = &configuration.providers { - entry["configuration"]["providers"] = json!({ "operations": providers.operations }); + entry["configuration"]["providers"] = providers.summary(); } } if let Some(icon) = &agent.icon { @@ -1058,8 +1139,10 @@ pub fn programs(agent: &AgentDeclaration) -> Vec { if let Some(skills) = &configuration.skills { program["skills"] = json!(skills.roots); } + // The review shows the probes too: they reach the network when the + // user asks. if let Some(providers) = &configuration.providers { - program["providers"] = json!({ "operations": providers.operations }); + program["providers"] = providers.summary(); } programs.push(program); } diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs index ad9e4b17..a94db536 100644 --- a/rust/crates/plugin-agents/src/tests.rs +++ b/rust/crates/plugin-agents/src/tests.rs @@ -508,6 +508,102 @@ fn providers_are_consistent_with_files_and_operations() { assert!(serde_json::from_value::(unknown).is_err()); } +/// The probe function and the header switch reach the catalog and the +/// install review without the function ID; both are left out when not +/// declared, so a review without them reads as before. +#[test] +fn accepts_probes_and_headers_and_reports_them() { + let mut agents = [agent(with_providers(json!({ + "read": "configuration.providers.read", + "edit": "configuration.providers.edit", + "operations": ["addProvider", "updateProvider"], + "editsHeaders": true, + "probe": "configuration.providers.probe", + "probes": ["fetchModels", "testConnection"] + })))]; + check(&mut agents, true).expect("probes and headers validate"); + let summary = json!({ + "operations": ["addProvider", "updateProvider"], + "probes": ["fetchModels", "testConnection"], + "editsHeaders": true + }); + assert_eq!( + catalog_entry("dev.lithe.test.agents", &agents[0])["configuration"]["providers"], + summary + ); + let programs = programs(&agents[0]); + let program = programs + .iter() + .find(|program| program["kind"] == "agentConfiguration") + .expect("configuration is in the install review"); + assert_eq!(program["providers"], summary); + + // A probe needs no edit function: a read-only agent can still be probed. + let mut agents = [agent(with_providers(json!({ + "read": "providers.read", + "probe": "providers.probe", + "probes": ["testConnection"] + })))]; + check(&mut agents, true).expect("a probe without edit validates"); +} + +#[test] +fn probes_and_headers_are_consistent_with_their_declaration() { + let files = json!([{ "id": "settings", "roots": ["${userHome}/a.json"] }]); + let cases: [(&str, Value, &str); 7] = [ + ( + "a probe without probes", + json!({ "read": "providers.read", "probe": "providers.probe" }), + "agents[0].configuration.providers.probes", + ), + ( + "probes without a probe", + json!({ "read": "providers.read", "probes": ["fetchModels"] }), + "agents[0].configuration.providers.probe", + ), + ( + "an invalid probe ID", + json!({ "read": "providers.read", "probe": "Probe It", "probes": ["fetchModels"] }), + "agents[0].configuration.providers.probe", + ), + ( + "an unknown probe", + json!({ "read": "providers.read", "probe": "providers.probe", "probes": ["ping"] }), + "agents[0].configuration.providers.probes[0]", + ), + ( + "a repeated probe", + json!({ + "read": "providers.read", "probe": "providers.probe", + "probes": ["fetchModels", "fetchModels"] + }), + "agents[0].configuration.providers.probes[1]", + ), + ( + "headers without a change that saves a provider", + json!({ + "read": "providers.read", "edit": "providers.edit", + "operations": ["setModel"], "editsHeaders": true + }), + "agents[0].configuration.providers.editsHeaders", + ), + ( + "headers where Lithe keeps the list", + json!({ + "read": "providers.read", "edit": "providers.edit", + "operations": ["addProvider", "setProvider"], "listKeptBy": "lithe", + "editsHeaders": true + }), + "agents[0].configuration.providers.editsHeaders", + ), + ]; + for (name, providers, field) in cases { + let mut value = sample(); + value["configuration"] = json!({ "files": files, "providers": providers }); + assert_eq!(rejected_field(value, true), field, "{name}"); + } +} + /// `terminal.resumeArguments` names the session once with the only template /// it takes; the review lists it with the placeholder, and Core substitutes /// only IDs that are safe as one argument. diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index ad5027f1..9717ad5c 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -651,6 +651,91 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "agent.providers.probe_finished", + "channel": "agent", + "level": "info", + "message": "An agent plugin reached a model provider for the user and reported what came back", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "probe": { + "type": "token", + "required": true, + "description": "Probe the user asked for: fetchModels or testConnection" + }, + "category": { + "type": "token", + "required": true, + "description": "What came of the exchange, such as ok, unauthorized, timeout or tlsFailed; never the server's message" + }, + "status": { + "type": "int", + "required": false, + "description": "HTTP status of the provider's answer when one came back, such as 200 or 401" + }, + "models": { + "type": "int", + "required": false, + "description": "Models the provider listed, for a fetchModels probe that went ok" + }, + "draft": { + "type": "bool", + "required": true, + "description": "Whether the request carried fields, a key or headers the user typed rather than only a saved provider's ID" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took, including reading the agent and the plugin's exchange" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.providers.probe_failed", + "channel": "agent", + "level": "warn", + "message": "A probe of a model provider was refused or the agent plugin could not answer it", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "probe": { + "type": "token", + "required": true, + "description": "Probe the user asked for: fetchModels or testConnection" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code such as agentProviders.noEndpoint or agentProviders.probeFailed; never endpoints, keys, headers or text" + }, + "call_code": { + "type": "token", + "required": false, + "description": "Failure code of the plugin function call behind agentProviders.probeFailed, such as plugin.function.timeout" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "agent.library.skill_import_finished", "channel": "agent", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d429a6ec..d021067d 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; `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/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; `provider-probes.json` holds a providers `read` answer with presets and request headers and the view Core makes of it, `agentProviders.fetchModels` and `agentProviders.testConnection` requests with the fields the `probe` function receives, its answers and the host's answers, the requests Core refuses with their codes, and probe answers Core refuses | | `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`, 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)). | +| `providers` | `{read, edit?, operations?, listKeptBy?, editsHeaders?, probe?, probes?}`: 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 and the providers it can add (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)). `editsHeaders: true` says `edit` saves a provider's request headers (see [Request headers](#request-headers)); it needs `addProvider` or `updateProvider` and `listKeptBy: "cli"`. `probe` is the function that reaches a provider over the network for the user, and `probes` lists, each once, the requests it answers: `fetchModels` and `testConnection` (see [Probes](#probes)); the two come together. | - A configuration declares at least one of `instructions`, `skills` and `files`. A function ID is dot-separated lowerCamelCase segments. @@ -4860,7 +4860,12 @@ A server or hook changes through the plugin, on a copy: on the copy. 3. When `edit` answers `changed` and the copy differs from the file, Core calls `read` again with the copy in place of the file. The change must - show there (`agentLibrary.editNotApplied`). + show there (`agentLibrary.editNotApplied`). When `edit` answers + `changed: false`, or leaves the copy as the file was, nothing is written, + but the change must already show in the file: Core drops whatever the + plugin left in its copy and calls `read` again with a fresh copy of the + file (`agentLibrary.editNotApplied` when the change is not there). So a + plugin that ignores a change cannot pass it off as already made. 4. Core replaces the file only if it still holds the bytes it copied (`agentLibrary.fileChanged`): a new file next to it, with the old file's permissions (owner-only for a new file), written to disk and renamed over @@ -5074,9 +5079,15 @@ signed in, and lets the user change the operations the plugin declares. 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. +It may list presets of the providers its CLI can reach, for the user to add +([Provider presets](#provider-presets)), save a provider's request headers +([Request headers](#request-headers)), and, when the user asks, reach a +provider over the network to list the models it serves or test the +connection ([Probes](#probes)). +Core knows no CLI, model, provider, 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, provider +presets or addresses of their own. | Command | Payload | Result | | --- | --- | --- | @@ -5086,6 +5097,8 @@ there is none: the host and Core keep no model names of their own. | `agentProviders.showModels` | `{agent, show?, hide?}` | `{changed}` | | `agentProviders.readModelSettings` | `{agent}` | `{settings}` | | `agentProviders.applyModelSettings` | `{agent, settings}` | `{changed}` | +| `agentProviders.fetchModels` | `{agent, provider, key?, headers?}` | `{agent, result, models?}` | +| `agentProviders.testConnection` | `{agent, provider, key?, headers?}` | `{agent, result}` | `restore` puts back every file of the agent Lithe changed, for any agent that declares `configuration`, with or without `providers`; see @@ -5106,6 +5119,8 @@ without `providers`): "mayConfigure": true, "operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setProvider"], "listKeptBy": "cli", + "editsHeaders": true, + "probes": ["fetchModels", "testConnection"], "files": [{"id": "main", "path": "/home/user/.alpha/config.json", "exists": true}], "backup": {"savedAtMs": 1764633600000, "modifiedSince": false}, "cliVersion": "1.4.0", @@ -5114,10 +5129,18 @@ without `providers`): "providers": [ {"id": "builtin", "name": "Built-in", "keySet": false, "builtIn": true, "saved": false, "origin": "configuration"}, {"id": "gateway", "name": "Gateway", "baseUrl": "https://gateway.example.com/v1", "protocol": "responses", - "keyVariable": "GATEWAY_KEY", "keySet": true, "headerNames": ["X-Team"], "enabled": true, "builtIn": false, + "keyVariable": "GATEWAY_KEY", "keySet": true, "headers": [{"name": "X-Team", "valueSet": true}], + "headerNames": ["X-Team"], "enabled": true, "builtIn": false, "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}, "saved": false, "origin": "configuration"} ], + "presets": [ + {"id": "vendor", "name": "Vendor", "description": "The models' own maker.", "kind": "vendor", + "baseUrl": "https://api.vendor.example.com/v1", "protocol": "responses", "model": "vendor-large", + "keyVariable": "VENDOR_API_KEY", "headerNames": ["X-Vendor-Project"], "keysUrl": "https://vendor.example.com/keys"}, + {"id": "on-device", "name": "On-device server", "kind": "local", "baseUrl": "http://127.0.0.1:11434/v1", + "protocol": "chat", "keyOptional": true} + ], "profiles": [{"name": "fast", "model": "model-b", "provider": "gateway"}], "profile": {"name": "fast", "source": {"layer": "user", "file": "main", "path": "/home/user/.alpha/config.json"}}, "account": {"label": "Team plan"}, @@ -5140,7 +5163,9 @@ without `providers`): ``` - An agent whose plugin is not granted `agents.configuration` gives only - the fields up to `operations`, and is not read. + the fields up to `probes`, and is not read. +- `listKeptBy`, `editsHeaders` and `probes` are the manifest's: + `editsHeaders` is `false` and `probes` empty when it declares none. - The rest is what the plugin's `read` reported, after Core's checks: Core adds the resolved `path` to each `source` that names a declared `file`, and the current provider's `name` from `providers` when the plugin left @@ -5150,7 +5175,11 @@ without `providers`): provider the plugin read from the CLI's configuration, `origin: "lithe"` one Lithe saved that the configuration does not use now (only with `listKeptBy: "lithe"`); `saved` is whether Lithe keeps it. `keySet` is - always there. + always there. A provider the plugin reports with `headers` also has + `headerNames`, the same names, so a host finds every provider's header + names in one field. +- `presets` is always there, empty when the plugin lists none (see + [Provider presets](#provider-presets)). - `backup?: {savedAtMs, modifiedSince}` is there while Core keeps a backup of the agent's files (see [Backups and restore](#backups-and-restore)), whichever command changed them: when it was kept, in milliseconds since @@ -5169,8 +5198,8 @@ without `providers`): | `change` | Effect | Target | | --- | --- | --- | -| `{op: "addProvider", provider, key?}` | adds a provider of a new `id` (`agentProviders.providerExists`) | `providers` | -| `{op: "updateProvider", provider, key?, clearKey?}` | replaces the provider's `name`, `baseUrl`, `protocol`, `keyVariable` and, when given, `enabled`; a `key` replaces its key, `clearKey: true` removes it, neither keeps it | `providers` | +| `{op: "addProvider", provider, key?, headers?}` | adds a provider of a new `id` (`agentProviders.providerExists`), with the request headers `headers` gives | `providers` | +| `{op: "updateProvider", provider, key?, clearKey?, headers?}` | replaces the provider's `name`, `baseUrl`, `protocol`, `keyVariable` and, when given, `enabled`; a `key` replaces its key, `clearKey: true` removes it, neither keeps it; `headers` replaces its whole list of request headers, none keeps them | `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, 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` | @@ -5184,8 +5213,10 @@ 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, +enabled?, model?}`; the provider's query parameters, and its headers when +the change has no `headers`, stay as the plugin keeps them. `headers` is +only for an agent that declares `editsHeaders` (see +[Request headers](#request-headers)). With `listKeptBy: "lithe"` it is `{id, name, baseUrl, protocol?, model?}`: `baseUrl` is required, `model` is the model to use with the provider, and `keyVariable` and `enabled` are refused; elsewhere `model` is refused. @@ -5205,7 +5236,10 @@ whether there is one. Core checks, in this order: `baseUrl` that is not an allowed endpoint is `agentProviders.invalidEndpoint`; a `key` that breaks the rule above is `agentProviders.invalidKey`; `key` with `clearKey: true` is - `agentProviders.invalidChange`. + `agentProviders.invalidChange`. `headers` from an agent that does not + declare `editsHeaders` is `agentProviders.unsupportedOperation`, and + headers that break the rules of [Request headers](#request-headers) are + `agentProviders.invalidHeaders`. 3. Core calls `read`. `updateProvider`, `removeProvider`, `setProviderEnabled` and `setProvider` name a provider the agent has (`agentProviders.unknownProvider`); the first three refuse a `builtIn` @@ -5214,16 +5248,21 @@ whether there is one. Core checks, in this order: `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 + [Listed models](#listed-models)). A header without a value names a + header the provider has (`agentProviders.unknownHeader`; a new provider + has none). With `listKeptBy: "lithe"`, the provider changes check the saved list instead, as [Providers Lithe keeps](#providers-lithe-keeps) describes. 4. The snapshot's `targets` names the file for the change (`agentProviders.noTarget`). The file changes through a staged copy exactly like a server or hook: Core calls `edit` on the copy, reads the - copy back with `read`, and the change must show there + copy back with `read` (or, when `edit` reports no change, a fresh copy of + the file), and the change must show there (`agentProviders.editNotApplied`; a `key` shows as `keySet: true`, `clearKey` as `keySet: false`, an effort or speed as `effort` or `speed` - in use); the file is replaced only if it still + in use, `headers` as the same header names, case ignored, each header + given a value with `valueSet: true` when the plugin reports `headers`); + 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. @@ -5231,7 +5270,8 @@ whether there is one. Core checks, in this order: ([Backups and restore](#backups-and-restore)); when it cannot, the file is not changed (`agentProviders.backupFailed`). -`apply` answers `changed: false` when the file already held the change. +`apply` answers `changed: false` when the file already held the change, +which the read of the file confirms. ##### Listed models @@ -5352,7 +5392,175 @@ ID. built-in provider has no `provider`: the plugin removes the endpoint and key it wrote, and nothing else. `removeProvider` deletes the key the plugin keeps. A plugin that stores a key and changes no file answers - `changed: false`. + `changed: false`; for a provider not in use the configuration has nothing + to show, so Core looks for no change there. + +##### Provider presets + +A plugin may list `presets` in its `read` answer: the providers its CLI can +reach that the plugin knows, for the host to offer when the user adds a +provider. Core keeps no preset and no address of its own: without a list +from the plugin, `presets` is empty and the host offers only a provider the +user describes. + +A preset is `{id, name, description?, kind?, baseUrl?, protocol?, model?, +keyVariable?, keyOptional?, headerNames?, keysUrl?}`; at most 128, IDs +unique: + +- `id` follows the provider ID rule; the host offers it as the new + provider's `id`, which the user may change. `name` follows the display + name rule and `description`, one line about the provider, is at most 1024 + characters without NUL. +- `kind` is `vendor` (the models' own maker), `relay` (a service that + resells the models of many makers) or `local` (a server on the user's + machine); the host may group presets by it. +- `baseUrl` follows the endpoint rule; a preset without one is a provider + reached at the user's own address, which the host asks for. +- `protocol` is the wire protocol as the CLI names it, and `model` the + model to use with the provider. +- `keyVariable` is where the CLI reads the key from, by the environment + variable name rule. With `listKeptBy: "lithe"` a provider names none, so + a preset that names one is refused. +- `keyOptional: true` marks a provider that takes no key or an optional + one, such as a local server. +- `headerNames` are at most 16 optional request headers the vendor + documents, by the rules of [Request headers](#request-headers), unique + ignoring ASCII case; the user types their values. +- `keysUrl` is the page where the user makes a key, by the endpoint rule; + the host opens it in the browser only on the user's click. + +A preset that breaks a rule makes the answer `agentProviders.invalidSnapshot`. + +The host adds a provider from a preset with an ordinary `addProvider`: the +preset's `id`, `name`, `baseUrl`, `protocol` and `keyVariable` (with +`listKeptBy: "lithe"`, `model` too) as the user confirmed them, the `key` +the user typed and, for an agent that declares `editsHeaders`, the headers +the user filled in. Core records no link between a provider and a preset; +the change follows every rule of `apply`. Elsewhere the host may set the +preset's `model` with `setModel` once the provider is in use. + +##### Request headers + +Some providers take request headers besides the key, such as an +organization or a project. A plugin reports a provider's headers in its +`read` answer either as `headerNames`, names only, or as `headers`: at most +64 `{name, valueSet?, variable?}`, where `valueSet` (default `false`) is +whether the configuration holds a value for the header and `variable` +names the environment variable the CLI reads the value from. A provider +has one of the two fields, never both. A header value is never reported: +like a key it is write-only. + +A plugin whose `edit` saves headers declares `editsHeaders: true` (only +with `listKeptBy: "cli"`: Lithe keeps no header values for a provider it +saves). Then `addProvider` and `updateProvider` may carry `headers`, the +provider's whole list of headers after the change, each `{name, value?}`, +the shape the library takes for an MCP server's variables: + +- a header with `value` takes it; +- a header without `value` keeps the value the provider has for that name, + ASCII case ignored (`agentProviders.unknownHeader` when it has none; a new + provider has none); +- a header left out is removed, and `headers: []` removes them all; a + change without `headers` keeps them all. + +A `valueSet` in a header is accepted and ignored, so the host can send back +what it read. Headers are at most 64, each name follows the header name +rule, is unique ignoring ASCII case and is none of the headers an HTTP +client sets itself (`Host`, `Connection`, `Content-Length`, +`Transfer-Encoding`, `Proxy-Authorization`, `Proxy-Connection`, `Upgrade`, +`Trailer`, `TE`), and each value is 1–8192 bytes without a control +character or line break; other headers are `agentProviders.invalidHeaders`. +The same names, case ignored, are refused in a snapshot's `headers`, +`headerNames` and a preset's `headerNames`. + +Core hands header values in memory to the plugin's `edit` and `probe` and +nowhere else: no answer, refusal, log, event or debug output carries one. +The re-read copy must show the headers: the same names, case ignored, and, +from a plugin that reports `headers`, `valueSet: true` for each header the +change gave a value (`agentProviders.editNotApplied`). + +##### Probes + +When the user asks, Lithe reaches a provider over the network through the +agent's plugin: it lists the models the provider serves +(`agentProviders.fetchModels`) or sends it the smallest request of its +protocol to test the endpoint, key and model +(`agentProviders.testConnection`). The plugin's `probe` function makes the +request, not Core: the key is in the CLI's configuration or the plugin's +own credentials and Core never reads it back, and only the plugin knows the +wire protocol, its paths, how the key is sent and what the answer looks +like. Nothing probes in the background, on a timer or when a view opens: +each probe is one request the user started, and a probe changes nothing. + +Both commands take `{agent, provider, key?, headers?}`: + +- `provider` is `{id?, baseUrl?, protocol?, keyVariable?, model?}`: a + provider the agent has, by `id`, with any field the user changed, or a + provider the user is adding, by its fields and the `id` it will have. + Core fills each field left out from the provider the agent has: with + `listKeptBy: "lithe"` a saved provider of that `id` first, then one the + configuration holds. `model` is the model a connection test asks for. +- `key` is a key the user typed, by the rule of a change's `key`; without + it the plugin uses the key it finds for the provider. +- `headers` replace the provider's headers for this request, by the rules + of [Request headers](#request-headers): a header without a value takes + the provider's value. Without `headers` the plugin sends the provider's + own. + +Core checks, in this order, and calls the plugin only when every check +passes: + +1. The request's origin is the user (`agentLibrary.userActionRequired`); + the payload has exactly these fields (`agents.invalidPayload`, whose + message quotes nothing of the payload); the agent declares + `configuration` and its plugin is granted (`agentLibrary.unknownAgent`, + `agentLibrary.notGranted`). +2. The agent declares `providers` (`agentProviders.notDeclared`), a `probe` + function and this probe in `probes` (`agentProviders.unsupportedProbe`). +3. Each field follows the snapshot rules (`agentProviders.invalidProbe`); + a `baseUrl` that is not an allowed endpoint is + `agentProviders.invalidEndpoint`, a bad `key` + `agentProviders.invalidKey`, bad headers `agentProviders.invalidHeaders`. +4. Core reads the agent, with that read's own refusals. An `id` the agent + does not have, without a `baseUrl`, is `agentProviders.unknownProvider`; + a provider left without an endpoint is `agentProviders.noEndpoint`; a + header without a value the provider does not have is + `agentProviders.unknownHeader`. +5. Core calls `probe` and waits at most 30 seconds. A failed call is + `agentProviders.probeFailed`, and an answer that breaks the rules of + [Provider functions](#provider-functions) is + `agentProviders.invalidProbeAnswer`. + +The answer is the plugin's `result` and, for `fetchModels` that went `ok`, +its `models`: + +```json +{ + "agent": "dev.example.agents/alpha", + "result": {"category": "ok", "status": 200, "durationMs": 182}, + "models": [{"id": "model-a", "name": "Model A", "contextWindow": 400000}, {"id": "model-b"}] +} +``` + +```json +{ + "agent": "dev.example.agents/alpha", + "result": {"category": "unauthorized", "status": 401, "code": "invalid_api_key", "durationMs": 95, "model": "model-b"} +} +``` + +A failed connection is a `result`, not a refusal. `result` carries no text: +the host shows a message of its own for each `category`, with `status`, +`code` and `durationMs`, so no server message, which may quote a key, +reaches the host. Core keeps no fetched model; they are not the agent's +listed `models`, and where the plugin lists models, a `setModel` takes only +those it lists (see [Listed models](#listed-models)). + +Core logs `agent.providers.probe_finished` with the plugin, agent, probe, +category, status, number of models, whether the request carried fields of +its own, and the duration, and `agent.providers.probe_failed` with the +refusal code and the call's failure code; never an endpoint, model, header +or key. ##### Provider functions @@ -5364,12 +5572,14 @@ configuration `read`, and answers within 10 seconds exactly: - `model?`: `{id, source?}`, the model in use; - `provider?`: `{id, name?, source?}`, the provider in use; - `providers`: at most 64 `{id, name, baseUrl?, protocol?, keyVariable?, - keySet?, model?, headerNames?, queryParameterNames?, enabled?, builtIn?, - source?}`, IDs unique. `keyVariable` is the environment variable the key + keySet?, model?, headerNames?, headers?, queryParameterNames?, enabled?, + builtIn?, source?}`, IDs unique. `keyVariable` is the environment variable the key is read from; `keySet` (default `false`) is whether the configuration holds a key value for the provider, the value itself never reported; `model` is the model the configuration pairs with the provider; - `headerNames` and `queryParameterNames` are at most 64 names each. + `headerNames` and `queryParameterNames` are at most 64 names each; + `headers` is at most 64 `{name, valueSet?, variable?}` in place of + `headerNames` (see [Request headers](#request-headers)). `enabled` is left out when the CLI has no on/off switch; `builtIn` marks a provider built into the CLI, which is shown and never changed; - `profiles`: at most 64 `{name, model?, provider?, source?}`, names unique; @@ -5393,6 +5603,8 @@ configuration `read`, and answers within 10 seconds exactly: - `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; +- `presets?`: at most 128 providers the user can add (see + [Provider presets](#provider-presets)); - `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 @@ -5453,7 +5665,83 @@ 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. +restriction when `models` holds every listed model. With `editsHeaders`, +`headers` in `change` is the provider's whole list of headers: the plugin +writes each header with a `value`, keeps the value it has for a header +without one (matching the name with ASCII case ignored), and removes the +headers left out; a change without `headers` keeps them all. + +The `probe` function receives `{agentID, files, probe, provider, existing, +timeoutMilliseconds, maximumResponseBytes, key?, headers?}`: + +- `probe` is `fetchModels` or `testConnection`; +- `provider` is `{id?, baseUrl, protocol?, keyVariable?, model?}`, the + host's request with the fields Core filled in, and `existing` whether the + agent has a provider of that `id`; +- `key` and `headers` are as the user gave them. Without `key` the plugin + finds the key as the CLI would: the provider's key in the configuration, + its `keyVariable` in the environment the CLI runs with, or, with + `listKeptBy: "lithe"`, the key it keeps in its credentials for `id`. + Without `headers` it sends the provider's own; a header without a value + takes the provider's value; +- `timeoutMilliseconds` (20000) is its budget for the whole exchange: + resolving the name, connecting, TLS, sending and reading the answer; + `maximumResponseBytes` (8 MiB for `fetchModels`, 64 KiB for + `testConnection`) is the most of an answer body it reads. + +The plugin makes the requests the probe needs with its own HTTP client, as +the CLI would make them, and: + +- reaches only the scheme, host and port of `baseUrl`, and follows no + redirect: a 3xx answer is `redirected`; +- uses the proxy and certificates the CLI would use; +- sends the key and headers as the CLI does, and nothing else of the + user's; +- for `testConnection`, sends the smallest request the protocol takes to + `model`, or to the provider's model without one, such as a single output + token; a request that costs nothing is better where the protocol has one; +- sends nothing when the provider needs a key and there is none (`noKey`) + or the protocol has no such request (`unsupported`); +- never puts a key, a header value or a server's message in its answer, an + error message or a log. + +It answers within 30 seconds exactly `{format: "litheAgentProvidersProbe", +version: 0, result, models?}`: + +- `result` is `{category, status?, code?, durationMs, model?}`. `status` is + the HTTP status of the provider's answer, which the category requires or + refuses as the table below says; `code` is the provider's own error code + from its answer, such as `invalid_api_key`, by the `protocol` rule and + only with a `status` of 400 or more; `durationMs` is the milliseconds from + sending the request to the answer or the failure, 0 when nothing was + sent, at most 30000; `model` is the model a `testConnection` asked for, + by the model rule, and refused for `fetchModels`. +- `models` is there exactly when a `fetchModels` went `ok`: at most 2048 + `{id, name?, contextWindow?}`, IDs unique; `id` is the model as the + provider names it in a request and `name` a display name, both by the + model rule; `contextWindow` is 1–1000000000. + +| `category` | `status` | Meaning | +| --- | --- | --- | +| `ok` | 2xx | The provider answered as its protocol does. | +| `unauthorized` | 401 or 403 | The key was refused or has no access. | +| `notFound` | 404 | Nothing at that address, usually a wrong endpoint. | +| `rateLimited` | 429 | The provider asks to wait. | +| `requestRejected` | another 4xx | The provider refused the request, such as a model it does not serve. | +| `serverError` | 5xx | The provider failed. | +| `redirected` | 3xx | The endpoint redirects, which the plugin does not follow. | +| `invalidResponse` | 2xx | The answer is not what the protocol answers. | +| `responseTooLarge` | any, or none | The answer was larger than `maximumResponseBytes`. | +| `timeout` | none | No whole answer within `timeoutMilliseconds`. | +| `dnsFailed` | none | The endpoint's host name did not resolve. | +| `connectFailed` | none | No connection could be made, directly or through a proxy. | +| `tlsFailed` | none | The TLS handshake or the certificate check failed. | +| `noKey` | none | The provider needs a key and there is none; nothing was sent. | +| `unsupported` | none | The plugin cannot make this probe for this provider; nothing was sent. | + +Any other answer, including one with an unknown field, is +`agentProviders.invalidProbeAnswer`; a failed call is +`agentProviders.probeFailed`. #### 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 7e98b547..0aca1dd9 100644 --- a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -98,6 +98,12 @@ "setSpeed", "setModelMenu", "setProvider" + ], + "editsHeaders": true, + "probe": "example.providers.probe", + "probes": [ + "fetchModels", + "testConnection" ] } } diff --git a/shared/plugins/contract/v1/fixtures/agents/provider-probes.json b/shared/plugins/contract/v1/fixtures/agents/provider-probes.json new file mode 100644 index 00000000..022ae204 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/agents/provider-probes.json @@ -0,0 +1,344 @@ +{ + "description": "Provider presets, request headers and probes of an agent (configuration.providers, plan API-45). `providers` is the providers declaration of the agent; `answer` is what the plugin's read function returns; `view` the matching fields of the agent's entry in agentProviders.read. Each of `probes` is a host request to the command it names (the host adds `agent`), the fields Core gives the plugin's probe function besides agentID and files (`params`), the plugin's `answer`, and the host's answer besides `agent` (`view`). `refusals` are requests Core refuses before calling the plugin, with their code; each of `invalidAnswers` is a plugin answer Core refuses with agentProviders.invalidProbeAnswer. Keys and header values here are synthetic.", + "providers": { + "operations": ["addProvider", "updateProvider", "removeProvider", "setProvider"], + "editsHeaders": true, + "probe": "example.providers.probe", + "probes": ["fetchModels", "testConnection"] + }, + "answer": { + "format": "litheAgentProviders", + "version": 0, + "providers": [ + { "id": "builtin", "name": "Built-in", "builtIn": true }, + { + "id": "gateway", + "name": "Gateway", + "baseUrl": "https://gateway.example.com/v1", + "protocol": "chat", + "keyVariable": "GATEWAY_API_KEY", + "keySet": true, + "headers": [ + { "name": "X-Team", "valueSet": true }, + { "name": "X-Region", "valueSet": false, "variable": "GATEWAY_REGION" } + ] + } + ], + "presets": [ + { + "id": "vendor", + "name": "Vendor", + "description": "The models' own maker.", + "kind": "vendor", + "baseUrl": "https://api.vendor.example.com/v1", + "protocol": "responses", + "model": "vendor-large", + "keyVariable": "VENDOR_API_KEY", + "headerNames": ["X-Vendor-Project"], + "keysUrl": "https://vendor.example.com/keys" + }, + { + "id": "relay", + "name": "Relay", + "kind": "relay", + "baseUrl": "https://relay.example.com/v1", + "protocol": "chat", + "keyVariable": "RELAY_API_KEY" + }, + { + "id": "on-device", + "name": "On-device server", + "kind": "local", + "baseUrl": "http://127.0.0.1:11434/v1", + "protocol": "chat", + "keyOptional": true + }, + { "id": "own", "name": "Your own endpoint", "protocol": "chat" } + ] + }, + "view": { + "editsHeaders": true, + "probes": ["fetchModels", "testConnection"], + "providers": [ + { + "id": "builtin", + "name": "Built-in", + "builtIn": true, + "keySet": false, + "saved": false, + "origin": "configuration" + }, + { + "id": "gateway", + "name": "Gateway", + "baseUrl": "https://gateway.example.com/v1", + "protocol": "chat", + "keyVariable": "GATEWAY_API_KEY", + "keySet": true, + "headers": [ + { "name": "X-Team", "valueSet": true }, + { "name": "X-Region", "valueSet": false, "variable": "GATEWAY_REGION" } + ], + "builtIn": false, + "headerNames": ["X-Team", "X-Region"], + "saved": false, + "origin": "configuration" + } + ], + "presets": [ + { + "id": "vendor", + "name": "Vendor", + "description": "The models' own maker.", + "kind": "vendor", + "baseUrl": "https://api.vendor.example.com/v1", + "protocol": "responses", + "model": "vendor-large", + "keyVariable": "VENDOR_API_KEY", + "headerNames": ["X-Vendor-Project"], + "keysUrl": "https://vendor.example.com/keys" + }, + { + "id": "relay", + "name": "Relay", + "kind": "relay", + "baseUrl": "https://relay.example.com/v1", + "protocol": "chat", + "keyVariable": "RELAY_API_KEY" + }, + { + "id": "on-device", + "name": "On-device server", + "kind": "local", + "baseUrl": "http://127.0.0.1:11434/v1", + "protocol": "chat", + "keyOptional": true + }, + { "id": "own", "name": "Your own endpoint", "protocol": "chat" } + ] + }, + "probes": [ + { + "command": "agentProviders.fetchModels", + "request": { "provider": { "id": "gateway" } }, + "params": { + "probe": "fetchModels", + "provider": { + "id": "gateway", + "baseUrl": "https://gateway.example.com/v1", + "protocol": "chat", + "keyVariable": "GATEWAY_API_KEY" + }, + "existing": true, + "timeoutMilliseconds": 20000, + "maximumResponseBytes": 8388608 + }, + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "ok", "status": 200, "durationMs": 182 }, + "models": [ + { "id": "model-a", "name": "Model A", "contextWindow": 400000 }, + { "id": "model-b" } + ] + }, + "view": { + "result": { "category": "ok", "status": 200, "durationMs": 182 }, + "models": [ + { "id": "model-a", "name": "Model A", "contextWindow": 400000 }, + { "id": "model-b" } + ] + } + }, + { + "command": "agentProviders.testConnection", + "request": { + "provider": { + "id": "relay", + "baseUrl": "https://relay.example.com/v1", + "protocol": "chat", + "keyVariable": "RELAY_API_KEY", + "model": "model-b" + }, + "key": "fixture-key-not-real", + "headers": [{ "name": "X-Team", "value": "fixture-header-not-real" }] + }, + "params": { + "probe": "testConnection", + "provider": { + "id": "relay", + "baseUrl": "https://relay.example.com/v1", + "protocol": "chat", + "keyVariable": "RELAY_API_KEY", + "model": "model-b" + }, + "existing": false, + "timeoutMilliseconds": 20000, + "maximumResponseBytes": 65536, + "key": "fixture-key-not-real", + "headers": [{ "name": "X-Team", "value": "fixture-header-not-real" }] + }, + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { + "category": "unauthorized", + "status": 401, + "code": "invalid_api_key", + "durationMs": 95, + "model": "model-b" + } + }, + "view": { + "result": { + "category": "unauthorized", + "status": 401, + "code": "invalid_api_key", + "durationMs": 95, + "model": "model-b" + } + } + }, + { + "command": "agentProviders.testConnection", + "request": { + "provider": { "id": "gateway", "model": "model-a" }, + "headers": [{ "name": "x-team", "valueSet": true }] + }, + "params": { + "probe": "testConnection", + "provider": { + "id": "gateway", + "baseUrl": "https://gateway.example.com/v1", + "protocol": "chat", + "keyVariable": "GATEWAY_API_KEY", + "model": "model-a" + }, + "existing": true, + "timeoutMilliseconds": 20000, + "maximumResponseBytes": 65536, + "headers": [{ "name": "x-team" }] + }, + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "timeout", "durationMs": 20000, "model": "model-a" } + }, + "view": { + "result": { "category": "timeout", "durationMs": 20000, "model": "model-a" } + } + } + ], + "refusals": [ + { + "command": "agentProviders.fetchModels", + "request": { "provider": { "id": "missing" } }, + "code": "agentProviders.unknownProvider" + }, + { + "command": "agentProviders.fetchModels", + "request": { "provider": { "id": "builtin" } }, + "code": "agentProviders.noEndpoint" + }, + { + "command": "agentProviders.testConnection", + "request": { "provider": { "baseUrl": "https://user:secret@gateway.example.com/v1" } }, + "code": "agentProviders.invalidEndpoint" + }, + { + "command": "agentProviders.testConnection", + "request": { "provider": { "id": "gateway", "protocol": "two words" } }, + "code": "agentProviders.invalidProbe" + }, + { + "command": "agentProviders.testConnection", + "request": { "provider": { "id": "gateway" }, "key": "line\nbreak" }, + "code": "agentProviders.invalidKey" + }, + { + "command": "agentProviders.testConnection", + "request": { "provider": { "id": "gateway" }, "headers": [{ "name": "X-Missing" }] }, + "code": "agentProviders.unknownHeader" + }, + { + "command": "agentProviders.testConnection", + "request": { + "provider": { "id": "gateway" }, + "headers": [{ "name": "Host", "value": "fixture-header-not-real" }] + }, + "code": "agentProviders.invalidHeaders" + } + ], + "invalidAnswers": [ + { + "case": "a server message, which may quote a key", + "command": "agentProviders.testConnection", + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { + "category": "unauthorized", + "status": 401, + "durationMs": 95, + "message": "Incorrect API key provided: fixture-key-not-real" + } + } + }, + { + "case": "a status that disagrees with the category", + "command": "agentProviders.testConnection", + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "ok", "status": 401, "durationMs": 95 } + } + }, + { + "case": "a server code without an error status", + "command": "agentProviders.testConnection", + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "ok", "status": 200, "code": "fine", "durationMs": 95 } + } + }, + { + "case": "a list of models without its probe", + "command": "agentProviders.testConnection", + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "ok", "status": 200, "durationMs": 95 }, + "models": [] + } + }, + { + "case": "a listing that went well without its models", + "command": "agentProviders.fetchModels", + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "ok", "status": 200, "durationMs": 95 } + } + }, + { + "case": "a model listed twice", + "command": "agentProviders.fetchModels", + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "ok", "status": 200, "durationMs": 95 }, + "models": [{ "id": "model-a" }, { "id": "model-a" }] + } + }, + { + "case": "longer than Core waits", + "command": "agentProviders.fetchModels", + "answer": { + "format": "litheAgentProvidersProbe", + "version": 0, + "result": { "category": "timeout", "durationMs": 30001 } + } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index a163a05f..eb2456fb 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -1014,6 +1014,10 @@ {"name": "a provider operation is a contract operation", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": ["setModel", "setSecret"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations[1]"}, {"name": "a provider operation is listed once", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": ["setModel", "setModel"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations[1]"}, {"name": "a providers field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/secrets", "value": "example.providers.secrets"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a providers probe function declares its probes", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/providers/probes"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.probes"}, + {"name": "provider probes need a probe function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/providers/probe"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.probe"}, + {"name": "a provider probe is a contract probe", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/probes", "value": ["fetchModels", "ping"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.probes[1]"}, + {"name": "provider headers are saved only where the CLI keeps the list", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/listKeptBy", "value": "lithe"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.editsHeaders"}, {"name": "a configuration edit function needs read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": []}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "a configuration function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/edit", "value": "Example Edit"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "an agent field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/environment", "value": {"EXAMPLE": "1"}}], "expectedCode": "plugin.manifest.invalid"} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 327bed37..541a3f6f 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -554,13 +554,15 @@ "$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, 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.", + "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, and presets of the providers the user can add. 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"], "dependentRequired": { "edit": ["operations"], - "operations": ["edit"] + "operations": ["edit"], + "probe": ["probes"], + "probes": ["probe"] }, "properties": { "read": { @@ -583,6 +585,23 @@ "listKeptBy": { "description": "Added within agents 0. Who keeps the list of custom providers. cli (the default): the CLI's configuration holds every provider, each with its key if one is set. lithe: the CLI's configuration holds one active custom endpoint, Lithe keeps the list of providers the user saved (without keys; the plugin keeps each key through credentials), and setProvider hands the plugin the chosen provider's whole definition.", "enum": ["cli", "lithe"] + }, + "editsHeaders": { + "description": "Added within agents 0. Whether edit saves the request headers addProvider and updateProvider carry ({name, value?}, values write-only like keys). Needs addProvider or updateProvider among operations, and listKeptBy cli; Core refuses headers in a change of an agent without it with agentProviders.unsupportedOperation.", + "type": "boolean" + }, + "probe": { + "description": "Added within agents 0. Backend function that reaches a provider over the network for the user: {agentID, files, probe, provider, existing, key?, headers?, timeoutMilliseconds, maximumResponseBytes} to a litheAgentProvidersProbe answer. Core calls it only for a request the user started.", + "$ref": "#/$defs/pluginFunctionID" + }, + "probes": { + "description": "Added within agents 0. The requests probe answers: fetchModels lists the models a provider serves, testConnection sends it the smallest request its protocol takes. A manifest lists each at most once, and Core answers only the probes it lists (agentProviders.unsupportedProbe otherwise).", + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "enum": ["fetchModels", "testConnection"] + } } } } diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index fd00d60f..c1cb7423 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 内的补充);插件可在 `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-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 内的补充);插件可在快照里列出[供应商预设](../contract/v1/README.md#provider-presets)供用户添加(插件不列就没有,Core 不内置名单和地址),声明 `editsHeaders` 后供应商的[请求头](../contract/v1/README.md#request-headers)可随添加和修改保存(值只写不读),声明 `probe` 后用户点击时由插件后端[联网探测](../contract/v1/README.md#probes):获取模型列表(`agentProviders.fetchModels`)或测试连接(`agentProviders.testConnection`),Core 自己不联网,只检查请求、限定时间和回答大小,回答只有封闭的结果类别、状态码和耗时(`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); 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) | +| 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); the plugin may list [provider presets](../contract/v1/README.md#provider-presets) in the snapshot for the user to add (none without a list from the plugin; Core keeps no list or address), a plugin that declares `editsHeaders` saves a provider's [request headers](../contract/v1/README.md#request-headers) with an add or update (values write-only), and a plugin that declares `probe` has its backend [reach a provider](../contract/v1/README.md#probes) on the user's click, to list the models it serves (`agentProviders.fetchModels`) or test the connection (`agentProviders.testConnection`); Core does no networking itself, checks the request, bounds the time and answer size, and answers only a closed result category, a status and a duration (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 00e29abf..0c6c5b4b 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`,也不回答这三个命令;插件在 `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) | +| `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` 是其后的补充;`configuration.providers` 的 `editsHeaders`、`probe`、`probes`,快照的供应商预设 `presets` 和供应商的 `headers`,`addProvider`、`updateProvider` 的 `headers`,以及命令 `agentProviders.fetchModels`、`agentProviders.testConnection` 是最后的补充 | ✅ | 待宿主接入 | [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; 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) | +| `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 after that; `editsHeaders`, `probe` and `probes` of `configuration.providers`, the snapshot's provider `presets` and a provider's `headers`, the `headers` of `addProvider` and `updateProvider`, and the commands `agentProviders.fetchModels` and `agentProviders.testConnection` 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 55dfd42d..f0d45291 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -58,7 +58,7 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 宿主的 Agent 资源库把指令、技能、MCP 服务器和 Hooks 存一份,用户按 Agent 开关后,Core 写进每个 CLI 自己的配置。插件只声明 `configuration`: - `instructions`、`skills`:CLI 读取的用户指令文件和用户技能目录。Core 自己读写它们:指令文件里 Core 只写自己的一块(见下面的“指令文件”),块外的文字都是用户的、逐字节保留;技能以符号链接放进技能目录,资源库外的技能只显示、不改。 -- `files` 和 `read`、`edit`:保存 MCP 服务器和 Hooks 的 CLI 配置文件。只有后端认识它们的格式:`read` 报告文件里有哪些服务器和 Hooks(环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本,并保留文件里其他内容;Core 校验后用原子替换写回,文件在此期间被改动就拒绝。 +- `files` 和 `read`、`edit`:保存 MCP 服务器和 Hooks 的 CLI 配置文件。只有后端认识它们的格式:`read` 报告文件里有哪些服务器和 Hooks(环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本,并保留文件里其他内容;Core 校验后用原子替换写回,文件在此期间被改动就拒绝。`edit` 回答没有改动(或副本和文件一样)时不写文件,但 Core 会用文件的新副本再读一遍,确认文件里确实已经是要求的状态,否则是 `agentLibrary.editNotApplied`,插件忽略改动不能当成“已经是这样”。 - CLI 自己装的内容(比如 CLI 插件带来的 MCP 服务器、Hooks 和技能)标为 `origin: "agent"`,宿主只显示、不改。 - 宿主按插件声明的 `displayName` 和 `icon` 显示每个 Agent,不按名字特殊处理。 @@ -82,9 +82,9 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 ### 模型与模型供应商 -`configuration` 里再声明 `providers: {read, edit?, operations?, listKeptBy?}`,宿主就能显示 CLI 当前用的模型、可用的模型供应商、配置档和登录账号标签,并让用户修改。它和 MCP 服务器、Hooks 共用 `files`、`agents.configuration` 授权和暂存副本流程: +`configuration` 里再声明 `providers: {read, edit?, operations?, listKeptBy?, editsHeaders?, probe?, probes?}`,宿主就能显示 CLI 当前用的模型、可用的模型供应商、配置档和登录账号标签,并让用户修改。它和 MCP 服务器、Hooks 共用 `files`、`agents.configuration` 授权和暂存副本流程: -- `read` 报告 `litheAgentProviders` 快照,每个值带来源层(`user`、`profile`、`default`、`environment`)和来源文件或变量名;`edit` 只改 Core 给的暂存副本,Core 再读一遍副本确认改动生效后原子替换。 +- `read` 报告 `litheAgentProviders` 快照,每个值带来源层(`user`、`profile`、`default`、`environment`)和来源文件或变量名;`edit` 只改 Core 给的暂存副本,Core 再读一遍副本确认改动生效后原子替换;`edit` 回答没有改动时,Core 同样确认文件里已经是要求的状态,否则是 `agentProviders.editNotApplied`。 - `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` 地址;名称、列表都有上限。 @@ -97,8 +97,11 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 - **显示开关**:`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 菜单跟上。以后的“方案”保存和切换的就是这一组。 +- **供应商预设**(`agents` 0 内的补充):插件可以在 `read` 的快照里列出 `presets`,即 CLI 能连、插件已经知道的供应商(每项 `{id, name, description?, kind?, baseUrl?, protocol?, model?, keyVariable?, keyOptional?, headerNames?, keysUrl?}`,最多 128 个,ID 不重复)。`kind` 是 `vendor`(模型厂商)、`relay`(转售多家模型的服务)或 `local`(本机上的服务);没有 `baseUrl` 的预设由用户填自己的地址;`keysUrl` 是创建密钥的网页,只在用户点击时用浏览器打开;`listKeptBy: "lithe"` 时预设不能带 `keyVariable`。违反规则时整份快照按 `agentProviders.invalidSnapshot` 拒绝。插件不列就是空的,宿主和 Core 不内置任何供应商名单或地址。用户选中预设后,宿主照常发 `addProvider`(带用户确认过的字段、填写的密钥和请求头),Core 不记录供应商来自哪个预设。 +- **请求头**(`agents` 0 内的补充):插件报告供应商的请求头时,可以只给 `headerNames`,也可以给 `headers: [{name, valueSet?, variable?}]`(最多 64 个),同一个供应商只能给其中一种;`valueSet` 表示配置里有没有值,值本身从不报告。插件的 `edit` 能保存请求头时声明 `editsHeaders: true`(只能配 `listKeptBy: "cli"`,Lithe 不替自己保存的供应商存请求头的值)。这时 `addProvider`、`updateProvider` 可以带 `headers: [{name, value?}]`,表示改动后的完整列表:带 `value` 的用新值;不带的按名字(不区分 ASCII 大小写)保留原值,原来没有就是 `agentProviders.unknownHeader`;没列的删除;不带 `headers` 就全部保留。最多 64 个,名字不能重复,也不能是 HTTP 客户端自己设置的头(如 `Host`、`Content-Length`),值 1–8192 字节、不含控制字符,否则 `agentProviders.invalidHeaders`;没声明 `editsHeaders` 时带 `headers` 是 `agentProviders.unsupportedOperation`。请求头的值和密钥一样只写不读,只在内存里交给插件的 `edit` 和 `probe`。 +- **联网探测**(`agents` 0 内的补充):插件声明探测函数 `probe` 和它支持的 `probes`(`fetchModels`、`testConnection`)后,用户点击时宿主可以发 `agentProviders.fetchModels` 获取供应商提供的模型列表,或发 `agentProviders.testConnection` 用协议最小的请求测试端点、密钥和模型。请求由插件后端用自己的 HTTP 客户端发出,Core 不联网、不读密钥。Core 只检查请求来自用户(`agentLibrary.userActionRequired`)、插件声明了这项探测(`agentProviders.unsupportedProbe`)、字段和端点合法、供应商存在(`agentProviders.unknownProvider`、`agentProviders.noEndpoint`),再把补全后的供应商、用户填写的密钥和请求头、时间预算 `timeoutMilliseconds`(20 秒)和回答大小上限 `maximumResponseBytes`(模型列表 8 MiB、连接测试 64 KiB)交给插件,最多等 30 秒。插件只访问端点的同一来源、不跟随重定向,使用 CLI 会用的代理和证书。回答只有封闭的结果类别 `category`(`ok`、`unauthorized`、`notFound`、`rateLimited`、`requestRejected`、`serverError`、`redirected`、`invalidResponse`、`responseTooLarge`、`timeout`、`dnsFailed`、`connectFailed`、`tlsFailed`、`noKey`、`unsupported`)、HTTP 状态 `status`、服务端错误码 `code`、耗时 `durationMs` 和模型列表 `models`,没有放文字的字段,服务端的消息不会到宿主,宿主按类别显示自己的文案。连接失败是结果,不是拒绝;调用失败是 `agentProviders.probeFailed`,回答不合规是 `agentProviders.invalidProbeAnswer`。探测不保存任何东西,也没有后台轮询。 -命令是 `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`。 +命令是 `agentProviders.read {agent?}`、`agentProviders.apply {agent, change}`、`agentProviders.restore {agent, discardLaterChanges?}`、`agentProviders.showModels {agent, show?, hide?}`、`agentProviders.readModelSettings {agent}`、`agentProviders.applyModelSettings {agent, settings}`、`agentProviders.fetchModels {agent, provider, key?, headers?}` 和 `agentProviders.testConnection {agent, provider, key?, headers?}`,字段、拒绝码和完整示例见[契约](../../contract/v1/README.md#models-and-providers),模型清单的规则见[契约的 Listed models](../../contract/v1/README.md#listed-models),预设、请求头和探测见契约的 [Provider presets](../../contract/v1/README.md#provider-presets)、[Request headers](../../contract/v1/README.md#request-headers) 和 [Probes](../../contract/v1/README.md#probes),示例数据见 `fixtures/agents/model-catalog.json` 和 `fixtures/agents/provider-probes.json`。 ### 修改前备份与恢复 @@ -214,7 +217,7 @@ and the [shared Core/desktop fixture](../../../../rust/fixtures/agents/turn-inte The host's agent library keeps one copy of instructions, skills, MCP servers and hooks; once the user turns them on per agent, Core writes them into each CLI's own configuration. The plugin only declares `configuration`: - `instructions` and `skills`: the user instruction file and the user skills directory the CLI reads. Core reads and writes them itself: in the instruction file it writes only its own block (see "Instruction files" below), and every line outside it is the user's and kept byte for byte; it puts skills into the skills directory as symbolic links. Skills outside the library are shown and never changed. -- `files` with `read` and `edit`: the CLI configuration files that hold MCP servers and hooks. Only the backend knows their format. `read` reports the servers and hooks a file holds (names only for environment variables and headers), and `edit` changes only the staged copy Core gives it and keeps everything else in the file. Core checks the copy and replaces the file atomically, refusing when the file changed meanwhile. +- `files` with `read` and `edit`: the CLI configuration files that hold MCP servers and hooks. Only the backend knows their format. `read` reports the servers and hooks a file holds (names only for environment variables and headers), and `edit` changes only the staged copy Core gives it and keeps everything else in the file. Core checks the copy and replaces the file atomically, refusing when the file changed meanwhile. When `edit` reports no change (or leaves the copy as the file was), nothing is written, but Core reads a fresh copy of the file and the change must already be there (`agentLibrary.editNotApplied` otherwise), so a plugin that ignores a change cannot pass it off as already made. - What the CLI installed itself, such as the MCP servers, hooks and skills a CLI plugin brings, has `origin: "agent"`; the host shows it and never changes it. - The host shows each agent by the `displayName` and `icon` its plugin declares and never special-cases agents by name. @@ -238,9 +241,9 @@ See the [contract](../../contract/v1/README.md#instruction-files). ### Models and model providers -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: +An agent whose `configuration` also declares `providers: {read, edit?, operations?, listKeptBy?, editsHeaders?, probe?, probes?}` 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. +- `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; when `edit` reports no change, Core likewise sees that the file already holds it, else `agentProviders.editNotApplied`. - `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. @@ -253,8 +256,11 @@ An agent whose `configuration` also declares `providers: {read, edit?, operation - **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. +- **Provider presets** (added within `agents` 0): the plugin may list `presets` in the `read` snapshot, the providers its CLI can reach that the plugin knows (each `{id, name, description?, kind?, baseUrl?, protocol?, model?, keyVariable?, keyOptional?, headerNames?, keysUrl?}`, at most 128, IDs unique). `kind` is `vendor` (the models' own maker), `relay` (a service that resells the models of many makers) or `local` (a server on the user's machine); a preset without `baseUrl` is reached at an address the user gives; `keysUrl` is the page where the user makes a key, opened in the browser only on the user's click; with `listKeptBy: "lithe"` a preset names no `keyVariable`. A preset that breaks a rule refuses the whole snapshot as `agentProviders.invalidSnapshot`. Without a list from the plugin there is none: neither the host nor Core keeps provider lists or addresses of its own. When the user picks a preset, the host sends an ordinary `addProvider` (the fields the user confirmed, the key and the headers the user typed); Core records no link between a provider and a preset. +- **Request headers** (added within `agents` 0): the plugin reports a provider's request headers either as `headerNames`, names only, or as `headers: [{name, valueSet?, variable?}]` (at most 64), never both for one provider; `valueSet` is whether the configuration holds a value, and the value is never reported. A plugin whose `edit` saves headers declares `editsHeaders: true` (only with `listKeptBy: "cli"`: Lithe keeps no header values for a provider it saves). Then `addProvider` and `updateProvider` may carry `headers: [{name, value?}]`, the whole list after the change: a header with `value` takes it; one without keeps the value of that name (ASCII case ignored), `agentProviders.unknownHeader` when there is none; a header left out is removed; a change without `headers` keeps them all. At most 64 headers, names unique and none an HTTP client sets itself (such as `Host` or `Content-Length`), values 1–8192 bytes without control characters, else `agentProviders.invalidHeaders`; `headers` without `editsHeaders` is `agentProviders.unsupportedOperation`. Header values are write-only like keys, handed in memory to the plugin's `edit` and `probe` only. +- **Probes** (added within `agents` 0): once the plugin declares a `probe` function and the `probes` it answers (`fetchModels`, `testConnection`), the host may, on the user's click, send `agentProviders.fetchModels` to list the models a provider serves, or `agentProviders.testConnection` to test the endpoint, key and model with the smallest request of the protocol. The plugin's backend makes the request with its own HTTP client; Core does no networking and reads no key. Core checks that the request comes from the user (`agentLibrary.userActionRequired`), that the plugin declares the probe (`agentProviders.unsupportedProbe`), that the fields and endpoint are valid, and that the provider exists (`agentProviders.unknownProvider`, `agentProviders.noEndpoint`); then it gives the plugin the provider with what the agent has filled in, the key and headers the user typed, the time budget `timeoutMilliseconds` (20 seconds) and the answer size limit `maximumResponseBytes` (8 MiB for a list of models, 64 KiB for a connection test), and waits at most 30 seconds. The plugin reaches only the endpoint's origin, follows no redirect, and uses the proxy and certificates the CLI would. The answer has only a closed `category` (`ok`, `unauthorized`, `notFound`, `rateLimited`, `requestRejected`, `serverError`, `redirected`, `invalidResponse`, `responseTooLarge`, `timeout`, `dnsFailed`, `connectFailed`, `tlsFailed`, `noKey`, `unsupported`), the HTTP `status`, the server's error `code`, `durationMs` and the `models`; no field holds text, so no server message reaches the host, which shows its own message for each category. A failed connection is a result, not a refusal; a failed call is `agentProviders.probeFailed` and an answer that breaks the rules `agentProviders.invalidProbeAnswer`. A probe saves nothing, and nothing probes in the background. -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`. +The commands are `agentProviders.read {agent?}`, `agentProviders.apply {agent, change}`, `agentProviders.restore {agent, discardLaterChanges?}`, `agentProviders.showModels {agent, show?, hide?}`, `agentProviders.readModelSettings {agent}`, `agentProviders.applyModelSettings {agent, settings}`, `agentProviders.fetchModels {agent, provider, key?, headers?}` and `agentProviders.testConnection {agent, provider, key?, headers?}`; 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), presets, headers and probes in its [Provider presets](../../contract/v1/README.md#provider-presets), [Request headers](../../contract/v1/README.md#request-headers) and [Probes](../../contract/v1/README.md#probes), and sample data in `fixtures/agents/model-catalog.json` and `fixtures/agents/provider-probes.json`. ### Backups before a change, and restore diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1139c36a..8d9034e1 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#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 不改代码,只更新说明。 | +| [#266](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/266)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 模型供应商的预设、请求头和联网探测。**预设**:插件可在 `configuration.providers` 的 `read` 快照里列出 `presets`(每项 `{id, name, description?, kind?, baseUrl?, protocol?, model?, keyVariable?, keyOptional?, headerNames?, keysUrl?}`,最多 128 个,`kind` 为 `vendor`、`relay`、`local`),`agentProviders.read` 总是回答 `presets`(插件不列为空),宿主用普通的 `addProvider` 从预设添加。**请求头**:快照的供应商可用 `headers: [{name, valueSet?, variable?}]` 代替 `headerNames`(两者只能给一个,值从不报告);清单新增 `providers.editsHeaders`(需 `addProvider` 或 `updateProvider`,且 `listKeptBy` 为 `cli`),声明后 `addProvider`、`updateProvider` 可带 `headers: [{name, value?}]`,不带值的按名字保留原值;新拒绝码 `agentProviders.invalidHeaders`、`agentProviders.unknownHeader`。**探测**:清单新增 `providers.probe`(插件函数)和 `providers.probes`(`fetchModels`、`testConnection`,两者同时出现);新命令 `agentProviders.fetchModels`、`agentProviders.testConnection`(`{agent, provider, key?, headers?}`,只接受用户发起的请求),插件函数收到 `{agentID, files, probe, provider, existing, timeoutMilliseconds, maximumResponseBytes, key?, headers?}`,回答 `litheAgentProvidersProbe` 0 的 `{result: {category, status?, code?, durationMs, model?}, models?}`;新拒绝码 `agentProviders.unsupportedProbe`、`agentProviders.invalidProbe`、`agentProviders.noEndpoint`、`agentProviders.probeFailed`、`agentProviders.invalidProbeAnswer`。`agentProviders.read` 的每项新增 `editsHeaders`、`probes`。新增契约样例 `fixtures/agents/provider-probes.json`,日志事件 `agent.providers.probe_finished`、`agent.providers.probe_failed`。**确认没有改动**:资源库的服务器、Hook 和供应商的 `edit` 回答 `changed: false`(或副本与文件相同)时,Core 也用文件的新副本重读,要求的改动确实已在文件里才回答 `changed: false`,否则是 `agentLibrary.editNotApplied` 或 `agentProviders.editNotApplied`;`listKeptBy: "lithe"` 时,未在使用的供应商只改插件的凭据,不在配置里检查 | ## 按协议查首次出现 @@ -241,6 +241,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#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 不改代码,只更新说明。 | | [#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`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index cd210919..df8b1682 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -689,7 +689,8 @@ and gives each call 10 seconds. the file holds, and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real - file. + file. With `changed: false`, Core reads the file as it is and the change + must already be there. - Both need `agents.configuration`. `read` reads the declared files at the paths Core passes, which may be staged copies, and may also read what the CLI installed itself, such as its plugins, to report it with @@ -699,8 +700,10 @@ and gives each call 10 seconds. An agent may also declare [`configuration.providers`](../../contract/v1/README.md#models-and-providers) with a `read` function, an optional `edit` function and the `operations` -`edit` makes. They are ordinary plugin functions too, registered the same -way, with the same 10 seconds and the same `agents.configuration` permission: +`edit` makes, and an optional `probe` function with the `probes` it answers. +They are ordinary plugin functions too, registered the same way, under the +same `agents.configuration` permission, `read` and `edit` with the same 10 +seconds: - `providers.read` receives `{agentID, files: [{id, path, exists}]}` and answers `{format: "litheAgentProviders", version: 0, ...}`: the model, @@ -710,25 +713,46 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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`. + It may also list `presets`, the providers the user can add, and report a + provider's `headers` as `{name, valueSet?, variable?}` in place of + `headerNames`. - `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}`. + `{format: "litheAgentProvidersEdit", version: 0, changed}`; with + `changed: false` the change must already be in the file. - `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 - reported by name only; a `baseUrl` has no user, password, query or - fragment. Neither function opens a CLI's credential files (such as + answer, error or log carries a key. Headers are reported by name, with + whether a value is set, and query parameters by name only; a `baseUrl` + has no user, password, query or fragment. Neither function opens a CLI's credential files (such as `auth.json` or `.credentials.json`) or the system keychain. Core refuses any answer that breaks these rules. - With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the plugin keeps their keys with `lithe/host/credentials/*` under the `credentials.store` permission; see the contract for the extra `change` fields. +- A plugin whose `edit` saves request headers declares `editsHeaders: true` + (with `listKeptBy: "cli"`). `addProvider` and `updateProvider` then may + carry `headers: [{name, value?}]`, the provider's whole list: `edit` + writes each value given, keeps the value it has for a header without one, + and removes the headers left out. Values are write-only like keys. +- The `probe` function runs only when the user asks to list a provider's + models (`fetchModels`) or test the connection (`testConnection`). It + receives `{agentID, files, probe, provider, existing, + timeoutMilliseconds, maximumResponseBytes, key?, headers?}`, makes the + request with the plugin's own HTTP client, and answers + `{format: "litheAgentProvidersProbe", version: 0, result: {category, + status?, code?, durationMs, model?}, models?}` within 30 seconds. It + reaches only the endpoint's scheme, host and port, follows no redirect, + stays within the time and answer size it is given, and never puts a key, + a header value or a server's message in its answer, an error or a log; + see the contract's [Probes](../../contract/v1/README.md#probes) for the + categories. ## Testing diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 6d3b2a71..315440ec 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -656,7 +656,8 @@ and gives each call 10 seconds. the file holds, and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real - file. + file. With `changed: false`, Core reads the file as it is and the change + must already be there. - Both need `agents.configuration`. `read` reads the declared files at the paths Core passes, which may be staged copies, and may also read what the CLI installed itself, such as its plugins, to report it with @@ -666,8 +667,10 @@ and gives each call 10 seconds. An agent may also declare [`configuration.providers`](../../contract/v1/README.md#models-and-providers) with a `read` function, an optional `edit` function and the `operations` -`edit` makes. They are ordinary plugin functions too, registered the same -way, with the same 10 seconds and the same `agents.configuration` permission: +`edit` makes, and an optional `probe` function with the `probes` it answers. +They are ordinary plugin functions too, registered the same way, under the +same `agents.configuration` permission, `read` and `edit` with the same 10 +seconds: - `providers.read` receives `{agentID, files: [{id, path, exists}]}` and answers `{format: "litheAgentProviders", version: 0, ...}`: the model, @@ -677,25 +680,46 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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`. + It may also list `presets`, the providers the user can add, and report a + provider's `headers` as `{name, valueSet?, variable?}` in place of + `headerNames`. - `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}`. + `{format: "litheAgentProvidersEdit", version: 0, changed}`; with + `changed: false` the change must already be in the file. - `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 - reported by name only; a `baseUrl` has no user, password, query or - fragment. Neither function opens a CLI's credential files (such as + answer, error or log carries a key. Headers are reported by name, with + whether a value is set, and query parameters by name only; a `baseUrl` + has no user, password, query or fragment. Neither function opens a CLI's credential files (such as `auth.json` or `.credentials.json`) or the system keychain. Core refuses any answer that breaks these rules. - With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the plugin keeps their keys with `lithe/host/credentials/*` under the `credentials.store` permission; see the contract for the extra `change` fields. +- A plugin whose `edit` saves request headers declares `editsHeaders: true` + (with `listKeptBy: "cli"`). `addProvider` and `updateProvider` then may + carry `headers: [{name, value?}]`, the provider's whole list: `edit` + writes each value given, keeps the value it has for a header without one, + and removes the headers left out. Values are write-only like keys. +- The `probe` function runs only when the user asks to list a provider's + models (`fetchModels`) or test the connection (`testConnection`). It + receives `{agentID, files, probe, provider, existing, + timeoutMilliseconds, maximumResponseBytes, key?, headers?}`, makes the + request with the plugin's own HTTP client, and answers + `{format: "litheAgentProvidersProbe", version: 0, result: {category, + status?, code?, durationMs, model?}, models?}` within 30 seconds. It + reaches only the endpoint's scheme, host and port, follows no redirect, + stays within the time and answer size it is given, and never puts a key, + a header value or a server's message in its answer, an error or a log; + see the contract's [Probes](../../contract/v1/README.md#probes) for the + categories. ## Testing diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 28da19fd..e3c4fe78 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -669,7 +669,8 @@ and gives each call 10 seconds. the file holds, and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real - file. + file. With `changed: false`, Core reads the file as it is and the change + must already be there. - Both need `agents.configuration`. `read` reads the declared files at the paths Core passes, which may be staged copies, and may also read what the CLI installed itself, such as its plugins, to report it with @@ -679,8 +680,10 @@ and gives each call 10 seconds. An agent may also declare [`configuration.providers`](../../contract/v1/README.md#models-and-providers) with a `read` function, an optional `edit` function and the `operations` -`edit` makes. They are ordinary plugin functions too, registered the same -way, with the same 10 seconds and the same `agents.configuration` permission: +`edit` makes, and an optional `probe` function with the `probes` it answers. +They are ordinary plugin functions too, registered the same way, under the +same `agents.configuration` permission, `read` and `edit` with the same 10 +seconds: - `providers.read` receives `{agentID, files: [{id, path, exists}]}` and answers `{format: "litheAgentProviders", version: 0, ...}`: the model, @@ -690,25 +693,46 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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`. + It may also list `presets`, the providers the user can add, and report a + provider's `headers` as `{name, valueSet?, variable?}` in place of + `headerNames`. - `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}`. + `{format: "litheAgentProvidersEdit", version: 0, changed}`; with + `changed: false` the change must already be in the file. - `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 - reported by name only; a `baseUrl` has no user, password, query or - fragment. Neither function opens a CLI's credential files (such as + answer, error or log carries a key. Headers are reported by name, with + whether a value is set, and query parameters by name only; a `baseUrl` + has no user, password, query or fragment. Neither function opens a CLI's credential files (such as `auth.json` or `.credentials.json`) or the system keychain. Core refuses any answer that breaks these rules. - With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the plugin keeps their keys with `lithe/host/credentials/*` under the `credentials.store` permission; see the contract for the extra `change` fields. +- A plugin whose `edit` saves request headers declares `editsHeaders: true` + (with `listKeptBy: "cli"`). `addProvider` and `updateProvider` then may + carry `headers: [{name, value?}]`, the provider's whole list: `edit` + writes each value given, keeps the value it has for a header without one, + and removes the headers left out. Values are write-only like keys. +- The `probe` function runs only when the user asks to list a provider's + models (`fetchModels`) or test the connection (`testConnection`). It + receives `{agentID, files, probe, provider, existing, + timeoutMilliseconds, maximumResponseBytes, key?, headers?}`, makes the + request with the plugin's own HTTP client, and answers + `{format: "litheAgentProvidersProbe", version: 0, result: {category, + status?, code?, durationMs, model?}, models?}` within 30 seconds. It + reaches only the endpoint's scheme, host and port, follows no redirect, + stays within the time and answer size it is given, and never puts a key, + a header value or a server's message in its answer, an error or a log; + see the contract's [Probes](../../contract/v1/README.md#probes) for the + categories. ## Testing diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index b9ac12ce..b79b3b08 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -866,7 +866,8 @@ and gives each call 10 seconds. the file holds, and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real - file. + file. With `changed: false`, Core reads the file as it is and the change + must already be there. - Both need `agents.configuration`. `read` reads the declared files at the paths Core passes, which may be staged copies, and may also read what the CLI installed itself, such as its plugins, to report it with @@ -876,8 +877,10 @@ and gives each call 10 seconds. An agent may also declare [`configuration.providers`](../../contract/v1/README.md#models-and-providers) with a `read` function, an optional `edit` function and the `operations` -`edit` makes. They are ordinary plugin functions too, registered the same -way, with the same 10 seconds and the same `agents.configuration` permission: +`edit` makes, and an optional `probe` function with the `probes` it answers. +They are ordinary plugin functions too, registered the same way, under the +same `agents.configuration` permission, `read` and `edit` with the same 10 +seconds: - `providers.read` receives `{agentID, files: [{id, path, exists}]}` and answers `{format: "litheAgentProviders", version: 0, ...}`: the model, @@ -887,25 +890,46 @@ way, with the same 10 seconds and the same `agents.configuration` permission: 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`. + It may also list `presets`, the providers the user can add, and report a + provider's `headers` as `{name, valueSet?, variable?}` in place of + `headerNames`. - `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}`. + `{format: "litheAgentProvidersEdit", version: 0, changed}`; with + `changed: false` the change must already be in the file. - `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 - reported by name only; a `baseUrl` has no user, password, query or - fragment. Neither function opens a CLI's credential files (such as + answer, error or log carries a key. Headers are reported by name, with + whether a value is set, and query parameters by name only; a `baseUrl` + has no user, password, query or fragment. Neither function opens a CLI's credential files (such as `auth.json` or `.credentials.json`) or the system keychain. Core refuses any answer that breaks these rules. - With `listKeptBy: "lithe"`, Lithe keeps the saved providers and the plugin keeps their keys with `lithe/host/credentials/*` under the `credentials.store` permission; see the contract for the extra `change` fields. +- A plugin whose `edit` saves request headers declares `editsHeaders: true` + (with `listKeptBy: "cli"`). `addProvider` and `updateProvider` then may + carry `headers: [{name, value?}]`, the provider's whole list: `edit` + writes each value given, keeps the value it has for a header without one, + and removes the headers left out. Values are write-only like keys. +- The `probe` function runs only when the user asks to list a provider's + models (`fetchModels`) or test the connection (`testConnection`). It + receives `{agentID, files, probe, provider, existing, + timeoutMilliseconds, maximumResponseBytes, key?, headers?}`, makes the + request with the plugin's own HTTP client, and answers + `{format: "litheAgentProvidersProbe", version: 0, result: {category, + status?, code?, durationMs, model?}, models?}` within 30 seconds. It + reaches only the endpoint's scheme, host and port, follows no redirect, + stays within the time and answer size it is given, and never puts a key, + a header value or a server's message in its answer, an error or a log; + see the contract's [Probes](../../contract/v1/README.md#probes) for the + categories. ## Testing