diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index bfec6cc5..d8199899 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -479,7 +479,8 @@ or removing a command fails until the table changes in the same commit. | `ai.inlineEdit.plan` | Plan a credential-free inline edit request | | `ai.inlineEdit.decode` | Decode the replacement text of an inline edit response | | `agents.configure` | Load the agents enabled plugins declare, with the permissions the user granted | -| `agents.catalog` | List the configured agents | +| `agents.catalog` | List the configured agents, with whether each checks for a newer CLI and its `install` (`{installers, url?}`: the IDs of the command installers that provide its tool and the install page it declares) | +| `agents.cliVersions` | Compare each named agent's installed CLI version with the newest one its plugin's `latestVersion` function reported, kept in memory per installation; `check` is `cached` (ask no plugin), `ifStale` (ask once an answer is six hours old, 15 minutes after a failure) or `now` (user requests only); answers each agent's `latest`, `comparison`, `updateAvailable` and `checkFailed`, and `updates`, the update commands of the agents behind, which the host runs in its terminal | | `agents.sessions` | List the live agent sessions | | `agents.start` | Start a native agent session the user asked for | | `agents.prompt` | Send, queue or steer the user's prompt and attachments, retaining queued or unconfirmed input until its outcome | diff --git a/rust/crates/agent-runtime/src/catalog.rs b/rust/crates/agent-runtime/src/catalog.rs index 5215e979..a4292cbd 100644 --- a/rust/crates/agent-runtime/src/catalog.rs +++ b/rust/crates/agent-runtime/src/catalog.rs @@ -21,8 +21,13 @@ const MAX_PLUGINS: usize = 1024; /// One plugin's agents and grants. #[derive(Debug, Clone)] pub(crate) struct PluginAgents { + /// The plugin's own version, which tells a cached answer of an older + /// build of the plugin from one of this build. + pub version: String, pub agents: Vec, pub granted: BTreeSet, + /// The command installers that provide each agent's tool, by agent ID. + pub installers: BTreeMap>, } impl PluginAgents { @@ -43,6 +48,8 @@ impl PluginAgents { #[derive(Debug, Clone)] pub(crate) struct CatalogAgent { pub plugin_id: String, + /// The version of the plugin that declares the agent. + pub plugin_version: String, pub agent: AgentDeclaration, pub may_run: bool, pub may_read_sessions: bool, @@ -127,11 +134,18 @@ impl Catalog { .into_iter() .filter(|permission| declared.contains(permission.as_str())) .collect(); + let installers = manifest + .agents() + .iter() + .map(|agent| (agent.id.clone(), manifest.agent_installers(&agent.id))) + .collect(); plugins.insert( manifest.id().to_string(), PluginAgents { + version: manifest.version().to_string(), agents: manifest.agents().to_vec(), granted, + installers, }, ); } @@ -150,7 +164,11 @@ impl Catalog { .iter() .flat_map(|(plugin_id, plugin)| { plugin.agents.iter().map(move |agent| { - let mut entry = catalog_entry(plugin_id, agent); + let installers = plugin + .installers + .get(&agent.id) + .map_or(&[][..], Vec::as_slice); + let mut entry = catalog_entry(plugin_id, agent, installers); entry["mayRun"] = json!(plugin.may_run()); entry["mayReadSessions"] = json!(plugin.may_read_sessions()); if agent.configuration.is_some() { @@ -169,6 +187,7 @@ impl Catalog { let agent = plugin.agents.iter().find(|agent| agent.id == agent_id)?; Some(CatalogAgent { plugin_id: plugin_id.to_string(), + plugin_version: plugin.version.clone(), agent: agent.clone(), may_run: plugin.may_run(), may_read_sessions: plugin.may_read_sessions(), @@ -191,6 +210,7 @@ impl Catalog { .flat_map(|(plugin_id, plugin)| { plugin.agents.iter().map(move |agent| CatalogAgent { plugin_id: plugin_id.clone(), + plugin_version: plugin.version.clone(), agent: agent.clone(), may_run: plugin.may_run(), may_read_sessions: true, @@ -214,6 +234,7 @@ impl Catalog { .filter(|agent| agent.configuration.is_some()) .map(move |agent| CatalogAgent { plugin_id: plugin_id.clone(), + plugin_version: plugin.version.clone(), agent: agent.clone(), may_run: plugin.may_run(), may_read_sessions: plugin.may_read_sessions(), diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 2ae3836b..c996c9a9 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. `agents.cliVersions` compares +//! each CLI the host found installed with the newest version its plugin +//! reports (the `versions` module). Backends reach it with //! `lithe/host/agents/*` requests, which the engine hands to the installed //! [`AgentHost`] and which never reach the host application. //! @@ -45,6 +47,7 @@ mod library; mod live; mod projection; mod records; +mod versions; #[cfg(test)] mod tests; @@ -62,15 +65,17 @@ use serde_json::Value; use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use std::time::{SystemTime, UNIX_EPOCH}; +use versions::Versions; -/// The agent catalog, the live sessions, the session records and the -/// agent library. +/// The agent catalog, the live sessions, the session records, the agent +/// library and the CLI versions. pub(crate) struct Runtime { pub link: Arc, pub catalog: Catalog, pub live: Live, pub records: Records, pub library: Library, + pub versions: Versions, } impl Runtime { @@ -81,6 +86,7 @@ impl Runtime { live: Live::default(), records: Records::default(), library: Library::default(), + versions: Versions::default(), }) } @@ -93,6 +99,7 @@ impl Runtime { "agents.configure" => { let answer = self.catalog.configure(payload)?; self.live.queue.views.purge_unreadable(&self.catalog); + self.versions.retain(self); // A session whose agent is gone or no longer granted ends. self.live.end_where(|plugin_id, agent_id| { self.catalog @@ -102,6 +109,7 @@ impl Runtime { Ok(answer) } "agents.catalog" => Ok(self.catalog.list()), + "agents.cliVersions" => self.versions.read(self, payload), "agents.sessions" => Ok(self.live.list()), "agents.start" => live::start(self, payload), "agents.prompt" => live::prompt(self, payload), diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 97a59f3a..7ad72050 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -2508,6 +2508,7 @@ fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { mod library; mod providers; mod sessions; +mod versions; #[test] fn turn_interaction_follows_the_shared_application_fixture() { diff --git a/rust/crates/agent-runtime/src/tests/versions.rs b/rust/crates/agent-runtime/src/tests/versions.rs new file mode 100644 index 00000000..309c09ce --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/versions.rs @@ -0,0 +1,539 @@ +//! The versions of the agents' CLIs (`agents.cliVersions`): when Core asks +//! a plugin for the newest version, what it keeps, how it compares, and the +//! update commands it lists. Time comes from a clock the tests set, so no +//! test waits for an answer to grow stale. + +use super::*; +use crate::versions::{FRESH_MS, RETRY_MS}; +use std::sync::atomic::AtomicI64; +use std::sync::mpsc; + +const FIXTURE: &str = + include_str!("../../../../../shared/plugins/contract/v1/fixtures/agents/cli-versions.json"); +const LATEST_FUNCTION: &str = "agent.latestVersion"; +/// Where the synthetic clock starts: 2026-12-04, in milliseconds. +const START_MS: i64 = 1_764_806_400_000; + +/// The synthetic plugin with a latest-version function and an install page. +fn versions_manifest(version: &str) -> Value { + let mut manifest = manifest(); + manifest["version"] = json!(version); + manifest["agents"][0]["latestVersion"] = json!({ "function": LATEST_FUNCTION }); + manifest["agents"][0]["install"] = json!({ "url": "https://example.com/sample/install" }); + manifest +} + +fn latest_answer(version: &str) -> Value { + json!({ "format": "litheAgentLatestVersion", "version": 0, "latest": version }) +} + +/// A harness whose plugin declares `latestVersion`, answered with `latest`, +/// and whose clock the test moves. +struct Test { + harness: Harness, + now: Arc, + latest: Arc>>, +} + +impl Test { + fn new(name: &str) -> Self { + let harness = Harness::new(name, ALL_GRANTS); + harness.configure(&versions_manifest("1.0.0"), ALL_GRANTS); + let now = Arc::new(AtomicI64::new(START_MS)); + let clock = now.clone(); + harness + .runtime + .versions + .set_clock(move || clock.load(Ordering::SeqCst)); + let latest = Arc::new(Mutex::new(Ok(latest_answer("1.5.0")))); + let answer = latest.clone(); + harness.link.set_answer(move |function, params| { + if function == LATEST_FUNCTION { + answer.lock().unwrap().clone() + } else { + sample_backend(function, params) + } + }); + Self { + harness, + now, + latest, + } + } + + fn answer_with(&self, answer: Result) { + *self.latest.lock().unwrap() = answer; + } + + fn advance(&self, milliseconds: i64) { + self.now.fetch_add(milliseconds, Ordering::SeqCst); + } + + fn calls(&self) -> usize { + self.harness.link.calls_of(LATEST_FUNCTION).len() + } + + fn tool_path(&self) -> String { + path_text(&self.harness.tool) + } + + fn query(&self, installed: &str, check: &str) -> Value { + json!({ + "agents": [{ "agent": AGENT_KEY, "installedVersion": installed, "toolPath": self.tool_path() }], + "check": check, + }) + } + + fn versions(&self, installed: &str, check: &str) -> Value { + let answer = self + .harness + .run("agents.cliVersions", self.query(installed, check)); + answer["agents"][0].clone() + } +} + +impl Harness { + fn configure(&self, manifest: &Value, grants: &[&str]) -> Value { + self.run( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": grants }] }), + ) + } +} + +/// Runs `body` as a request no user started. +fn in_background(body: impl FnOnce() -> T) -> T { + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let value = body(); + trace::replace(previous); + value +} + +#[test] +fn comparisons_follow_the_contract_fixture() { + let fixture: Value = serde_json::from_str(FIXTURE).unwrap(); + for case in fixture["comparisons"].as_array().unwrap() { + let installed = case["installed"].as_str().unwrap(); + let latest = case["latest"].as_str().unwrap(); + assert_eq!( + crate::versions::compare_for_test(installed, latest), + case["comparison"], + "{installed} against {latest}" + ); + } +} + +#[test] +fn answers_follow_the_contract_fixture() { + let test = Test::new("versions answers"); + let fixture: Value = serde_json::from_str(FIXTURE).unwrap(); + for case in fixture["answers"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + test.answer_with(Ok(case["answer"].clone())); + let entry = test.versions("1.0.0", "now"); + match case.get("latest") { + Some(expected) => { + let mut latest = entry["latest"].clone(); + assert_eq!(latest["checkedAtMs"], json!(START_MS), "{name}"); + assert_eq!(latest["stale"], json!(false), "{name}"); + let shown = latest.as_object_mut().unwrap(); + shown.remove("checkedAtMs"); + shown.remove("stale"); + assert_eq!(&latest, expected, "{name}"); + assert!(entry.get("checkFailed").is_none(), "{name}"); + } + None => assert_eq!( + entry["checkFailed"]["code"], "agents.invalidLatestVersion", + "{name}: {entry}" + ), + } + } +} + +/// `cached` never asks; `ifStale` asks once and again only after the answer +/// is six hours old; `now` asks every time. +#[test] +fn plugins_are_asked_only_when_due_or_when_the_user_asks() { + let test = Test::new("versions due"); + let cached = test.versions("1.4.0", "cached"); + assert_eq!(test.calls(), 0); + assert!(cached.get("latest").is_none()); + assert_eq!(cached["checksLatestVersion"], true); + assert_eq!(cached["updateAvailable"], false); + + let first = test.versions("1.4.0", "ifStale"); + assert_eq!(test.calls(), 1); + assert_eq!(first["latest"]["version"], "1.5.0"); + assert_eq!(first["comparison"], "older"); + assert_eq!(first["updateAvailable"], true); + + test.advance(FRESH_MS - 1); + let fresh = test.versions("1.4.0", "ifStale"); + assert_eq!(test.calls(), 1, "a fresh answer is not asked again"); + assert_eq!(fresh["latest"]["stale"], false); + assert_eq!( + test.versions("1.4.0", "cached")["latest"]["version"], + "1.5.0", + "cached reads what was kept" + ); + + test.advance(1); + assert_eq!( + test.versions("1.4.0", "cached")["latest"]["stale"], + true, + "six hours later the answer is stale" + ); + test.answer_with(Ok(latest_answer("1.6.0"))); + let again = test.versions("1.4.0", "ifStale"); + assert_eq!(test.calls(), 2); + assert_eq!(again["latest"]["version"], "1.6.0"); + assert_eq!(again["latest"]["checkedAtMs"], START_MS + FRESH_MS); + + test.versions("1.4.0", "now"); + test.versions("1.4.0", "now"); + assert_eq!(test.calls(), 4, "the user's check always asks"); +} + +#[test] +fn checking_now_is_for_the_user_only() { + let test = Test::new("versions user"); + let refused = in_background(|| { + test.harness + .refused("agents.cliVersions", test.query("1.4.0", "now")) + }); + assert_eq!(refused, "agents.userActionRequired"); + assert_eq!(test.calls(), 0); + + // The host's check when its agents page opens may come from any origin; + // the answers Core keeps bound it to once per interval. + let opened = in_background(|| test.versions("1.4.0", "ifStale")); + assert_eq!(opened["latest"]["version"], "1.5.0"); + in_background(|| test.versions("1.4.0", "ifStale")); + assert_eq!(test.calls(), 1); +} + +/// A failed check keeps the last answer, says why, and is not repeated by +/// `ifStale` for fifteen minutes. +#[test] +fn a_failed_check_keeps_the_last_answer_and_rests() { + let test = Test::new("versions failure"); + test.versions("1.4.0", "now"); + test.answer_with(Err(failure("plugin.function.timeout"))); + test.advance(FRESH_MS); + let (failed, logs) = capture::run(false, || test.versions("1.4.0", "ifStale")); + assert_eq!(test.calls(), 2); + assert_eq!( + failed["latest"]["version"], "1.5.0", + "the last answer stays" + ); + assert_eq!(failed["latest"]["stale"], true); + assert_eq!(failed["updateAvailable"], true); + assert_eq!( + failed["checkFailed"], + json!({ "code": "agents.latestVersionFailed", "atMs": START_MS + FRESH_MS }) + ); + let logged = logs + .iter() + .find(|log| log.event == "agent.versions.check_failed") + .expect("the failure is logged"); + assert_eq!(logged.fields["reason"], "agents.latestVersionFailed"); + assert_eq!(logged.fields["call_code"], "plugin.function.timeout"); + assert_eq!(logged.fields["check"], "ifStale"); + + test.advance(RETRY_MS - 1); + test.versions("1.4.0", "ifStale"); + assert_eq!(test.calls(), 2, "a failure rests for fifteen minutes"); + test.advance(1); + test.answer_with(Ok(latest_answer("1.5.1"))); + let recovered = test.versions("1.4.0", "ifStale"); + assert_eq!(test.calls(), 3); + assert_eq!(recovered["latest"]["version"], "1.5.1"); + assert!(recovered.get("checkFailed").is_none()); + + test.harness.link.set_backend(None); + let stopped = test.versions("1.4.0", "now"); + assert_eq!(stopped["checkFailed"]["code"], "agents.backendUnavailable"); + assert_eq!(test.calls(), 3, "no backend, no call"); +} + +/// The plugin receives what the host found, and the answer is the +/// installation's: another tool path or another plugin build is asked anew. +#[test] +fn an_answer_belongs_to_one_installation_and_plugin_build() { + let test = Test::new("versions identity"); + test.versions("1.4.0", "ifStale"); + let params = &test.harness.link.calls_of(LATEST_FUNCTION)[0]; + assert_eq!( + params, + &json!({ + "agentID": AGENT, + "installedVersion": "1.4.0", + "toolPath": test.tool_path(), + "timeoutMilliseconds": 20000, + "maximumResponseBytes": 1048576, + }) + ); + + let elsewhere = path_text(&test.harness.dir.path().join("other").join("sample-cli")); + let query = |check: &str| { + json!({ + "agents": [{ "agent": AGENT_KEY, "installedVersion": "1.4.0", "toolPath": elsewhere }], + "check": check, + }) + }; + let other = test.harness.run("agents.cliVersions", query("cached")); + assert!( + other["agents"][0].get("latest").is_none(), + "another installation has no answer yet" + ); + test.harness.run("agents.cliVersions", query("ifStale")); + assert_eq!(test.calls(), 2); + + // A new build of the plugin is asked again; an agent the catalog no + // longer has keeps nothing. + test.harness + .configure(&versions_manifest("1.1.0"), ALL_GRANTS); + assert!(test.versions("1.4.0", "cached").get("latest").is_none()); + test.versions("1.4.0", "ifStale"); + assert_eq!(test.calls(), 3); + test.harness.configure(&manifest(), ALL_GRANTS); + test.harness + .configure(&versions_manifest("1.1.0"), ALL_GRANTS); + assert!(test.versions("1.4.0", "cached").get("latest").is_none()); +} + +/// `updates` lists the agents behind the newest version with the update +/// command the host runs, only where the user may run the agent. +#[test] +fn updates_list_the_agents_behind_with_their_commands() { + let test = Test::new("versions updates"); + let answer = test + .harness + .run("agents.cliVersions", test.query("1.4.0", "ifStale")); + assert_eq!( + answer["updates"], + json!([{ + "agent": AGENT_KEY, + "displayName": "Sample Agent", + "from": "1.4.0", + "to": "1.5.0", + "arguments": ["update"], + }]) + ); + assert_eq!( + answer["agents"][0]["update"], + json!({ "arguments": ["update"] }) + ); + + for (installed, comparison) in [ + ("1.5.0", "same"), + ("v1.5.0", "same"), + ("1.6.0-alpha.1", "newer"), + ("nightly", "different"), + ] { + let answer = test + .harness + .run("agents.cliVersions", test.query(installed, "cached")); + assert_eq!(answer["agents"][0]["comparison"], comparison, "{installed}"); + assert_eq!(answer["agents"][0]["updateAvailable"], false, "{installed}"); + assert_eq!(answer["updates"], json!([]), "{installed}"); + } + + // Without an installed version there is nothing to compare. + let unknown = test.harness.run( + "agents.cliVersions", + json!({ "agents": [{ "agent": AGENT_KEY, "toolPath": test.tool_path() }] }), + ); + assert!(unknown["agents"][0].get("comparison").is_none()); + assert_eq!(unknown["updates"], json!([])); + + // An agent without an update command is behind, but has no command. + let mut no_update = versions_manifest("1.0.0"); + no_update["agents"][0] + .as_object_mut() + .unwrap() + .remove("update"); + test.harness.configure(&no_update, ALL_GRANTS); + let behind = test + .harness + .run("agents.cliVersions", test.query("1.4.0", "cached")); + assert_eq!(behind["agents"][0]["updateAvailable"], true); + assert!(behind["agents"][0].get("update").is_none()); + assert_eq!(behind["updates"], json!([])); + + // A plugin not granted agents.run is neither asked nor offered. + test.harness.configure( + &versions_manifest("1.0.0"), + &["agents.native", "backend.launch"], + ); + let denied = test + .harness + .run("agents.cliVersions", test.query("1.4.0", "now")); + assert_eq!(denied["agents"][0]["mayRun"], false); + assert_eq!( + denied["agents"][0]["checkFailed"]["code"], + "agents.runNotGranted" + ); + assert_eq!(denied["updates"], json!([])); + assert_eq!(test.calls(), 1); +} + +/// An agent that declares no `latestVersion` is listed, never asked. +#[test] +fn an_agent_without_the_function_is_never_asked() { + let test = Test::new("versions undeclared"); + test.harness.configure(&manifest(), ALL_GRANTS); + let entry = test.versions("1.4.0", "now"); + assert_eq!(entry["checksLatestVersion"], false); + assert!(entry.get("latest").is_none()); + assert!(entry.get("checkFailed").is_none()); + assert_eq!(test.calls(), 0); +} + +#[test] +fn malformed_requests_are_refused_before_any_check() { + let test = Test::new("versions requests"); + let tool = test.tool_path(); + let refused = |payload: Value| { + capture::run(false, || { + test.harness.refused("agents.cliVersions", payload) + }) + }; + for (payload, code) in [ + (json!({ "agents": [] }), "agents.invalidVersionQuery"), + ( + json!({ "agents": vec![json!({ "agent": AGENT_KEY }); 2] }), + "agents.invalidVersionQuery", + ), + ( + json!({ "agents": (0..65).map(|n| json!({ "agent": format!("{PLUGIN}/a{n}") })).collect::>() }), + "agents.invalidVersionQuery", + ), + ( + json!({ "agents": [{ "agent": AGENT_KEY, "installedVersion": "1.4.0 (stable)" }] }), + "agents.invalidVersionQuery", + ), + ( + json!({ "agents": [{ "agent": AGENT_KEY, "installedVersion": "" }] }), + "agents.invalidVersionQuery", + ), + ( + json!({ "agents": [{ "agent": AGENT_KEY, "toolPath": "bin/sample-cli" }] }), + "agents.invalidVersionQuery", + ), + ( + json!({ "agents": [{ "agent": AGENT_KEY, "toolPath": format!("{tool}\u{0}") }] }), + "agents.invalidVersionQuery", + ), + ( + json!({ "agents": [{ "agent": format!("{PLUGIN}/missing") }] }), + "agents.unknownAgent", + ), + ( + json!({ "agents": [{ "agent": AGENT_KEY }], "check": "always" }), + "agents.invalidPayload", + ), + ( + json!({ "agents": [{ "agent": AGENT_KEY, "path": tool }] }), + "agents.invalidPayload", + ), + ] { + let (code_seen, logs) = refused(payload.clone()); + assert_eq!(code_seen, code, "{payload}"); + assert!( + logs.iter().any( + |log| log.event == "agent.versions.read_failed" && log.fields["reason"] == code + ), + "{payload}" + ); + } + assert_eq!(test.calls(), 0); +} + +/// Logs carry IDs, the check, the comparison, counts and durations; never +/// a version, a path or a URL. +#[test] +fn logs_carry_no_version_path_or_url() { + let test = Test::new("versions logs"); + test.answer_with(Ok(json!({ + "format": "litheAgentLatestVersion", + "version": 0, + "latest": "1.5.0", + "releaseNotesUrl": "https://example.com/sample/1.5.0", + }))); + let (_, logs) = capture::run(true, || test.versions("1.4.0", "ifStale")); + let finished = logs + .iter() + .find(|log| log.event == "agent.versions.check_finished") + .expect("the check is logged"); + assert_eq!(finished.fields["comparison"], "older"); + assert_eq!(finished.fields["plugin"], PLUGIN); + assert_eq!(finished.fields["agent"], AGENT); + let read = logs + .iter() + .find(|log| log.event == "agent.versions.read_finished") + .expect("the read is logged"); + assert_eq!(read.fields["checked"], 1); + assert_eq!(read.fields["updates"], 1); + let text = + serde_json::to_string(&logs.iter().map(|log| &log.fields).collect::>()).unwrap(); + for secret in ["1.4.0", "1.5.0", "example.com", &test.tool_path()] { + assert!(!text.contains(secret), "{secret} is not logged: {text}"); + } +} + +/// Two requests for the same agent never ask the plugin twice: the second +/// waits for the first check or reads its answer. +#[test] +fn one_check_of_an_agent_runs_at_a_time() { + let test = Arc::new(Test::new("versions one at a time")); + let (started, started_rx) = mpsc::channel(); + let (release, release_rx) = mpsc::channel::<()>(); + let release_rx = Mutex::new(release_rx); + test.harness.link.set_answer(move |function, params| { + if function != LATEST_FUNCTION { + return sample_backend(function, params); + } + started.send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(WAIT) + .expect("the test releases the check"); + Ok(latest_answer("1.5.0")) + }); + let first = { + let test = test.clone(); + std::thread::spawn(move || in_background(|| test.versions("1.4.0", "ifStale"))) + }; + started_rx + .recv_timeout(WAIT) + .expect("the first check starts"); + let second = { + let test = test.clone(); + std::thread::spawn(move || in_background(|| test.versions("1.4.0", "ifStale"))) + }; + release.send(()).unwrap(); + let first = first.join().unwrap(); + let second = second.join().unwrap(); + assert_eq!(first["latest"]["version"], "1.5.0"); + assert_eq!(second["latest"]["version"], "1.5.0"); + assert_eq!(test.calls(), 1); +} + +/// The catalog says which agents check versions and how a missing CLI is +/// installed: the page the plugin declares and the installers of its tool. +#[test] +fn the_catalog_lists_version_checks_and_install_pages() { + let test = Test::new("versions catalog"); + let catalog = test.harness.run("agents.catalog", json!({})); + let entry = &catalog["agents"][0]; + assert_eq!(entry["checksLatestVersion"], true); + assert_eq!( + entry["install"], + json!({ "installers": [], "url": "https://example.com/sample/install" }) + ); +} diff --git a/rust/crates/agent-runtime/src/versions.rs b/rust/crates/agent-runtime/src/versions.rs new file mode 100644 index 00000000..3ea2b760 --- /dev/null +++ b/rust/crates/agent-runtime/src/versions.rs @@ -0,0 +1,705 @@ +//! The versions of the agents' CLIs (`agents.cliVersions`): the newest +//! version each plugin reports, kept for a while, compared with the version +//! the host found installed, and the update commands of the agents that are +//! behind. +//! +//! The plugin's `latestVersion` function looks the version up, not Core: +//! only the plugin knows where its CLI is published, which channel an +//! installation follows and what the answer looks like, and it uses the +//! proxy and certificates the CLI would use. Core has no HTTP client. Core +//! decides when the plugin is asked and checks what comes back: +//! +//! - Nothing is asked in the background or on a timer. `ifStale`, the +//! host's check when the user opens its agents page, asks only for an +//! agent whose last answer is older than [`FRESH_MS`], and not again +//! within [`RETRY_MS`] of a failed check; `now`, the user's own check, +//! asks for every agent named and only for a request the user started. +//! - Answers live in memory for the life of the Core process, keyed by the +//! agent and valid only for the plugin build, the function and the tool +//! path they were asked for. Nothing is written to disk, so the +//! installed package and the user's files never change. +//! - One check of an agent runs at a time; a request that finds one running +//! waits for it, bounded, and uses its answer. +//! - Core runs nothing. The answer lists the update commands of the agents +//! that are behind; the host runs each, after the user confirms it, as it +//! runs an agent's `update` today. +//! - Logs carry plugin and agent IDs, the check, the comparison, counts, +//! durations and refusal codes; never a version, a path or a URL. +//! +//! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-25-agent-native-cli-and-local-session-records.md + +mod compare; + +pub(crate) use compare::Comparison; + +use crate::catalog::CatalogAgent; +use crate::{log_fields, now_ms, Runtime}; +use lithe_lsp_engine::agent_host::AgentCallFailure; +use lithe_plugin_agents::is_page_url; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_request_context::{trace, Source}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::sync::{Arc, Condvar, Mutex, PoisonError, RwLock}; +use std::time::{Duration, Instant}; + +/// The `format` of a latest-version answer. +const ANSWER_FORMAT: &str = "litheAgentLatestVersion"; + +/// The plugin's budget for its exchange with the place the CLI is published: +/// resolving the name, connecting, sending and reading the answer. +const EXCHANGE_MILLISECONDS: u64 = 20_000; + +/// How long Core waits for the function: the exchange plus time to decide +/// where to ask and to decode the answer. +const CHECK_TIMEOUT: Duration = Duration::from_secs(30); + +/// How long a request waits for a check of the same agent that another +/// request started: the check's own wait and a margin. +const WAIT_FOR_RUNNING_CHECK: Duration = Duration::from_secs(35); + +/// The most of an answer body the plugin reads from the place it asks. +const MAXIMUM_RESPONSE_BYTES: u64 = 1024 * 1024; + +/// How long an answer stays fresh: `ifStale` does not ask again sooner. +pub(crate) const FRESH_MS: i64 = 6 * 60 * 60 * 1000; + +/// How long after a failed check `ifStale` waits before it asks again. +pub(crate) const RETRY_MS: i64 = 15 * 60 * 1000; + +/// Most agents one request names. +const MAX_QUERY_AGENTS: usize = 64; + +/// Longest version, in bytes. +const MAX_VERSION_BYTES: usize = 64; + +/// Longest tool path, in bytes. +const MAX_TOOL_PATH_BYTES: usize = 4096; + +/// The largest integer a JSON number carries exactly. +const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; + +/// When the plugin is asked. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Check { + /// Never: answer from what Core keeps. + #[default] + Cached, + /// For an agent without a fresh answer and without a recent failure. + IfStale, + /// For every agent named, for the user. + Now, +} + +impl Check { + fn name(self) -> &'static str { + match self { + Self::Cached => "cached", + Self::IfStale => "ifStale", + Self::Now => "now", + } + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + agents: Vec, + #[serde(default)] + check: Check, +} + +/// One agent the host asks about, with what its tool resolution found. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Query { + /// `/`. + agent: String, + /// The version the host's tool resolution read from the installed CLI. + #[serde(default)] + installed_version: Option, + /// The absolute path of the CLI the host resolved; it tells the plugin + /// how the CLI was installed, and so where it updates from. + #[serde(default)] + tool_path: Option, +} + +/// Whether `version` is a version as the contract writes it: 1–64 bytes of +/// ASCII letters, digits, `.`, `-`, `_` and `+`. +fn is_version(version: &str) -> bool { + !version.is_empty() + && version.len() <= MAX_VERSION_BYTES + && version + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'+')) +} + +impl Request { + /// The request's own rules; the message names the field. + fn check(&self) -> Result<(), CoreError> { + if self.agents.is_empty() || self.agents.len() > MAX_QUERY_AGENTS { + return Err(invalid_query(&format!( + "agents names 1 to {MAX_QUERY_AGENTS} agents." + ))); + } + let mut seen = BTreeSet::new(); + for (index, query) in self.agents.iter().enumerate() { + if !seen.insert(query.agent.as_str()) { + return Err(invalid_query(&format!( + "agents[{index}].agent names an agent twice." + ))); + } + if query + .installed_version + .as_deref() + .is_some_and(|version| !is_version(version)) + { + return Err(invalid_query(&format!( + "agents[{index}].installedVersion is 1 to 64 bytes of ASCII letters, digits, '.', '-', '_' and '+'." + ))); + } + if query.tool_path.as_deref().is_some_and(|path| { + path.len() > MAX_TOOL_PATH_BYTES + || path.contains('\0') + || !Path::new(path).is_absolute() + }) { + return Err(invalid_query(&format!( + "agents[{index}].toolPath is an absolute path of at most 4096 bytes without NUL." + ))); + } + } + Ok(()) + } +} + +/// What a plugin's `latestVersion` function answers. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Answer { + format: String, + version: u32, + latest: String, + #[serde(default)] + published_at_ms: Option, + #[serde(default)] + release_notes_url: Option, +} + +impl Answer { + fn is_valid(&self) -> bool { + self.format == ANSWER_FORMAT + && self.version == 0 + && is_version(&self.latest) + && self + .published_at_ms + .is_none_or(|at| (1..=MAX_SAFE_INTEGER).contains(&at)) + && self.release_notes_url.as_deref().is_none_or(is_page_url) + } +} + +/// Decodes and checks an answer; `None` for any answer that breaks the +/// contract, including one with an unknown field. +fn decode(answer: Value) -> Option { + serde_json::from_value::(answer) + .ok() + .filter(Answer::is_valid) +} + +/// The newest version a check reported. +#[derive(Debug, Clone)] +struct Latest { + version: String, + published_at_ms: Option, + release_notes_url: Option, + checked_at_ms: i64, +} + +/// What an answer was asked for. An answer of another plugin build, function +/// or tool path is not this installation's. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Identity { + plugin_version: String, + function: String, + tool_path: Option, +} + +/// A failed check. +#[derive(Debug, Clone, Copy)] +struct Failure { + code: &'static str, + at_ms: i64, +} + +/// What Core keeps of one agent. +#[derive(Debug)] +struct Entry { + identity: Identity, + latest: Option, + /// The last check, when it failed; `latest` keeps the answer before it. + failure: Option, + /// Whether a check of the agent is running. + checking: bool, +} + +impl Entry { + /// Whether `ifStale` asks again at `now`. + fn is_due(&self, now: i64) -> bool { + let stale = self + .latest + .as_ref() + .is_none_or(|latest| now.saturating_sub(latest.checked_at_ms) >= FRESH_MS); + let resting = self + .failure + .is_some_and(|failure| now.saturating_sub(failure.at_ms) < RETRY_MS); + stale && !resting + } +} + +/// The clock checks are timed by; tests replace it. +type Clock = Arc i64 + Send + Sync>; + +/// The answers Core keeps, by agent key. +pub(crate) struct Versions { + entries: Mutex>, + /// Signalled when a check ends. + checked: Condvar, + clock: RwLock, +} + +impl Default for Versions { + fn default() -> Self { + Self { + entries: Mutex::default(), + checked: Condvar::new(), + clock: RwLock::new(Arc::new(now_ms)), + } + } +} + +/// One check to make: the agent and what it is asked for. +struct Pending { + agent: CatalogAgent, + key: String, + identity: Identity, + installed_version: Option, +} + +/// What came of one check. +enum Outcome { + Answered(Latest), + Failed { + code: &'static str, + call_code: Option, + }, +} + +impl Versions { + fn now(&self) -> i64 { + (self.clock.read().unwrap_or_else(PoisonError::into_inner))() + } + + /// Replaces the clock, so tests time checks without waiting. + #[cfg(test)] + pub(crate) fn set_clock(&self, clock: impl Fn() -> i64 + Send + Sync + 'static) { + *self.clock.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(clock); + } + + /// Drops what Core keeps of agents the catalog no longer has or that no + /// longer declare `latestVersion`. A check still running keeps its entry. + pub(crate) fn retain(&self, runtime: &Runtime) { + let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner); + entries.retain(|key, entry| { + entry.checking + || runtime + .catalog + .find_key(key) + .is_some_and(|agent| agent.agent.latest_version.is_some()) + }); + } + + /// `agents.cliVersions`. + pub(crate) fn read(&self, runtime: &Runtime, payload: Value) -> Result { + let started = Instant::now(); + let outcome = self.read_checked(runtime, payload, started); + if let Err(error) = &outcome { + let reason = error.details.as_deref().unwrap_or("agents.invalidPayload"); + log_fields( + "agent.versions.read_failed", + [("reason", json!(reason))].into_iter(), + ); + } + outcome + } + + fn read_checked( + &self, + runtime: &Runtime, + payload: Value, + started: Instant, + ) -> Result { + let request: Request = crate::decode(payload)?; + if request.check == Check::Now && trace::current().source != Source::User { + return Err(refusal( + ErrorCode::PermissionDenied, + "agents.userActionRequired", + "Only the user can check the agents' CLIs for a newer version now.", + )); + } + request.check()?; + let agents = request + .agents + .iter() + .map(|query| { + runtime.catalog.find_key(&query.agent).ok_or_else(|| { + refusal( + ErrorCode::EntryNotFound, + "agents.unknownAgent", + "No configured plugin declares this agent.", + ) + }) + }) + .collect::, _>>()?; + + let mut denied = BTreeSet::new(); + let mut pending = Vec::new(); + for (query, agent) in request.agents.iter().zip(&agents) { + let Some(latest) = &agent.agent.latest_version else { + continue; + }; + if request.check == Check::Cached { + continue; + } + if !agent.may_run { + denied.insert(query.agent.clone()); + continue; + } + pending.push(Pending { + agent: agent.clone(), + key: query.agent.clone(), + identity: Identity { + plugin_version: agent.plugin_version.clone(), + function: latest.function.clone(), + tool_path: query.tool_path.clone(), + }, + installed_version: query.installed_version.clone(), + }); + } + let pending = self.claim(pending, request.check); + let checked = pending.len(); + let failed = self.run_checks(runtime, pending, request.check); + + let now = self.now(); + let entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner); + let mut views = Vec::new(); + let mut updates = Vec::new(); + for (query, agent) in request.agents.iter().zip(&agents) { + let entry = agent.agent.latest_version.as_ref().and_then(|latest| { + let identity = Identity { + plugin_version: agent.plugin_version.clone(), + function: latest.function.clone(), + tool_path: query.tool_path.clone(), + }; + entries + .get(&query.agent) + .filter(|entry| entry.identity == identity) + }); + let view = view(query, agent, entry, denied.contains(&query.agent), now); + if view["updateAvailable"] == true && agent.may_run { + if let (Some(update), Some(latest)) = ( + &agent.agent.update, + entry.and_then(|entry| entry.latest.as_ref()), + ) { + updates.push(json!({ + "agent": query.agent, + "displayName": agent.agent.display_name, + "from": query.installed_version, + "to": latest.version, + "arguments": update.arguments, + })); + } + } + views.push(view); + } + drop(entries); + log_fields( + "agent.versions.read_finished", + [ + ("check", json!(request.check.name())), + ("agents", json!(views.len())), + ("checked", json!(checked)), + ("failed", json!(failed)), + ("updates", json!(updates.len())), + ("duration_ms", json!(elapsed_ms(started))), + ] + .into_iter(), + ); + Ok(json!({ "agents": views, "updates": updates })) + } + + /// Marks the checks this request makes as running and returns them. A + /// check of the same agent that another request is running is waited + /// for, bounded, and its answer used instead. `ifStale` keeps only the + /// agents that are due. + fn claim(&self, pending: Vec, check: Check) -> Vec { + let deadline = Instant::now() + WAIT_FOR_RUNNING_CHECK; + let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner); + let mut claimed = Vec::new(); + for item in pending { + let mut waited = false; + while entries.get(&item.key).is_some_and(|entry| entry.checking) { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + waited = true; + entries = self + .checked + .wait_timeout(entries, remaining) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + let now = self.now(); + let entry = entries.get_mut(&item.key); + let wanted = match entry.as_ref() { + // Still running past the bound: this request does not start a + // second check of the same agent. + Some(entry) if entry.checking => false, + // The check this request waited for answered it. + Some(entry) if waited && entry.identity == item.identity => false, + Some(entry) if entry.identity == item.identity => { + check == Check::Now || entry.is_due(now) + } + _ => true, + }; + if !wanted { + continue; + } + match entries.get_mut(&item.key) { + Some(entry) if entry.identity == item.identity => entry.checking = true, + _ => { + entries.insert( + item.key.clone(), + Entry { + identity: item.identity.clone(), + latest: None, + failure: None, + checking: true, + }, + ); + } + } + claimed.push(item); + } + claimed + } + + /// Asks each plugin in parallel, keeps the outcomes, logs them on this + /// thread and returns how many failed. The threads only call the + /// plugins; every lock and every log stays here. + fn run_checks(&self, runtime: &Runtime, pending: Vec, check: Check) -> usize { + if pending.is_empty() { + return 0; + } + let context = trace::current(); + let outcomes: Vec<(Pending, Outcome, u64)> = std::thread::scope(|scope| { + let handles: Vec<_> = pending + .into_iter() + .map(|item| { + let context = context.clone(); + scope.spawn(move || { + let previous = trace::replace(context); + let started = Instant::now(); + let outcome = ask(runtime, &item, self.now()); + trace::replace(previous); + (item, outcome, elapsed_ms(started)) + }) + }) + .collect(); + handles + .into_iter() + .map(|handle| handle.join().expect("a version check does not panic")) + .collect() + }); + + let mut failed = 0; + let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner); + for (item, outcome, duration) in outcomes { + let mut fields = vec![ + ("plugin", json!(item.agent.plugin_id)), + ("agent", json!(item.agent.agent.id)), + ("check", json!(check.name())), + ]; + let entry = entries.entry(item.key.clone()).or_insert_with(|| Entry { + identity: item.identity.clone(), + latest: None, + failure: None, + checking: false, + }); + entry.checking = false; + if entry.identity != item.identity { + entry.identity = item.identity.clone(); + entry.latest = None; + entry.failure = None; + } + match outcome { + Outcome::Answered(latest) => { + if let Some(installed) = &item.installed_version { + fields.push(( + "comparison", + json!(compare::compare(installed, &latest.version).name()), + )); + } + entry.latest = Some(latest); + entry.failure = None; + fields.push(("duration_ms", json!(duration))); + log_fields("agent.versions.check_finished", fields.into_iter()); + } + Outcome::Failed { code, call_code } => { + failed += 1; + entry.failure = Some(Failure { + code, + at_ms: self.now(), + }); + fields.push(("reason", json!(code))); + if let Some(call_code) = call_code.as_deref().and_then(log_token) { + fields.push(("call_code", json!(call_code))); + } + fields.push(("duration_ms", json!(duration))); + log_fields("agent.versions.check_failed", fields.into_iter()); + } + } + } + drop(entries); + self.checked.notify_all(); + failed + } +} + +/// Calls the agent's `latestVersion` function once, holding no lock. +fn ask(runtime: &Runtime, item: &Pending, now: i64) -> Outcome { + let failed = + |code: &'static str, call_code: Option| Outcome::Failed { code, call_code }; + let function = item.identity.function.as_str(); + let link = &*runtime.link; + let Some(backend) = link.session_for(&item.agent.plugin_id, function, None) else { + return failed("agents.backendUnavailable", None); + }; + let mut params = json!({ + "agentID": item.agent.agent.id, + "timeoutMilliseconds": EXCHANGE_MILLISECONDS, + "maximumResponseBytes": MAXIMUM_RESPONSE_BYTES, + }); + if let Some(installed) = &item.installed_version { + params["installedVersion"] = json!(installed); + } + if let Some(path) = &item.identity.tool_path { + params["toolPath"] = json!(path); + } + match link.call( + &backend, + &item.agent.plugin_id, + function, + params, + CHECK_TIMEOUT, + ) { + Err(AgentCallFailure { code, .. }) => failed("agents.latestVersionFailed", Some(code)), + Ok(answer) => match decode(answer) { + Some(answer) => Outcome::Answered(Latest { + version: answer.latest, + published_at_ms: answer.published_at_ms, + release_notes_url: answer.release_notes_url, + checked_at_ms: now, + }), + None => failed("agents.invalidLatestVersion", None), + }, + } +} + +/// One agent of the answer. +fn view( + query: &Query, + agent: &CatalogAgent, + entry: Option<&Entry>, + denied: bool, + now: i64, +) -> Value { + let mut view = json!({ + "agent": query.agent, + "pluginID": agent.plugin_id, + "agentID": agent.agent.id, + "displayName": agent.agent.display_name, + "checksLatestVersion": agent.agent.latest_version.is_some(), + "mayRun": agent.may_run, + "updateAvailable": false, + }); + if let Some(installed) = &query.installed_version { + view["installedVersion"] = json!(installed); + } + if let Some(update) = &agent.agent.update { + view["update"] = json!({ "arguments": update.arguments }); + } + if denied { + view["checkFailed"] = json!({ "code": "agents.runNotGranted", "atMs": now }); + } + let Some(entry) = entry else { + return view; + }; + if let Some(latest) = &entry.latest { + let mut shown = json!({ + "version": latest.version, + "checkedAtMs": latest.checked_at_ms, + "stale": now.saturating_sub(latest.checked_at_ms) >= FRESH_MS, + }); + if let Some(at) = latest.published_at_ms { + shown["publishedAtMs"] = json!(at); + } + if let Some(url) = &latest.release_notes_url { + shown["releaseNotesUrl"] = json!(url); + } + view["latest"] = shown; + if let Some(installed) = &query.installed_version { + let comparison = compare::compare(installed, &latest.version); + view["comparison"] = json!(comparison); + view["updateAvailable"] = json!(comparison == Comparison::Older); + } + } + if let Some(failure) = entry.failure.filter(|_| !denied) { + view["checkFailed"] = json!({ "code": failure.code, "atMs": failure.at_ms }); + } + view +} + +fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { + CoreError::new(code, message).with_details(details) +} + +fn invalid_query(message: &str) -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agents.invalidVersionQuery", + message, + ) +} + +fn elapsed_ms(started: Instant) -> u64 { + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +/// 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) +} + +#[cfg(test)] +pub(crate) fn compare_for_test(installed: &str, latest: &str) -> &'static str { + compare::compare(installed, latest).name() +} diff --git a/rust/crates/agent-runtime/src/versions/compare.rs b/rust/crates/agent-runtime/src/versions/compare.rs new file mode 100644 index 00000000..b34b6483 --- /dev/null +++ b/rust/crates/agent-runtime/src/versions/compare.rs @@ -0,0 +1,160 @@ +//! How Core tells whether an installed agent CLI is older than the newest +//! version its plugin reported. +//! +//! Both versions are read as semantic versions first: an optional `v`, one +//! to four dot-separated decimal numbers (missing ones count as 0, so `1.2` +//! is `1.2.0`), an optional `-` pre-release of dot-separated identifiers and +//! an optional `+` build, which is ignored. Precedence follows Semantic +//! Versioning 2.0.0, section 11. A version that does not read this way is +//! compared as text and only for equality, so Core never claims an order it +//! cannot know. + +use serde::Serialize; +use std::cmp::Ordering; + +/// Most numbers in the dotted part of a version. +const MAX_NUMBERS: usize = 4; + +/// Most digits of one number, which keeps every number within `u64`. +const MAX_DIGITS: usize = 19; + +/// How the installed version compares with the newest one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum Comparison { + /// The installed version precedes the newest: there is an update. + Older, + /// The two are the same version. + Same, + /// The installed version follows the newest one, such as a pre-release + /// of the next version. + Newer, + /// At least one of the two is not a semantic version and the two differ + /// as text, so their order is unknown. + Different, +} + +impl Comparison { + /// The token the answer and the log use. + pub(crate) fn name(self) -> &'static str { + match self { + Self::Older => "older", + Self::Same => "same", + Self::Newer => "newer", + Self::Different => "different", + } + } +} + +/// A version read as a semantic version. +struct Parsed<'a> { + /// The dotted numbers, padded with zeros to [`MAX_NUMBERS`]. + numbers: [u64; MAX_NUMBERS], + /// The pre-release identifiers; empty for a release. + pre_release: Vec<&'a str>, +} + +/// Compares `installed` with `latest`. +pub(crate) fn compare(installed: &str, latest: &str) -> Comparison { + let installed = without_prefix(installed); + let latest = without_prefix(latest); + match (parse(installed), parse(latest)) { + (Some(installed), Some(latest)) => match precedence(&installed, &latest) { + Ordering::Less => Comparison::Older, + Ordering::Equal => Comparison::Same, + Ordering::Greater => Comparison::Newer, + }, + _ if installed == latest => Comparison::Same, + _ => Comparison::Different, + } +} + +/// The version without one leading `v` or `V`. +fn without_prefix(version: &str) -> &str { + version + .strip_prefix('v') + .or_else(|| version.strip_prefix('V')) + .unwrap_or(version) +} + +fn parse(version: &str) -> Option> { + let (rest, build) = match version.split_once('+') { + Some((rest, build)) => (rest, Some(build)), + None => (version, None), + }; + if build.is_some_and(|build| !identifiers(build)) { + return None; + } + let (core, pre_release) = match rest.split_once('-') { + Some((core, pre_release)) => (core, Some(pre_release)), + None => (rest, None), + }; + if pre_release.is_some_and(|pre_release| !identifiers(pre_release)) { + return None; + } + let parts: Vec<&str> = core.split('.').collect(); + if parts.len() > MAX_NUMBERS { + return None; + } + let mut numbers = [0; MAX_NUMBERS]; + for (slot, part) in numbers.iter_mut().zip(&parts) { + if part.is_empty() || part.len() > MAX_DIGITS || !part.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + *slot = part.parse().ok()?; + } + Some(Parsed { + numbers, + pre_release: pre_release.map_or_else(Vec::new, |p| p.split('.').collect()), + }) +} + +/// Whether `text` is dot-separated nonempty identifiers of ASCII letters, +/// digits and `-`. +fn identifiers(text: &str) -> bool { + text.split('.').all(|identifier| { + !identifier.is_empty() + && identifier + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + }) +} + +/// Semantic Versioning 2.0.0, section 11, over [`Parsed`]. +fn precedence(left: &Parsed<'_>, right: &Parsed<'_>) -> Ordering { + left.numbers.cmp(&right.numbers).then_with(|| { + match (left.pre_release.is_empty(), right.pre_release.is_empty()) { + (true, true) => Ordering::Equal, + // A release follows its pre-releases. + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + (false, false) => pre_release_precedence(&left.pre_release, &right.pre_release), + } + }) +} + +/// Identifier by identifier: numeric ones by value, others in ASCII order, a +/// numeric one before an alphanumeric one; when one list is a prefix of the +/// other, the longer one follows. +fn pre_release_precedence(left: &[&str], right: &[&str]) -> Ordering { + for (left, right) in left.iter().zip(right) { + let numeric = |identifier: &str| identifier.bytes().all(|b| b.is_ascii_digit()); + let order = match (numeric(left), numeric(right)) { + (true, true) => numeric_order(left, right), + (true, false) => Ordering::Less, + (false, true) => Ordering::Greater, + (false, false) => left.cmp(right), + }; + if order != Ordering::Equal { + return order; + } + } + left.len().cmp(&right.len()) +} + +/// Orders two decimal numbers of any length by value. +fn numeric_order(left: &str, right: &str) -> Ordering { + let left = left.trim_start_matches('0'); + let right = right.trim_start_matches('0'); + left.len().cmp(&right.len()).then_with(|| left.cmp(right)) +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 45cc3444..f7b2ab4c 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -248,6 +248,10 @@ pub enum AgentsCommand { WaitEvents, /// Reads or releases a bounded Agent conversation view. Projection, + /// Compares each installed agent CLI with the newest version its plugin + /// reports, with the update commands of the agents behind + /// (`agents.cliVersions`). + CliVersions, /// Opens the session record cache (`agentSessions.configure`). RecordsConfigure, /// Reads one agent's changed session files through its plugin (`agentSessions.sync`). @@ -319,6 +323,7 @@ impl AgentsCommand { Self::Close => "agents.close", Self::WaitEvents => "agents.waitEvents", Self::Projection => "agents.projection", + Self::CliVersions => "agents.cliVersions", Self::RecordsConfigure => "agentSessions.configure", Self::RecordsSync => "agentSessions.sync", Self::RecordsForget => "agentSessions.forget", @@ -1348,6 +1353,7 @@ impl CoreCommand { "agents.close" => Some(Self::Agents(AgentsCommand::Close)), "agents.waitEvents" => Some(Self::Agents(AgentsCommand::WaitEvents)), "agents.projection" => Some(Self::Agents(AgentsCommand::Projection)), + "agents.cliVersions" => Some(Self::Agents(AgentsCommand::CliVersions)), "agentSessions.configure" => Some(Self::Agents(AgentsCommand::RecordsConfigure)), "agentSessions.sync" => Some(Self::Agents(AgentsCommand::RecordsSync)), "agentSessions.forget" => Some(Self::Agents(AgentsCommand::RecordsForget)), diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index e534f272..1196c516 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -304,7 +304,10 @@ fn agents_are_reviewed_programs() { .filter(|program| { matches!( program["kind"].as_str(), - Some("agent") | Some("agentSessions") | Some("agentConfiguration") + Some("agent") + | Some("agentLatestVersion") + | Some("agentSessions") + | Some("agentConfiguration") ) }) .cloned() @@ -325,6 +328,7 @@ fn agents_are_reviewed_programs() { "skills": ["${userHome}/.example/skills"], "providers": {"operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setEffort", "setSpeed", "setModelMenu", "setProvider"]} }), + json!({"kind": "agentLatestVersion", "agentID": "example", "tool": "example-agent", "function": "example.latestVersion"}), json!({ "kind": "agentSessions", "agentID": "example", diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 17195436..ce8c47e2 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -380,6 +380,68 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.versions.check_failed", + channel: "agent", + level: LogLevel::Warn, + message: "Checking the newest version of an agent CLI failed", + 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 agents.latestVersionFailed, such as plugin.function.timeout", reason: None }, + FieldMetadata { name: "check", field_type: FieldType::Token, required: true, description: "Why the plugin was asked: ifStale or now", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the check took, including the plugin function call when a backend was running", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code: agents.backendUnavailable, agents.latestVersionFailed or agents.invalidLatestVersion; never versions, paths, URLs or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.versions.check_finished", + channel: "agent", + level: LogLevel::Info, + message: "An agent plugin reported the newest version of its CLI", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "check", field_type: FieldType::Token, required: true, description: "Why the plugin was asked: ifStale (the host's check when its agents page opens, for an answer older than six hours) or now (the user asked)", reason: None }, + FieldMetadata { name: "comparison", field_type: FieldType::Token, required: false, description: "How the installed version compares with the newest: older, same, newer or different; absent when the host gave no installed version. Never a version itself", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the plugin function took", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.versions.read_failed", + channel: "agent", + level: LogLevel::Warn, + message: "A request for agent CLI versions was refused", + fields: &[ + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code such as agents.invalidVersionQuery, agents.unknownAgent or agents.userActionRequired; never versions, paths or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.versions.read_finished", + channel: "agent", + level: LogLevel::Debug, + message: "Agent CLI versions read", + fields: &[ + FieldMetadata { name: "agents", field_type: FieldType::Int, required: true, description: "Agents the host asked about", reason: None }, + FieldMetadata { name: "check", field_type: FieldType::Token, required: true, description: "When plugins were asked: cached, ifStale or now", reason: None }, + FieldMetadata { name: "checked", field_type: FieldType::Int, required: true, description: "Agents whose plugin this request asked", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took, including plugin calls", reason: None }, + FieldMetadata { name: "failed", field_type: FieldType::Int, required: true, description: "Checks of this request that failed", reason: None }, + FieldMetadata { name: "updates", field_type: FieldType::Int, required: true, description: "Agents behind the newest version with an update command the user may run", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "app.action.performed", channel: "app", diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index d97356ab..f1499bad 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -17,6 +17,12 @@ //! that the ID is safe as one command-line argument. //! - `update.arguments` runs `tool` to update itself, after the user //! confirms. +//! - `latestVersion.function` is a backend function that answers the newest +//! version of the CLI, from where the CLI would update. Only the plugin +//! knows that place and how to ask it; Core decides when it is asked, +//! checks the answer and keeps it. `install.url` is the page that explains +//! how to install the CLI; the commands that install it are the plugin's +//! command installers for the commands of `tool`. //! - `sessionSources` names the directories of the CLI's session files and //! the backend functions that parse and display them. Core reads the files //! only after the user consents, per agent. @@ -138,6 +144,12 @@ pub struct AgentDeclaration { /// How the user updates the CLI. #[serde(default, skip_serializing_if = "Option::is_none")] pub update: Option, + /// The backend function that answers the newest version of the CLI. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub latest_version: Option, + /// Where the user reads how to install the CLI when it is missing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub install: Option, /// Where the CLI keeps its session files. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub session_sources: Vec, @@ -338,6 +350,55 @@ pub struct UpdateDeclaration { pub arguments: Vec, } +/// How Core learns the newest version of the agent's CLI: a backend +/// function, because only the plugin knows where the CLI is published and +/// how its installation updates. Core calls it only when the host asks, at +/// most once per check interval unless the user asks again. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LatestVersionDeclaration { + /// The backend function that answers the newest version. + pub function: String, +} + +/// How the user installs the agent's CLI when it is missing. The commands +/// that install it are the plugin's command installers for the commands of +/// the agent's tool; this adds the page that explains it. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct InstallDeclaration { + /// An `https` page about installing the CLI, which the host opens only + /// when the user clicks it; see [`is_page_url`]. + pub url: String, +} + +/// Longest page URL an agent declaration or a latest-version answer may +/// carry, in bytes. +pub const MAX_PAGE_URL_BYTES: usize = 2048; + +/// Whether `url` is a page Lithe may open in the browser for the user: an +/// `https` URL with a host, no user or password and no fragment, without a +/// space or control character, at most [`MAX_PAGE_URL_BYTES`]. A query is +/// allowed. The host opens it only on the user's click. +pub fn is_page_url(url: &str) -> bool { + if url.len() > MAX_PAGE_URL_BYTES + || url + .chars() + .any(|c| c.is_control() || c.is_whitespace() || c == '#') + { + return false; + } + let Some(rest) = url.strip_prefix("https://") else { + return false; + }; + let authority = rest.split(['/', '?']).next().unwrap_or_default(); + let host = authority.strip_prefix('[').map_or_else( + || authority.split(':').next().unwrap_or_default(), + |v6| v6.split(']').next().unwrap_or_default(), + ); + !authority.contains('@') && !host.is_empty() +} + /// The format of a session source's files. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -375,11 +436,12 @@ pub struct DeclarationContext<'a> { impl AgentDeclaration { /// Whether Core starts the backend for this agent: a native session, a - /// session source or configuration files are served by backend functions. - /// A terminal or ACP agent alone runs only its tool. + /// session source, configuration files or the latest version are served + /// by backend functions. A terminal or ACP agent alone runs only its tool. pub fn needs_backend(&self) -> bool { self.native.is_some() || !self.session_sources.is_empty() + || self.latest_version.is_some() || self.configuration.as_ref().is_some_and(|configuration| { configuration.read.is_some() || configuration.providers.is_some() }) @@ -495,6 +557,22 @@ pub fn validate_declarations( )); } } + if let Some(latest) = &agent.latest_version { + if !is_function_id(&latest.function) { + return Err(invalid( + format!("{field}.latestVersion.function"), + "A latest-version function ID is dot-separated lowerCamelCase segments.", + )); + } + } + if let Some(install) = &agent.install { + if !is_page_url(&install.url) { + return Err(invalid( + format!("{field}.install.url"), + "An install page is an https URL with a host, without a user, password, fragment, space or control character, at most 2048 bytes.", + )); + } + } check_session_sources(&agent.session_sources, &field)?; if let Some(configuration) = &agent.configuration { check_configuration(configuration, &format!("{field}.configuration"))?; @@ -502,7 +580,7 @@ pub fn validate_declarations( if agent.needs_backend() && !context.has_backend { return Err(invalid( field, - "Native sessions, session sources and configuration files are served by the plugin backend.", + "Native sessions, session sources, configuration files and the latest version are served by the plugin backend.", )); } } @@ -948,9 +1026,11 @@ pub fn launch_params(agent_id: &str, cwd: &str, resume: Option<&str>) -> Value { params } -/// What the host shows of one agent: its forms and how it updates. The -/// session functions stay inside Core. -pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { +/// What the host shows of one agent: its forms, how it updates and how it is +/// installed. The session and version functions stay inside Core. +/// `installers` are the IDs of the plugin's command installers that provide +/// a command of the agent's tool, which the manifest knows. +pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration, installers: &[String]) -> Value { let mut entry = json!({ "pluginID": plugin_id, "agentID": agent.id, @@ -959,7 +1039,14 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { "modes": modes(agent), "forms": forms(agent), "readsSessions": !agent.session_sources.is_empty(), + "checksLatestVersion": agent.latest_version.is_some(), }); + if !installers.is_empty() || agent.install.is_some() { + entry["install"] = json!({ "installers": installers }); + if let Some(install) = &agent.install { + entry["install"]["url"] = json!(install.url); + } + } if let Some(configuration) = &agent.configuration { entry["configuration"] = json!({ "instructions": configuration.instructions.is_some(), @@ -991,9 +1078,10 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { } /// The programs an agent runs, for the install review: each form with its -/// fixed arguments, the update command, and where its session records are -/// read. A native launch's arguments come from the backend at start, so the -/// entry names the function that decides them. +/// fixed arguments, the update command, the function that looks up the +/// newest version over the network, and where its session records are read. +/// A native launch's arguments come from the backend at start, so the entry +/// names the function that decides them. pub fn programs(agent: &AgentDeclaration) -> Vec { let entry = |form: &str| { json!({ @@ -1030,6 +1118,16 @@ pub fn programs(agent: &AgentDeclaration) -> Vec { programs.push(program); } } + // The backend reaches the network to look the version up, so the user + // sees the function before installing the plugin. + if let Some(latest) = &agent.latest_version { + programs.push(json!({ + "kind": "agentLatestVersion", + "agentID": agent.id, + "tool": agent.tool, + "function": latest.function, + })); + } for source in &agent.session_sources { programs.push(json!({ "kind": "agentSessions", diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs index ad9e4b17..474575d3 100644 --- a/rust/crates/plugin-agents/src/tests.rs +++ b/rust/crates/plugin-agents/src/tests.rs @@ -227,7 +227,7 @@ fn launch_answer_runs_only_the_agent_tool() { #[test] fn catalog_entry_hides_session_functions() { - let entry = catalog_entry("dev.lithe.test.agents", &agent(sample())); + let entry = catalog_entry("dev.lithe.test.agents", &agent(sample()), &[]); assert_eq!(entry["modes"], json!(["native"])); assert_eq!(entry["forms"], json!(["conversation", "terminal"])); assert_eq!(entry["readsSessions"], json!(true)); @@ -243,7 +243,7 @@ fn image_types_are_distinct_known_types_and_reach_the_catalog() { value["native"]["imageTypes"] = json!(["image/png", "image/webp"]); let mut agents = [agent(value.clone())]; check(&mut agents, true).expect("image types validate"); - let entry = catalog_entry("dev.lithe.test.agents", &agents[0]); + let entry = catalog_entry("dev.lithe.test.agents", &agents[0], &[]); assert_eq!(entry["imageTypes"], json!(["image/png", "image/webp"])); for types in [ @@ -295,7 +295,7 @@ fn accepts_configuration_and_reports_it() { BTreeSet::from(["SAMPLE_CONFIG".to_string(), "SAMPLE_HOME".to_string()]) ); - let entry = catalog_entry("dev.lithe.test.agents", &agents[0]); + let entry = catalog_entry("dev.lithe.test.agents", &agents[0], &[]); assert_eq!( entry["configuration"], json!({ "instructions": true, "skills": true, "files": true, "editable": true }) @@ -416,7 +416,7 @@ fn accepts_providers_and_reports_their_operations() { "operations": ["addProvider", "setModel"] })))]; check(&mut agents, true).expect("providers validate"); - let entry = catalog_entry("dev.lithe.test.agents", &agents[0]); + let entry = catalog_entry("dev.lithe.test.agents", &agents[0], &[]); assert_eq!( entry["configuration"]["providers"], json!({ "operations": ["addProvider", "setModel"] }) @@ -441,7 +441,7 @@ fn accepts_providers_and_reports_their_operations() { check(&mut agents, true).expect("providers alone read the files"); assert!(agents[0].needs_backend()); assert_eq!( - catalog_entry("dev.lithe.test.agents", &agents[0])["configuration"]["providers"], + catalog_entry("dev.lithe.test.agents", &agents[0], &[])["configuration"]["providers"], json!({ "operations": [] }) ); } @@ -588,3 +588,104 @@ fn resume_arguments_name_the_session_and_reach_the_review() { ); } } + +/// `latestVersion` is a backend function: the agent needs the backend and +/// its activation event, the catalog says the agent checks versions, and the +/// review lists the function that reaches the network. +#[test] +fn latest_version_is_a_reviewed_backend_function() { + let terminal_only = json!({ + "id": "sample", + "displayName": "Sample", + "tool": "sample-cli", + "terminal": { "arguments": [] }, + "latestVersion": { "function": "sample.latestVersion" } + }); + let mut agents = [agent(terminal_only.clone())]; + check(&mut agents, true).expect("a latest-version function validates"); + assert!(agents[0].needs_backend()); + assert_eq!( + catalog_entry("dev.lithe.test.agents", &agents[0], &[])["checksLatestVersion"], + json!(true) + ); + assert_eq!( + programs(&agents[0]) + .into_iter() + .filter(|program| program["kind"] == "agentLatestVersion") + .collect::>(), + vec![json!({ + "kind": "agentLatestVersion", + "agentID": "sample", + "tool": "sample-cli", + "function": "sample.latestVersion" + })] + ); + assert_eq!(rejected_field(terminal_only.clone(), false), "agents[0]"); + + let mut misnamed = terminal_only.clone(); + misnamed["latestVersion"]["function"] = json!("Sample Latest"); + assert_eq!( + rejected_field(misnamed, true), + "agents[0].latestVersion.function" + ); + let mut extra = terminal_only; + extra["latestVersion"]["url"] = json!("https://example.com/latest"); + assert!(serde_json::from_value::(extra).is_err()); + + let plain = catalog_entry("dev.lithe.test.agents", &agent(sample()), &[]); + assert_eq!(plain["checksLatestVersion"], json!(false)); + assert!(plain.get("install").is_none()); +} + +/// The install page is an https page the host may open on a click; the +/// catalog lists it with the installers the manifest has for the tool. +#[test] +fn install_pages_are_https_pages_and_reach_the_catalog() { + let mut value = sample(); + value["install"] = json!({ "url": "https://example.com/docs/install?channel=stable" }); + let mut agents = [agent(value.clone())]; + check(&mut agents, true).expect("an install page validates"); + let installers = ["sample-cli".to_string()]; + assert_eq!( + catalog_entry("dev.lithe.test.agents", &agents[0], &installers)["install"], + json!({ + "installers": ["sample-cli"], + "url": "https://example.com/docs/install?channel=stable" + }) + ); + // Installers alone are enough for an install section. + assert_eq!( + catalog_entry("dev.lithe.test.agents", &agent(sample()), &installers)["install"], + json!({ "installers": ["sample-cli"] }) + ); + + for url in [ + "http://example.com/install", + "https://", + "https:///install", + "https://user@example.com/install", + "https://user:secret@example.com/install", + "https://example.com/install#steps", + "https://example.com/in stall", + "https://example.com/\u{7}", + "file:///etc/passwd", + "javascript:alert(1)", + &format!("https://example.com/{}", "a".repeat(MAX_PAGE_URL_BYTES)), + ] { + let mut refused = value.clone(); + refused["install"]["url"] = json!(url); + assert_eq!( + rejected_field(refused, true), + "agents[0].install.url", + "{url}" + ); + } + for url in [ + "https://example.com", + "https://example.com:8443/install", + "https://[2001:db8::1]/install", + "https://example.com?step=1", + ] { + assert!(is_page_url(url), "{url}"); + } +} diff --git a/rust/crates/plugin-manifest/src/command_installers.rs b/rust/crates/plugin-manifest/src/command_installers.rs index e61ebe9e..4a17faa3 100644 --- a/rust/crates/plugin-manifest/src/command_installers.rs +++ b/rust/crates/plugin-manifest/src/command_installers.rs @@ -650,6 +650,31 @@ impl DeclarativePluginManifest { Ok(()) } + /// The IDs of the installers that provide a command of the tool of the + /// agent `agent_id`, in installer order: what the agent catalog offers + /// when the agent's CLI is missing. Empty when the plugin does not define + /// the agent's tool or no installer provides its commands. A download + /// installer is listed whatever the host's platform; + /// `plugins.commandInstallers.requirements` with the platform leaves out + /// one without an archive for it. + pub fn agent_installers(&self, agent_id: &str) -> Vec { + let Some(consumer) = self.command_consumers().into_iter().find(|consumer| { + consumer.kind == AGENT_CONSUMER && consumer.id.as_deref() == Some(agent_id) + }) else { + return Vec::new(); + }; + self.command_installers + .iter() + .filter(|installer| { + installer + .commands + .iter() + .any(|command| consumer.commands.contains(command)) + }) + .map(|installer| installer.id.clone()) + .collect() + } + /// Every `systemCommand` launch the host may start, in the order of the /// reviewed program list, then every agent whose tool this plugin defines, /// in declaration order, with the commands of that definition. The host @@ -1198,6 +1223,26 @@ mod tests { } } + /// The agent catalog offers the installers of the commands of the agent's + /// tool, and none for an agent whose tool no installer provides. + #[test] + fn an_agent_is_offered_the_installers_of_its_tool() { + let manifest = + validate_manifest_value(serde_json::from_str(AGENT_PLUGIN).unwrap()).unwrap(); + assert_eq!(manifest.agent_installers("example"), vec!["example-agent"]); + assert!(manifest.agent_installers("missing").is_empty()); + + let mut without: Value = serde_json::from_str(AGENT_PLUGIN).unwrap(); + without["commandInstallers"] = json!([]); + without["requires"] + .as_object_mut() + .unwrap() + .remove("commandInstallers"); + without["permissions"] = json!(["agents.run"]); + let manifest = validate_manifest_value(without).unwrap(); + assert!(manifest.agent_installers("example").is_empty()); + } + fn probe(path_list: bool, append: Option<&str>) -> DirectoryProbe { DirectoryProbe { arguments: vec!["env".to_string()], diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index ad5027f1..48939be1 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -651,6 +651,136 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "agent.versions.check_finished", + "channel": "agent", + "level": "info", + "message": "An agent plugin reported the newest version of its CLI", + "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" + }, + "check": { + "type": "token", + "required": true, + "description": "Why the plugin was asked: ifStale (the host's check when its agents page opens, for an answer older than six hours) or now (the user asked)" + }, + "comparison": { + "type": "token", + "required": false, + "description": "How the installed version compares with the newest: older, same, newer or different; absent when the host gave no installed version. Never a version itself" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the plugin function took" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.versions.check_failed", + "channel": "agent", + "level": "warn", + "message": "Checking the newest version of an agent CLI failed", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "check": { + "type": "token", + "required": true, + "description": "Why the plugin was asked: ifStale or now" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code: agents.backendUnavailable, agents.latestVersionFailed or agents.invalidLatestVersion; never versions, paths, URLs or text" + }, + "call_code": { + "type": "token", + "required": false, + "description": "Failure code of the plugin function call behind agents.latestVersionFailed, such as plugin.function.timeout" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the check took, including the plugin function call when a backend was running" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.versions.read_finished", + "channel": "agent", + "level": "debug", + "message": "Agent CLI versions read", + "fields": { + "check": { + "type": "token", + "required": true, + "description": "When plugins were asked: cached, ifStale or now" + }, + "agents": { + "type": "int", + "required": true, + "description": "Agents the host asked about" + }, + "checked": { + "type": "int", + "required": true, + "description": "Agents whose plugin this request asked" + }, + "failed": { + "type": "int", + "required": true, + "description": "Checks of this request that failed" + }, + "updates": { + "type": "int", + "required": true, + "description": "Agents behind the newest version with an update command the user may run" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took, including plugin calls" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.versions.read_failed", + "channel": "agent", + "level": "warn", + "message": "A request for agent CLI versions was refused", + "fields": { + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code such as agents.invalidVersionQuery, agents.unknownAgent or agents.userActionRequired; never versions, paths or text" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "agent.library.skill_import_finished", "channel": "agent", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d429a6ec..f0d5f380 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; `cli-versions.json` holds how `agents.cliVersions` compares an installed version with the newest one, and the `latestVersion` answers it takes and 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 | @@ -3716,6 +3716,8 @@ rejections. "native": { "function": "example.launch" }, "terminal": { "arguments": [] }, "update": { "arguments": ["update"] }, + "latestVersion": { "function": "example.latestVersion" }, + "install": { "url": "https://example.com/agent/install" }, "sessionSources": [{ "id": "projects", "roots": ["${env:EXAMPLE_HOME}/sessions", "${userHome}/.example/sessions"], @@ -3739,6 +3741,8 @@ rejections. | `acp` | `{arguments}`: runs `tool` with these arguments as an Agent Client Protocol server. See [Limits of version 0](#limits-of-version-0). | | `terminal` | `{arguments, resumeArguments?}`: runs `tool` with `arguments` in a host terminal, the CLI's own interactive interface. `resumeArguments`, 1–64 arguments, continue one recorded session instead: every `${sessionID}` in them becomes the session's ID; it occurs at least once and no other `${` appears. See [Continuing a recorded session](#continuing-a-recorded-session). | | `update` | `{arguments}`, nonempty: runs `tool` with these arguments to update the CLI, after the user confirms. A CLI without a self-update command declares none. | +| `latestVersion` | `{function}`: a backend function that looks up the newest published version of the CLI. See [CLI versions and installation](#cli-versions-and-installation). | +| `install` | `{url}`: the page that explains how to install the CLI, which the host opens in the browser when the user asks. The commands that install it are the plugin's [command installers](#command-installers). | | `sessionSources` | Up to four [session sources](#session-records): where the CLI keeps its session files and the backend functions that parse them. | | `configuration` | Where the CLI keeps the instructions, skills, MCP servers and hooks the [agent library](#agent-configuration) manages, and the backend functions that read and edit its files. | @@ -3748,9 +3752,12 @@ rejections. each, without NUL. Arguments are fixed: they take no templates, except `${sessionID}` in `terminal.resumeArguments`. - A function ID is dot-separated lowerCamelCase segments, as in - [plugin functions](#plugin-functions). `native`, `sessionSources` and the - `read` and `edit` of `configuration` are served by the plugin backend, so - they need `backend`. + [plugin functions](#plugin-functions). `native`, `sessionSources`, + `latestVersion` and the `read` and `edit` of `configuration` are served by + the plugin backend, so they need `backend`. +- `install.url` is an `https` URL with a host, at most 2048 bytes, without a + user or password, fragment, space or control character; a query is + allowed. - Every rejection is `plugin.manifest.invalid` with `field` naming the place, such as `agents[0].tool` or `agents[0].sessionSources[1].include[0]`. @@ -3758,7 +3765,9 @@ The install review lists one program per form: `kind: "agent"` with `agentID`, `tool`, `form` (`native`, `acp`, `terminal` or `update`), and `launchFunction` for `native` or the fixed `arguments` otherwise, with `resumeArguments` (the template, `${sessionID}` kept) for a `terminal` that -declares them; and one +declares them; one `kind: "agentLatestVersion"` entry per agent that +declares `latestVersion`, with `agentID`, `tool` and `function`, since the +function reaches the network; and one `kind: "agentSessions"` entry per source with `agentID`, `tool`, `source`, `roots` and `include`; and one `kind: "agentConfiguration"` entry per agent that declares `configuration`, with `agentID`, `tool`, `instructions?`, @@ -3780,15 +3789,15 @@ A missing permission is `plugin.permission.undeclared`; a permission no agent needs is `plugin.manifest.invalid` (`" is declared, but no agent needs it."`). `agents.usage.read` is the exception, since a plugin without agents of its own may read the totals. Every agent that declares -`native`, `sessionSources` or a `configuration` with `read` needs the -activation event `onAgent:`, and +`native`, `sessionSources`, `latestVersion` or a `configuration` with `read` +needs the activation event `onAgent:`, and the event is refused for an agent that needs no backend (`plugin.activation.invalid` either way): a terminal-only or ACP-only agent runs only its tool, and a plugin of such agents alone needs no `backend`. `onAgent:` is one of the ways a [backend](#backend-lifecycle-and-workspace-contexts) starts: the host starts the backend before it starts a native session of the agent, syncs its -records or reads its configuration files. +records, reads its configuration files or checks its newest version. ### Host commands @@ -3798,12 +3807,17 @@ is installed, updated, enabled, disabled, removed or its grants change. Core validates each manifest itself, keeps the grants the manifest declares, and answers `{agents, rejected: [{pluginID, code, message}]}`. `agents.catalog` answers `{agents}` again. Each entry is `{pluginID, agentID, displayName, -tool, modes, forms, readsSessions, mayRun, mayReadSessions, icon?, -imageTypes?, terminalArguments?, update?, sessionRootVariables?, -configuration?, mayConfigure?}`: `modes` lists `native` and `acp`, `forms` -lists `conversation` and `terminal`, `imageTypes` is the native -declaration's list when it has one, and `sessionRootVariables` names the -environment variables the session and configuration roots read. An agent +tool, modes, forms, readsSessions, checksLatestVersion, mayRun, +mayReadSessions, icon?, imageTypes?, terminalArguments?, update?, install?, +sessionRootVariables?, configuration?, mayConfigure?}`: `modes` lists +`native` and `acp`, `forms` lists `conversation` and `terminal`, +`checksLatestVersion` says whether the agent declares `latestVersion`, +`imageTypes` is the native declaration's list when it has one, and +`sessionRootVariables` names the environment variables the session and +configuration roots read. `install` is `{installers, url?}` for an agent +that declares `install` or whose `tool` a command installer of its plugin +provides: `installers` are those installers' IDs in declaration order, and +`url` is the declared page. An agent that declares `configuration` gives `configuration: {instructions, skills, files, editable}`, which of them it declares and whether it declares `edit`, and `mayConfigure`, whether its plugin is granted `agents.configuration`. @@ -3819,6 +3833,7 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. | `agents.setConfigOption` | `{session, option, value}` | `{}` | | `agents.close` | `{session}` | `{}` | | `agents.sessions` | `{}` | `{sessions}`: the live sessions | +| `agents.cliVersions` | `{agents: [{agent, installedVersion?, toolPath?}], check?}` | `{agents, updates}`; see [CLI versions and installation](#cli-versions-and-installation) | | `agents.waitEvents` | `{after?, timeoutMilliseconds?, limit?, acknowledge?: [sequence]}` | `{events: [{sequence, session, event}], next, missed, recoveries: [{sequence, session, event}]}` | - `agents.start`, `agents.prompt`, `agents.cancel`, `agents.updateQueue`, @@ -3941,6 +3956,149 @@ The `terminal` form needs no command: the host runs `toolPath` with the same trust and remote checks. `update` runs `toolPath` with the update arguments in a host terminal after the user confirms the command line. +### CLI versions and installation + +The host shows each agent's installed CLI version, whether a newer one is +published, and how to install a CLI that is missing. Each side does what it +knows: the host's tool resolution finds the CLI (`toolPath`) and probes its +version, as for any tool; the plugin's `latestVersion` function looks up the +newest version where the CLI is published; Core decides when the plugin is +asked, checks and keeps the answer, compares the versions and lists the +update commands. Core runs no command and reaches no network itself. + +`agents.cliVersions` takes: + +| Field | Meaning | +| --- | --- | +| `agents` | 1–64 `{agent, installedVersion?, toolPath?}`, each agent once. `agent` is `/`. `installedVersion` is the version the host's tool resolution read: 1–64 bytes of ASCII letters, digits, `.`, `-`, `_` and `+`. `toolPath` is the absolute path of the CLI the host resolved, at most 4096 bytes, without NUL. The host leaves both out for a CLI it did not find. | +| `check` | `cached` (the default) answers from what Core keeps and asks no plugin. `ifStale` asks for each agent whose last answer is missing or at least six hours old, unless its last check failed less than 15 minutes ago; the host sends it when the user opens its agents page, and may let the user turn that off. `now` asks for every agent named, and is accepted only from a request whose origin is the user. Core never checks on its own or on a timer. | + +It answers, for example: + +```json +{ + "agents": [{ + "agent": "dev.example.agents/example", + "pluginID": "dev.example.agents", + "agentID": "example", + "displayName": "Example Agent", + "checksLatestVersion": true, + "mayRun": true, + "installedVersion": "1.4.0", + "latest": { + "version": "1.5.0", + "checkedAtMs": 1764806400000, + "stale": false, + "publishedAtMs": 1764633600000, + "releaseNotesUrl": "https://example.com/agent/releases/1.5.0" + }, + "comparison": "older", + "updateAvailable": true, + "update": { "arguments": ["update"] } + }], + "updates": [{ + "agent": "dev.example.agents/example", + "displayName": "Example Agent", + "from": "1.4.0", + "to": "1.5.0", + "arguments": ["update"] + }] +} +``` + +- `agents` follows the request's order. `latest` is the last answer for this + installation: `checkedAtMs` is when the plugin answered and `stale` turns + true six hours later; it is absent until a check answered and for an agent + without `latestVersion` (`checksLatestVersion: false`), which is never + asked. `comparison` and `updateAvailable` are given when both versions are + known. `update` is the declared update command. `checkFailed: {code, atMs}` + reports the last failed check; `latest` keeps the answer before it. +- `updates` lists, in request order, every agent that is `older` than the + newest version, declares `update` and whose plugin is granted `agents.run`: + what "update all" runs. The host shows the list, and after the user + confirms it runs each in its terminal one after another, as an agent's + `update` (`toolPath` with the arguments). Core runs none of them. The host + then probes the versions again and reads with `cached`. + +Core compares the installed version with the newest one as semantic +versions: an optional leading `v` or `V`, one to four dot-separated decimal +numbers of at most 19 digits (a missing number is 0, so `1.5` is `1.5.0`), +an optional `-` pre-release of dot-separated identifiers of ASCII letters, +digits and `-`, and an optional `+` build, which is ignored. Precedence +follows Semantic Versioning 2.0.0, section 11. `comparison` is `older` (an +update), `same` or `newer` (such as a pre-release of the next version). When +either version does not read this way, Core compares the two as text, +without the `v`, and answers `same` or `different`; `different` is never an +update. `fixtures/agents/cli-versions.json` holds the cases. + +Core keeps the answers in memory, for the life of the Core process, one per +agent. An answer is valid only for the plugin version, the function and the +`toolPath` it was asked for, so another plugin build or another installation +of the CLI is asked again; `agents.configure` drops the answers of agents +that are gone or no longer declare `latestVersion`. Nothing is written to +disk. One check of an agent runs at a time: a request that finds one running +waits for it, at most 35 seconds, and uses its answer. Checks of different +agents run in parallel. + +The `latestVersion` function receives `{agentID, installedVersion?, +toolPath?, timeoutMilliseconds, maximumResponseBytes}` and Core waits 30 +seconds for it. It looks the newest version up where the CLI is published, +within `timeoutMilliseconds` (20000) for the whole exchange and reading at +most `maximumResponseBytes` (1 MiB), with the proxy and certificates the CLI +itself would use. `toolPath` and `installedVersion` tell it how the CLI was +installed and so where it updates from, such as the registry of a package +manager or the vendor's release feed. The function only reads: it never +runs the update, and it reaches the network for nothing else. It answers: + +```json +{ + "format": "litheAgentLatestVersion", + "version": 0, + "latest": "1.5.0", + "publishedAtMs": 1764633600000, + "releaseNotesUrl": "https://example.com/agent/releases/1.5.0" +} +``` + +`latest` is a version of 1–64 bytes as `installedVersion` is; +`publishedAtMs` is the release time in milliseconds since the Unix epoch, +1 to 2^53 − 1; `releaseNotesUrl` is a page under the rules of `install.url`. +An unknown field, another `format` or another `version` breaks the answer. + +`agents.cliVersions` refuses the whole request with: + +| Code | When | +| --- | --- | +| `agents.invalidPayload` | The payload does not have this shape, including an unknown field or `check`. | +| `agents.userActionRequired` | `check: "now"` from a request the user did not start. | +| `agents.invalidVersionQuery` | `agents` is empty or names more than 64, names an agent twice, or holds a malformed `installedVersion` or `toolPath`. | +| `agents.unknownAgent` | No configured plugin declares an agent named. | + +A check that fails is not a refusal: the agent's `checkFailed.code` says +why, and `ifStale` waits 15 minutes before it asks again. + +| Code | When | +| --- | --- | +| `agents.runNotGranted` | The plugin is not granted `agents.run`, so `ifStale` and `now` do not ask it. Core reports it and does not keep it. | +| `agents.backendUnavailable` | The plugin backend is not running. | +| `agents.latestVersionFailed` | The function failed or did not answer in time. | +| `agents.invalidLatestVersion` | The answer breaks the rules above. | + +Logs carry the plugin and agent IDs, the check, the comparison, counts, +durations and these codes, with the plugin call's own failure code; never +a version, a path or a URL: `agent.versions.check_finished`, +`agent.versions.check_failed`, `agent.versions.read_finished` (debug) and +`agent.versions.read_failed`. + +A CLI the host's tool resolution does not find is not installed, and the +catalog's `install` says what the host offers for it. Each of `installers` +goes through the [installation steps](#installation-steps): +`plugins.commandInstallers.requirements` lists the agent with them and +`plugins.commandInstallers.plan` expands the one the user picks, which the +host shows and runs after the user confirms, then resolves the tool again. +`url` is opened in the browser. An agent with neither has no `install`, and +the host shows only that the CLI is missing. + ### Native sessions A native session runs the CLI's own machine interface, such as a JSON-lines diff --git a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json index 7e98b547..06f9dba0 100644 --- a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -49,6 +49,12 @@ "update" ] }, + "latestVersion": { + "function": "example.latestVersion" + }, + "install": { + "url": "https://example.com/agent/install" + }, "sessionSources": [ { "id": "projects", diff --git a/shared/plugins/contract/v1/fixtures/agents/cli-versions.json b/shared/plugins/contract/v1/fixtures/agents/cli-versions.json new file mode 100644 index 00000000..ca05fd5a --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/agents/cli-versions.json @@ -0,0 +1,112 @@ +{ + "description": "CLI versions of agents (plan API-45). `comparisons`: how agents.cliVersions compares the version the host found installed with the newest one the plugin reported, from the installed version's side: older (an update), same, newer, or different when either is not a semantic version and the two differ as text. `answers`: what a latestVersion function may answer; a valid one gives the `latest` shown (without the checkedAtMs and stale Core adds), an invalid one makes the check fail with agents.invalidLatestVersion.", + "comparisons": [ + { "installed": "1.4.0", "latest": "1.5.0", "comparison": "older" }, + { "installed": "1.5.0", "latest": "1.5.0", "comparison": "same" }, + { "installed": "1.6.0", "latest": "1.5.0", "comparison": "newer" }, + { "installed": "0.9.10", "latest": "0.10.0", "comparison": "older" }, + { "installed": "v1.5.0", "latest": "1.5.0", "comparison": "same" }, + { "installed": "1.5", "latest": "1.5.0", "comparison": "same" }, + { "installed": "1.5.0.1", "latest": "1.5.0", "comparison": "newer" }, + { "installed": "2025.01.03", "latest": "2025.1.10", "comparison": "older" }, + { "installed": "1.5.0-beta.2", "latest": "1.5.0", "comparison": "older" }, + { "installed": "1.6.0-alpha.1", "latest": "1.5.0", "comparison": "newer" }, + { "installed": "1.0.0-alpha", "latest": "1.0.0-alpha.1", "comparison": "older" }, + { "installed": "1.0.0-alpha.1", "latest": "1.0.0-alpha.beta", "comparison": "older" }, + { "installed": "1.0.0-alpha.beta", "latest": "1.0.0-beta", "comparison": "older" }, + { "installed": "1.0.0-beta.2", "latest": "1.0.0-beta.11", "comparison": "older" }, + { "installed": "1.0.0-beta.11", "latest": "1.0.0-rc.1", "comparison": "older" }, + { "installed": "1.0.0+build.1", "latest": "1.0.0+build.2", "comparison": "same" }, + { "installed": "nightly-2025-11-03", "latest": "nightly-2025-11-03", "comparison": "same" }, + { "installed": "nightly-2025-11-03", "latest": "1.5.0", "comparison": "different" }, + { "installed": "1.5.0", "latest": "1.5.0_hotfix", "comparison": "different" }, + { "installed": "1.2.3.4.5", "latest": "1.2.3.4.6", "comparison": "different" }, + { "installed": "1..5", "latest": "1.5.0", "comparison": "different" }, + { "installed": "12345678901234567890.0.0", "latest": "1.0.0", "comparison": "different" } + ], + "answers": [ + { + "name": "the newest version alone", + "answer": { "format": "litheAgentLatestVersion", "version": 0, "latest": "1.5.0" }, + "latest": { "version": "1.5.0" } + }, + { + "name": "with its release date and notes", + "answer": { + "format": "litheAgentLatestVersion", + "version": 0, + "latest": "v2.0.0-rc.1", + "publishedAtMs": 1764633600000, + "releaseNotesUrl": "https://example.com/agent/releases?version=2.0.0-rc.1" + }, + "latest": { + "version": "v2.0.0-rc.1", + "publishedAtMs": 1764633600000, + "releaseNotesUrl": "https://example.com/agent/releases?version=2.0.0-rc.1" + } + }, + { + "name": "another format", + "answer": { "format": "litheAgentProviders", "version": 0, "latest": "1.5.0" } + }, + { + "name": "another format version", + "answer": { "format": "litheAgentLatestVersion", "version": 1, "latest": "1.5.0" } + }, + { + "name": "no version", + "answer": { "format": "litheAgentLatestVersion", "version": 0 } + }, + { + "name": "a version with a space", + "answer": { "format": "litheAgentLatestVersion", "version": 0, "latest": "1.5.0 (stable)" } + }, + { + "name": "a version longer than 64 bytes", + "answer": { + "format": "litheAgentLatestVersion", + "version": 0, + "latest": "1.0.0-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + }, + { + "name": "a release date of zero", + "answer": { "format": "litheAgentLatestVersion", "version": 0, "latest": "1.5.0", "publishedAtMs": 0 } + }, + { + "name": "a release date past the largest exact JSON integer", + "answer": { "format": "litheAgentLatestVersion", "version": 0, "latest": "1.5.0", "publishedAtMs": 9007199254740992 } + }, + { + "name": "release notes over http", + "answer": { + "format": "litheAgentLatestVersion", + "version": 0, + "latest": "1.5.0", + "releaseNotesUrl": "http://example.com/agent/releases" + } + }, + { + "name": "release notes with credentials", + "answer": { + "format": "litheAgentLatestVersion", + "version": 0, + "latest": "1.5.0", + "releaseNotesUrl": "https://token@example.com/agent/releases" + } + }, + { + "name": "release notes with a fragment", + "answer": { + "format": "litheAgentLatestVersion", + "version": 0, + "latest": "1.5.0", + "releaseNotesUrl": "https://example.com/agent/releases#1.5.0" + } + }, + { + "name": "an unknown field", + "answer": { "format": "litheAgentLatestVersion", "version": 0, "latest": "1.5.0", "message": "Update now" } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index a163a05f..ad498b7c 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -1016,6 +1016,13 @@ {"name": "a providers field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/secrets", "value": "example.providers.secrets"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a configuration edit function needs read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": []}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "a configuration function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/edit", "value": "Example Edit"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, + {"name": "a latest-version function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/latestVersion/function", "value": "Example Latest"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].latestVersion.function"}, + {"name": "a latest-version field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/latestVersion/url", "value": "https://example.com/agent/latest"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a latest version needs a backend", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/agents/0/latestVersion", "value": {"function": "example.latestVersion"}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0]"}, + {"name": "an install page uses HTTPS", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/install/url", "value": "http://example.com/agent/install"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].install.url"}, + {"name": "an install page carries no credentials", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/install/url", "value": "https://token@example.com/agent/install"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].install.url"}, + {"name": "an install page has no fragment", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/install/url", "value": "https://example.com/agent/install#macos"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].install.url"}, + {"name": "an install field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/install/command", "value": "npm install -g example-agent"}], "expectedCode": "plugin.manifest.invalid"}, {"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..a0cf399a 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -10,6 +10,7 @@ {"if": {"required": ["agents"]}, "then": {"required": ["permissions", "requiresTools"], "properties": {"requires": {"required": ["agents"]}, "permissions": {"contains": {"const": "agents.run"}}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["native"]}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}, "permissions": {"contains": {"const": "agents.native"}}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["sessionSources"]}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}, "permissions": {"contains": {"const": "agents.sessions.read"}}}}}, + {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["latestVersion"]}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"]}}}}, "then": {"properties": {"permissions": {"contains": {"const": "agents.configuration"}}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"], "properties": {"configuration": {"required": ["read"]}}}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"], "properties": {"configuration": {"required": ["providers"]}}}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, @@ -389,7 +390,7 @@ } }, "agent": { - "description": "One agent command-line tool. It declares at least one of native, acp and terminal. native, sessionSources and the read and edit of configuration are served by the plugin backend and need the activation event onAgent:.", + "description": "One agent command-line tool. It declares at least one of native, acp and terminal. native, sessionSources, latestVersion and the read and edit of configuration are served by the plugin backend and need the activation event onAgent:.", "type": "object", "additionalProperties": false, "required": [ @@ -486,6 +487,36 @@ } ] }, + "latestVersion": { + "description": "function, a backend function, looks up the newest published version of the CLI when agents.cliVersions asks for it: when the host opens its agents page and the last answer is older than six hours, or when the user checks. It answers {format: litheAgentLatestVersion, version: 0, latest, publishedAtMs?, releaseNotesUrl?}. The install review lists it, because it reaches the network.", + "type": "object", + "additionalProperties": false, + "required": [ + "function" + ], + "properties": { + "function": { + "$ref": "#/$defs/pluginFunctionID" + } + } + }, + "install": { + "description": "How a missing CLI is installed. url is the page that explains it, which the host opens in the browser when the user asks; the commands that install the tool are the plugin's commandInstallers, which the catalog lists by ID.", + "type": "object", + "additionalProperties": false, + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string", + "minLength": 9, + "maxLength": 2048, + "pattern": "^https://", + "description": "HTTPS with a host, without credentials, fragment, space or control character; semantic URL validation is performed by Core." + } + } + }, "sessionSources": { "description": "Where the CLI keeps its session files. Core reads them only after the user consents; needs agents.sessions.read.", "type": "array", diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index fd00d60f..2bf66b5a 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 内的补充);声明了 [`latestVersion`](../contract/v1/README.md#cli-versions-and-installation) 的 Agent 由插件后端查 CLI 的最新版本,宿主用 `agents.cliVersions` 读取(用户打开 Agent 页时回答满 6 小时才问,或用户点检查),Core 只在内存里按安装保存、按语义化版本比较,并列出“全部更新”要在终端逐个运行的更新命令;`agents.catalog` 给出安装区 `install`(提供该工具的命令安装器 ID 和插件声明的安装说明页)(`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); for an agent that declares [`latestVersion`](../contract/v1/README.md#cli-versions-and-installation) the plugin backend looks up the newest CLI version, the host reads it with `agents.cliVersions` (asked when the user opens the agents page and the answer is six hours old, or when the user checks), Core keeps it in memory per installation, compares by semantic version, and lists the update commands "update all" runs one after another in the terminal; `agents.catalog` gives the install section `install` (the IDs of the command installers that provide the tool and the install page the plugin declares) (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..6646cc93 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` 是其后的补充;Agent 的 `latestVersion`(查 CLI 最新版本的后端函数,安装审查列为 `agentLatestVersion`)、`install`(安装说明页)、`agents.catalog` 的 `checksLatestVersion` 与 `install`,以及命令 `agents.cliVersions` 是最后的补充 | ✅ | 待宿主接入 | [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; an agent's `latestVersion` (the backend function that looks up the newest CLI version, an `agentLatestVersion` program of the install review), `install` (the install page), `checksLatestVersion` and `install` in `agents.catalog`, and the command `agents.cliVersions` 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..dad941ca 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -8,14 +8,14 @@ | 项目 | 内容 | | --- | --- | -| 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`,每个插件最多 8 个 | -| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read`、`providers` 的 `configuration` 时还需要 `backend` 0。`configuration`、`agents.configuration`、`native.imageTypes`、提示附件、`configuration.providers` 和 `agentLibrary.read` 的筛选排序参数是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单、带 `attachments` 的 `agents.prompt` 和带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, latestVersion?, install?, sessionSources?, configuration?}`,每个插件最多 8 个 | +| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources`、`latestVersion` 或带 `read`、`providers` 的 `configuration` 时还需要 `backend` 0。`latestVersion`、`install`、`agents.catalog` 的 `checksLatestVersion` 与 `install`、`agents.cliVersions` 是 `agents` 0 内的补充。`configuration`、`agents.configuration`、`native.imageTypes`、提示附件、`configuration.providers` 和 `agentLibrary.read` 的筛选排序参数是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单、带 `attachments` 的 `agents.prompt` 和带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | API 编号 | API-45 | | 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.configuration`(有 `configuration`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | -| 激活事件 | 声明了 `native`、`sessionSources` 或带 `read`、`providers` 的 `configuration` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | -| 后端启动 | 只有终端形式的 Agent 不需要后端 | -| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有。`configuration` 的 `read`、`edit` 和 `providers` 的 `read`、`edit` 都是普通插件函数,任何 SDK 版本都能注册,见各 SDK 的 Agent configuration functions 一节 | -| 安装审查 | 每种运行形式列成一条 `agent` 程序,每个会话来源列成一条 `agentSessions` 程序,声明了 `configuration` 的 Agent 列成一条 `agentConfiguration` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录和文件会被读取或修改 | +| 激活事件 | 声明了 `native`、`sessionSources`、`latestVersion` 或带 `read`、`providers` 的 `configuration` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | +| 后端启动 | 只有终端形式、且不声明 `latestVersion` 的 Agent 不需要后端 | +| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有。`configuration` 的 `read`、`edit`,`providers` 的 `read`、`edit` 和 `latestVersion` 都是普通插件函数,任何 SDK 版本都能注册,见各 SDK 的 Agent configuration functions 一节 | +| 安装审查 | 每种运行形式列成一条 `agent` 程序,声明了 `latestVersion` 的 Agent 列成一条 `agentLatestVersion` 程序(这个函数会联网),每个会话来源列成一条 `agentSessions` 程序,声明了 `configuration` 的 Agent 列成一条 `agentConfiguration` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录和文件会被读取或修改 | | Lithe 桌面端 | 接入中,尚未声明 `agents` | ### 运行形式 @@ -29,6 +29,22 @@ 工具一律来自插件的 `requiresTools`:宿主发现并探测版本,会话运行的始终是用户装好的那份 CLI,插件不能指定路径。会话只在可信的本地工作区运行,远程工作区按 API-40 拒绝。 +### CLI 版本、全部更新与安装 + +宿主的 Agent 页显示每个 CLI 装的版本、有没有新版本,以及没装的 CLI 怎样安装。三方各做自己知道的事:宿主的工具解析找到 CLI(`toolPath`)并探测版本;插件的 `latestVersion` 函数到 CLI 发布的地方查最新版本;Core 决定什么时候问插件,校验并保存回答,比较版本,列出更新命令。Core 自己不运行命令,也不联网。 + +- **声明**:`latestVersion: {function}` 是后端函数,所以需要 `backend` 和 `onAgent:`。`install: {url}` 是说明怎样安装的页面(`https`、有主机名、不带用户名密码和片段,最长 2048 字节);安装命令用插件已有的 [`commandInstallers`](../../contract/v1/README.md#command-installers),不另写命令行。 +- **目录**:`agents.catalog` 的每个条目带 `checksLatestVersion`;声明了 `install`、或插件有命令安装器提供该 Agent 的工具时,再带 `install: {installers, url?}`,`installers` 是这些安装器的 ID。宿主照[安装步骤](../../contract/v1/README.md#installation-steps)用 `plugins.commandInstallers.plan` 展开用户选的那个,给用户看过并确认后运行,然后重新解析工具;`url` 在浏览器打开。 +- **查询**:`agents.cliVersions {agents: [{agent, installedVersion?, toolPath?}], check?}`,`installedVersion` 和 `toolPath` 都来自宿主的工具解析,没找到 CLI 就不带。`check` 默认 `cached`,只读 Core 保存的回答、不问插件;`ifStale` 只问回答缺失或已满 6 小时的 Agent,上次查询失败不到 15 分钟的除外,宿主在用户打开 Agent 页时发一次,并可让用户关掉;`now` 每个都问,只接受用户发起的请求。Core 不在后台、也不定时检查。 +- **回答**:每个 Agent 带 `latest {version, checkedAtMs, stale, publishedAtMs?, releaseNotesUrl?}`、`comparison`(`older`、`same`、`newer`、`different`)、`updateAvailable`、声明的 `update` 和失败时的 `checkFailed {code, atMs}`;`updates` 列出所有比最新版本旧、声明了 `update`、插件有 `agents.run` 的 Agent 和它们的更新命令,“全部更新”就用它:宿主给用户看过整张清单、确认后在终端里逐个运行,Core 不运行。 +- **比较**:两个版本都按语义化版本读(可带 `v`,1–4 段数字,缺的段算 0,可带 `-` 预发布和 `+` 构建,构建忽略),按 Semantic Versioning 2.0.0 第 11 节比较;有一个读不出来就只比文字是否相同,回答 `same` 或 `different`,`different` 不算有更新。 +- **缓存**:回答只存在内存里,随 Core 进程结束;每个 Agent 一份,只对问到它时的插件版本、函数和 `toolPath` 有效,换了插件版本或另一处安装就重新问;`agents.configure` 时丢掉已不存在或不再声明 `latestVersion` 的 Agent 的回答。不写磁盘。同一个 Agent 同时只查一次,后来的请求等它(最多 35 秒)并用它的结果。 +- **函数**:Core 传 `{agentID, installedVersion?, toolPath?, timeoutMilliseconds: 20000, maximumResponseBytes: 1048576}`,等 30 秒。插件在时限内、按 CLI 自己会用的代理和证书查询,`toolPath` 告诉它 CLI 是怎么装的、从哪里更新。回答 `{format: "litheAgentLatestVersion", version: 0, latest, publishedAtMs?, releaseNotesUrl?}`,多一个字段也不收。 +- **拒绝码**:整个请求被拒绝时是 `agents.invalidPayload`、`agents.userActionRequired`、`agents.invalidVersionQuery` 或 `agents.unknownAgent`;单个 Agent 查询失败不算拒绝,`checkFailed.code` 是 `agents.runNotGranted`、`agents.backendUnavailable`、`agents.latestVersionFailed` 或 `agents.invalidLatestVersion`,上次成功的回答保留。 +- **日志**:`agent.versions.check_finished`、`agent.versions.check_failed`、`agent.versions.read_finished`(调试级)和 `agent.versions.read_failed`,只记插件和 Agent 的 ID、查询方式、比较结果、数量、耗时和代码,不记版本号、路径和网址。 + +规则全文见[契约的 CLI versions and installation](../../contract/v1/README.md#cli-versions-and-installation),比较和回答的用例见 `fixtures/agents/cli-versions.json`。 + ### 进行中的输入、队列和问答 Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮,`queue` 排到下一轮,`steer` 携带 `expectedTurn` 补充当前轮。插件先根据 CLI 的真实能力报告 `interactionCapabilities`;没有报告的能力默认关闭。立即补充必须等 CLI 确认后报告 `inputResolved`,拒绝时由 Core 把原输入交回宿主草稿,不把一次普通写入当作接收成功。 @@ -118,6 +134,7 @@ Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库 | [Agent declarations](../../contract/v1/README.md#agent-declarations) | 字段、限制、安装审查列出的程序 | | [Agent permissions and activation](../../contract/v1/README.md#agent-permissions-and-activation) | 五个权限、`onAgent:`、拒绝码 | | [Host commands](../../contract/v1/README.md#host-commands) | 宿主调用的 `agents.*` 命令和事件队列 | +| [CLI versions and installation](../../contract/v1/README.md#cli-versions-and-installation) | `latestVersion` 函数、`agents.cliVersions`、版本比较、缓存、全部更新、安装区与拒绝码 | | [Native sessions](../../contract/v1/README.md#native-sessions) | 启动流程、通知、宿主方法、会话事件 | | [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储、命令和筛选、`read` 与 `edit` 函数、限制和拒绝码 | @@ -132,9 +149,10 @@ Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库 | 文件 | 内容 | | --- | --- | -| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | 一个带原生会话、终端形式、更新命令、一个会话来源和一份资源库配置声明的 Agent | +| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | 一个带原生会话、终端形式、更新命令、最新版本函数、安装页、一个会话来源和一份资源库配置声明的 Agent | | [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | 只有终端形式、不需要后端的 Agent | | [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | 以这两个清单为基础的拒绝用例 | +| [`agents/cli-versions.json`](../../contract/v1/fixtures/agents/cli-versions.json) | `agents.cliVersions` 怎样比较装的版本和最新版本,以及 `latestVersion` 函数的回答哪些收、哪些拒 | | [`agents/native-session.json`](../../contract/v1/fixtures/agents/native-session.json) | 原生会话通知和每个会话的处理器依次收到的调用、启动或提示失败时报告的 `turnEnded`、`agents` 宿主方法的请求;四个 SDK 的测试都用它 | | [`folder-categories-v1.json`](../../../../rust/fixtures/agents/folder-categories-v1.json) | 会话目录分组 `category` 的用例:macOS、Linux 和 Windows 三种路径形式的根目录、临时目录和隐藏文件夹 | @@ -146,14 +164,14 @@ A plugin can connect an agent command-line tool that the user installed and sign | Item | Value | | --- | --- | -| Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`, at most 8 per plugin | -| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read` or `providers`. `configuration`, `agents.configuration`, `native.imageTypes`, prompt attachments, `configuration.providers` and the filter and sort parameters of `agentLibrary.read` were added within `agents` 0; a Core that does not know them refuses such a manifest, an `agents.prompt` with `attachments` and an `agentLibrary.read` with filters, and answers no `agentProviders.*` command. See [versions](../capabilities-and-versions.md#capability-versions-requires) | +| Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, latestVersion?, install?, sessionSources?, configuration?}`, at most 8 per plugin | +| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources`, `latestVersion` or a `configuration` with `read` or `providers`. `latestVersion`, `install`, `checksLatestVersion` and `install` in `agents.catalog`, and `agents.cliVersions` were added within `agents` 0. `configuration`, `agents.configuration`, `native.imageTypes`, prompt attachments, `configuration.providers` and the filter and sort parameters of `agentLibrary.read` were added within `agents` 0; a Core that does not know them refuses such a manifest, an `agents.prompt` with `attachments` and an `agentLibrary.read` with filters, and answers no `agentProviders.*` command. See [versions](../capabilities-and-versions.md#capability-versions-requires) | | API IDs | API-45 | | Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.configuration` (with `configuration`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | -| Activation events | An agent that declares `native`, `sessionSources` or a `configuration` with `read` or `providers` needs `onAgent:`; other agents may not have one | -| Backend launch | A terminal-only agent needs no backend | -| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not. The `read` and `edit` of `configuration` and of `providers` are ordinary plugin functions any SDK version registers; see each SDK's Agent configuration functions section | -| Install review | Each form is an `agent` program, each session source an `agentSessions` program, and each agent that declares `configuration` an `agentConfiguration` program, so the user sees how the CLI will run and which directories and files will be read or changed before installing | +| Activation events | An agent that declares `native`, `sessionSources`, `latestVersion` or a `configuration` with `read` or `providers` needs `onAgent:`; other agents may not have one | +| Backend launch | A terminal-only agent that declares no `latestVersion` needs no backend | +| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not. The `read` and `edit` of `configuration` and of `providers`, and `latestVersion`, are ordinary plugin functions any SDK version registers; see each SDK's Agent configuration functions section | +| Install review | Each form is an `agent` program, each agent that declares `latestVersion` an `agentLatestVersion` program (the function reaches the network), each session source an `agentSessions` program, and each agent that declares `configuration` an `agentConfiguration` program, so the user sees how the CLI will run and which directories and files will be read or changed before installing | | Lithe desktop | Integration in progress; does not declare `agents` yet | ### Forms @@ -167,6 +185,22 @@ A plugin can connect an agent command-line tool that the user installed and sign The tool always comes from the plugin's `requiresTools`: the host discovers it and probes its version, so a session always runs the CLI the user installed and the plugin cannot name a path. Sessions run only in trusted local workspaces; remote workspaces are refused as API-40 describes. +### CLI versions, update all, and installation + +The host's agents page shows the version of each installed CLI, whether a newer one is published, and how to install a CLI that is missing. Each side does what it knows: the host's tool resolution finds the CLI (`toolPath`) and probes its version; the plugin's `latestVersion` function looks up the newest version where the CLI is published; Core decides when the plugin is asked, checks and keeps the answer, compares the versions and lists the update commands. Core runs no command and reaches no network itself. + +- **Declaration**: `latestVersion: {function}` is a backend function, so it needs `backend` and `onAgent:`. `install: {url}` is the page that explains the installation (`https`, with a host, without user, password or fragment, at most 2048 bytes); the commands that install the CLI are the plugin's existing [`commandInstallers`](../../contract/v1/README.md#command-installers), not a new command line. +- **Catalog**: each `agents.catalog` entry carries `checksLatestVersion`, and `install: {installers, url?}` when the agent declares `install` or a command installer of its plugin provides its tool; `installers` are those installers' IDs. The host expands the one the user picks with `plugins.commandInstallers.plan`, as the [installation steps](../../contract/v1/README.md#installation-steps) describe, runs it after the user saw and confirmed it, and resolves the tool again; `url` opens in the browser. +- **Query**: `agents.cliVersions {agents: [{agent, installedVersion?, toolPath?}], check?}`; `installedVersion` and `toolPath` come from the host's tool resolution and are left out for a CLI it did not find. `check` defaults to `cached`, which reads what Core keeps and asks no plugin; `ifStale` asks only for agents whose answer is missing or six hours old, not within 15 minutes of a failed check, and the host sends it when the user opens its agents page and may let the user turn it off; `now` asks for every agent and is accepted only from a request the user started. Core never checks in the background or on a timer. +- **Answer**: each agent carries `latest {version, checkedAtMs, stale, publishedAtMs?, releaseNotesUrl?}`, `comparison` (`older`, `same`, `newer`, `different`), `updateAvailable`, the declared `update`, and `checkFailed {code, atMs}` after a failure. `updates` lists every agent that is older than the newest version, declares `update` and whose plugin holds `agents.run`, with its update command: this is "update all". The host shows the whole list and, once the user confirms, runs each in its terminal one after another; Core runs none. +- **Comparison**: both versions are read as semantic versions (an optional `v`, 1–4 numbers with missing ones as 0, an optional `-` pre-release and `+` build, the build ignored) and compared by Semantic Versioning 2.0.0, section 11. When either does not read, only textual equality is decided: `same` or `different`, and `different` is never an update. +- **Cache**: answers live in memory and end with the Core process; one per agent, valid only for the plugin version, the function and the `toolPath` they were asked for, so another plugin build or installation is asked again; `agents.configure` drops the answers of agents that are gone or no longer declare `latestVersion`. Nothing is written to disk. One check of an agent runs at a time, and a later request waits for it (at most 35 seconds) and uses its answer. +- **Function**: Core passes `{agentID, installedVersion?, toolPath?, timeoutMilliseconds: 20000, maximumResponseBytes: 1048576}` and waits 30 seconds. The plugin asks within the budget, with the proxy and certificates the CLI itself would use; `toolPath` tells it how the CLI was installed and where it updates from. It answers `{format: "litheAgentLatestVersion", version: 0, latest, publishedAtMs?, releaseNotesUrl?}`; one more field breaks the answer. +- **Codes**: a refused request is `agents.invalidPayload`, `agents.userActionRequired`, `agents.invalidVersionQuery` or `agents.unknownAgent`. A failed check of one agent is not a refusal: its `checkFailed.code` is `agents.runNotGranted`, `agents.backendUnavailable`, `agents.latestVersionFailed` or `agents.invalidLatestVersion`, and the last good answer stays. +- **Logs**: `agent.versions.check_finished`, `agent.versions.check_failed`, `agent.versions.read_finished` (debug) and `agent.versions.read_failed` carry plugin and agent IDs, the check, the comparison, counts, durations and codes; never a version, a path or a URL. + +The full rules are in the contract's [CLI versions and installation](../../contract/v1/README.md#cli-versions-and-installation), and the comparison and answer cases in `fixtures/agents/cli-versions.json`. + ### Running input, queue and questions Core distinguishes default `send` (a new turn only when idle with no queued input), @@ -274,6 +308,7 @@ Before Core replaces any of an agent's files, it backs the file up under `backup | [Agent declarations](../../contract/v1/README.md#agent-declarations) | Fields, limits, and the programs the install review lists | | [Agent permissions and activation](../../contract/v1/README.md#agent-permissions-and-activation) | The five permissions, `onAgent:`, and refusal codes | | [Host commands](../../contract/v1/README.md#host-commands) | The `agents.*` commands the host calls and the event queue | +| [CLI versions and installation](../../contract/v1/README.md#cli-versions-and-installation) | The `latestVersion` function, `agents.cliVersions`, version comparison, the cache, update all, the install section, and refusal codes | | [Native sessions](../../contract/v1/README.md#native-sessions) | Launch flow, notifications, host methods, session events | | [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage, commands and filters, the `read` and `edit` functions, limits, and refusal codes | @@ -288,9 +323,10 @@ Before Core replaces any of an agent's files, it backs the file up under `backup | File | Content | | --- | --- | -| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | An agent with a native session, a terminal form, an update command, one session source, and a library configuration declaration | +| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | An agent with a native session, a terminal form, an update command, a latest-version function, an install page, one session source, and a library configuration declaration | | [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | A terminal-only agent without a backend | | [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | Rejection cases built on these two manifests | +| [`agents/cli-versions.json`](../../contract/v1/fixtures/agents/cli-versions.json) | How `agents.cliVersions` compares an installed version with the newest one, and which `latestVersion` answers it takes and refuses | | [`agents/native-session.json`](../../contract/v1/fixtures/agents/native-session.json) | Native-session notifications with the calls each session's handler receives, the `turnEnded` reports of failed starts and prompts, and the `agents` host method requests; all four SDKs test against it | | [`folder-categories-v1.json`](../../../../rust/fixtures/agents/folder-categories-v1.json) | Cases of the `category` of a session directory group: roots, temporary directories and hidden folders in macOS, Linux and Windows path forms | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1139c36a..4d604f63 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 不改代码,只更新说明。 | +| [#268](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/268)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | Agent CLI 的最新版本、全部更新和安装区。清单 `agents[]` 新增可选 `latestVersion: {function}`(后端函数,所以需要 `backend` 和 `onAgent:`;安装审查列为 `kind: "agentLatestVersion"` 程序,因为它会联网)和 `install: {url}`(安装说明页:`https`、有主机名、不带用户名密码和片段,最长 2048 字节);安装命令沿用插件已有的 `commandInstallers`,不新增命令行字段。`agents.catalog` 的条目新增 `checksLatestVersion` 和 `install: {installers, url?}`(`installers` 是提供该 Agent 工具的命令安装器 ID,宿主照 `plugins.commandInstallers.plan` 展开、用户确认后运行)。新增宿主命令 `agents.cliVersions {agents: [{agent, installedVersion?, toolPath?}], check?}`:`installedVersion`、`toolPath` 来自宿主的工具解析;`check` 为 `cached`(默认,不问插件)、`ifStale`(回答缺失或满 6 小时才问,失败后 15 分钟内不再问;宿主在用户打开 Agent 页时发一次)或 `now`(只接受用户发起的请求);Core 不在后台或定时检查。回答每个 Agent 的 `latest {version, checkedAtMs, stale, publishedAtMs?, releaseNotesUrl?}`、`comparison`(`older`、`same`、`newer`、`different`)、`updateAvailable`、`update`、`checkFailed {code, atMs}`,以及 `updates`:比最新版本旧、声明了 `update`、插件有 `agents.run` 的 Agent 和更新命令,供宿主“全部更新”时在终端逐个运行,Core 不运行。版本按语义化版本(可带 `v`,1–4 段数字,SemVer 2.0.0 第 11 节)比较,读不出来时只判断文字是否相同。回答只存在内存里,按 Agent 保存、只对问到它时的插件版本、函数和 `toolPath` 有效,不写磁盘;同一 Agent 同时只查一次。新增插件函数 `latestVersion`:收 `{agentID, installedVersion?, toolPath?, timeoutMilliseconds: 20000, maximumResponseBytes: 1048576}`,Core 等 30 秒,回答 `{format: "litheAgentLatestVersion", version: 0, latest, publishedAtMs?, releaseNotesUrl?}`。新增错误码 `agents.invalidVersionQuery`(请求本身不合规则)、`agents.latestVersionFailed`(函数失败或超时)、`agents.invalidLatestVersion`(回答不合规则),沿用 `agents.invalidPayload`、`agents.userActionRequired`、`agents.unknownAgent`、`agents.runNotGranted`、`agents.backendUnavailable`。新增日志事件 `agent.versions.check_finished`、`agent.versions.check_failed`、`agent.versions.read_finished`、`agent.versions.read_failed`,不记版本号、路径和网址。样例见 `contract/v1/fixtures/agents/cli-versions.json`。没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码,只更新说明。 | ## 按协议查首次出现 @@ -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..a47b8cde 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -730,6 +730,26 @@ way, with the same 10 seconds and the same `agents.configuration` permission: `credentials.store` permission; see the contract for the extra `change` fields. +An agent may also declare +[`latestVersion`](../../contract/v1/README.md#cli-versions-and-installation), +a function that looks up the newest published version of the agent's CLI. +It is an ordinary plugin function too, registered with `backend.Function(id, handler)`, +under `agents.run`; Core calls it only when the host asks +`agents.cliVersions` and waits 30 seconds: + +- It receives `{agentID, installedVersion?, toolPath?, timeoutMilliseconds, + maximumResponseBytes}` and answers + `{format: "litheAgentLatestVersion", version: 0, latest, publishedAtMs?, + releaseNotesUrl?}`. `latest` is 1–64 bytes of ASCII letters, digits, `.`, + `-`, `_` and `+`; `releaseNotesUrl` is an `https` page without user, + password or fragment. Core refuses any other field. +- It asks where the CLI is published, chosen from `toolPath` and + `installedVersion` (how the CLI was installed), within + `timeoutMilliseconds` for the whole exchange, reading at most + `maximumResponseBytes`, with the proxy and certificates the CLI itself + would use. It only reads: it never runs the update, and it reaches the + network for nothing else. + ## Testing Run these from this directory: diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 6d3b2a71..792cd5e4 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -697,6 +697,26 @@ way, with the same 10 seconds and the same `agents.configuration` permission: `credentials.store` permission; see the contract for the extra `change` fields. +An agent may also declare +[`latestVersion`](../../contract/v1/README.md#cli-versions-and-installation), +a function that looks up the newest published version of the agent's CLI. +It is an ordinary plugin function too, registered with `backend.function(id, handler)`, +under `agents.run`; Core calls it only when the host asks +`agents.cliVersions` and waits 30 seconds: + +- It receives `{agentID, installedVersion?, toolPath?, timeoutMilliseconds, + maximumResponseBytes}` and answers + `{format: "litheAgentLatestVersion", version: 0, latest, publishedAtMs?, + releaseNotesUrl?}`. `latest` is 1–64 bytes of ASCII letters, digits, `.`, + `-`, `_` and `+`; `releaseNotesUrl` is an `https` page without user, + password or fragment. Core refuses any other field. +- It asks where the CLI is published, chosen from `toolPath` and + `installedVersion` (how the CLI was installed), within + `timeoutMilliseconds` for the whole exchange, reading at most + `maximumResponseBytes`, with the proxy and certificates the CLI itself + would use. It only reads: it never runs the update, and it reaches the + network for nothing else. + ## Testing Run these from the root of this repository: diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 28da19fd..7b942fc9 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -710,6 +710,26 @@ way, with the same 10 seconds and the same `agents.configuration` permission: `credentials.store` permission; see the contract for the extra `change` fields. +An agent may also declare +[`latestVersion`](../../contract/v1/README.md#cli-versions-and-installation), +a function that looks up the newest published version of the agent's CLI. +It is an ordinary plugin function too, registered with `backend.function(id, handler)`, +under `agents.run`; Core calls it only when the host asks +`agents.cliVersions` and waits 30 seconds: + +- It receives `{agentID, installedVersion?, toolPath?, timeoutMilliseconds, + maximumResponseBytes}` and answers + `{format: "litheAgentLatestVersion", version: 0, latest, publishedAtMs?, + releaseNotesUrl?}`. `latest` is 1–64 bytes of ASCII letters, digits, `.`, + `-`, `_` and `+`; `releaseNotesUrl` is an `https` page without user, + password or fragment. Core refuses any other field. +- It asks where the CLI is published, chosen from `toolPath` and + `installedVersion` (how the CLI was installed), within + `timeoutMilliseconds` for the whole exchange, reading at most + `maximumResponseBytes`, with the proxy and certificates the CLI itself + would use. It only reads: it never runs the update, and it reaches the + network for nothing else. + ## Testing Run these from the root of this repository: diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index b9ac12ce..a30b09e0 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -907,6 +907,26 @@ way, with the same 10 seconds and the same `agents.configuration` permission: `credentials.store` permission; see the contract for the extra `change` fields. +An agent may also declare +[`latestVersion`](../../contract/v1/README.md#cli-versions-and-installation), +a function that looks up the newest published version of the agent's CLI. +It is an ordinary plugin function too, registered with `backend.function(id, handler)`, +under `agents.run`; Core calls it only when the host asks +`agents.cliVersions` and waits 30 seconds: + +- It receives `{agentID, installedVersion?, toolPath?, timeoutMilliseconds, + maximumResponseBytes}` and answers + `{format: "litheAgentLatestVersion", version: 0, latest, publishedAtMs?, + releaseNotesUrl?}`. `latest` is 1–64 bytes of ASCII letters, digits, `.`, + `-`, `_` and `+`; `releaseNotesUrl` is an `https` page without user, + password or fragment. Core refuses any other field. +- It asks where the CLI is published, chosen from `toolPath` and + `installedVersion` (how the CLI was installed), within + `timeoutMilliseconds` for the whole exchange, reading at most + `maximumResponseBytes`, with the proxy and certificates the CLI itself + would use. It only reads: it never runs the update, and it reaches the + network for nothing else. + ## Testing Run these from the root of this repository: