From 2148493dcfe28c68c089e499153fd00276c32940 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 23:27:19 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(agents):=20agentSessions.calls=20?= =?UTF-8?q?=E6=8C=89=E6=97=B6=E9=97=B4=E5=80=92=E5=BA=8F=E5=88=86=E9=A1=B5?= =?UTF-8?q?=E5=88=97=E5=87=BA=E8=B0=83=E7=94=A8=EF=BC=8C=E5=B8=A6=E8=B4=B9?= =?UTF-8?q?=E7=94=A8=E3=80=81=E7=BC=93=E5=AD=98=E5=91=BD=E4=B8=AD=E7=8E=87?= =?UTF-8?q?=E5=92=8C=E9=80=9F=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 1 + rust/crates/agent-runtime/src/lib.rs | 2 + rust/crates/agent-runtime/src/records.rs | 146 ++++++++++++++++++++++- rust/crates/agent-runtime/src/tests.rs | 34 ++++++ rust/crates/core/src/protocol/command.rs | 4 + shared/plugins/contract/v1/README.md | 14 +++ 6 files changed, 197 insertions(+), 4 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 673ff7b7..050afb55 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -497,6 +497,7 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.search` | Search recorded agent session text | | `agentSessions.read` | Read one recorded range as messages and where the next page starts | | `agentSessions.stats` | Sum recorded agent usage with the latest rate limits | +| `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | | `plugins.declarative.validate` | Validate and normalize a declarative plugin manifest | | `plugins.ui.applyResult` | Check a backend result for a plugin view and return the whole view to draw | | `plugins.web.open` | Register a plugin page for a web tool window | diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index f1b6aa89..874a0194 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -75,6 +75,7 @@ pub const AGENT_SESSION_COMMANDS: &[&str] = &[ "agentSessions.search", "agentSessions.read", "agentSessions.stats", + "agentSessions.calls", ]; /// The agent catalog, the live sessions and the session records. @@ -127,6 +128,7 @@ impl Runtime { "agentSessions.search" => self.records.search(self, payload), "agentSessions.read" => self.records.read(self, payload), "agentSessions.stats" => self.records.stats(self, payload), + "agentSessions.calls" => self.records.calls(self, payload), _ => Err(CoreError::new( ErrorCode::NotSupported, format!("Unknown agent command {command}."), diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 0eadbeed..ed539be9 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -18,10 +18,10 @@ use crate::backend::BackendLink; use crate::catalog::{record_key, split_record_key, CatalogAgent}; use crate::events::{check_rate_limits, RateLimits, RateWindow, MAX_RATE_WINDOWS}; use crate::{log, now_ms, Runtime}; -use lithe_agent_sessions::pricing::PriceTable; -use lithe_agent_sessions::stats::{GroupBy, SpeedRanker, Summarizer}; +use lithe_agent_sessions::pricing::{call_cost, PriceTable}; +use lithe_agent_sessions::stats::{call_speed, model_name, GroupBy, SpeedRanker, Summarizer}; use lithe_agent_sessions::{ - discover, ByteRange, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, + discover, ByteRange, CallEntry, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, SessionOrder, SessionParser, SessionSource, SessionStore, MAX_FILTER_DIRECTORIES, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, }; @@ -31,7 +31,7 @@ use lithe_plugin_rpc::codes; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, VecDeque}; use std::fs; use std::path::{Path, PathBuf}; use std::sync::{Mutex, MutexGuard, PoisonError, RwLock}; @@ -55,6 +55,13 @@ const MAX_MESSAGE_TEXT_BYTES: usize = 1024 * 1024; /// Longest range `lithe/host/agents/usage` sums, in days. const MAX_USAGE_DAYS: i64 = 366; +/// Most calls one `agentSessions.calls` page returns. +const MAX_CALLS_PAGE: usize = 500; + +/// Largest `offset` `agentSessions.calls` takes, which bounds the calls it +/// keeps while it walks the cache. +const MAX_CALLS_OFFSET: usize = 50_000; + /// Longest directory `agentSessions.list`'s `cwdUnder` takes, in bytes. const MAX_FILTER_DIRECTORY_BYTES: usize = 4096; @@ -678,6 +685,89 @@ impl Records { })) } + /// `agentSessions.calls`: one page of the readable agents' calls for the + /// host's request table, most recent first, each with what it would cost + /// at API prices, its cache hit rate and its output speed. `total` counts + /// every call the filter keeps. + pub fn calls(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct CallsRequest { + #[serde(default)] + agents: Option>, + #[serde(rename = "sessionID", default)] + session_id: Option, + #[serde(default)] + since_ms: Option, + #[serde(default)] + until_ms: Option, + #[serde(default)] + model: Option, + #[serde(default)] + failed: Option, + #[serde(default)] + offset: usize, + limit: usize, + } + let request: CallsRequest = crate::decode(payload)?; + if request.limit == 0 || request.limit > MAX_CALLS_PAGE || request.offset > MAX_CALLS_OFFSET + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidPage", + "Ask for 1 to 500 calls at an offset of at most 50000.", + )); + } + let Some(agents) = allowed_agents(runtime, request.agents) else { + return Ok(json!({ "calls": [], "total": 0 })); + }; + let filter = CallFilter { + agents, + session_id: request.session_id, + since_ms: request.since_ms, + until_ms: request.until_ms, + }; + // The store visits calls oldest first; the page is the newest + // `offset + limit` of them, so only that many are kept. + let keep = request.offset + request.limit; + let mut newest = VecDeque::with_capacity(keep.min(MAX_CALLS_PAGE * 2)); + let mut total = 0u64; + { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + store.for_each_call(&filter, |entry| { + let call = &entry.call; + if request + .model + .as_deref() + .is_some_and(|model| model_name(call) != Some(model)) + { + return Ok(()); + } + if request + .failed + .is_some_and(|failed| call.error_category.is_some() != failed) + { + return Ok(()); + } + total += 1; + if newest.len() == keep { + newest.pop_front(); + } + newest.push_back(entry); + Ok(()) + })?; + } + let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); + let calls: Vec = newest + .into_iter() + .rev() + .skip(request.offset) + .map(|entry| call_row(entry, prices.as_ref())) + .collect(); + Ok(json!({ "calls": calls, "total": total })) + } + /// The summaries of the calls `filter` selects, grouped by `group_by`, /// and the models ranked by median output speed over the same calls. fn summarize( @@ -921,6 +1011,54 @@ fn allowed_agents(runtime: &Runtime, requested: Option>) -> Option) -> Value { + let call = &entry.call; + let cost = prices + .and_then(|prices| { + model_name(call).and_then(|model| prices.lookup(call.provider.as_deref(), model)) + }) + .and_then(|price| call_cost(price, &call.tokens)) + .map(|cost| json!({ "usd": cost.usd, "approximate": cost.approximate })); + let tokens = &call.tokens; + let cache_hit_rate = tokens.reports_cache().then(|| { + let read = tokens.cache_read.unwrap_or(0); + let prompt = [ + tokens.input, + Some(read), + tokens.cache_write_5m, + tokens.cache_write_1h, + ] + .into_iter() + .flatten() + .fold(0u64, u64::saturating_add); + (prompt > 0).then(|| read as f64 / prompt as f64) + }); + let speed = call_speed(call); + let mut row = json!({ + "agent": entry.agent, + "path": entry.path, + "call": call, + }); + add_agent_ids(&mut row, &entry.agent); + if let Some(cwd) = &entry.cwd { + row["cwd"] = json!(cwd); + } + if let Some(cost) = cost { + row["cost"] = cost; + } + if let Some(Some(rate)) = cache_hit_rate { + row["cacheHitRate"] = json!(rate); + } + if let Some(speed) = speed { + row["speed"] = json!(speed); + } + row +} + fn add_agent_ids(value: &mut Value, key: &str) { if let Some((plugin_id, agent_id)) = split_record_key(key) { value["pluginID"] = json!(plugin_id); diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index c035c19a..4d26a714 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1548,6 +1548,40 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() { ); assert_eq!(stats["rateLimits"][0]["plan"], "pro"); + // The request table lists the same call with what Core derives from it. + let calls = harness.run("agentSessions.calls", json!({ "limit": 50 })); + assert_eq!(calls["total"], 1, "{calls}"); + let row = &calls["calls"][0]; + assert_eq!(row["agent"], AGENT_KEY, "{calls}"); + assert_eq!(row["agentID"], "sample", "{calls}"); + assert_eq!(row["call"]["tokens"]["input"], 100, "{calls}"); + assert_eq!(row["speed"]["kind"], "measured", "{calls}"); + assert_eq!(row["speed"]["tokensPerSecond"], 150.0, "{calls}"); + for (filter, total) in [ + (json!({ "limit": 1, "model": "sample-model" }), 1), + (json!({ "limit": 1, "model": "other-model" }), 0), + (json!({ "limit": 1, "failed": true }), 0), + (json!({ "limit": 1, "failed": false }), 1), + (json!({ "limit": 1, "offset": 1 }), 1), + ] { + let page = harness.run("agentSessions.calls", filter.clone()); + assert_eq!(page["total"], total, "{filter} {page}"); + } + assert_eq!( + harness.run("agentSessions.calls", json!({ "limit": 1, "offset": 1 }))["calls"], + json!([]) + ); + for page in [ + json!({ "limit": 0 }), + json!({ "limit": 501 }), + json!({ "limit": 1, "offset": 50_001 }), + ] { + assert_eq!( + harness.refused("agentSessions.calls", page), + "agentSessions.invalidPage" + ); + } + // A plugin granted agents.usage.read sees totals, never what the // sessions hold. let usage = harness diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 5eb70e86..64156de0 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -255,6 +255,8 @@ pub enum AgentsCommand { RecordsRead, /// Sums recorded usage with the latest rate limits (`agentSessions.stats`). RecordsStats, + /// Lists a page of recorded calls, most recent first (`agentSessions.calls`). + RecordsCalls, } impl AgentsCommand { @@ -278,6 +280,7 @@ impl AgentsCommand { Self::RecordsSearch => "agentSessions.search", Self::RecordsRead => "agentSessions.read", Self::RecordsStats => "agentSessions.stats", + Self::RecordsCalls => "agentSessions.calls", } } } @@ -1273,6 +1276,7 @@ impl CoreCommand { "agentSessions.search" => Some(Self::Agents(AgentsCommand::RecordsSearch)), "agentSessions.read" => Some(Self::Agents(AgentsCommand::RecordsRead)), "agentSessions.stats" => Some(Self::Agents(AgentsCommand::RecordsStats)), + "agentSessions.calls" => Some(Self::Agents(AgentsCommand::RecordsCalls)), "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index b1368697..23ab366d 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3984,6 +3984,20 @@ Lithe list, search and sum them without the CLI running: groupBy, utcOffsetSeconds}` serve the host's own views; `agent` is `/`, and `stats` groups by `day`, `agent`, `model`, `session` or `cwd`. +- `agentSessions.calls {agents?, sessionID?, sinceMs?, untilMs?, model?, + failed?, offset?, limit}` serves the host's request table: the calls the + filter keeps, most recent first, `limit` 1–500 at an `offset` of at most + 50000, with `total`, how many the filter keeps. `model` matches the model + that answered, or the one asked for when the answer did not name it; + `failed` keeps only failed (`true`) or only successful (`false`) calls. Each + row gives `agent`, `pluginID`, `agentID`, `path`, `cwd?` and `call`, the + call as `scan` reported it, plus what Core derives: `cost {usd, + approximate}` at API prices when the model is priced, `cacheHitRate` when + the call reports a cache count, and `speed {kind: measured|atLeast, + tokensPerSecond}` when its timing allows. `path` and `call.range` are what + `agentSessions.read` takes to show the call's messages. Another page or + limit refuses with `agentSessions.invalidPage`. It was added within + `agents` 0; an older Core refuses it as an unknown command. - A listed session gives `readBytes`, how many bytes of `path` the cache has read; a read range ends at most there and spans at most 16 MiB. `read` answers `{changed, messages, end}`. `end` is where the next page starts: the From 07c12d982d48a315f4488f8076283ae13bbde45e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 29 Nov 2026 00:30:05 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(agents):=20Agent=20=E8=B5=84=E6=BA=90?= =?UTF-8?q?=E5=BA=93=E7=BB=9F=E4=B8=80=E7=AE=A1=E7=90=86=E6=8C=87=E4=BB=A4?= =?UTF-8?q?=E3=80=81=E6=8A=80=E8=83=BD=E3=80=81MCP=20=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=99=A8=E5=92=8C=20Hooks=EF=BC=8C=E6=8C=89=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E5=86=99=E8=BF=9B=E5=90=84=20Agent=EF=BC=88A?= =?UTF-8?q?PI-45=200=20=E5=86=85=E8=A1=A5=E5=85=85=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 清单 agents[] 新增可选 configuration {instructions?, skills?, files?, read?, edit?},新增权限 agents.configuration; 安装审查新增 agentConfiguration 程序,Agent 目录条目带 configuration 和 mayConfigure - 新增 agent-runtime library 模块:资源库存放在平台应用数据目录,read 带修订号,save 只在修订号未变时替换, apply 把用户选中的一项改动写进一个 Agent(指令文件整份重写、技能用符号链接、MCP 与 Hooks 交给插件 edit 改暂存副本, Core 校验后原子替换,期间文件被改动就拒绝);importSkill、removeSkill 管理技能目录 - 新增宿主命令 agentLibrary.configure/read/save/apply/importSkill/removeSkill,写操作只接受用户发起的请求 - 新增 agentLibrary.* 错误码(一码一义)与日志事件 agent.library.*,日志只带分类码和计数 - 契约 README、schema、fixture(agents 插件补配置声明,invalid-manifests 新增 10 个拒绝用例)、 agents 领域参考、能力版本页、API 总表、四种官方 SDK 说明同步补充 - 协议更新记录:新增本 PR 待合入条目,回填 #220 的合入日期(其余 19 条过期记录见 #222) --- rust/Cargo.lock | 2 + rust/contracts/rust-core-api.md | 6 + rust/crates/agent-runtime/Cargo.toml | 2 + rust/crates/agent-runtime/src/catalog.rs | 35 +- rust/crates/agent-runtime/src/lib.rs | 36 +- rust/crates/agent-runtime/src/library.rs | 2375 +++++++++++++++++ rust/crates/agent-runtime/src/tests.rs | 2 + .../crates/agent-runtime/src/tests/library.rs | 677 +++++ rust/crates/core/src/protocol/command.rs | 31 +- .../core/src/runtime/dispatcher/agents.rs | 4 +- .../core/src/tests/declarative_plugins.rs | 16 +- .../diagnostics/src/catalog_generated.rs | 100 + rust/crates/plugin-agents/src/lib.rs | 222 +- rust/crates/plugin-agents/src/tests.rs | 133 + .../crates/plugin-manifest/src/permissions.rs | 9 +- rust/logging/events/agent.json | 347 ++- shared/plugins/contract/v1/README.md | 309 ++- .../v1/fixtures/agents/agents.plugin.json | 26 +- .../fixtures/manifest/invalid-manifests.json | 18 +- .../contract/v1/plugin-manifest.schema.json | 88 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 62 +- .../plugins/reference/protocol-changelog.md | 7 +- shared/plugins/sdk/go/README.md | 23 + shared/plugins/sdk/java/README.md | 23 + shared/plugins/sdk/node/README.md | 23 + shared/plugins/sdk/rust/README.md | 23 + 28 files changed, 4511 insertions(+), 96 deletions(-) create mode 100644 rust/crates/agent-runtime/src/library.rs create mode 100644 rust/crates/agent-runtime/src/tests/library.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 7d8f762b..cfba92f0 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -943,6 +943,7 @@ dependencies = [ "lithe-diagnostics", "lithe-lsp-engine", "lithe-lsp-transport", + "lithe-platform", "lithe-plugin-agents", "lithe-plugin-manifest", "lithe-plugin-model", @@ -952,6 +953,7 @@ dependencies = [ "lithe-workspace", "serde", "serde_json", + "sha2", ] [[package]] diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 050afb55..1d951ce0 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -498,6 +498,12 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.read` | Read one recorded range as messages and where the next page starts | | `agentSessions.stats` | Sum recorded agent usage with the latest rate limits | | `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | +| `agentLibrary.configure` | Open the agent library in the platform's application data | +| `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold | +| `agentLibrary.save` | Replace the library the user edited if it is still at the revision read | +| `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration | +| `agentLibrary.importSkill` | Copy a skill from an agent or a directory the user chose into the library | +| `agentLibrary.removeSkill` | Remove a library skill and its links from agents | | `plugins.declarative.validate` | Validate and normalize a declarative plugin manifest | | `plugins.ui.applyResult` | Check a backend result for a plugin view and return the whole view to draw | | `plugins.web.open` | Register a plugin page for a web tool window | diff --git a/rust/crates/agent-runtime/Cargo.toml b/rust/crates/agent-runtime/Cargo.toml index 6d45e58f..9ec10816 100644 --- a/rust/crates/agent-runtime/Cargo.toml +++ b/rust/crates/agent-runtime/Cargo.toml @@ -11,6 +11,7 @@ lithe-agent-sessions = { path = "../agent-sessions" } lithe-diagnostics = { path = "../diagnostics" } lithe-lsp-engine = { path = "../lsp-engine" } lithe-lsp-transport = { path = "../lsp-transport" } +lithe-platform = { path = "../platform" } lithe-plugin-agents = { path = "../plugin-agents" } lithe-plugin-manifest = { path = "../plugin-manifest" } lithe-plugin-model = { path = "../plugin-model" } @@ -20,6 +21,7 @@ lithe-request-context = { path = "../request-context" } lithe-workspace = { path = "../workspace" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +sha2 = "0.10" [dev-dependencies] lithe-diagnostics = { path = "../diagnostics", features = ["test-support"] } diff --git a/rust/crates/agent-runtime/src/catalog.rs b/rust/crates/agent-runtime/src/catalog.rs index f5397e0b..5215e979 100644 --- a/rust/crates/agent-runtime/src/catalog.rs +++ b/rust/crates/agent-runtime/src/catalog.rs @@ -6,7 +6,8 @@ //! session only ever runs what a valid manifest declares. use lithe_plugin_agents::{ - catalog_entry, AgentDeclaration, PERMISSION_AGENTS_RUN, PERMISSION_AGENTS_SESSIONS, + catalog_entry, AgentDeclaration, PERMISSION_AGENTS_CONFIGURATION, PERMISSION_AGENTS_RUN, + PERMISSION_AGENTS_SESSIONS, }; use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; @@ -32,6 +33,10 @@ impl PluginAgents { pub fn may_read_sessions(&self) -> bool { self.granted.contains(PERMISSION_AGENTS_SESSIONS) } + + pub fn may_configure(&self) -> bool { + self.granted.contains(PERMISSION_AGENTS_CONFIGURATION) + } } /// An agent found in the catalog. @@ -41,6 +46,7 @@ pub(crate) struct CatalogAgent { pub agent: AgentDeclaration, pub may_run: bool, pub may_read_sessions: bool, + pub may_configure: bool, } impl CatalogAgent { @@ -147,6 +153,9 @@ impl Catalog { let mut entry = catalog_entry(plugin_id, agent); entry["mayRun"] = json!(plugin.may_run()); entry["mayReadSessions"] = json!(plugin.may_read_sessions()); + if agent.configuration.is_some() { + entry["mayConfigure"] = json!(plugin.may_configure()); + } entry }) }) @@ -163,6 +172,7 @@ impl Catalog { agent: agent.clone(), may_run: plugin.may_run(), may_read_sessions: plugin.may_read_sessions(), + may_configure: plugin.may_configure(), }) } @@ -184,9 +194,32 @@ impl Catalog { agent: agent.clone(), may_run: plugin.may_run(), may_read_sessions: true, + may_configure: plugin.may_configure(), }) }) .filter(|agent| !agent.agent.session_sources.is_empty()) .collect() } + + /// Every agent that declares configuration, granted or not, in catalog + /// order. + pub fn configurable(&self) -> Vec { + let plugins = self.plugins.read().unwrap_or_else(PoisonError::into_inner); + plugins + .iter() + .flat_map(|(plugin_id, plugin)| { + plugin + .agents + .iter() + .filter(|agent| agent.configuration.is_some()) + .map(move |agent| CatalogAgent { + plugin_id: plugin_id.clone(), + agent: agent.clone(), + may_run: plugin.may_run(), + may_read_sessions: plugin.may_read_sessions(), + may_configure: plugin.may_configure(), + }) + }) + .collect() + } } diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 874a0194..1ceaa170 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -10,9 +10,11 @@ //! Core knows no agent: every agent-specific name, argument, protocol and file //! layout comes from a plugin manifest and its backend. //! -//! The host drives the runtime with two command families. `agents.*` covers -//! the catalog of declared agents and the live sessions; `agentSessions.*` -//! covers the local session records. Backends reach it with +//! The host drives the runtime with three command families. `agents.*` +//! covers the catalog of declared agents and the live sessions; +//! `agentSessions.*` covers the local session records; `agentLibrary.*` +//! covers Lithe's library of MCP servers, hooks, skills and instructions and +//! applies them to the agents' own configuration (the `library` module). Backends reach it with //! `lithe/host/agents/*` requests, which the engine hands to the installed //! [`AgentHost`] and which never reach the host application. //! @@ -27,12 +29,16 @@ //! - Session records are read only for agents the user granted //! `agents.sessions.read`. Plugins granted `agents.usage.read` see totals //! and rate limits, never text, titles, session IDs or directories. +//! - An agent's configuration changes only for a request the user started, +//! only for plugins granted `agents.configuration`, and MCP servers and +//! hooks only through a staged copy the plugin edits and Core checks. //! - Logs carry opaque IDs and stable codes, never what flows through a //! session. mod backend; mod catalog; mod events; +mod library; mod live; mod records; @@ -41,6 +47,7 @@ mod tests; use backend::{BackendLink, EngineLink}; use catalog::Catalog; +use library::Library; use lithe_lsp_engine::agent_host::{install_agent_host, AgentBackend, AgentHost, AgentHostFailure}; use lithe_plugin_rpc::{codes, AGENTS_REPORT, AGENTS_USAGE, AGENTS_WRITE}; use lithe_protocol::{CoreError, ErrorCode}; @@ -78,12 +85,24 @@ pub const AGENT_SESSION_COMMANDS: &[&str] = &[ "agentSessions.calls", ]; -/// The agent catalog, the live sessions and the session records. +/// The commands of the `agentLibrary.*` family. +pub const AGENT_LIBRARY_COMMANDS: &[&str] = &[ + "agentLibrary.configure", + "agentLibrary.read", + "agentLibrary.save", + "agentLibrary.apply", + "agentLibrary.importSkill", + "agentLibrary.removeSkill", +]; + +/// The agent catalog, the live sessions, the session records and the +/// agent library. pub(crate) struct Runtime { pub link: Arc, pub catalog: Catalog, pub live: Live, pub records: Records, + pub library: Library, } impl Runtime { @@ -93,6 +112,7 @@ impl Runtime { catalog: Catalog::default(), live: Live::default(), records: Records::default(), + library: Library::default(), }) } @@ -129,6 +149,12 @@ impl Runtime { "agentSessions.read" => self.records.read(self, payload), "agentSessions.stats" => self.records.stats(self, payload), "agentSessions.calls" => self.records.calls(self, payload), + "agentLibrary.configure" => self.library.configure(payload), + "agentLibrary.read" => self.library.read(self, payload), + "agentLibrary.save" => self.library.save(payload), + "agentLibrary.apply" => self.library.apply(self, payload), + "agentLibrary.importSkill" => self.library.import_skill(self, payload), + "agentLibrary.removeSkill" => self.library.remove_skill(self, payload), _ => Err(CoreError::new( ErrorCode::NotSupported, format!("Unknown agent command {command}."), @@ -174,7 +200,7 @@ fn runtime() -> &'static Arc { }) } -/// Runs one `agents.*` or `agentSessions.*` command. +/// Runs one `agents.*`, `agentSessions.*` or `agentLibrary.*` command. pub fn execute(command: &str, payload: Value) -> Result { runtime().execute(command, payload) } diff --git a/rust/crates/agent-runtime/src/library.rs b/rust/crates/agent-runtime/src/library.rs new file mode 100644 index 00000000..911f4c75 --- /dev/null +++ b/rust/crates/agent-runtime/src/library.rs @@ -0,0 +1,2375 @@ +//! Lithe's agent library (plan API-45): MCP servers, hooks, skills and +//! instruction sets the user keeps once and turns on for each agent. +//! +//! The library is Lithe's own data, in a directory of the platform's +//! application data that the host names with `agentLibrary.configure`: +//! `library.json` holds the servers, hooks and instruction sets, +//! `skills//` holds one directory per skill, `state.json` records what +//! Core last wrote to each agent's instruction file, and `staging/` holds the +//! copies plugins edit. +//! +//! What an agent has is read from the agent's own files every time and never +//! kept. An agent plugin declares where they are (`configuration` in the +//! manifest). Core reads the instruction file and the skills directory +//! itself; the plugin backend reads the MCP servers and hooks from the CLI's +//! own formats. A library item is on for an agent when the agent's files hold +//! an identical item. +//! +//! Core changes an agent's files only for a user request, only for a plugin +//! granted `agents.configuration`, and only in these ways: +//! +//! - MCP servers and hooks: Core copies the file into `staging/`, the plugin +//! edits only the copy, the plugin reads the copy back to show the change +//! took effect, and Core replaces the file with the copy if the file has +//! not changed since it was copied. The replacement is a new file, with the +//! old file's permissions, renamed over it. +//! - Skills: a library skill is turned on as a symbolic link in the agent's +//! skills directory; turning it off removes only a link into the library. +//! - Instructions: Core writes the active instruction set and the agent's +//! extra text, and refuses to replace text it did not write unless the user +//! confirms. +//! +//! Logs carry plugin and agent IDs, categories, counts and codes, never +//! names, commands, paths or text. + +use crate::backend::BackendLink; +use crate::catalog::CatalogAgent; +use crate::{log, Runtime}; +use lithe_plugin_agents::{resolve_root, ConfigurationDeclaration}; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_request_context::Source; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError, RwLock}; +use std::time::{Duration, Instant}; + +const LIBRARY_FILE: &str = "library.json"; +const STATE_FILE: &str = "state.json"; +const SKILLS_DIRECTORY: &str = "skills"; +const STAGING_DIRECTORY: &str = "staging"; +const SKILL_FILE: &str = "SKILL.md"; +/// The revision of a library that was never saved. +const EMPTY_REVISION: &str = "empty"; + +const READ_FORMAT: &str = "litheAgentConfiguration"; +const EDIT_FORMAT: &str = "litheAgentConfigurationEdit"; +const FUNCTION_TIMEOUT: Duration = Duration::from_secs(10); + +const MAX_SERVERS: usize = 256; +const MAX_HOOKS: usize = 256; +const MAX_HOOK_EVENTS: usize = 32; +const MAX_EVENT_BYTES: usize = 64; +const MAX_SKILLS: usize = 512; +const MAX_NAME_CHARS: usize = 128; +const MAX_TEXT_BYTES: usize = 4096; +const MAX_DESCRIPTION_CHARS: usize = 1024; +const MAX_ARGUMENTS: usize = 64; +const MAX_VARIABLE_NAMES: usize = 64; +const MAX_HOOK_TIMEOUT_SECONDS: u32 = 86_400; +const MAX_SETS: usize = 64; +const MAX_SET_TEXT_BYTES: usize = 256 * 1024; +const MAX_EXTRA_BYTES: usize = 64 * 1024; +const MAX_AGENT_ENTRIES: usize = 256; +const MAX_LIBRARY_FILE_BYTES: u64 = 8 * 1024 * 1024; +const MAX_CONFIGURATION_FILE_BYTES: u64 = 16 * 1024 * 1024; +const MAX_INSTRUCTIONS_FILE_BYTES: u64 = 1024 * 1024; +const MAX_SKILL_FILE_BYTES: u64 = 64 * 1024; +const MAX_IMPORT_FILES: usize = 1024; +const MAX_IMPORT_BYTES: u64 = 16 * 1024 * 1024; +const MAX_IMPORT_DEPTH: usize = 16; + +#[derive(Debug, Clone)] +struct Config { + directory: PathBuf, + user_home: String, + environment: BTreeMap, +} + +/// The library directory and the lock that orders changes. +#[derive(Default)] +pub(crate) struct Library { + config: RwLock>, + /// Held while a change checks and replaces a file, so two changes never + /// interleave. Never held across a backend call. + writing: Mutex<()>, +} + +// --------------------------------------------------------------------------- +// The library's data. + +/// How a client reaches an MCP server. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +enum Transport { + Stdio, + Http, + Sse, +} + +/// An MCP server of the library. A server with environment variables or +/// headers is not kept in version 0: their values are secrets Lithe does not +/// store. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Server { + name: String, + transport: Transport, + #[serde(default, skip_serializing_if = "Option::is_none")] + command: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + args: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + url: Option, +} + +/// A hook command as the agents run it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Hook { + event: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + matcher: Option, + command: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + timeout_seconds: Option, +} + +impl Hook { + /// Two hooks are the same when they run the same command for the same + /// event and matcher; an empty matcher is no matcher. + fn same(&self, event: &str, matcher: Option<&str>, command: &str) -> bool { + self.event == event + && self.matcher.as_deref().filter(|m| !m.is_empty()) + == matcher.filter(|m| !m.is_empty()) + && self.command == command + } +} + +/// A hook of the library, with an ID the host chose. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LibraryHook { + id: String, + event: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + matcher: Option, + command: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + timeout_seconds: Option, +} + +impl LibraryHook { + fn hook(&self) -> Hook { + Hook { + event: self.event.clone(), + matcher: self.matcher.clone().filter(|m| !m.is_empty()), + command: self.command.clone(), + timeout_seconds: self.timeout_seconds, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct InstructionSet { + id: String, + name: String, + #[serde(default)] + text: String, +} + +/// Whether an agent's instruction file follows the library, and the text +/// only that agent gets after the shared set. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AgentInstructions { + #[serde(default)] + enabled: bool, + #[serde(default, skip_serializing_if = "String::is_empty")] + extra: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Instructions { + #[serde(default)] + sets: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + active: Option, + /// By agent key, `/`. + #[serde(default)] + agents: BTreeMap, +} + +/// What the user keeps in the library, as the host reads and saves it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LibraryData { + #[serde(default)] + mcp_servers: Vec, + #[serde(default)] + hooks: Vec, + #[serde(default)] + instructions: Instructions, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LibraryFile { + version: u32, + library: LibraryData, +} + +/// What Core wrote, kept apart from the library so writing an agent's file +/// never changes the library's revision. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StateFile { + version: u32, + /// SHA-256 of the text Core last wrote to each agent's instruction file. + #[serde(default)] + instructions: BTreeMap, +} + +// --------------------------------------------------------------------------- +// What an agent plugin reports. + +/// Where an item an agent has comes from: the user's own configuration, +/// which the plugin can edit, or something the CLI installed itself, such as +/// a CLI plugin, which Lithe only shows. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +enum Origin { + User, + Agent, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AgentServer { + name: String, + transport: Transport, + #[serde(default, skip_serializing_if = "Option::is_none")] + command: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + args: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + url: Option, + /// Names of the environment variables the server is given; never values. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + environment_names: Vec, + /// Names of the HTTP headers the server is sent; never values. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + header_names: Vec, + origin: Origin, + /// What installed it when `origin` is `agent`, such as a CLI plugin. + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, +} + +impl AgentServer { + /// Whether it is exactly `server`, with nothing Lithe does not keep. + fn is(&self, server: &Server) -> bool { + self.environment_names.is_empty() + && self.header_names.is_empty() + && self.name == server.name + && self.transport == server.transport + && self.command == server.command + && self.args == server.args + && self.url == server.url + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AgentHook { + event: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + matcher: Option, + command: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + timeout_seconds: Option, + origin: Origin, + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, +} + +impl AgentHook { + fn is(&self, hook: &Hook) -> bool { + hook.same(&self.event, self.matcher.as_deref(), &self.command) + } +} + +/// A skill the CLI installed itself; the skills directory is read by Core. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProvidedSkill { + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, +} + +/// The declared file a plugin changes for each category. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Targets { + #[serde(default, skip_serializing_if = "Option::is_none")] + mcp_servers: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + hooks: Option, +} + +/// The answer of a configuration `read` function. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Snapshot { + format: String, + version: u32, + #[serde(default)] + mcp_servers: Vec, + #[serde(default)] + hooks: Vec, + /// The hook events the CLI runs, for choosing one. + #[serde(default)] + hook_events: Vec, + #[serde(default)] + skills: Vec, + #[serde(default)] + targets: Targets, +} + +/// Whether a re-read staged copy shows the change the plugin was asked for. +type ShowsChange = Box bool>; + +/// The answer of a configuration `edit` function. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct EditAnswer { + format: String, + version: u32, + changed: bool, +} + +// --------------------------------------------------------------------------- +// Checks. + +/// A field of `field` is invalid. +type Check = Result<(), String>; + +fn check_name(name: &str, field: &str) -> Check { + let count = name.chars().count(); + if count == 0 + || count > MAX_NAME_CHARS + || name.trim() != name + || name.chars().any(char::is_control) + { + return Err(field.to_string()); + } + Ok(()) +} + +fn check_text(text: &str, field: &str, required: bool) -> Check { + if (required && text.trim().is_empty()) || text.len() > MAX_TEXT_BYTES || text.contains('\0') { + return Err(field.to_string()); + } + Ok(()) +} + +fn check_optional_text(text: Option<&str>, field: &str) -> Check { + text.map_or(Ok(()), |text| check_text(text, field, false)) +} + +fn check_optional_name(name: Option<&str>, field: &str) -> Check { + name.map_or(Ok(()), |name| check_name(name, field)) +} + +fn check_description(text: Option<&str>, field: &str) -> Check { + match text { + Some(text) if text.chars().count() > MAX_DESCRIPTION_CHARS || text.contains('\0') => { + Err(field.to_string()) + } + _ => Ok(()), + } +} + +/// An ID the host chose: lowercase letters, digits and `-`, 1 to 64 bytes. +fn is_item_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 64 + && id + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +/// A hook event as the CLIs name them: ASCII letters, digits and `_`. +fn is_event(event: &str) -> bool { + !event.is_empty() + && event.len() <= MAX_EVENT_BYTES + && event.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// An environment variable or header name: ASCII letters, digits, `_` and +/// `-`, 1 to 128 bytes. +fn is_variable_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= MAX_NAME_CHARS + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +/// A skill's directory name: ASCII letters, digits, `.`, `_` and `-`, not +/// starting with `.`, 1 to 64 bytes. +fn is_skill_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 64 + && !name.starts_with('.') + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-') +} + +fn check_transport( + transport: Transport, + command: Option<&str>, + args: &[String], + url: Option<&str>, + field: &str, +) -> Check { + check_optional_text(command, &format!("{field}.command"))?; + check_optional_text(url, &format!("{field}.url"))?; + if args.len() > MAX_ARGUMENTS { + return Err(format!("{field}.args")); + } + for (index, argument) in args.iter().enumerate() { + check_text(argument, &format!("{field}.args[{index}]"), false)?; + } + match transport { + Transport::Stdio => { + if command.is_none_or(|command| command.trim().is_empty()) || url.is_some() { + return Err(format!("{field}.command")); + } + } + Transport::Http | Transport::Sse => { + let web = + url.is_some_and(|url| url.starts_with("http://") || url.starts_with("https://")); + if !web || command.is_some() || !args.is_empty() { + return Err(format!("{field}.url")); + } + } + } + Ok(()) +} + +fn check_hook_fields( + event: &str, + matcher: Option<&str>, + command: &str, + timeout: Option, + field: &str, +) -> Check { + if !is_event(event) { + return Err(format!("{field}.event")); + } + check_optional_text(matcher, &format!("{field}.matcher"))?; + check_text(command, &format!("{field}.command"), true)?; + if timeout.is_some_and(|seconds| seconds == 0 || seconds > MAX_HOOK_TIMEOUT_SECONDS) { + return Err(format!("{field}.timeoutSeconds")); + } + Ok(()) +} + +impl Server { + fn check(&self, field: &str) -> Check { + check_name(&self.name, &format!("{field}.name"))?; + check_transport( + self.transport, + self.command.as_deref(), + &self.args, + self.url.as_deref(), + field, + ) + } +} + +impl LibraryData { + fn check(&self) -> Check { + if self.mcp_servers.len() > MAX_SERVERS { + return Err("mcpServers".into()); + } + let mut names = BTreeSet::new(); + for (index, server) in self.mcp_servers.iter().enumerate() { + let field = format!("mcpServers[{index}]"); + server.check(&field)?; + if !names.insert(server.name.as_str()) { + return Err(format!("{field}.name")); + } + } + if self.hooks.len() > MAX_HOOKS { + return Err("hooks".into()); + } + let mut ids = BTreeSet::new(); + for (index, hook) in self.hooks.iter().enumerate() { + let field = format!("hooks[{index}]"); + if !is_item_id(&hook.id) || !ids.insert(hook.id.as_str()) { + return Err(format!("{field}.id")); + } + check_hook_fields( + &hook.event, + hook.matcher.as_deref(), + &hook.command, + hook.timeout_seconds, + &field, + )?; + } + let instructions = &self.instructions; + if instructions.sets.len() > MAX_SETS { + return Err("instructions.sets".into()); + } + let mut set_ids = BTreeSet::new(); + for (index, set) in instructions.sets.iter().enumerate() { + let field = format!("instructions.sets[{index}]"); + if !is_item_id(&set.id) || !set_ids.insert(set.id.as_str()) { + return Err(format!("{field}.id")); + } + check_name(&set.name, &format!("{field}.name"))?; + if set.text.len() > MAX_SET_TEXT_BYTES || set.text.contains('\0') { + return Err(format!("{field}.text")); + } + } + if instructions + .active + .as_deref() + .is_some_and(|active| !set_ids.contains(active)) + { + return Err("instructions.active".into()); + } + if instructions.agents.len() > MAX_AGENT_ENTRIES { + return Err("instructions.agents".into()); + } + for (key, agent) in &instructions.agents { + let field = format!("instructions.agents[{key}]"); + if key.len() > 512 || !key.contains('/') { + return Err(field); + } + if agent.extra.len() > MAX_EXTRA_BYTES || agent.extra.contains('\0') { + return Err(format!("{field}.extra")); + } + } + Ok(()) + } + + /// The instruction text of the agent `key`: the active set, then the + /// agent's extra text, ending with one line break. Empty when neither has + /// text. + fn compose(&self, key: &str) -> String { + let instructions = &self.instructions; + let shared = instructions + .active + .as_deref() + .and_then(|active| instructions.sets.iter().find(|set| set.id == active)) + .map_or("", |set| set.text.trim_end()); + let extra = instructions + .agents + .get(key) + .map_or("", |agent| agent.extra.trim()); + let mut text = shared.to_string(); + if !extra.is_empty() { + if !text.is_empty() { + text.push_str("\n\n"); + } + text.push_str(extra); + } + if !text.is_empty() { + text.push('\n'); + } + text + } +} + +impl Snapshot { + fn check(&self, file_ids: &BTreeSet<&str>) -> Check { + if self.format != READ_FORMAT || self.version != 0 { + return Err("format".into()); + } + if self.mcp_servers.len() > MAX_SERVERS { + return Err("mcpServers".into()); + } + for (index, server) in self.mcp_servers.iter().enumerate() { + let field = format!("mcpServers[{index}]"); + check_name(&server.name, &format!("{field}.name"))?; + check_transport( + server.transport, + server.command.as_deref(), + &server.args, + server.url.as_deref(), + &field, + )?; + for (list, names) in [ + ("environmentNames", &server.environment_names), + ("headerNames", &server.header_names), + ] { + if names.len() > MAX_VARIABLE_NAMES || !names.iter().all(|n| is_variable_name(n)) { + return Err(format!("{field}.{list}")); + } + } + check_optional_name(server.provider.as_deref(), &format!("{field}.provider"))?; + } + if self.hooks.len() > MAX_HOOKS { + return Err("hooks".into()); + } + for (index, hook) in self.hooks.iter().enumerate() { + let field = format!("hooks[{index}]"); + check_hook_fields( + &hook.event, + hook.matcher.as_deref(), + &hook.command, + hook.timeout_seconds, + &field, + )?; + check_optional_name(hook.provider.as_deref(), &format!("{field}.provider"))?; + } + if self.hook_events.len() > MAX_HOOK_EVENTS + || !self.hook_events.iter().all(|event| is_event(event)) + || self.hook_events.iter().collect::>().len() != self.hook_events.len() + { + return Err("hookEvents".into()); + } + if self.skills.len() > MAX_SKILLS { + return Err("skills".into()); + } + for (index, skill) in self.skills.iter().enumerate() { + let field = format!("skills[{index}]"); + check_name(&skill.name, &format!("{field}.name"))?; + check_description( + skill.description.as_deref(), + &format!("{field}.description"), + )?; + check_optional_name(skill.provider.as_deref(), &format!("{field}.provider"))?; + } + for (name, target) in [ + ("targets.mcpServers", &self.targets.mcp_servers), + ("targets.hooks", &self.targets.hooks), + ] { + if target.as_deref().is_some_and(|id| !file_ids.contains(id)) { + return Err(name.into()); + } + } + Ok(()) + } + + fn supports_event(&self, event: &str) -> bool { + self.hook_events.is_empty() || self.hook_events.iter().any(|known| known == event) + } +} + +// --------------------------------------------------------------------------- +// Files. + +/// Why a bounded read failed. +#[derive(Debug)] +enum ReadFailure { + TooLarge, + Io, +} + +/// The bytes of the file at `path`, following links; `None` when nothing is +/// there. +fn read_bounded(path: &Path, max: u64) -> Result>, ReadFailure> { + let mut file = match fs::File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(_) => return Err(ReadFailure::Io), + }; + let metadata = file.metadata().map_err(|_| ReadFailure::Io)?; + if !metadata.is_file() { + return Err(ReadFailure::Io); + } + if metadata.len() > max { + return Err(ReadFailure::TooLarge); + } + let mut bytes = Vec::new(); + Read::by_ref(&mut file) + .take(max + 1) + .read_to_end(&mut bytes) + .map_err(|_| ReadFailure::Io)?; + if bytes.len() as u64 > max { + return Err(ReadFailure::TooLarge); + } + Ok(Some(bytes)) +} + +fn digest(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// A new name next to `target` for a file that replaces it. +fn sibling_temporary(target: &Path, purpose: &str) -> Option { + static NEXT: AtomicU64 = AtomicU64::new(0); + let parent = target.parent()?; + let name = target.file_name()?.to_string_lossy(); + Some(parent.join(format!( + ".{name}.lithe-{purpose}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + ))) +} + +/// Replaces the file at `target` with `bytes`: a new file next to it, with +/// the old file's permissions (owner-only for a new file), written to disk, +/// then renamed over it. `target` is never a link; callers resolve links +/// first. +fn write_replacing(target: &Path, bytes: &[u8]) -> io::Result<()> { + let temporary = sibling_temporary(target, "write") + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + let existing = fs::metadata(target).ok(); + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + let mode = existing + .as_ref() + .map_or(0o600, |metadata| metadata.permissions().mode() & 0o7777); + options.mode(mode); + } + let result = (|| { + let mut file = options.open(&temporary)?; + file.write_all(bytes)?; + if let Some(metadata) = &existing { + // The mode given to `open` is narrowed by the umask. + fs::set_permissions(&temporary, metadata.permissions())?; + } + file.sync_all()?; + drop(file); + fs::rename(&temporary, target) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + } + result +} + +/// The file a path names, through any links. A path whose link leads +/// nowhere is refused, since replacing the link would lose where it pointed. +fn real_file(path: &Path) -> Result { + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_symlink() => fs::canonicalize(path).map_err(|_| { + refusal( + ErrorCode::EntryNotFound, + "agentLibrary.brokenLink", + "A configuration file is a link to nothing.", + ) + }), + Ok(_) => Ok(path.to_path_buf()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(path.to_path_buf()), + Err(_) => Err(unreadable_file()), + } +} + +fn ensure_directory(path: &Path) -> Result<(), CoreError> { + fs::create_dir_all(path).map_err(|_| write_failed()) +} + +/// Creates the library directory owner-only. +fn ensure_private_directory(path: &Path) -> Result<(), CoreError> { + if path.is_dir() { + return Ok(()); + } + fs::create_dir_all(path).map_err(|_| write_failed())?; + lithe_platform::fs::restrict_directory_to_owner(path).map_err(|_| write_failed()) +} + +/// Removes a link, which Windows keeps as a directory when it points at one. +fn remove_link(path: &Path) -> io::Result<()> { + fs::remove_file(path).or_else(|_| fs::remove_dir(path)) +} + +/// Whether the link at `link` leads into `directory`. +fn links_into(link: &Path, directory: &Path) -> bool { + let (Ok(target), Ok(directory)) = (fs::canonicalize(link), fs::canonicalize(directory)) else { + return false; + }; + target.starts_with(directory) +} + +// --------------------------------------------------------------------------- +// Skills. + +/// A skill's `name` and `description` from the YAML front matter of its +/// `SKILL.md`. Only plain, quoted and block scalars are read. +fn front_matter(text: &str) -> (Option, Option) { + /// A block scalar being read: its key, whether it folds its lines, and + /// the lines so far. + type Block = (&'static str, bool, Vec); + fn finish(values: &mut BTreeMap<&'static str, String>, block: Option) { + if let Some((key, folded, parts)) = block { + let parts: Vec<&str> = parts + .iter() + .map(String::as_str) + .filter(|part| !folded || !part.is_empty()) + .collect(); + let text = parts.join(if folded { " " } else { "\n" }); + values.insert(key, text.trim().to_string()); + } + } + + let mut lines = text.lines(); + if lines.next().map(str::trim_end) != Some("---") { + return (None, None); + } + let mut values: BTreeMap<&'static str, String> = BTreeMap::new(); + let mut block: Option = None; + for line in lines { + if line.trim_end() == "---" { + break; + } + let indented = line.starts_with(' ') || line.starts_with('\t'); + if let Some((_, _, parts)) = block.as_mut() { + if indented || line.trim().is_empty() { + parts.push(line.trim().to_string()); + continue; + } + finish(&mut values, block.take()); + } + if indented { + continue; + } + let Some((key, value)) = line.split_once(':') else { + continue; + }; + let key: &'static str = match key.trim() { + "name" => "name", + "description" => "description", + _ => continue, + }; + let value = value.trim(); + if value.starts_with('|') || value.starts_with('>') { + block = Some((key, value.starts_with('>'), Vec::new())); + } else { + values.insert(key, unquote(value)); + } + } + finish(&mut values, block.take()); + let mut take = |key| values.remove(key).filter(|value| !value.is_empty()); + let name = take("name"); + let description = + take("description").map(|text| text.chars().take(MAX_DESCRIPTION_CHARS).collect()); + (name, description) +} + +fn unquote(value: &str) -> String { + let bytes = value.as_bytes(); + if bytes.len() >= 2 { + let (first, last) = (bytes[0], bytes[bytes.len() - 1]); + if first == last && (first == b'"' || first == b'\'') { + let inner = &value[1..value.len() - 1]; + return if first == b'"' { + inner.replace("\\\"", "\"") + } else { + inner.replace("''", "'") + }; + } + } + value.to_string() +} + +/// The description in the `SKILL.md` of `directory`, if it has one; `None` +/// as the outer value when there is no readable `SKILL.md`. +fn skill_description(directory: &Path) -> Option> { + let bytes = match read_bounded(&directory.join(SKILL_FILE), MAX_SKILL_FILE_BYTES) { + Ok(Some(bytes)) => bytes, + Ok(None) | Err(ReadFailure::Io) => return None, + // A skill too large to read for its description is still a skill. + Err(ReadFailure::TooLarge) => return Some(None), + }; + Some(front_matter(&String::from_utf8_lossy(&bytes)).1) +} + +/// The skills of the library, by name. +fn library_skills(directory: &Path) -> Vec<(String, Option)> { + let Ok(entries) = fs::read_dir(directory.join(SKILLS_DIRECTORY)) else { + return Vec::new(); + }; + let mut skills: Vec<(String, Option)> = entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + if !is_skill_name(&name) { + return None; + } + Some((name, skill_description(&entry.path())?)) + }) + .take(MAX_SKILLS) + .collect(); + skills.sort_by(|left, right| left.0.cmp(&right.0)); + skills +} + +/// What one entry of an agent's skills directory is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SkillKind { + /// A link into the library. + Library, + /// A directory of the agent's own. + Own, + /// A link somewhere else. + Link, +} + +impl SkillKind { + fn token(self) -> &'static str { + match self { + SkillKind::Library => "library", + SkillKind::Own => "own", + SkillKind::Link => "link", + } + } +} + +struct AgentSkill { + name: String, + description: Option, + kind: SkillKind, +} + +/// The skills in an agent's skills directory; empty when it does not exist. +fn agent_skills(root: &Path, library: &Path) -> Result, ReadFailure> { + let entries = match fs::read_dir(root) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(_) => return Err(ReadFailure::Io), + }; + let library_skills = library.join(SKILLS_DIRECTORY); + let mut skills = Vec::new(); + for entry in entries.filter_map(Result::ok) { + let Ok(name) = entry.file_name().into_string() else { + continue; + }; + if name.starts_with('.') || check_name(&name, "").is_err() { + continue; + } + let path = entry.path(); + let Ok(kind) = entry.file_type() else { + continue; + }; + let kind = if kind.is_symlink() { + if links_into(&path, &library_skills) { + SkillKind::Library + } else { + SkillKind::Link + } + } else if kind.is_dir() { + SkillKind::Own + } else { + continue; + }; + let Some(description) = skill_description(&path) else { + continue; + }; + skills.push(AgentSkill { + name, + description, + kind, + }); + if skills.len() == MAX_SKILLS { + break; + } + } + skills.sort_by(|left, right| left.name.cmp(&right.name)); + Ok(skills) +} + +/// Counts of a tree copy. +#[derive(Default)] +struct Copied { + files: usize, + bytes: u64, + skipped: usize, +} + +/// Copies the regular files and directories of `from` into the new directory +/// `to`, skipping links and other entries, within the import bounds. +fn copy_tree(from: &Path, to: &Path, depth: usize, copied: &mut Copied) -> Result<(), CoreError> { + if depth > MAX_IMPORT_DEPTH { + return Err(too_large_skill()); + } + fs::create_dir(to).map_err(|_| write_failed())?; + let entries = fs::read_dir(from).map_err(|_| unreadable_file())?; + for entry in entries { + let entry = entry.map_err(|_| unreadable_file())?; + let kind = entry.file_type().map_err(|_| unreadable_file())?; + let target = to.join(entry.file_name()); + if kind.is_dir() { + copy_tree(&entry.path(), &target, depth + 1, copied)?; + } else if kind.is_file() { + copied.files += 1; + if copied.files > MAX_IMPORT_FILES { + return Err(too_large_skill()); + } + let length = entry.metadata().map_err(|_| unreadable_file())?.len(); + copied.bytes += length; + if copied.bytes > MAX_IMPORT_BYTES { + return Err(too_large_skill()); + } + fs::copy(entry.path(), &target).map_err(|_| write_failed())?; + } else { + copied.skipped += 1; + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Refusals. + +fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { + CoreError::new(code, message).with_details(details) +} + +fn not_configured() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.notConfigured", + "The agent library is not configured.", + ) +} + +fn unreadable_file() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentLibrary.unreadable", + "A file of the agent library or an agent could not be read.", + ) +} + +fn write_failed() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentLibrary.writeFailed", + "A file of the agent library or an agent could not be written.", + ) +} + +fn too_large_file() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.fileTooLarge", + "A configuration file is larger than Lithe reads.", + ) +} + +fn too_large_skill() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.skillTooLarge", + "The skill has more files, bytes or levels than Lithe copies.", + ) +} + +fn read_failure(failure: ReadFailure) -> CoreError { + match failure { + ReadFailure::TooLarge => too_large_file(), + ReadFailure::Io => unreadable_file(), + } +} + +fn invalid_change(message: &str) -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidChange", + message, + ) +} + +fn require_user() -> Result<(), CoreError> { + if lithe_request_context::trace::current().source == Source::User { + Ok(()) + } else { + Err(refusal( + ErrorCode::PermissionDenied, + "agentLibrary.userActionRequired", + "Only the user can change the agent library or an agent's configuration.", + )) + } +} + +// --------------------------------------------------------------------------- +// One agent's files. + +/// Where an agent's configuration is on this machine. +struct AgentPaths { + instructions: Option, + skills: Option, + /// Declared files whose path resolves, by ID. + files: Vec<(String, PathBuf)>, +} + +fn agent_paths(config: &Config, configuration: &ConfigurationDeclaration) -> AgentPaths { + let resolve = |roots: &[String]| resolve_root(roots, &config.user_home, &config.environment); + AgentPaths { + instructions: configuration + .instructions + .as_ref() + .and_then(|roots| resolve(&roots.roots)), + skills: configuration + .skills + .as_ref() + .and_then(|roots| resolve(&roots.roots)), + files: configuration + .files + .iter() + .filter_map(|file| Some((file.id.clone(), resolve(&file.roots)?))) + .collect(), + } +} + +fn path_text(path: &Path) -> String { + path.to_string_lossy().into_owned() +} + +/// Asks the plugin for what the agent's files hold. `files` gives each +/// declared file's path; a staged copy stands in for a file being changed. +fn read_snapshot( + link: &dyn BackendLink, + agent: &CatalogAgent, + configuration: &ConfigurationDeclaration, + files: &[(String, PathBuf)], +) -> Result { + let Some(function) = configuration.read.as_deref() else { + return Ok(Snapshot { + format: READ_FORMAT.into(), + version: 0, + mcp_servers: Vec::new(), + hooks: Vec::new(), + hook_events: Vec::new(), + skills: Vec::new(), + targets: Targets::default(), + }); + }; + let backend = link + .session_for(&agent.plugin_id, function, None) + .ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.backendUnavailable", + "The agent plugin's backend is not running.", + ) + })?; + let params = json!({ + "agentID": agent.agent.id, + "files": files + .iter() + .map(|(id, path)| json!({ + "id": id, + "path": path_text(path), + "exists": fs::symlink_metadata(path).is_ok(), + })) + .collect::>(), + }); + let answer = link + .call( + &backend, + &agent.plugin_id, + function, + params, + FUNCTION_TIMEOUT, + ) + .map_err(|_| { + refusal( + ErrorCode::ProcessFailed, + "agentLibrary.readFailed", + "The agent plugin could not read the agent's configuration.", + ) + })?; + let invalid = || { + refusal( + ErrorCode::ParseFailed, + "agentLibrary.invalidSnapshot", + "The agent plugin returned an invalid configuration.", + ) + }; + let snapshot: Snapshot = serde_json::from_value(answer).map_err(|_| invalid())?; + let ids: BTreeSet<&str> = configuration.files.iter().map(|f| f.id.as_str()).collect(); + snapshot.check(&ids).map_err(|_| invalid())?; + Ok(snapshot) +} + +/// What an agent's instruction file holds, compared with the library. +fn instructions_state( + current: &Result>, ReadFailure>, + composed: &str, + written: Option<&String>, +) -> &'static str { + match current { + Err(ReadFailure::TooLarge) => "tooLarge", + Err(ReadFailure::Io) => "unreadable", + Ok(None) => "absent", + Ok(Some(bytes)) if bytes == composed.as_bytes() => "current", + Ok(Some(bytes)) if String::from_utf8_lossy(bytes).trim().is_empty() => "empty", + Ok(Some(bytes)) if written.is_some_and(|written| *written == digest(bytes)) => "written", + Ok(Some(_)) => "other", + } +} + +/// An agent as `agentLibrary.read` reports it, with what Core needs to +/// derive the library's states. +struct AgentView { + key: String, + entry: Value, + snapshot: Option, + skills: Option>, +} + +// --------------------------------------------------------------------------- +// Commands. + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct EmptyRequest {} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Category { + McpServers, + Hooks, + Skills, + Instructions, +} + +impl Category { + fn token(self) -> &'static str { + match self { + Category::McpServers => "mcpServers", + Category::Hooks => "hooks", + Category::Skills => "skills", + Category::Instructions => "instructions", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Operation { + Put, + Remove, + Link, + Unlink, + Write, +} + +impl Operation { + fn token(self) -> &'static str { + match self { + Operation::Put => "put", + Operation::Remove => "remove", + Operation::Link => "link", + Operation::Unlink => "unlink", + Operation::Write => "write", + } + } +} + +/// One change to one agent's configuration. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Change { + category: Category, + op: Operation, + /// The MCP server or skill. + #[serde(default)] + name: Option, + /// The library hook to put. + #[serde(default)] + id: Option, + /// The agent's hook to remove. + #[serde(default)] + hook: Option, + /// Write instructions over text Lithe did not write. + #[serde(default)] + replace: bool, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ApplyRequest { + agent: String, + change: Change, +} + +impl Library { + fn config(&self) -> Result { + self.config + .read() + .unwrap_or_else(PoisonError::into_inner) + .clone() + .ok_or_else(not_configured) + } + + fn lock_writing(&self) -> MutexGuard<'_, ()> { + self.writing.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// `agentLibrary.configure`. + pub fn configure(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ConfigureRequest { + /// A directory of the platform's application data for the + /// library. + directory: String, + user_home: String, + /// Values of the variables in the catalog's + /// `sessionRootVariables`. + #[serde(default)] + environment: BTreeMap, + } + let request: ConfigureRequest = crate::decode(payload)?; + let directory = PathBuf::from(&request.directory); + if !directory.is_absolute() || !Path::new(&request.user_home).is_absolute() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidDirectory", + "The library directory and user home must be absolute paths.", + )); + } + if request.environment.len() > 256 + || request + .environment + .iter() + .any(|(name, value)| name.is_empty() || name.len() > 256 || value.len() > 32 * 1024) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidEnvironment", + "The environment for configuration paths is invalid.", + )); + } + *self.config.write().unwrap_or_else(PoisonError::into_inner) = Some(Config { + directory, + user_home: request.user_home, + environment: request.environment, + }); + Ok(json!({})) + } + + /// The library and its revision: the SHA-256 of the file, or `empty`. + fn load(&self, config: &Config) -> Result<(LibraryData, String), CoreError> { + let path = config.directory.join(LIBRARY_FILE); + let Some(bytes) = read_bounded(&path, MAX_LIBRARY_FILE_BYTES).map_err(read_failure)? else { + return Ok((LibraryData::default(), EMPTY_REVISION.to_string())); + }; + let invalid = || { + refusal( + ErrorCode::ParseFailed, + "agentLibrary.invalidLibraryFile", + "The agent library file is not a library Lithe reads.", + ) + }; + let file: LibraryFile = serde_json::from_slice(&bytes).map_err(|_| invalid())?; + if file.version != 0 || file.library.check().is_err() { + return Err(invalid()); + } + Ok((file.library, digest(&bytes))) + } + + fn load_state(config: &Config) -> StateFile { + read_bounded(&config.directory.join(STATE_FILE), MAX_LIBRARY_FILE_BYTES) + .ok() + .flatten() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|state| state.version == 0) + .unwrap_or_default() + } + + fn store_state(config: &Config, state: &StateFile) -> Result<(), CoreError> { + ensure_private_directory(&config.directory)?; + let bytes = serde_json::to_vec_pretty(state).map_err(|_| write_failed())?; + write_replacing(&config.directory.join(STATE_FILE), &bytes).map_err(|_| write_failed()) + } + + /// `agentLibrary.read`: the library, its skills, and each agent that + /// declares configuration with what its files hold. + pub fn read(&self, runtime: &Runtime, payload: Value) -> Result { + let _: EmptyRequest = crate::decode(payload)?; + let started = Instant::now(); + let config = self.config()?; + let (library, revision) = self.load(&config)?; + let state = Self::load_state(&config); + let skills = library_skills(&config.directory); + let mut failed = 0u64; + let views: Vec = runtime + .catalog + .configurable() + .into_iter() + .map(|agent| { + let view = self.view(runtime, &config, &library, &state, &agent); + if view.entry.get("readError").is_some() { + failed += 1; + } + view + }) + .collect(); + + let states_of = |state: &dyn Fn(&AgentView) -> Option<&'static str>| -> Value { + let map: serde_json::Map = views + .iter() + .filter_map(|view| Some((view.key.clone(), json!(state(view)?)))) + .collect(); + Value::Object(map) + }; + let server_states: serde_json::Map = library + .mcp_servers + .iter() + .map(|server| { + let states = states_of(&|view| { + let snapshot = view.snapshot.as_ref()?; + Some( + match snapshot.mcp_servers.iter().find(|s| s.name == server.name) { + Some(found) if found.is(server) => "on", + Some(_) => "conflict", + None if snapshot.targets.mcp_servers.is_none() => "unsupported", + None => "off", + }, + ) + }); + (server.name.clone(), states) + }) + .collect(); + let hook_states: serde_json::Map = library + .hooks + .iter() + .map(|hook| { + let wanted = hook.hook(); + let states = states_of(&|view| { + let snapshot = view.snapshot.as_ref()?; + Some(if snapshot.hooks.iter().any(|h| h.is(&wanted)) { + "on" + } else if snapshot.targets.hooks.is_none() + || !snapshot.supports_event(&hook.event) + { + "unsupported" + } else { + "off" + }) + }); + (hook.id.clone(), states) + }) + .collect(); + let skill_rows: Vec = skills + .iter() + .map(|(name, description)| { + let states = states_of(&|view| { + let skills = view.skills.as_ref()?; + Some(match skills.iter().find(|skill| skill.name == *name) { + Some(skill) if skill.kind == SkillKind::Library => "on", + Some(_) => "conflict", + None => "off", + }) + }); + let mut row = json!({ "name": name, "agents": states }); + if let Some(description) = description { + row["description"] = json!(description); + } + row + }) + .collect(); + + log( + "agent.library.read_finished", + [ + ("agents", json!(views.len())), + ("failed", json!(failed)), + ( + "duration", + json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), + ), + ], + ); + Ok(json!({ + "revision": revision, + "library": library, + "skills": skill_rows, + "states": { "mcpServers": server_states, "hooks": hook_states }, + "agents": views.into_iter().map(|view| view.entry).collect::>(), + })) + } + + fn view( + &self, + runtime: &Runtime, + config: &Config, + library: &LibraryData, + state: &StateFile, + agent: &CatalogAgent, + ) -> AgentView { + let key = agent.record_key(); + let configuration = agent + .agent + .configuration + .clone() + .expect("configurable agents declare configuration"); + let mut entry = json!({ + "agent": key, + "pluginID": agent.plugin_id, + "agentID": agent.agent.id, + "displayName": agent.agent.display_name, + "mayConfigure": agent.may_configure, + "editable": configuration.edit.is_some(), + }); + if let Some(icon) = &agent.agent.icon { + entry["icon"] = json!(icon); + } + let mut view = AgentView { + key: key.clone(), + entry, + snapshot: None, + skills: None, + }; + if !agent.may_configure { + return view; + } + let paths = agent_paths(config, &configuration); + if let Some(path) = &paths.instructions { + let current = read_bounded(path, MAX_INSTRUCTIONS_FILE_BYTES); + let composed = library.compose(&key); + view.entry["instructions"] = json!({ + "path": path_text(path), + "state": instructions_state(¤t, &composed, state.instructions.get(&key)), + }); + } + if let Some(root) = &paths.skills { + let mut skills = json!({ "path": path_text(root) }); + match agent_skills(root, &config.directory) { + Ok(found) => { + skills["items"] = json!(found + .iter() + .map(|skill| { + let mut item = + json!({ "name": skill.name, "kind": skill.kind.token() }); + if let Some(description) = &skill.description { + item["description"] = json!(description); + } + item + }) + .collect::>()); + view.skills = Some(found); + } + Err(_) => skills["error"] = json!("agentLibrary.unreadable"), + } + view.entry["skills"] = skills; + } + if configuration.read.is_some() { + match read_snapshot(&*runtime.link, agent, &configuration, &paths.files) { + Ok(snapshot) => { + let servers: Vec = snapshot + .mcp_servers + .iter() + .map(|server| { + let mut row = json!(server); + row["inLibrary"] = + json!(library.mcp_servers.iter().any(|kept| server.is(kept))); + row + }) + .collect(); + let hooks: Vec = snapshot + .hooks + .iter() + .map(|hook| { + let mut row = json!(hook); + row["inLibrary"] = + json!(library.hooks.iter().any(|kept| hook.is(&kept.hook()))); + row + }) + .collect(); + view.entry["mcpServers"] = json!(servers); + view.entry["hooks"] = json!(hooks); + view.entry["hookEvents"] = json!(snapshot.hook_events); + view.entry["providedSkills"] = json!(snapshot.skills); + view.entry["targets"] = json!({ + "mcpServers": snapshot.targets.mcp_servers.is_some(), + "hooks": snapshot.targets.hooks.is_some(), + }); + view.snapshot = Some(snapshot); + } + Err(error) => { + let reason = error + .details + .as_deref() + .unwrap_or("agentLibrary.readFailed"); + log( + "agent.library.read_failed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("reason", json!(reason)), + ], + ); + view.entry["readError"] = json!(reason); + } + } + } + view + } + + /// `agentLibrary.save`: replaces the library if it is still at + /// `revision`. + pub fn save(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct SaveRequest { + revision: String, + library: LibraryData, + } + require_user()?; + let request: SaveRequest = crate::decode(payload)?; + let config = self.config()?; + if let Err(field) = request.library.check() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidLibrary", + &format!("The library is invalid at {field}."), + )); + } + let path = config.directory.join(LIBRARY_FILE); + let _writing = self.lock_writing(); + let current = match read_bounded(&path, MAX_LIBRARY_FILE_BYTES) { + Ok(Some(bytes)) => digest(&bytes), + Ok(None) => EMPTY_REVISION.to_string(), + // An unreadable library is replaced only by a save that read it. + Err(_) => return Err(unreadable_file()), + }; + if current != request.revision { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.revisionChanged", + "The agent library changed since it was read.", + )); + } + ensure_private_directory(&config.directory)?; + let file = LibraryFile { + version: 0, + library: request.library, + }; + let bytes = serde_json::to_vec_pretty(&file).map_err(|_| write_failed())?; + write_replacing(&path, &bytes).map_err(|_| write_failed())?; + log( + "agent.library.updated", + [ + ("servers", json!(file.library.mcp_servers.len())), + ("hooks", json!(file.library.hooks.len())), + ("sets", json!(file.library.instructions.sets.len())), + ], + ); + Ok(json!({ "revision": digest(&bytes) })) + } + + /// `agentLibrary.apply`: one change to one agent's configuration. + pub fn apply(&self, runtime: &Runtime, payload: Value) -> Result { + require_user()?; + let request: ApplyRequest = crate::decode(payload)?; + let started = Instant::now(); + let agent = configurable_agent(runtime, &request.agent)?; + let category = request.change.category; + let op = request.change.op; + let outcome = self.apply_checked(runtime, &agent, &request.change); + match &outcome { + Ok(changed) => log( + "agent.library.change_applied", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("category", json!(category.token())), + ("change", json!(op.token())), + ("changed", json!(changed)), + ( + "duration", + json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), + ), + ], + ), + Err(error) => log( + "agent.library.change_failed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("category", json!(category.token())), + ("change", json!(op.token())), + ( + "reason", + json!(error + .details + .as_deref() + .unwrap_or("agentLibrary.applyFailed")), + ), + ], + ), + } + outcome.map(|changed| json!({ "changed": changed })) + } + + fn apply_checked( + &self, + runtime: &Runtime, + agent: &CatalogAgent, + change: &Change, + ) -> Result { + let config = self.config()?; + let configuration = agent + .agent + .configuration + .as_ref() + .expect("configurable agents declare configuration"); + let paths = agent_paths(&config, configuration); + match (change.category, change.op) { + (Category::McpServers | Category::Hooks, Operation::Put | Operation::Remove) => { + self.apply_file(runtime, &config, agent, configuration, &paths, change) + } + (Category::Skills, Operation::Link | Operation::Unlink) => { + let name = change + .name + .as_deref() + .filter(|name| is_skill_name(name)) + .ok_or_else(|| invalid_change("A skill change names a library skill."))?; + self.apply_skill(&config, &paths, change.op, name) + } + (Category::Instructions, Operation::Write) => { + self.apply_instructions(&config, &agent.record_key(), &paths, change.replace) + } + _ => Err(invalid_change( + "MCP servers and hooks take put and remove, skills link and unlink, instructions write.", + )), + } + } + + /// Changes an MCP server or hook through the plugin, on a staged copy. + fn apply_file( + &self, + runtime: &Runtime, + config: &Config, + agent: &CatalogAgent, + configuration: &ConfigurationDeclaration, + paths: &AgentPaths, + change: &Change, + ) -> Result { + let Some(edit) = configuration.edit.as_deref() else { + return Err(refusal( + ErrorCode::NotSupported, + "agentLibrary.notEditable", + "The agent plugin does not edit this agent's configuration.", + )); + }; + let link = &*runtime.link; + let snapshot = read_snapshot(link, agent, configuration, &paths.files)?; + let target = match change.category { + Category::McpServers => snapshot.targets.mcp_servers.as_deref(), + _ => snapshot.targets.hooks.as_deref(), + }; + let Some((target_id, target_path)) = target + .and_then(|id| paths.files.iter().find(|(file, _)| file == id)) + .cloned() + else { + return Err(refusal( + ErrorCode::NotSupported, + "agentLibrary.noTarget", + "The agent keeps no editable file for this kind of item.", + )); + }; + + // What the plugin is asked to do, and how a staged copy shows it. + let (library, _) = self.load(config)?; + let (plugin_change, applied): (Value, ShowsChange) = match (change.category, change.op) { + (Category::McpServers, Operation::Put) => { + let name = change.name.as_deref().unwrap_or_default(); + let server = library + .mcp_servers + .iter() + .find(|server| server.name == name) + .cloned() + .ok_or_else(unknown_item)?; + let wanted = server.clone(); + ( + json!({ "category": "mcpServers", "op": "put", "server": server }), + Box::new(move |snapshot: &Snapshot| { + snapshot.mcp_servers.iter().any(|s| s.is(&wanted)) + }), + ) + } + (Category::McpServers, _) => { + let name = change.name.clone().unwrap_or_default(); + if !snapshot + .mcp_servers + .iter() + .any(|server| server.name == name && server.origin == Origin::User) + { + return Err(not_in_agent()); + } + let gone = name.clone(); + ( + json!({ "category": "mcpServers", "op": "remove", "name": name }), + Box::new(move |snapshot: &Snapshot| { + !snapshot + .mcp_servers + .iter() + .any(|s| s.name == gone && s.origin == Origin::User) + }), + ) + } + (_, Operation::Put) => { + let id = change.id.as_deref().unwrap_or_default(); + let hook = library + .hooks + .iter() + .find(|hook| hook.id == id) + .map(LibraryHook::hook) + .ok_or_else(unknown_item)?; + if !snapshot.supports_event(&hook.event) { + return Err(refusal( + ErrorCode::NotSupported, + "agentLibrary.unsupportedEvent", + "The agent does not run hooks for this event.", + )); + } + let wanted = hook.clone(); + ( + json!({ "category": "hooks", "op": "put", "hook": hook }), + Box::new(move |snapshot: &Snapshot| { + snapshot.hooks.iter().any(|h| h.is(&wanted)) + }), + ) + } + (_, _) => { + let hook = change + .hook + .clone() + .ok_or_else(|| invalid_change("Removing a hook names the hook."))?; + if !snapshot + .hooks + .iter() + .any(|h| h.is(&hook) && h.origin == Origin::User) + { + return Err(not_in_agent()); + } + let gone = hook.clone(); + ( + json!({ "category": "hooks", "op": "remove", "hook": hook }), + Box::new(move |snapshot: &Snapshot| { + !snapshot + .hooks + .iter() + .any(|h| h.is(&gone) && h.origin == Origin::User) + }), + ) + } + }; + + let real = real_file(&target_path)?; + let original = read_bounded(&real, MAX_CONFIGURATION_FILE_BYTES).map_err(read_failure)?; + let staging = self.stage(config, &real, original.as_deref())?; + let outcome = (|| { + let backend = link + .session_for(&agent.plugin_id, edit, None) + .ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.backendUnavailable", + "The agent plugin's backend is not running.", + ) + })?; + let params = json!({ + "agentID": agent.agent.id, + "file": { + "id": target_id, + "staging": path_text(&staging), + "exists": original.is_some(), + }, + "change": plugin_change, + }); + let answer = link + .call(&backend, &agent.plugin_id, edit, params, FUNCTION_TIMEOUT) + .map_err(|_| { + refusal( + ErrorCode::ProcessFailed, + "agentLibrary.editFailed", + "The agent plugin could not change the agent's configuration.", + ) + })?; + let answer: EditAnswer = serde_json::from_value(answer) + .ok() + .filter(|answer: &EditAnswer| answer.format == EDIT_FORMAT && answer.version == 0) + .ok_or_else(|| { + refusal( + ErrorCode::ParseFailed, + "agentLibrary.invalidEdit", + "The agent plugin returned an invalid edit answer.", + ) + })?; + if !answer.changed { + return Ok(false); + } + let edited = read_bounded(&staging, MAX_CONFIGURATION_FILE_BYTES) + .map_err(read_failure)? + .unwrap_or_default(); + if original.as_deref() == Some(edited.as_slice()) { + return Ok(false); + } + + // The plugin reads the staged copy in place of the file, which + // shows it can read what it wrote and that the change is there. + let staged_files: Vec<(String, PathBuf)> = paths + .files + .iter() + .map(|(id, path)| { + if *id == target_id { + (id.clone(), staging.clone()) + } else { + (id.clone(), path.clone()) + } + }) + .collect(); + let staged = read_snapshot(link, agent, configuration, &staged_files)?; + if !applied(&staged) { + return Err(refusal( + ErrorCode::ParseFailed, + "agentLibrary.editNotApplied", + "The agent plugin's edit did not make the change.", + )); + } + + let _writing = self.lock_writing(); + let now = read_bounded(&real, MAX_CONFIGURATION_FILE_BYTES).map_err(read_failure)?; + if now != original { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.fileChanged", + "The configuration file changed while it was being edited.", + )); + } + if let Some(parent) = real.parent() { + ensure_directory(parent)?; + } + write_replacing(&real, &edited).map_err(|_| write_failed())?; + Ok(true) + })(); + let _ = fs::remove_file(&staging); + outcome + } + + /// A private copy of `original` for a plugin to edit; an empty file when + /// the file does not exist yet. + fn stage( + &self, + config: &Config, + real: &Path, + original: Option<&[u8]>, + ) -> Result { + static NEXT: AtomicU64 = AtomicU64::new(0); + let directory = config.directory.join(STAGING_DIRECTORY); + ensure_private_directory(&config.directory)?; + ensure_private_directory(&directory)?; + let extension = real + .extension() + .and_then(|extension| extension.to_str()) + .filter(|extension| extension.chars().all(|c| c.is_ascii_alphanumeric())) + .map(|extension| format!(".{extension}")) + .unwrap_or_default(); + let path = directory.join(format!( + "edit-{}-{}{extension}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + lithe_platform::fs::owner_only_file(&mut options); + let mut file = options.open(&path).map_err(|_| write_failed())?; + if let Err(_error) = file.write_all(original.unwrap_or_default()) { + let _ = fs::remove_file(&path); + return Err(write_failed()); + } + Ok(path) + } + + fn apply_skill( + &self, + config: &Config, + paths: &AgentPaths, + op: Operation, + name: &str, + ) -> Result { + let Some(root) = &paths.skills else { + return Err(refusal( + ErrorCode::NotSupported, + "agentLibrary.noSkills", + "The agent keeps no skills directory.", + )); + }; + let library_skills = config.directory.join(SKILLS_DIRECTORY); + let skill = library_skills.join(name); + let link = root.join(name); + let _writing = self.lock_writing(); + match op { + Operation::Link => { + if !skill.join(SKILL_FILE).is_file() { + return Err(unknown_item()); + } + match fs::symlink_metadata(&link) { + Ok(metadata) + if metadata.file_type().is_symlink() && links_into(&link, &skill) => + { + Ok(false) + } + Ok(_) => Err(refusal( + ErrorCode::EntryExists, + "agentLibrary.agentSkillExists", + "The agent already has a skill of this name.", + )), + Err(error) if error.kind() == io::ErrorKind::NotFound => { + ensure_directory(root)?; + lithe_platform::entries::create_symlink(&skill, &link).map_err(|_| { + refusal( + ErrorCode::PermissionDenied, + "agentLibrary.linkFailed", + "The skill could not be linked into the agent's skills directory.", + ) + })?; + Ok(true) + } + Err(_) => Err(unreadable_file()), + } + } + _ => match fs::symlink_metadata(&link) { + Ok(metadata) + if metadata.file_type().is_symlink() && links_into(&link, &library_skills) => + { + remove_link(&link).map_err(|_| write_failed())?; + Ok(true) + } + Ok(_) => Err(refusal( + ErrorCode::PermissionDenied, + "agentLibrary.notLibraryLink", + "The agent's skill of this name is its own, not a link into the library.", + )), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(_) => Err(unreadable_file()), + }, + } + } + + fn apply_instructions( + &self, + config: &Config, + key: &str, + paths: &AgentPaths, + replace: bool, + ) -> Result { + let Some(path) = &paths.instructions else { + return Err(refusal( + ErrorCode::NotSupported, + "agentLibrary.noInstructions", + "The agent keeps no instruction file.", + )); + }; + let (library, _) = self.load(config)?; + if !library + .instructions + .agents + .get(key) + .is_some_and(|agent| agent.enabled) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.instructionsOff", + "The library's instructions are off for this agent.", + )); + } + let text = library.compose(key); + let _writing = self.lock_writing(); + let real = real_file(path)?; + let current = read_bounded(&real, MAX_INSTRUCTIONS_FILE_BYTES).map_err(read_failure)?; + let mut state = Self::load_state(config); + if current.as_deref() == Some(text.as_bytes()) { + return Ok(false); + } + if let Some(current) = ¤t { + let empty = String::from_utf8_lossy(current).trim().is_empty(); + let written = state + .instructions + .get(key) + .is_some_and(|written| *written == digest(current)); + if !empty && !written && !replace { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.otherInstructions", + "The instruction file holds text Lithe did not write.", + )); + } + } + if let Some(parent) = real.parent() { + ensure_directory(parent)?; + } + write_replacing(&real, text.as_bytes()).map_err(|_| write_failed())?; + state.version = 0; + state + .instructions + .insert(key.to_string(), digest(text.as_bytes())); + Self::store_state(config, &state)?; + Ok(true) + } + + /// `agentLibrary.importSkill`: copies a skill into the library, from an + /// agent's skills directory or from a directory the user chose. + pub fn import_skill(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ImportRequest { + #[serde(default)] + agent: Option, + #[serde(default)] + name: Option, + #[serde(default)] + directory: Option, + } + require_user()?; + let request: ImportRequest = crate::decode(payload)?; + let config = self.config()?; + let source = match (&request.agent, &request.name, &request.directory) { + (Some(agent), Some(name), None) => { + let agent = configurable_agent(runtime, agent)?; + let configuration = agent + .agent + .configuration + .as_ref() + .expect("configurable agents declare configuration"); + let root = agent_paths(&config, configuration).skills.ok_or_else(|| { + refusal( + ErrorCode::NotSupported, + "agentLibrary.noSkills", + "The agent keeps no skills directory.", + ) + })?; + if !is_skill_name(name) { + return Err(invalid_skill_name()); + } + let source = root.join(name); + if fs::symlink_metadata(&source).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.notOwnSkill", + "Only a skill directory of the agent's own is imported.", + )); + } + source + } + (None, None, Some(directory)) => { + let directory = PathBuf::from(directory); + if !directory.is_absolute() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidSkillDirectory", + "The skill directory must be an absolute path.", + )); + } + directory + } + _ => { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidImport", + "A skill is imported from an agent and a name, or from a directory.", + )) + } + }; + if skill_description(&source).is_none() { + return Err(refusal( + ErrorCode::EntryNotFound, + "agentLibrary.notSkill", + "The directory has no readable SKILL.md.", + )); + } + let name = match request.name { + Some(name) => name, + None => { + let bytes = read_bounded(&source.join(SKILL_FILE), MAX_SKILL_FILE_BYTES) + .ok() + .flatten() + .unwrap_or_default(); + front_matter(&String::from_utf8_lossy(&bytes)) + .0 + .or_else(|| { + source + .file_name() + .and_then(|name| name.to_str()) + .map(str::to_string) + }) + .unwrap_or_default() + } + }; + if !is_skill_name(&name) { + return Err(invalid_skill_name()); + } + + let skills = config.directory.join(SKILLS_DIRECTORY); + let destination = skills.join(&name); + if fs::symlink_metadata(&destination).is_ok() { + return Err(refusal( + ErrorCode::EntryExists, + "agentLibrary.skillExists", + "The library already has a skill of this name.", + )); + } + ensure_private_directory(&config.directory)?; + ensure_private_directory(&config.directory.join(STAGING_DIRECTORY))?; + ensure_directory(&skills)?; + let partial = sibling_temporary( + &config.directory.join(STAGING_DIRECTORY).join(&name), + "import", + ) + .ok_or_else(write_failed)?; + let mut copied = Copied::default(); + let outcome = copy_tree(&source, &partial, 0, &mut copied).and_then(|()| { + let _writing = self.lock_writing(); + lithe_platform::entries::rename_no_replace(&partial, &destination).map_err(|error| { + if error.kind() == io::ErrorKind::AlreadyExists { + refusal( + ErrorCode::EntryExists, + "agentLibrary.skillExists", + "The library already has a skill of this name.", + ) + } else { + write_failed() + } + }) + }); + if outcome.is_err() { + let _ = fs::remove_dir_all(&partial); + } + outcome?; + log( + "agent.library.skill_import_finished", + [ + ("files", json!(copied.files)), + ("skipped", json!(copied.skipped)), + ], + ); + Ok(json!({ "name": name, "files": copied.files, "skipped": copied.skipped })) + } + + /// `agentLibrary.removeSkill`: removes a library skill and every link to + /// it in the agents' skills directories. + pub fn remove_skill(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct RemoveRequest { + name: String, + } + require_user()?; + let request: RemoveRequest = crate::decode(payload)?; + let config = self.config()?; + if !is_skill_name(&request.name) { + return Err(invalid_skill_name()); + } + let skill = config.directory.join(SKILLS_DIRECTORY).join(&request.name); + if !skill.is_dir() { + return Err(unknown_item()); + } + let mut unlinked = 0u64; + let _writing = self.lock_writing(); + for agent in runtime.catalog.configurable() { + if !agent.may_configure { + continue; + } + let configuration = agent + .agent + .configuration + .as_ref() + .expect("configurable agents declare configuration"); + let Some(root) = agent_paths(&config, configuration).skills else { + continue; + }; + let link = root.join(&request.name); + if fs::symlink_metadata(&link).is_ok_and(|m| m.file_type().is_symlink()) + && links_into(&link, &skill) + { + remove_link(&link).map_err(|_| write_failed())?; + unlinked += 1; + } + } + fs::remove_dir_all(&skill).map_err(|_| write_failed())?; + log( + "agent.library.skill_removed", + [("unlinked", json!(unlinked))], + ); + Ok(json!({ "unlinked": unlinked })) + } +} + +fn unknown_item() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentLibrary.unknownItem", + "The library has no such item.", + ) +} + +fn not_in_agent() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentLibrary.notInAgent", + "The agent's own configuration has no such item.", + ) +} + +fn invalid_skill_name() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentLibrary.invalidSkillName", + "A skill name uses ASCII letters, digits, `.`, `_` and `-`.", + ) +} + +/// The agent `key` names, if it declares configuration and its plugin is +/// granted `agents.configuration`. +fn configurable_agent(runtime: &Runtime, key: &str) -> Result { + let agent = runtime + .catalog + .find_key(key) + .filter(|agent| agent.agent.configuration.is_some()) + .ok_or_else(|| { + refusal( + ErrorCode::EntryNotFound, + "agentLibrary.unknownAgent", + "No installed plugin declares configuration for this agent.", + ) + })?; + if !agent.may_configure { + return Err(refusal( + ErrorCode::PermissionDenied, + "agentLibrary.notGranted", + "The user has not allowed the plugin to change this agent's configuration.", + )); + } + Ok(agent) +} + +#[cfg(test)] +pub(crate) fn front_matter_for_test(text: &str) -> (Option, Option) { + front_matter(text) +} + +#[cfg(test)] +pub(crate) fn compose_for_test(library: Value, key: &str) -> String { + let library: LibraryData = serde_json::from_value(library).expect("library decodes"); + library.compose(key) +} diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 4d26a714..d31b01a8 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1725,3 +1725,5 @@ fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { assert_eq!(crate::records::text_lines_for_test(b"a\r\nb\n"), ["a", "b"]); assert!(crate::records::text_lines_for_test(b"").is_empty()); } + +mod library; diff --git a/rust/crates/agent-runtime/src/tests/library.rs b/rust/crates/agent-runtime/src/tests/library.rs new file mode 100644 index 00000000..0db77e55 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/library.rs @@ -0,0 +1,677 @@ +//! The agent library: saving with revisions, MCP servers and hooks through a +//! staged copy the synthetic plugin edits, instructions, skills and grants. + +use super::*; + +const CONFIGURATION_GRANTS: &[&str] = &[ + "agents.native", + "agents.run", + "agents.sessions.read", + "agents.configuration", + "backend.launch", +]; + +/// How the synthetic plugin's `configuration.edit` behaves. +#[derive(Clone)] +enum Edit { + /// Applies the change to the staged copy. + Apply, + /// Writes something else to the staged copy. + Wrong, + /// Applies the change, and something else changes the real file + /// meanwhile. + Race(PathBuf), +} + +/// The synthetic plugin with configuration declared for its agent. +fn configuration_manifest() -> Value { + let mut manifest = manifest(); + manifest["permissions"] = json!(CONFIGURATION_GRANTS); + manifest["agents"][0]["configuration"] = json!({ + "instructions": { "roots": ["${userHome}/.sample/INSTRUCTIONS.md"] }, + "skills": { "roots": ["${userHome}/.sample/skills"] }, + "files": [{ "id": "main", "roots": ["${userHome}/.sample/config.json"] }], + "read": "configuration.read", + "edit": "configuration.edit" + }); + manifest +} + +/// The synthetic plugin's configuration file: the snapshot's servers keyed +/// by name and its hooks, as JSON. +fn read_file(path: &Path) -> Value { + match fs::read(path) { + Ok(bytes) if !bytes.is_empty() => { + serde_json::from_slice(&bytes).expect("configuration is JSON") + } + _ => json!({}), + } +} + +fn configuration_read(params: &Value) -> Result { + let file = params["files"] + .as_array() + .and_then(|files| files.iter().find(|file| file["id"] == "main")) + .ok_or_else(|| failure("plugin.params.invalid"))?; + let config = read_file(Path::new(file["path"].as_str().unwrap())); + let servers: Vec = config["servers"] + .as_object() + .map(|servers| { + servers + .iter() + .map(|(name, server)| { + let mut row = server.clone(); + row["name"] = json!(name); + if row.get("origin").is_none() { + row["origin"] = json!("user"); + } + row + }) + .collect() + }) + .unwrap_or_default(); + let hooks: Vec = config["hooks"] + .as_array() + .cloned() + .unwrap_or_default() + .into_iter() + .map(|mut hook| { + if hook.get("origin").is_none() { + hook["origin"] = json!("user"); + } + hook + }) + .collect(); + Ok(json!({ + "format": "litheAgentConfiguration", + "version": 0, + "mcpServers": servers, + "hooks": hooks, + "hookEvents": ["PreToolUse", "Stop"], + "skills": [{ "name": "provided-skill", "provider": "sample-plugin" }], + "targets": { "mcpServers": "main", "hooks": "main" } + })) +} + +fn same_hook(left: &Value, right: &Value) -> bool { + left["event"] == right["event"] + && left["command"] == right["command"] + && left.get("matcher") == right.get("matcher") +} + +fn configuration_edit(params: &Value, edit: &Edit) -> Result { + let staging = PathBuf::from(params["file"]["staging"].as_str().unwrap()); + let mut config = read_file(&staging); + let before = config.clone(); + let change = ¶ms["change"]; + match (change["category"].as_str(), change["op"].as_str()) { + (Some("mcpServers"), Some("put")) => { + let mut server = change["server"].clone(); + let name = server["name"].as_str().unwrap().to_string(); + server.as_object_mut().unwrap().remove("name"); + config["servers"][name.as_str()] = server; + } + (Some("mcpServers"), Some("remove")) => { + if let Some(servers) = config["servers"].as_object_mut() { + servers.remove(change["name"].as_str().unwrap()); + } + } + (Some("hooks"), Some("put")) => { + let hooks = config["hooks"].as_array().cloned().unwrap_or_default(); + if !hooks.iter().any(|hook| same_hook(hook, &change["hook"])) { + let mut hooks = hooks; + hooks.push(change["hook"].clone()); + config["hooks"] = json!(hooks); + } + } + (Some("hooks"), Some("remove")) => { + let mut hooks = config["hooks"].as_array().cloned().unwrap_or_default(); + hooks.retain(|hook| !same_hook(hook, &change["hook"])); + config["hooks"] = json!(hooks); + } + _ => return Err(failure("plugin.params.invalid")), + } + match edit { + Edit::Apply => {} + Edit::Wrong => config = json!({ "servers": before["servers"], "noise": true }), + Edit::Race(real) => fs::write(real, br#"{"servers":{}}"#).unwrap(), + } + let changed = config != before; + if changed { + fs::write(&staging, serde_json::to_vec(&config).unwrap()).unwrap(); + } + Ok(json!({ "format": "litheAgentConfigurationEdit", "version": 0, "changed": changed })) +} + +/// A harness with the configuration plugin granted `grants` and the library +/// configured, and the synthetic plugin's configuration functions. +struct LibraryTest { + harness: Harness, + edit: Arc>, + home: PathBuf, + library: PathBuf, +} + +impl LibraryTest { + fn new(name: &str, grants: &[&str]) -> Self { + let harness = Harness::new(name, ALL_GRANTS); + harness.run( + "agents.configure", + json!({ "plugins": [{ "manifest": configuration_manifest(), "grantedPermissions": grants }] }), + ); + let home = harness.dir.path().join("home"); + let library = harness.dir.path().join("library"); + harness.run( + "agentLibrary.configure", + json!({ "directory": path_text(&library), "userHome": path_text(&home) }), + ); + let edit = Arc::new(Mutex::new(Edit::Apply)); + let current = edit.clone(); + harness + .link + .set_answer(move |function, params| match function { + "configuration.read" => configuration_read(params), + "configuration.edit" => { + let edit = current.lock().unwrap().clone(); + configuration_edit(params, &edit) + } + other => sample_backend(other, params), + }); + fs::create_dir_all(home.join(".sample")).unwrap(); + Self { + harness, + edit, + home, + library, + } + } + + fn read(&self) -> Value { + self.harness.run("agentLibrary.read", json!({})) + } + + fn save(&self, library: Value) -> String { + let revision = self.read()["revision"].clone(); + let saved = self.harness.run( + "agentLibrary.save", + json!({ "revision": revision, "library": library }), + ); + saved["revision"].as_str().unwrap().to_string() + } + + fn apply(&self, change: Value) -> bool { + self.harness.run( + "agentLibrary.apply", + json!({ "agent": AGENT_KEY, "change": change }), + )["changed"] + .as_bool() + .unwrap() + } + + fn refused_change(&self, change: Value) -> String { + self.harness.refused( + "agentLibrary.apply", + json!({ "agent": AGENT_KEY, "change": change }), + ) + } + + fn config_file(&self) -> PathBuf { + self.home.join(".sample").join("config.json") + } + + fn staged_files(&self) -> usize { + fs::read_dir(self.library.join("staging")).map_or(0, |entries| entries.count()) + } +} + +fn library_with(servers: Value, hooks: Value) -> Value { + json!({ "mcpServers": servers, "hooks": hooks }) +} + +#[test] +fn library_saves_only_unchanged_revisions_and_only_for_the_user() { + let test = LibraryTest::new("library save", CONFIGURATION_GRANTS); + let read = test.read(); + assert_eq!(read["revision"], "empty"); + let agent = &read["agents"][0]; + assert_eq!(agent["agent"], AGENT_KEY); + assert_eq!(agent["displayName"], "Sample Agent"); + assert_eq!(agent["mayConfigure"], true); + assert_eq!(agent["editable"], true); + assert_eq!(agent["instructions"]["state"], "absent"); + assert_eq!( + agent["targets"], + json!({ "mcpServers": true, "hooks": true }) + ); + assert_eq!(agent["hookEvents"], json!(["PreToolUse", "Stop"])); + assert_eq!(agent["providedSkills"][0]["provider"], "sample-plugin"); + + let server = json!([{ "name": "docs", "transport": "stdio", "command": "docs-mcp", "args": ["--stdio"] }]); + let saved = test.harness.run( + "agentLibrary.save", + json!({ "revision": "empty", "library": library_with(server.clone(), json!([])) }), + ); + let revision = saved["revision"].as_str().unwrap(); + assert_ne!(revision, "empty"); + let read = test.read(); + assert_eq!(read["revision"], revision); + assert_eq!(read["library"]["mcpServers"], server); + + let stale = test.harness.refused( + "agentLibrary.save", + json!({ "revision": "empty", "library": {} }), + ); + assert_eq!(stale, "agentLibrary.revisionChanged"); + let invalid = test.harness.refused( + "agentLibrary.save", + json!({ "revision": revision, "library": library_with(json!([{ "name": "docs", "transport": "stdio" }]), json!([])) }), + ); + assert_eq!(invalid, "agentLibrary.invalidLibrary"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(test.library.join("library.json")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o077, 0, "the library file is the owner's only"); + } + + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let save = test.harness.refused( + "agentLibrary.save", + json!({ "revision": revision, "library": {} }), + ); + let apply = + test.refused_change(json!({ "category": "mcpServers", "op": "put", "name": "docs" })); + trace::replace(previous); + assert_eq!(save, "agentLibrary.userActionRequired"); + assert_eq!(apply, "agentLibrary.userActionRequired"); + assert!(test.harness.link.calls_of("configuration.edit").is_empty()); +} + +#[test] +fn servers_and_hooks_change_only_through_a_checked_staged_copy() { + let test = LibraryTest::new("library servers", CONFIGURATION_GRANTS); + let file = test.config_file(); + fs::write( + &file, + br#"{"servers":{"plugin-tools":{"transport":"http","url":"https://tools.example.test/mcp","origin":"agent","provider":"sample-plugin"}},"keep":1}"#, + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&file, fs::Permissions::from_mode(0o640)).unwrap(); + } + test.save(library_with( + json!([{ "name": "docs", "transport": "stdio", "command": "docs-mcp", "args": ["--stdio"] }]), + json!([ + { "id": "check-on-stop", "event": "Stop", "command": "sample-check" }, + { "id": "on-end", "event": "SessionEnd", "command": "sample-end" } + ]), + )); + let read = test.read(); + assert_eq!(read["states"]["mcpServers"]["docs"][AGENT_KEY], "off"); + assert_eq!(read["states"]["hooks"]["check-on-stop"][AGENT_KEY], "off"); + assert_eq!(read["states"]["hooks"]["on-end"][AGENT_KEY], "unsupported"); + assert_eq!(read["agents"][0]["mcpServers"][0]["origin"], "agent"); + + assert!(test.apply(json!({ "category": "mcpServers", "op": "put", "name": "docs" }))); + let written = read_file(&file); + assert_eq!(written["servers"]["docs"]["command"], "docs-mcp"); + assert_eq!(written["servers"]["plugin-tools"]["origin"], "agent"); + assert_eq!( + written["keep"], 1, + "the plugin keeps what it does not change" + ); + let edits = test.harness.link.calls_of("configuration.edit"); + let staging = PathBuf::from(edits[0]["file"]["staging"].as_str().unwrap()); + assert!( + staging.starts_with(test.library.join("staging")), + "the plugin edits only a staged copy" + ); + assert_eq!(edits[0]["file"]["id"], "main"); + assert_eq!(test.staged_files(), 0); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(&file).unwrap().permissions().mode(); + assert_eq!( + mode & 0o777, + 0o640, + "the replaced file keeps its permissions" + ); + } + let read = test.read(); + assert_eq!(read["states"]["mcpServers"]["docs"][AGENT_KEY], "on"); + assert!(read["agents"][0]["mcpServers"] + .as_array() + .unwrap() + .iter() + .any(|server| server["name"] == "docs" && server["inLibrary"] == true)); + assert!(!test.apply(json!({ "category": "mcpServers", "op": "put", "name": "docs" }))); + + assert!(test.apply(json!({ "category": "hooks", "op": "put", "id": "check-on-stop" }))); + assert_eq!( + test.read()["states"]["hooks"]["check-on-stop"][AGENT_KEY], + "on" + ); + assert!(test.apply(json!({ "category": "hooks", "op": "remove", "hook": { "event": "Stop", "command": "sample-check" } }))); + assert_eq!( + test.read()["states"]["hooks"]["check-on-stop"][AGENT_KEY], + "off" + ); + assert_eq!( + test.refused_change(json!({ "category": "hooks", "op": "put", "id": "on-end" })), + "agentLibrary.unsupportedEvent" + ); + assert_eq!( + test.refused_change(json!({ "category": "mcpServers", "op": "put", "name": "absent" })), + "agentLibrary.unknownItem" + ); + assert_eq!( + test.refused_change( + json!({ "category": "mcpServers", "op": "remove", "name": "plugin-tools" }) + ), + "agentLibrary.notInAgent", + "what the CLI installed itself is only shown" + ); + assert_eq!( + test.refused_change(json!({ "category": "mcpServers", "op": "link", "name": "docs" })), + "agentLibrary.invalidChange" + ); + + let before = fs::read(&file).unwrap(); + *test.edit.lock().unwrap() = Edit::Wrong; + assert_eq!( + test.refused_change(json!({ "category": "mcpServers", "op": "remove", "name": "docs" })), + "agentLibrary.editNotApplied" + ); + assert_eq!( + fs::read(&file).unwrap(), + before, + "a wrong edit never reaches the file" + ); + *test.edit.lock().unwrap() = Edit::Race(file.clone()); + assert_eq!( + test.refused_change(json!({ "category": "mcpServers", "op": "remove", "name": "docs" })), + "agentLibrary.fileChanged" + ); + assert_eq!( + fs::read(&file).unwrap(), + br#"{"servers":{}}"#, + "the other change is kept" + ); + assert_eq!(test.staged_files(), 0); +} + +#[cfg(unix)] +#[test] +fn a_linked_configuration_file_is_replaced_where_it_points() { + let test = LibraryTest::new("library linked file", CONFIGURATION_GRANTS); + let real = test.home.join("dotfiles-config.json"); + fs::write(&real, b"{}").unwrap(); + std::os::unix::fs::symlink(&real, test.config_file()).unwrap(); + test.save(library_with( + json!([{ "name": "web", "transport": "http", "url": "https://web.example.test/mcp" }]), + json!([]), + )); + assert!(test.apply(json!({ "category": "mcpServers", "op": "put", "name": "web" }))); + assert!(fs::symlink_metadata(test.config_file()) + .unwrap() + .file_type() + .is_symlink()); + assert_eq!( + read_file(&real)["servers"]["web"]["url"], + "https://web.example.test/mcp" + ); +} + +#[test] +fn instructions_follow_the_library_and_keep_text_lithe_did_not_write() { + let test = LibraryTest::new("library instructions", CONFIGURATION_GRANTS); + let file = test.home.join(".sample").join("INSTRUCTIONS.md"); + fs::write(&file, b"My own notes\n").unwrap(); + let library = |text: &str, enabled: bool| { + json!({ + "instructions": { + "sets": [{ "id": "default", "name": "Default", "text": text }], + "active": "default", + "agents": { AGENT_KEY: { "enabled": enabled, "extra": "Only for the sample agent." } } + } + }) + }; + test.save(library("Shared rule.\n", true)); + assert_eq!(test.read()["agents"][0]["instructions"]["state"], "other"); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.otherInstructions" + ); + assert_eq!(fs::read(&file).unwrap(), b"My own notes\n"); + + assert!(test.apply(json!({ "category": "instructions", "op": "write", "replace": true }))); + assert_eq!( + fs::read_to_string(&file).unwrap(), + "Shared rule.\n\nOnly for the sample agent.\n" + ); + assert_eq!(test.read()["agents"][0]["instructions"]["state"], "current"); + + test.save(library("Shared rule, revised.", true)); + assert_eq!(test.read()["agents"][0]["instructions"]["state"], "written"); + assert!( + test.apply(json!({ "category": "instructions", "op": "write" })), + "Lithe rewrites what it wrote" + ); + assert_eq!( + fs::read_to_string(&file).unwrap(), + "Shared rule, revised.\n\nOnly for the sample agent.\n" + ); + assert!(!test.apply(json!({ "category": "instructions", "op": "write" }))); + + test.save(library("Shared rule, revised.", false)); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.instructionsOff" + ); +} + +#[cfg(unix)] +#[test] +fn skills_are_imported_without_links_and_linked_into_agents() { + let test = LibraryTest::new("library skills", CONFIGURATION_GRANTS); + let source = test.harness.dir.path().join("source").join("demo"); + fs::create_dir_all(source.join("references")).unwrap(); + fs::write( + source.join("SKILL.md"), + "---\nname: demo-skill\ndescription: >\n Checks the\n sample project.\n---\nBody\n", + ) + .unwrap(); + fs::write(source.join("references").join("notes.md"), "Notes\n").unwrap(); + std::os::unix::fs::symlink(test.harness.dir.path(), source.join("outside")).unwrap(); + + let imported = test.harness.run( + "agentLibrary.importSkill", + json!({ "directory": path_text(&source) }), + ); + assert_eq!( + imported, + json!({ "name": "demo-skill", "files": 2, "skipped": 1 }) + ); + assert!(!test + .library + .join("skills") + .join("demo-skill") + .join("outside") + .exists()); + let read = test.read(); + assert_eq!(read["skills"][0]["name"], "demo-skill"); + assert_eq!( + read["skills"][0]["description"], + "Checks the sample project." + ); + assert_eq!(read["skills"][0]["agents"][AGENT_KEY], "off"); + + let skills = test.home.join(".sample").join("skills"); + assert!(test.apply(json!({ "category": "skills", "op": "link", "name": "demo-skill" }))); + assert!(fs::symlink_metadata(skills.join("demo-skill")) + .unwrap() + .file_type() + .is_symlink()); + assert!(!test.apply(json!({ "category": "skills", "op": "link", "name": "demo-skill" }))); + let read = test.read(); + assert_eq!(read["skills"][0]["agents"][AGENT_KEY], "on"); + assert_eq!(read["agents"][0]["skills"]["items"][0]["kind"], "library"); + + fs::create_dir_all(skills.join("own-skill")).unwrap(); + fs::write( + skills.join("own-skill").join("SKILL.md"), + "---\nname: own-skill\n---\n", + ) + .unwrap(); + let own = test.harness.run( + "agentLibrary.importSkill", + json!({ "agent": AGENT_KEY, "name": "own-skill" }), + ); + assert_eq!(own["files"], 1); + assert_eq!( + test.harness.refused( + "agentLibrary.importSkill", + json!({ "agent": AGENT_KEY, "name": "own-skill" }), + ), + "agentLibrary.skillExists" + ); + let read = test.read(); + let own_row = read["skills"] + .as_array() + .unwrap() + .iter() + .find(|skill| skill["name"] == "own-skill") + .unwrap() + .clone(); + assert_eq!(own_row["agents"][AGENT_KEY], "conflict"); + assert_eq!( + test.refused_change(json!({ "category": "skills", "op": "unlink", "name": "own-skill" })), + "agentLibrary.notLibraryLink" + ); + assert_eq!( + test.refused_change(json!({ "category": "skills", "op": "link", "name": "own-skill" })), + "agentLibrary.agentSkillExists" + ); + assert!( + skills.join("own-skill").join("SKILL.md").is_file(), + "the agent's own skill stays" + ); + + let removed = test + .harness + .run("agentLibrary.removeSkill", json!({ "name": "demo-skill" })); + assert_eq!(removed["unlinked"], 1); + assert!(fs::symlink_metadata(skills.join("demo-skill")).is_err()); + assert!(!test.library.join("skills").join("demo-skill").exists()); + assert_eq!(test.staged_files(), 0); +} + +#[test] +fn agents_without_the_grant_are_listed_but_never_read_or_changed() { + let unconfigured = Harness::new("library unconfigured", ALL_GRANTS); + assert_eq!( + unconfigured.refused("agentLibrary.read", json!({})), + "agentLibrary.notConfigured" + ); + drop(unconfigured); + + let test = LibraryTest::new("library not granted", ALL_GRANTS); + let read = test.read(); + let agent = &read["agents"][0]; + assert_eq!(agent["mayConfigure"], false); + assert!(agent.get("instructions").is_none()); + assert!(agent.get("mcpServers").is_none()); + assert!(test.harness.link.calls_of("configuration.read").is_empty()); + assert_eq!( + test.refused_change(json!({ "category": "instructions", "op": "write" })), + "agentLibrary.notGranted" + ); + assert_eq!( + test.harness.refused( + "agentLibrary.apply", + json!({ "agent": "dev.lithe.test.agents/absent", "change": { "category": "instructions", "op": "write" } }), + ), + "agentLibrary.unknownAgent" + ); + + let granted = LibraryTest::new("library backend stopped", CONFIGURATION_GRANTS); + granted.harness.link.set_backend(None); + let read = granted.read(); + assert_eq!( + read["agents"][0]["readError"], + "agentLibrary.backendUnavailable" + ); + assert_eq!( + read["agents"][0]["instructions"]["state"], "absent", + "Core still reads its own files" + ); +} + +#[test] +fn skill_front_matter_and_instruction_text_are_read_as_written() { + use crate::library::{compose_for_test, front_matter_for_test}; + assert_eq!( + front_matter_for_test("---\nname: \"quoted name\"\ndescription: 'It''s short'\n---\n"), + (Some("quoted name".into()), Some("It's short".into())) + ); + assert_eq!( + front_matter_for_test("---\ndescription: |\n Line one\n Line two\nname: block\n---\n"), + (Some("block".into()), Some("Line one\nLine two".into())) + ); + assert_eq!( + front_matter_for_test("name: no front matter\n"), + (None, None) + ); + let library = json!({ + "instructions": { "sets": [], "agents": { "a/b": { "enabled": true, "extra": " Extra only. " } } } + }); + assert_eq!(compose_for_test(library.clone(), "a/b"), "Extra only.\n"); + assert_eq!(compose_for_test(library, "a/c"), ""); +} + +#[test] +fn malformed_requests_and_a_damaged_library_file_are_refused_each_with_its_own_code() { + let test = LibraryTest::new("library refusals", CONFIGURATION_GRANTS); + assert_eq!( + test.harness.refused( + "agentLibrary.configure", + json!({ "directory": "relative/library", "userHome": path_text(&test.home) }), + ), + "agentLibrary.invalidDirectory" + ); + assert_eq!( + test.harness.refused("agentLibrary.importSkill", json!({})), + "agentLibrary.invalidImport" + ); + assert_eq!( + test.harness.refused( + "agentLibrary.importSkill", + json!({ "directory": "relative/skill" }), + ), + "agentLibrary.invalidSkillDirectory" + ); + assert_eq!( + test.harness + .refused("agentLibrary.removeSkill", json!({ "name": "absent" })), + "agentLibrary.unknownItem" + ); + fs::create_dir_all(&test.library).unwrap(); + fs::write( + test.library.join("library.json"), + b"{\"version\":1,\"library\":{}}", + ) + .unwrap(); + assert_eq!( + test.harness.refused("agentLibrary.read", json!({})), + "agentLibrary.invalidLibraryFile" + ); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 64156de0..44585fca 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -63,8 +63,9 @@ pub enum CoreCommand { SearchActions, /// AI commit, pull request and inline edit planning run by `lithe-ai` (`ai.*`). Ai(AiCommand), - /// Agent catalog and live sessions (`agents.*`) and local session records - /// (`agentSessions.*`), run by `lithe-agent-runtime` (plan API-45). + /// Agent catalog and live sessions (`agents.*`), local session records + /// (`agentSessions.*`) and the agent library (`agentLibrary.*`), run by + /// `lithe-agent-runtime` (plan API-45). Agents(AgentsCommand), /// Plugin manifests, plugin views and web content, plugin settings, installed /// plugins and the marketplace (`plugins.*`). @@ -218,7 +219,7 @@ pub enum AiCommand { } #[derive(Debug, Clone, Copy)] -/// The `agents.*` and `agentSessions.*` commands; their names live in +/// The `agents.*`, `agentSessions.*` and `agentLibrary.*` commands; their names live in /// [`CoreCommand::parse`]. pub enum AgentsCommand { /// Loads the agents of enabled plugins with their grants (`agents.configure`). @@ -257,6 +258,18 @@ pub enum AgentsCommand { RecordsStats, /// Lists a page of recorded calls, most recent first (`agentSessions.calls`). RecordsCalls, + /// Opens the agent library directory (`agentLibrary.configure`). + LibraryConfigure, + /// Reads the library and what each agent's configuration holds (`agentLibrary.read`). + LibraryRead, + /// Saves the library if it is unchanged since it was read (`agentLibrary.save`). + LibrarySave, + /// Applies one library change to one agent's configuration (`agentLibrary.apply`). + LibraryApply, + /// Copies a skill into the library (`agentLibrary.importSkill`). + LibraryImportSkill, + /// Removes a library skill and its links (`agentLibrary.removeSkill`). + LibraryRemoveSkill, } impl AgentsCommand { @@ -281,6 +294,12 @@ impl AgentsCommand { Self::RecordsRead => "agentSessions.read", Self::RecordsStats => "agentSessions.stats", Self::RecordsCalls => "agentSessions.calls", + Self::LibraryConfigure => "agentLibrary.configure", + Self::LibraryRead => "agentLibrary.read", + Self::LibrarySave => "agentLibrary.save", + Self::LibraryApply => "agentLibrary.apply", + Self::LibraryImportSkill => "agentLibrary.importSkill", + Self::LibraryRemoveSkill => "agentLibrary.removeSkill", } } } @@ -1277,6 +1296,12 @@ impl CoreCommand { "agentSessions.read" => Some(Self::Agents(AgentsCommand::RecordsRead)), "agentSessions.stats" => Some(Self::Agents(AgentsCommand::RecordsStats)), "agentSessions.calls" => Some(Self::Agents(AgentsCommand::RecordsCalls)), + "agentLibrary.configure" => Some(Self::Agents(AgentsCommand::LibraryConfigure)), + "agentLibrary.read" => Some(Self::Agents(AgentsCommand::LibraryRead)), + "agentLibrary.save" => Some(Self::Agents(AgentsCommand::LibrarySave)), + "agentLibrary.apply" => Some(Self::Agents(AgentsCommand::LibraryApply)), + "agentLibrary.importSkill" => Some(Self::Agents(AgentsCommand::LibraryImportSkill)), + "agentLibrary.removeSkill" => Some(Self::Agents(AgentsCommand::LibraryRemoveSkill)), "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } diff --git a/rust/crates/core/src/runtime/dispatcher/agents.rs b/rust/crates/core/src/runtime/dispatcher/agents.rs index 103b3d65..80150192 100644 --- a/rust/crates/core/src/runtime/dispatcher/agents.rs +++ b/rust/crates/core/src/runtime/dispatcher/agents.rs @@ -1,5 +1,5 @@ -//! `agents.*` and `agentSessions.*` commands, run by `lithe-agent-runtime` -//! (plan API-45). +//! `agents.*`, `agentSessions.*` and `agentLibrary.*` commands, run by +//! `lithe-agent-runtime` (plan API-45). use crate::protocol::{AgentsCommand, CoreResponse}; use serde_json::Value; diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index c177a91c..61ca9709 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -287,8 +287,9 @@ fn invalid_manifest_fixtures_report_their_stable_codes() { } } -/// The install review shows every form an agent runs and every directory its -/// session sources read, so the user sees them before installing. +/// The install review shows every form an agent runs, every directory its +/// session sources read and every configuration path the agent library +/// reads or changes, so the user sees them before installing. #[test] fn agents_are_reviewed_programs() { let review = |name: &str| { @@ -303,7 +304,7 @@ fn agents_are_reviewed_programs() { .filter(|program| { matches!( program["kind"].as_str(), - Some("agent") | Some("agentSessions") + Some("agent") | Some("agentSessions") | Some("agentConfiguration") ) }) .cloned() @@ -314,6 +315,15 @@ fn agents_are_reviewed_programs() { json!({"kind": "agent", "agentID": "example", "tool": "example-agent", "form": "native", "launchFunction": "example.launch"}), json!({"kind": "agent", "agentID": "example", "tool": "example-agent", "form": "terminal", "arguments": []}), json!({"kind": "agent", "agentID": "example", "tool": "example-agent", "form": "update", "arguments": ["update"]}), + json!({ + "kind": "agentConfiguration", + "agentID": "example", + "tool": "example-agent", + "files": [{"id": "main", "roots": ["${userHome}/.example/config.json"]}], + "editable": true, + "instructions": ["${env:EXAMPLE_HOME}/INSTRUCTIONS.md", "${userHome}/.example/INSTRUCTIONS.md"], + "skills": ["${userHome}/.example/skills"] + }), json!({ "kind": "agentSessions", "agentID": "example", diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 267f20c1..94058504 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -6,6 +6,106 @@ use super::{EventMetadata, FieldMetadata, FieldType, LogLevel, SpanPhase}; /// Sorted, immutable metadata for every expanded catalog event. #[rustfmt::skip] pub static EVENTS: &[EventMetadata] = &[ + EventMetadata { + id: "agent.library.change_applied", + channel: "agent", + level: LogLevel::Info, + message: "A library change was applied to an agent's configuration", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "category", field_type: FieldType::Token, required: true, description: "Library category changed: mcpServers, hooks, skills or instructions", reason: None }, + FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Change applied: put, remove, link, unlink or write", reason: None }, + FieldMetadata { name: "changed", field_type: FieldType::Bool, required: true, description: "False when the agent's configuration already matched", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took, including plugin calls", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.change_failed", + channel: "agent", + level: LogLevel::Warn, + message: "A library change to an agent's configuration was refused", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "category", field_type: FieldType::Token, required: true, description: "Library category changed: mcpServers, hooks, skills or instructions", reason: None }, + FieldMetadata { name: "change", field_type: FieldType::Token, required: true, description: "Change applied: put, remove, link, unlink or write", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code such as agentLibrary.fileChanged; never names, commands, paths or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.read_failed", + channel: "agent", + level: LogLevel::Warn, + message: "An agent plugin could not read the agent's configuration", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal code such as agentLibrary.fileChanged; never names, commands, paths or text", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.read_finished", + channel: "agent", + level: LogLevel::Debug, + message: "Agent library and agent configuration read", + fields: &[ + FieldMetadata { name: "agents", field_type: FieldType::Int, required: true, description: "Agents declaring configuration that were reported", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the command took, including plugin calls", reason: None }, + FieldMetadata { name: "failed", field_type: FieldType::Int, required: true, description: "Agents whose plugin could not read their configuration", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.skill_import_finished", + channel: "agent", + level: LogLevel::Info, + message: "A skill was copied into the agent library", + fields: &[ + FieldMetadata { name: "files", field_type: FieldType::Int, required: true, description: "Regular files copied into the library skill", reason: None }, + FieldMetadata { name: "skipped", field_type: FieldType::Int, required: true, description: "Links and special entries left out of the copy", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.skill_removed", + channel: "agent", + level: LogLevel::Info, + message: "A skill was removed from the agent library", + fields: &[ + FieldMetadata { name: "unlinked", field_type: FieldType::Int, required: true, description: "Links to the skill removed from agents' skills directories", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.library.updated", + channel: "agent", + level: LogLevel::Info, + message: "Agent library saved", + fields: &[ + FieldMetadata { name: "hooks", field_type: FieldType::Int, required: true, description: "Hooks kept in the library after the save", reason: None }, + FieldMetadata { name: "servers", field_type: FieldType::Int, required: true, description: "MCP servers kept in the library after the save", reason: None }, + FieldMetadata { name: "sets", field_type: FieldType::Int, required: true, description: "Instruction sets kept in the library after the save", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.records.inspected", channel: "agent", diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index bc3a3c2a..ebb1b889 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -17,6 +17,10 @@ //! - `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. +//! - `configuration` names where the CLI keeps its instructions, skills and +//! the files that hold its MCP servers and hooks, and the backend functions +//! that read and edit those files. Core writes them only when the user +//! applies a change, and only through a staged copy it checks first. //! //! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-25-agent-native-cli-and-local-session-records.md @@ -76,6 +80,14 @@ pub const PERMISSION_AGENTS_RUN: &str = "agents.run"; /// agent, Core reads the listed session files and the backend parses them. pub const PERMISSION_AGENTS_SESSIONS: &str = "agents.sessions.read"; +/// Manifest permission of `configuration`: when the user applies a change +/// from Lithe's agent library, Core edits the declared configuration files, +/// writes the instruction file and links skills into the skills directory. +pub const PERMISSION_AGENTS_CONFIGURATION: &str = "agents.configuration"; + +/// Most configuration files one agent declares. +pub const MAX_CONFIGURATION_FILES: usize = 8; + /// Template variable of the user's home directory in a session root. const USER_HOME_VARIABLE: &str = "${userHome}"; @@ -108,6 +120,51 @@ pub struct AgentDeclaration { /// Where the CLI keeps its session files. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub session_sources: Vec, + /// Where the CLI keeps the configuration Lithe's agent library manages. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub configuration: Option, +} + +/// The configuration of an agent that Lithe's agent library reads and +/// changes: an instruction file and a skills directory Core handles itself, +/// and files in the CLI's own formats the backend reads and edits. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfigurationDeclaration { + /// The Markdown file the CLI reads as the user's own instructions. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option, + /// The directory of the CLI's user skills, one directory with a + /// `SKILL.md` per skill. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skills: Option, + /// The files that hold the CLI's MCP servers and hooks. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub files: Vec, + /// Backend function that reports the MCP servers and hooks of `files`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read: Option, + /// Backend function that applies changes to a staged copy of one file. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edit: Option, +} + +/// A path given as root candidates; the first that resolves is used. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RootsDeclaration { + /// Path candidates, written like session roots. + pub roots: Vec, +} + +/// One configuration file in the CLI's own format. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfigurationFileDeclaration { + /// The file's ID, unique within the agent. + pub id: String, + /// Path candidates, written like session roots. + pub roots: Vec, } /// The backend function that answers a native session's command line. @@ -183,11 +240,16 @@ pub struct DeclarationContext<'a> { } impl AgentDeclaration { - /// Whether Core starts the backend for this agent: a native session or a - /// session source is served by backend functions. A terminal or ACP agent - /// alone runs only its tool. + /// 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. pub fn needs_backend(&self) -> bool { - self.native.is_some() || !self.session_sources.is_empty() + self.native.is_some() + || !self.session_sources.is_empty() + || self + .configuration + .as_ref() + .is_some_and(|configuration| configuration.read.is_some()) } } @@ -202,6 +264,12 @@ pub fn uses_backend(agents: &[AgentDeclaration]) -> bool { agents.iter().any(AgentDeclaration::needs_backend) } +/// Whether any agent declares configuration, which needs +/// `agents.configuration`. +pub fn has_configuration(agents: &[AgentDeclaration]) -> bool { + agents.iter().any(|agent| agent.configuration.is_some()) +} + /// Whether any agent has a native session, which needs `agents.native`. pub fn has_native(agents: &[AgentDeclaration]) -> bool { agents.iter().any(|agent| agent.native.is_some()) @@ -283,10 +351,13 @@ pub fn validate_declarations( } } check_session_sources(&agent.session_sources, &field)?; - if (agent.native.is_some() || !agent.session_sources.is_empty()) && !context.has_backend { + if let Some(configuration) = &agent.configuration { + check_configuration(configuration, &format!("{field}.configuration"))?; + } + if agent.needs_backend() && !context.has_backend { return Err(invalid( field, - "Native sessions and session sources are served by the plugin backend.", + "Native sessions, session sources and configuration files are served by the plugin backend.", )); } } @@ -400,6 +471,99 @@ fn check_session_sources( Ok(()) } +fn check_roots(roots: &[String], field: &str) -> Validation<()> { + if roots.is_empty() || roots.len() > MAX_ROOTS { + return Err(invalid( + field, + format!("A path has 1 to {MAX_ROOTS} candidates."), + )); + } + for (index, root) in roots.iter().enumerate() { + let named = parse_root(root).is_some_and(|(_, segments)| !segments.is_empty()); + if !named { + return Err(invalid( + format!("{field}[{index}]"), + "A configuration path starts with ${userHome} or ${env:NAME}, followed by at least one relative path segment without `..`.", + )); + } + } + Ok(()) +} + +fn check_configuration(configuration: &ConfigurationDeclaration, field: &str) -> Validation<()> { + if configuration.instructions.is_none() + && configuration.skills.is_none() + && configuration.files.is_empty() + { + return Err(invalid( + field, + "Configuration declares at least one of instructions, skills and files.", + )); + } + if let Some(instructions) = &configuration.instructions { + check_roots(&instructions.roots, &format!("{field}.instructions.roots"))?; + } + if let Some(skills) = &configuration.skills { + check_roots(&skills.roots, &format!("{field}.skills.roots"))?; + } + if configuration.files.len() > MAX_CONFIGURATION_FILES { + return Err(invalid( + format!("{field}.files"), + format!("An agent declares at most {MAX_CONFIGURATION_FILES} configuration files."), + )); + } + let mut ids = BTreeSet::new(); + for (index, file) in configuration.files.iter().enumerate() { + let file_field = format!("{field}.files[{index}]"); + if !is_short_id(&file.id) { + return Err(invalid( + format!("{file_field}.id"), + "A configuration file ID uses lowercase letters, digits and hyphens.", + )); + } + if !ids.insert(file.id.as_str()) { + return Err(invalid( + format!("{file_field}.id"), + "A configuration file is declared more than once.", + )); + } + check_roots(&file.roots, &format!("{file_field}.roots"))?; + } + match (configuration.files.is_empty(), &configuration.read) { + (false, None) => { + return Err(invalid( + format!("{field}.read"), + "Configuration files need a read function.", + )) + } + (true, Some(_)) => { + return Err(invalid( + format!("{field}.read"), + "A read function reads the declared configuration files.", + )) + } + _ => {} + } + if configuration.edit.is_some() && configuration.read.is_none() { + return Err(invalid( + format!("{field}.edit"), + "An edit function needs configuration files and a read function.", + )); + } + for (name, function) in [("read", &configuration.read), ("edit", &configuration.edit)] { + if function + .as_deref() + .is_some_and(|function| !is_function_id(function)) + { + return Err(invalid( + format!("{field}.{name}"), + "A configuration function ID is dot-separated lowerCamelCase segments.", + )); + } + } + Ok(()) +} + /// The first part of a root: where it starts. #[derive(Debug, Clone, PartialEq, Eq)] enum RootBase { @@ -438,13 +602,27 @@ fn parse_root(root: &str) -> Option<(RootBase, Vec<&str>)> { Some((base, segments)) } -/// The environment variables the session roots of `agent` read, so the host -/// passes only those to [`resolve_root`]. +/// The environment variables the session and configuration roots of `agent` +/// read, so the host passes only those to [`resolve_root`]. pub fn root_variables(agent: &AgentDeclaration) -> BTreeSet { + let configuration = agent.configuration.iter().flat_map(|configuration| { + configuration + .instructions + .iter() + .chain(configuration.skills.iter()) + .flat_map(|roots| roots.roots.iter()) + .chain( + configuration + .files + .iter() + .flat_map(|file| file.roots.iter()), + ) + }); agent .session_sources .iter() .flat_map(|source| source.roots.iter()) + .chain(configuration) .filter_map(|root| match parse_root(root)?.0 { RootBase::Environment(name) => Some(name), RootBase::UserHome => None, @@ -565,6 +743,14 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { "forms": forms(agent), "readsSessions": !agent.session_sources.is_empty(), }); + if let Some(configuration) = &agent.configuration { + entry["configuration"] = json!({ + "instructions": configuration.instructions.is_some(), + "skills": configuration.skills.is_some(), + "files": !configuration.files.is_empty(), + "editable": configuration.edit.is_some(), + }); + } if let Some(icon) = &agent.icon { entry["icon"] = json!(icon); } @@ -621,6 +807,26 @@ pub fn programs(agent: &AgentDeclaration) -> Vec { "include": source.include, })); } + if let Some(configuration) = &agent.configuration { + let mut program = json!({ + "kind": "agentConfiguration", + "agentID": agent.id, + "tool": agent.tool, + "files": configuration + .files + .iter() + .map(|file| json!({ "id": file.id, "roots": file.roots })) + .collect::>(), + "editable": configuration.edit.is_some(), + }); + if let Some(instructions) = &configuration.instructions { + program["instructions"] = json!(instructions.roots); + } + if let Some(skills) = &configuration.skills { + program["skills"] = json!(skills.roots); + } + programs.push(program); + } programs } diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs index caced74a..f439c785 100644 --- a/rust/crates/plugin-agents/src/tests.rs +++ b/rust/crates/plugin-agents/src/tests.rs @@ -247,3 +247,136 @@ fn launch_params_carry_resume_only_when_given() { json!("abc") ); } + +fn configured() -> Value { + let mut value = sample(); + value["configuration"] = json!({ + "instructions": { "roots": ["${userHome}/.sample/INSTRUCTIONS.md"] }, + "skills": { "roots": ["${env:SAMPLE_CONFIG}/skills", "${userHome}/.sample/skills"] }, + "files": [ + { "id": "settings", "roots": ["${userHome}/.sample/settings.json"] }, + { "id": "servers", "roots": ["${userHome}/.sample.json"] } + ], + "read": "configuration.read", + "edit": "configuration.edit" + }); + value +} + +#[test] +fn accepts_configuration_and_reports_it() { + let mut agents = [agent(configured())]; + check(&mut agents, true).expect("configuration validates"); + assert!(has_configuration(&agents)); + assert!(!has_configuration(&[agent(sample())])); + assert_eq!( + root_variables(&agents[0]), + BTreeSet::from(["SAMPLE_CONFIG".to_string(), "SAMPLE_HOME".to_string()]) + ); + + let entry = catalog_entry("dev.lithe.test.agents", &agents[0]); + assert_eq!( + entry["configuration"], + json!({ "instructions": true, "skills": true, "files": true, "editable": true }) + ); + assert!(entry["configuration"].get("read").is_none()); + + let programs = programs(&agents[0]); + let program = programs + .iter() + .find(|program| program["kind"] == "agentConfiguration") + .expect("configuration is in the install review"); + assert_eq!(program["files"][0]["id"], "settings"); + assert_eq!(program["editable"], true); + assert_eq!(program["skills"][1], "${userHome}/.sample/skills"); +} + +#[test] +fn configuration_files_need_a_backend() { + let mut value = configured(); + value.as_object_mut().unwrap().remove("native"); + value.as_object_mut().unwrap().remove("sessionSources"); + assert!(agent(value.clone()).needs_backend()); + assert_eq!(rejected_field(value.clone(), false), "agents[0]"); + + let configuration = value["configuration"].as_object_mut().unwrap(); + for field in ["files", "read", "edit"] { + configuration.remove(field); + } + assert!(!agent(value.clone()).needs_backend()); + check(&mut [agent(value)], false).expect("instructions and skills need no backend"); +} + +#[test] +fn configuration_is_bounded_and_consistent() { + let cases: [(&str, Value, &str); 9] = [ + ("empty", json!({}), "agents[0].configuration"), + ( + "a root without a file name", + json!({ "instructions": { "roots": ["${userHome}"] } }), + "agents[0].configuration.instructions.roots[0]", + ), + ( + "a root leaving the base", + json!({ "skills": { "roots": ["${userHome}/../skills"] } }), + "agents[0].configuration.skills.roots[0]", + ), + ( + "too many candidates", + json!({ "skills": { "roots": [ + "${userHome}/a", "${userHome}/b", "${userHome}/c", "${userHome}/d", "${userHome}/e" + ] } }), + "agents[0].configuration.skills.roots", + ), + ( + "files without read", + json!({ "files": [{ "id": "settings", "roots": ["${userHome}/s.json"] }] }), + "agents[0].configuration.read", + ), + ( + "read without files", + json!({ "instructions": { "roots": ["${userHome}/A.md"] }, "read": "configuration.read" }), + "agents[0].configuration.read", + ), + ( + "edit without read", + json!({ "instructions": { "roots": ["${userHome}/A.md"] }, "edit": "configuration.edit" }), + "agents[0].configuration.edit", + ), + ( + "a duplicate file", + json!({ + "files": [ + { "id": "settings", "roots": ["${userHome}/a.json"] }, + { "id": "settings", "roots": ["${userHome}/b.json"] } + ], + "read": "configuration.read" + }), + "agents[0].configuration.files[1].id", + ), + ( + "an invalid function ID", + json!({ + "files": [{ "id": "settings", "roots": ["${userHome}/a.json"] }], + "read": "Configuration Read" + }), + "agents[0].configuration.read", + ), + ]; + for (name, configuration, field) in cases { + let mut value = sample(); + value["configuration"] = configuration; + assert_eq!(rejected_field(value, true), field, "{name}"); + } + + let mut many = sample(); + let files: Vec = (0..=MAX_CONFIGURATION_FILES) + .map(|index| json!({ "id": format!("file-{index}"), "roots": [format!("${{userHome}}/{index}.json")] })) + .collect(); + many["configuration"] = json!({ "files": files, "read": "configuration.read" }); + assert_eq!(rejected_field(many, true), "agents[0].configuration.files"); + + let mut unknown = configured(); + unknown["configuration"]["environment"] = json!({}); + assert!(serde_json::from_value::(unknown).is_err()); +} diff --git a/rust/crates/plugin-manifest/src/permissions.rs b/rust/crates/plugin-manifest/src/permissions.rs index d21c9326..fa776882 100644 --- a/rust/crates/plugin-manifest/src/permissions.rs +++ b/rust/crates/plugin-manifest/src/permissions.rs @@ -64,6 +64,7 @@ const PERMISSION_COMMAND_INSTALL: &str = "commands.install"; const PERMISSION_RUNTIME_INSTALL: &str = "runtimes.install"; const KNOWN_PERMISSIONS: &[&str] = &[ + lithe_plugin_agents::PERMISSION_AGENTS_CONFIGURATION, lithe_plugin_agents::PERMISSION_AGENTS_RUN, lithe_plugin_agents::PERMISSION_AGENTS_SESSIONS, PERMISSION_BACKEND, @@ -305,8 +306,8 @@ impl DeclarativePluginManifest { } /// Ties `agents[]` to its permissions: running the agents' tools, reading - /// their session files, and translating native sessions. A permission - /// nothing exercises is refused. + /// their session files, translating native sessions and changing their + /// configuration. A permission nothing exercises is refused. fn require_agent_permissions(&self, required: &mut BTreeSet<&'static str>) -> Validation<()> { let needs = [ ( @@ -323,6 +324,10 @@ impl DeclarativePluginManifest { lithe_plugin_rpc::PERMISSION_AGENTS_NATIVE, lithe_plugin_agents::has_native(&self.agents), ), + ( + lithe_plugin_agents::PERMISSION_AGENTS_CONFIGURATION, + lithe_plugin_agents::has_configuration(&self.agents), + ), ]; for (permission, used) in needs { if used { diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 6c88e27e..34df3c20 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -8,10 +8,26 @@ "level": "info", "message": "Agent session started", "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"}, - "session": {"type": "id", "required": true, "description": "Opaque session ID Core assigned; never the agent CLI's own session ID"}, - "mode": {"type": "token", "required": true, "description": "Connection mode Core selected, e.g. native"} + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "session": { + "type": "id", + "required": true, + "description": "Opaque session ID Core assigned; never the agent CLI's own session ID" + }, + "mode": { + "type": "token", + "required": true, + "description": "Connection mode Core selected, e.g. native" + } }, "rate": 60, "owner": "lithe-core" @@ -22,9 +38,21 @@ "level": "warn", "message": "Agent session could not start", "fields": { - "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, - "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, - "reason": {"type": "token", "required": true, "description": "Stable refusal or failure code; excludes paths, arguments and CLI output"} + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal or failure code; excludes paths, arguments and CLI output" + } }, "rate": 60, "owner": "lithe-core" @@ -35,10 +63,26 @@ "level": "info", "message": "Agent session ended", "fields": { - "session": {"type": "id", "required": true, "description": "Opaque session ID Core assigned"}, - "reason": {"type": "token", "required": true, "description": "Why the session ended: exited, closed, backendEnded or failed"}, - "exit_code": {"type": "int", "required": false, "description": "Exit code of the agent CLI; absent when a signal ended it"}, - "duration": {"type": "duration", "required": true, "description": "Milliseconds the session ran"} + "session": { + "type": "id", + "required": true, + "description": "Opaque session ID Core assigned" + }, + "reason": { + "type": "token", + "required": true, + "description": "Why the session ended: exited, closed, backendEnded or failed" + }, + "exit_code": { + "type": "int", + "required": false, + "description": "Exit code of the agent CLI; absent when a signal ended it" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the session ran" + } }, "rate": 60, "owner": "lithe-core" @@ -49,8 +93,16 @@ "level": "warn", "message": "Agent plugin reported an invalid session event", "fields": { - "plugin": {"type": "id", "required": true, "description": "Validated plugin identity of the reporting backend"}, - "code": {"type": "token", "required": true, "description": "Stable rejection code; the event content is never logged"} + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity of the reporting backend" + }, + "code": { + "type": "token", + "required": true, + "description": "Stable rejection code; the event content is never logged" + } }, "rate": 60, "owner": "lithe-core" @@ -61,11 +113,31 @@ "level": "info", "message": "Agent session records synchronized", "fields": { - "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, - "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, - "files_read": {"type": "int", "required": true, "description": "Session files read in this sync"}, - "files_failed": {"type": "int", "required": true, "description": "Session files that could not be read or parsed"}, - "duration": {"type": "duration", "required": true, "description": "Milliseconds the sync took"} + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "files_read": { + "type": "int", + "required": true, + "description": "Session files read in this sync" + }, + "files_failed": { + "type": "int", + "required": true, + "description": "Session files that could not be read or parsed" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the sync took" + } }, "rate": 60, "owner": "lithe-core" @@ -76,9 +148,21 @@ "level": "warn", "message": "Agent session records could not be synchronized", "fields": { - "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, - "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, - "reason": {"type": "token", "required": true, "description": "Stable failure code; excludes paths and session content"} + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable failure code; excludes paths and session content" + } }, "rate": 60, "owner": "lithe-core" @@ -89,9 +173,21 @@ "level": "info", "message": "Agent session records removed from the cache", "fields": { - "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, - "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, - "files": {"type": "int", "required": true, "description": "Session files whose records were dropped"} + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "files": { + "type": "int", + "required": true, + "description": "Session files whose records were dropped" + } }, "rate": 60, "owner": "lithe-core" @@ -102,12 +198,209 @@ "level": "info", "message": "An MCP client searched or read agent session records", "fields": { - "tool": {"type": "token", "required": true, "description": "IDE tool the MCP client called, lithe_sessions_search or lithe_sessions_read; never the query, session ID or content"}, - "results": {"type": "int", "required": true, "description": "Hits or messages answered"}, - "duration": {"type": "duration", "required": true, "description": "Milliseconds the call took"} + "tool": { + "type": "token", + "required": true, + "description": "IDE tool the MCP client called, lithe_sessions_search or lithe_sessions_read; never the query, session ID or content" + }, + "results": { + "type": "int", + "required": true, + "description": "Hits or messages answered" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the call took" + } }, "rate": 60, "owner": "Lithe" + }, + { + "id": "agent.library.read_finished", + "channel": "agent", + "level": "debug", + "message": "Agent library and agent configuration read", + "fields": { + "agents": { + "type": "int", + "required": true, + "description": "Agents declaring configuration that were reported" + }, + "failed": { + "type": "int", + "required": true, + "description": "Agents whose plugin could not read their configuration" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took, including plugin calls" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.read_failed", + "channel": "agent", + "level": "warn", + "message": "An agent plugin could not read the agent's configuration", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code such as agentLibrary.fileChanged; never names, commands, paths or text" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.updated", + "channel": "agent", + "level": "info", + "message": "Agent library saved", + "fields": { + "servers": { + "type": "int", + "required": true, + "description": "MCP servers kept in the library after the save" + }, + "hooks": { + "type": "int", + "required": true, + "description": "Hooks kept in the library after the save" + }, + "sets": { + "type": "int", + "required": true, + "description": "Instruction sets kept in the library after the save" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.change_applied", + "channel": "agent", + "level": "info", + "message": "A library change was applied to an agent's configuration", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "category": { + "type": "token", + "required": true, + "description": "Library category changed: mcpServers, hooks, skills or instructions" + }, + "change": { + "type": "token", + "required": true, + "description": "Change applied: put, remove, link, unlink or write" + }, + "changed": { + "type": "bool", + "required": true, + "description": "False when the agent's configuration already matched" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Milliseconds the command took, including plugin calls" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.change_failed", + "channel": "agent", + "level": "warn", + "message": "A library change to an agent's configuration was refused", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "category": { + "type": "token", + "required": true, + "description": "Library category changed: mcpServers, hooks, skills or instructions" + }, + "change": { + "type": "token", + "required": true, + "description": "Change applied: put, remove, link, unlink or write" + }, + "reason": { + "type": "token", + "required": true, + "description": "Stable refusal code such as agentLibrary.fileChanged; never names, commands, paths or text" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.skill_import_finished", + "channel": "agent", + "level": "info", + "message": "A skill was copied into the agent library", + "fields": { + "files": { + "type": "int", + "required": true, + "description": "Regular files copied into the library skill" + }, + "skipped": { + "type": "int", + "required": true, + "description": "Links and special entries left out of the copy" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.library.skill_removed", + "channel": "agent", + "level": "info", + "message": "A skill was removed from the agent library", + "fields": { + "unlinked": { + "type": "int", + "required": true, + "description": "Links to the skill removed from agents' skills directories" + } + }, + "rate": 60, + "owner": "lithe-core" } ] } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 23ab366d..7abec129 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1845,6 +1845,7 @@ Older hosts that do not advertise this capability reject | `agents.native` | an agent declares `native` (and only then); grants `lithe/host/agents/write`, `lithe/host/agents/report` and the `lithe/host/agents/did*` notifications for the plugin's own sessions | | `agents.sessions.read` | an agent declares `sessionSources` (and only then); after the user consents, Core reads the declared session files and hands their lines to the backend | | `agents.usage.read` | the backend reads [usage totals](#native-sessions) with `lithe/host/agents/usage`; requires `backend`. Grants numbers and model names only, no conversation text, titles, session IDs or directories | +| `agents.configuration` | an agent declares `configuration` (and only then); after the user consents, Core reads and changes the declared instruction file and skills directory, and the backend reads the declared configuration files and edits staged copies of them. See [Agent configuration](#agent-configuration) | | Activation event | Meaning | | --- | --- | @@ -1855,7 +1856,7 @@ Older hosts that do not advertise this capability reject | `onVcsRoot:` | Start the VCS provider once a root of its VCS is detected in the workspace. | | `onDebug:` | Start the debug adapter when a debug session needs it. | | `onWorkspaceOpen` | Start the [`backend`](#backend-lifecycle-and-workspace-contexts) process once a workspace is open. Optional, names no ID, refused without `backend`. | -| `onAgent:` | Start the backend before a native session of the agent starts or its session records sync. Required for, and only for, an agent that declares `native` or `sessionSources`. | +| `onAgent:` | Start the backend before a native session of the agent starts, its session records sync or its configuration files are read. Required for, and only for, an agent that declares `native`, `sessionSources` or a `configuration` with `read`. | Each provider needs its event and each event needs a provider; the only optional event is `onWorkspaceOpen`. There is no event that starts a plugin @@ -3651,7 +3652,8 @@ contexts. `fixtures/backend/backend-workspace.plugin.json` is the example. event, or a provider the host queries: a toolchain or keymap import provider, a language server with `launch.kind: "backend"`, whose start asks the backend for its command line, or an [agent](#agents) whose native - sessions or session records the backend serves (`onAgent:`). A backend + sessions, session records or configuration files the backend serves + (`onAgent:`). A backend with none of them is `plugin.manifest.invalid`. - It is one process per plugin, shared by every open workspace and window, on the machine that runs Lithe, also for remote workspaces. No @@ -3721,14 +3723,16 @@ rejections. | `terminal` | `{arguments}`: runs `tool` with these arguments in a host terminal, the CLI's own interactive interface. | | `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. | | `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. | - A plugin declares at most eight agents; the host shows them sorted by `id`. Each agent declares at least one of `native`, `acp` and `terminal`. - `acp`, `terminal` and `update` hold at most 64 arguments of at most 4 KiB each, without NUL. Arguments are fixed: they take no templates. - A function ID is dot-separated lowerCamelCase segments, as in - [plugin functions](#plugin-functions). `native` and `sessionSources` are - served by the plugin backend, so they need `backend`. + [plugin functions](#plugin-functions). `native`, `sessionSources` and the + `read` and `edit` of `configuration` are served by the plugin backend, so + they need `backend`. - Every rejection is `plugin.manifest.invalid` with `field` naming the place, such as `agents[0].tool` or `agents[0].sessionSources[1].include[0]`. @@ -3736,8 +3740,11 @@ 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; and one `kind: "agentSessions"` entry per source with `agentID`, `tool`, `source`, -`roots` and `include`, so the user sees every directory the plugin asks to -read before installing it. +`roots` and `include`; and one `kind: "agentConfiguration"` entry per agent +that declares `configuration`, with `agentID`, `tool`, `instructions?`, +`skills?` (their roots), `files` (`{id, roots}`) and `editable` (whether it +declares `edit`). The user sees every directory and file the plugin asks to +read or change before installing it. ### Agent permissions and activation @@ -3747,19 +3754,21 @@ read before installing it. | `agents.native` | an agent declares `native` | `lithe/host/agents/write`, `lithe/host/agents/report` and the `lithe/host/agents/did*` notifications, only for the plugin's own sessions | | `agents.sessions.read` | an agent declares `sessionSources` | after the user consents, Core reads the declared session files and the backend parses them | | `agents.usage.read` | the backend sums agent usage; needs `backend` | `lithe/host/agents/usage`: numbers and model names of the agents the user enabled, no conversation text, titles, session IDs or directories | +| `agents.configuration` | an agent declares `configuration` | after the user consents, Core reads and changes the declared instruction file and skills directory, the backend reads the declared files and edits staged copies; every change is one the user chose | 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` or `sessionSources` needs the activation event `onAgent:`, and +`native`, `sessionSources` 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 or syncs its -records. +the backend before it starts a native session of the agent, syncs its +records or reads its configuration files. ### Host commands @@ -3770,9 +3779,13 @@ 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?, -terminalArguments?, update?, sessionRootVariables?}`: `modes` lists -`native` and `acp`, `forms` lists `conversation` and `terminal`, and -`sessionRootVariables` names the environment variables the roots read. +terminalArguments?, update?, sessionRootVariables?, configuration?, +mayConfigure?}`: `modes` lists `native` and `acp`, `forms` lists +`conversation` and `terminal`, and `sessionRootVariables` names the +environment variables the session and configuration roots read. 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`. | Command | Payload | Result | | --- | --- | --- | @@ -4085,6 +4098,278 @@ under the agent's roots), `agentSessions.discoveryFailed`, `agentSessions.invalidScan`, `agentSessions.readFailed`, `agentSessions.invalidRead` and `agentSessions.invalidGroup`. +### Agent configuration + +An agent's CLI keeps the user's instructions, skills, MCP servers and hooks +in its own files. `configuration` says where, so the host's agent library +can show what each agent has and, when the user asks, turn an item of the +library on or off for it. The library is Lithe's own data; the host draws +every view of it. The host shows an agent by its `displayName` and `icon` +and keeps no name or icon of its own for any agent. + +```json +"configuration": { + "instructions": {"roots": ["${env:SAMPLE_HOME}/INSTRUCTIONS.md", "${userHome}/.sample/INSTRUCTIONS.md"]}, + "skills": {"roots": ["${userHome}/.sample/skills"]}, + "files": [{"id": "main", "roots": ["${userHome}/.sample/config.json"]}], + "read": "configuration.read", + "edit": "configuration.edit" +} +``` + +| Field | Meaning | +| --- | --- | +| `instructions` | `{roots}`: the Markdown file the CLI reads as the user's own instructions. Core reads and writes it. | +| `skills` | `{roots}`: the directory of the CLI's user skills, one directory with a `SKILL.md` per skill. Core reads it and links library skills into it. | +| `files` | At most 8 `{id, roots}`: the files in the CLI's own format that hold its MCP servers and hooks. `id` is 1–64 bytes of lowercase ASCII letters, digits and `-`, not starting or ending with `-`, unique in the agent. Only the backend reads their format. | +| `read` | Backend function that reports what `files` hold. Required with `files` and refused without them. | +| `edit` | Backend function that applies one change to a staged copy of one of `files`. Needs `read`. Without it the agent's MCP servers and hooks are shown, never changed. | + +- A configuration declares at least one of `instructions`, `skills` and + `files`. A function ID is dot-separated lowerCamelCase segments. +- Roots are written like [session roots](#session-records): 1–4 candidates, + each `${userHome}` or `${env:NAME}` followed by at least one relative + segment. The first candidate whose variable resolves to a nonempty value + is the path, whether or not anything is there yet. +- The plugin declares `agents.configuration`. Until the user grants it, the + agent is listed with `mayConfigure: false` and nothing of it is read or + changed. +- `configuration` was added within `agents` 0. A Core that predates it + refuses a manifest that declares it as invalid (`configuration` is an + unknown field of the agent), and answers none of the `agentLibrary.*` + commands. + +#### The library + +The host opens the library with `agentLibrary.configure {directory, +userHome, environment?}`. `directory` is a directory of the platform's +application data, never in the package or the installation, and both paths +are absolute (`agentLibrary.invalidDirectory`). `environment` gives the +values of the catalog's `sessionRootVariables`: at most 256, each name 1–256 +bytes and each value at most 32 KiB (`agentLibrary.invalidEnvironment`). In +`directory`, created owner-only, Core keeps `library.json` (the servers, +hooks and instruction sets), `skills//` (one directory per skill), +`state.json` (a digest of what Core last wrote to each agent's instruction +file) and `staging/` (the copies plugins edit). + +The library is `{mcpServers, hooks, instructions}`: + +- `mcpServers`: at most 256 `{name, transport, command?, args?, url?}`, + names unique. A `stdio` server has a nonblank `command` and at most 64 + `args`; an `http` or `sse` server has an `http://` or `https://` `url` and + neither. Version 0 keeps no environment variables or headers, whose values + are secrets. +- `hooks`: at most 256 `{id, event, matcher?, command, timeoutSeconds?}`. + The host chooses `id` (1–64 bytes of lowercase ASCII letters, digits and + `-`, unique); `event` is 1–64 ASCII letters, digits and `_`, as the CLIs + name their hook events; `command` is nonblank; `timeoutSeconds` is + 1–86400. +- `instructions`: `{sets, active?, agents}`. `sets` holds at most 64 `{id, + name, text}`, `id` like a hook's and `text` at most 256 KiB; `active` + names one set. `agents` maps at most 256 agent keys `/` + to `{enabled, extra?}`: whether the agent's instruction file follows the + library, and at most 64 KiB of text only that agent gets. + +A name is 1–128 characters without leading or trailing spaces or control +characters. A command, URL, matcher or argument is at most 4 KiB without +NUL. + +An agent's instructions are the active set's text, then, after a blank +line, the agent's `extra`, ending with one line break; they are empty when +neither has text. + +#### Library commands + +| Command | Payload | Result | +| --- | --- | --- | +| `agentLibrary.configure` | `{directory, userHome, environment?}` | `{}` | +| `agentLibrary.read` | `{}` | `{revision, library, skills, states, agents}` | +| `agentLibrary.save` | `{revision, library}` | `{revision}` | +| `agentLibrary.apply` | `{agent, change}` | `{changed}` | +| `agentLibrary.importSkill` | `{agent, name}` or `{directory}` | `{name, files, skipped}` | +| `agentLibrary.removeSkill` | `{name}` | `{unlinked}` | + +- `save`, `apply`, `importSkill` and `removeSkill` run only for a request + whose origin is the user (`agentLibrary.userActionRequired`): a plugin + never changes the library or an agent's configuration. +- `revision` is the SHA-256 of `library.json` in lowercase hex, or `empty` + before the first save. `save` replaces the library only while the file is + still at `revision` (`agentLibrary.revisionChanged`) and never replaces a + file it cannot read. A `library.json` Core cannot read as a library is + `agentLibrary.invalidLibraryFile`; Core never rewrites it on its own. +- `agent` is `/` of an agent that declares + `configuration` (`agentLibrary.unknownAgent`) and whose plugin is granted + `agents.configuration` (`agentLibrary.notGranted`). + +`read` answers the library, `skills`, `states` and `agents`: + +- `skills`: the library's skills, `{name, description?, agents}`, sorted by + name. `agents` maps each agent key to `on` (the agent's skills directory + has a link of that name into the library), `conflict` (an entry of that + name that is not) or `off`. +- `states.mcpServers` maps each library server's name, and + `states.hooks` each library hook's `id`, to the same kind of map. A server + is `on` when the agent has a server of that name that is the same server + (transport, `command`, `args` and `url`) with no environment variables or + headers, `conflict` when its server of that name differs, `unsupported` + when the plugin names no file for servers, otherwise `off`. A hook is `on` + when the agent has a hook with the same `event`, `matcher` and `command` + (an empty matcher is no matcher), `unsupported` when the plugin names no + file for hooks or the agent runs no hooks for the event, otherwise `off`. + An agent whose plugin is not granted, whose `read` failed or that declares + no `files` is in neither map; one whose skills directory Lithe could not + read, or that declares no `skills`, is in no skill's `agents`. +- `agents`: one entry per agent that declares `configuration`, in catalog + order: `{agent, pluginID, agentID, displayName, icon?, mayConfigure, + editable, instructions?, skills?, mcpServers?, hooks?, hookEvents?, + providedSkills?, targets?, readError?}`. An agent whose plugin is not + granted gives only the fields up to `editable`. + - `instructions`: `{path, state}`, `state` being `absent`, `empty` (only + whitespace), `current` (exactly the agent's instructions), `written` + (what Lithe last wrote, since changed in the library), `other` (text + Lithe did not write), `tooLarge` or `unreadable`. + - `skills`: `{path, items}` with up to 512 `{name, kind, description?}`, + `kind` being `library` (a link into the library), `own` (a directory of + the agent's own) or `link` (a link elsewhere); or `{path, error: + "agentLibrary.unreadable"}`. Entries without a readable `SKILL.md`, + hidden entries and plain files are left out. + - `mcpServers` and `hooks` are what `read` reported, each with + `inLibrary`, whether the library holds the same item; `hookEvents` and + `providedSkills` likewise; `targets` is `{mcpServers, hooks}`, whether + the plugin names a file for each. + - `readError` is the code of a failed `read` (`agentLibrary.backendUnavailable`, + `agentLibrary.readFailed` or `agentLibrary.invalidSnapshot`); the rest + of the entry still answers. + +`apply` makes one `change`, and answers `changed: false` when the agent +already had what it asks for: + +| `change` | Effect | +| --- | --- | +| `{category: "mcpServers", op: "put", name}` | puts the library server `name` into the agent | +| `{category: "mcpServers", op: "remove", name}` | removes the agent's own server `name` | +| `{category: "hooks", op: "put", id}` | puts the library hook `id` into the agent | +| `{category: "hooks", op: "remove", hook: {event, matcher?, command, timeoutSeconds?}}` | removes the agent's own hook that is this hook | +| `{category: "skills", op: "link", name}` | links the library skill `name` into the agent's skills directory | +| `{category: "skills", op: "unlink", name}` | removes the agent's link of that name into the library | +| `{category: "instructions", op: "write", replace?}` | writes the agent's instructions to its instruction file | + +Any other combination is `agentLibrary.invalidChange`; a library item that +does not exist is `agentLibrary.unknownItem`. + +A server or hook changes through the plugin, on a copy: + +1. Core asks `read` for what the files hold now and takes the file its + `targets` names for the category (`agentLibrary.noTarget`; an agent + without `edit` is `agentLibrary.notEditable`). Removing an item the + user's own configuration does not hold, including one the CLI installed + itself, is `agentLibrary.notInAgent`; putting a hook for an event the + agent does not run is `agentLibrary.unsupportedEvent`. +2. Core follows links in the file's path to the file itself (a link to + nothing is `agentLibrary.brokenLink`), copies the file, or nothing when it + does not exist, into an owner-only file in `staging/`, and calls `edit` + on the copy. +3. When `edit` answers `changed` and the copy differs from the file, Core + calls `read` again with the copy in place of the file. The change must + show there (`agentLibrary.editNotApplied`). +4. Core replaces the file only if it still holds the bytes it copied + (`agentLibrary.fileChanged`): a new file next to it, with the old file's + permissions (owner-only for a new file), written to disk and renamed over + it. The copy is removed either way. + +A skill is linked as a symbolic link to `skills/` of the library. +Unlinking removes only a link into the library +(`agentLibrary.notLibraryLink`); linking over an entry of the agent's own is +`agentLibrary.agentSkillExists`. On Windows a link needs Developer Mode or +an elevated process, otherwise `agentLibrary.linkFailed`. An agent without +`skills` is `agentLibrary.noSkills`. + +Instructions are written only while the agent's `enabled` is true +(`agentLibrary.instructionsOff`). Text Lithe did not write is replaced only +with `replace: true` (`agentLibrary.otherInstructions`); an empty file and +the text Lithe last wrote are replaced without it. The file is replaced the +same way as a configuration file. An agent without `instructions` is +`agentLibrary.noInstructions`. + +`importSkill` copies a skill into the library: `{agent, name}` the agent's +own skill directory `name` (a link is `agentLibrary.notOwnSkill`), +`{directory}` an absolute directory the user chose +(`agentLibrary.invalidSkillDirectory`); any other shape is +`agentLibrary.invalidImport`. The directory needs a readable `SKILL.md` +(`agentLibrary.notSkill`). The skill's name is `name`, else the `name` of the +`SKILL.md` front matter, else the directory's name, and is 1–64 bytes of +ASCII letters, digits, `.`, `_` and `-`, not starting with `.` +(`agentLibrary.invalidSkillName`). Core copies the regular files and +directories, counting the links and other entries it skips in `skipped`, +within 1024 files, 16 MiB and 16 levels (`agentLibrary.skillTooLarge`), and +moves the copy into the library without replacing a skill +(`agentLibrary.skillExists`). Of the front matter Core reads only `name` and +`description`, as plain, quoted or block scalars; a description is cut to +1024 characters. + +`removeSkill` removes the skill's links from the skills directory of every +agent whose plugin is granted, then the skill, and answers how many links it +removed. A link in an agent whose plugin is not granted is left, and leads +nowhere. + +#### Configuration functions + +`read` receives `{agentID, files: [{id, path, exists}]}`, one item per +declared file whose path resolves. `path` may be a staged copy standing in +for the file, with the same extension; `exists` says whether anything is at +`path`. It has 10 seconds and answers exactly: + +- `format: "litheAgentConfiguration"` and `version: 0`; +- `mcpServers`: at most 256 `{name, transport, command?, args?, url?, + environmentNames?, headerNames?, origin, provider?}`, the servers the + files configure. `environmentNames` and `headerNames` are at most 64 names + each of ASCII letters, digits, `_` and `-`, never values. `origin` is + `user` for the user's own configuration, which `edit` changes, or `agent` + for what the CLI installed itself, such as through a CLI plugin, which + `provider` (1–128 characters) names and Lithe only shows; +- `hooks`: at most 256 `{event, matcher?, command, timeoutSeconds?, origin, + provider?}`; +- `hookEvents`: at most 32 distinct events the CLI runs hooks for; empty + when the plugin does not say, and then every event is allowed; +- `skills`: at most 512 `{name, description?, provider?}`, skills the CLI + installed itself outside the skills directory, `description` at most 1024 + characters; +- `targets`: `{mcpServers?, hooks?}`, the `id` of the declared file a + change of each category goes to. A category without one is only shown. + +Any other answer is `agentLibrary.invalidSnapshot`; a failed call is +`agentLibrary.readFailed`. + +`edit` receives `{agentID, file: {id, staging, exists}, change}`, with +`change` one of `{category: "mcpServers", op: "put", server: {name, +transport, command?, args?, url?}}`, `{category: "mcpServers", op: +"remove", name}`, `{category: "hooks", op: "put", hook: {event, matcher?, +command, timeoutSeconds?}}` and `{category: "hooks", op: "remove", hook}`. +`put` makes the user's configuration hold exactly that server, replacing a +server of the same name, or that hook; `remove` takes the item out. The +backend changes only the file at `staging`, empty when `exists` is false, in +the CLI's own format, keeping everything else the file holds, and answers +`{format: "litheAgentConfigurationEdit", version: 0, changed}` within 10 +seconds. Any other answer is `agentLibrary.invalidEdit`; a failed call is +`agentLibrary.editFailed`. The backend never learns the file's own path from +`edit`. + +#### Limits, refusals and logging + +- Core reads at most 8 MiB of `library.json`, 16 MiB of a configuration + file, 1 MiB of an instruction file (`agentLibrary.fileTooLarge`) and 64 + KiB of a `SKILL.md`; a larger `SKILL.md` is a skill without a description. + A file Core cannot read is `agentLibrary.unreadable`, one it cannot write + `agentLibrary.writeFailed`. +- A request before `agentLibrary.configure` is `agentLibrary.notConfigured`. + A `save` whose library breaks a rule above is `agentLibrary.invalidLibrary`, + its message naming the field. A backend that is not running is + `agentLibrary.backendUnavailable`. +- Changes never interleave: Core checks and replaces one file at a time, + never while waiting for a backend. +- Core logs plugin and agent IDs, categories, operations, counts, durations + and refusal codes, never names, commands, paths or text. + ### Privacy and logging - Core and the host log only session IDs, plugin and agent IDs, counts, diff --git a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json index 7c0e5b45..e934f2e2 100644 --- a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -17,6 +17,7 @@ "signatureRequirement": "publisherPackage" }, "permissions": [ + "agents.configuration", "agents.native", "agents.run", "agents.sessions.read", @@ -58,7 +59,30 @@ "scan": "example.sessions.scan", "read": "example.sessions.read" } - ] + ], + "configuration": { + "instructions": { + "roots": [ + "${env:EXAMPLE_HOME}/INSTRUCTIONS.md", + "${userHome}/.example/INSTRUCTIONS.md" + ] + }, + "skills": { + "roots": [ + "${userHome}/.example/skills" + ] + }, + "files": [ + { + "id": "main", + "roots": [ + "${userHome}/.example/config.json" + ] + } + ], + "read": "example.configuration.read", + "edit": "example.configuration.edit" + } } ], "backend": { diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index 849134f6..bc573805 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -974,9 +974,9 @@ {"name": "a download archive is zip or tar.gz", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/archive", "value": "7z"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].archive"}, {"name": "a download strip prefix stays inside the archive", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/1/stripPrefix", "value": "../sample-lldb"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[1].stripPrefix"}, {"name": "agents need requires.agents", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/requires/agents"}], "expectedCode": "plugin.manifest.invalid"}, - {"name": "agents need agents.run", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.native", "agents.sessions.read", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, - {"name": "a native agent needs agents.native", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.run", "agents.sessions.read", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, - {"name": "session sources need agents.sessions.read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.native", "agents.run", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, + {"name": "agents need agents.run", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.configuration", "agents.native", "agents.sessions.read", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, + {"name": "a native agent needs agents.native", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.configuration", "agents.run", "agents.sessions.read", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, + {"name": "session sources need agents.sessions.read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.configuration", "agents.native", "agents.run", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, {"name": "agents.native without a native agent", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.native", "agents.run"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "permissions"}, {"name": "agents.sessions.read without a session source", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.run", "agents.sessions.read"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "permissions"}, {"name": "an agent runs one of the required tools", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/tool", "value": "other-agent"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].tool"}, @@ -992,9 +992,19 @@ {"name": "a session root does not leave its variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/sessionSources/0/roots", "value": ["${userHome}/../sessions"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].sessionSources[0].roots[0]"}, {"name": "a session include pattern stays in the root", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/sessionSources/0/include", "value": ["../**/*.jsonl"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].sessionSources[0].include[0]"}, {"name": "a session source format is jsonLines", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/sessionSources/0/format", "value": "json"}], "expectedCode": "plugin.manifest.invalid"}, - {"name": "a native agent needs a backend", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/backend"}, {"op": "remove", "path": "/requires/backend"}, {"op": "set", "path": "/permissions", "value": ["agents.native", "agents.run", "agents.sessions.read", "agents.usage.read"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a native agent needs a backend", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/backend"}, {"op": "remove", "path": "/requires/backend"}, {"op": "set", "path": "/permissions", "value": ["agents.configuration", "agents.native", "agents.run", "agents.sessions.read", "agents.usage.read"]}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a backend agent declares onAgent", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/activationEvents", "value": []}], "expectedCode": "plugin.activation.invalid", "expectedField": "activationEvents"}, {"name": "a terminal-only agent declares no onAgent", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/activationEvents", "value": ["onAgent:example"]}], "expectedCode": "plugin.activation.invalid", "expectedField": "activationEvents"}, + {"name": "configuration needs agents.configuration", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.native", "agents.run", "agents.sessions.read", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, + {"name": "agents.configuration without a configuration", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.configuration", "agents.run"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "permissions"}, + {"name": "a configuration declares something", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration", "value": {}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration"}, + {"name": "a configuration path starts with a variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/instructions/roots", "value": ["/etc/INSTRUCTIONS.md"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.instructions.roots[0]"}, + {"name": "a configuration path names something below its variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/skills/roots", "value": ["${userHome}"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.skills.roots[0]"}, + {"name": "a configuration path does not leave its variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files/0/roots", "value": ["${userHome}/../config.json"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.files[0].roots[0]"}, + {"name": "a configuration file is declared once", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": [{"id": "main", "roots": ["${userHome}/.example/a.json"]}, {"id": "main", "roots": ["${userHome}/.example/b.json"]}]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.files[1].id"}, + {"name": "configuration files need a read function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/edit"}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.read"}, + {"name": "a configuration edit function needs read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": []}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, + {"name": "a configuration function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/edit", "value": "Example Edit"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "an agent field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/environment", "value": {"EXAMPLE": "1"}}], "expectedCode": "plugin.manifest.invalid"} ] } diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index b54d7460..ee4a242e 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -10,6 +10,8 @@ {"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": ["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": ["permissions"], "properties": {"permissions": {"contains": {"const": "agents.usage.read"}}}}, "then": {"required": ["backend"]}}, {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, @@ -107,13 +109,13 @@ "languageServer.request", "documents.contentProvider", "documents.save", - "workspace.files.write", "window.input", "views.refresh", "output.write", "window.progress", "statusBar.write", "clipboard.read", "clipboard.write", "workspace.reveal", "workspace.directoryMarks", "network.request", "agents.run", "agents.native", "agents.sessions.read", "agents.usage.read"] } + "workspace.files.write", "window.input", "views.refresh", "output.write", "window.progress", "statusBar.write", "clipboard.read", "clipboard.write", "workspace.reveal", "workspace.directoryMarks", "network.request", "agents.run", "agents.native", "agents.sessions.read", "agents.usage.read", "agents.configuration"] } }, "activationEvents": { "type": "array", "items": { "type": "string", - "description": "onWorkspaceOpen names no ID and needs requires.backend; it starts the backend once a workspace is open. onAgent: starts the backend for an agent that declares native or sessionSources, and only for one.", + "description": "onWorkspaceOpen names no ID and needs requires.backend; it starts the backend once a workspace is open. onAgent: starts the backend for an agent that declares native, sessionSources or a configuration with read, and only for one.", "pattern": "^((onLanguage|onRun|onTest|onView|onCommand|onBuildSystem|onVcsRoot|onDebug|onAgent):[a-z0-9.+_-]+|onWorkspaceOpen)$" } }, @@ -352,7 +354,7 @@ } }, "agent": { - "description": "One agent command-line tool. It declares at least one of native, acp and terminal. native and sessionSources 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 and the read and edit of configuration are served by the plugin backend and need the activation event onAgent:.", "type": "object", "additionalProperties": false, "required": [ @@ -444,6 +446,86 @@ "items": { "$ref": "#/$defs/agentSessionSource" } + }, + "configuration": { + "$ref": "#/$defs/agentConfiguration" + } + } + }, + "agentConfiguration": { + "description": "Where the CLI keeps the instructions, skills, MCP servers and hooks Lithe's agent library manages. Core reads and changes them only for a change the user applies; needs agents.configuration. Declares at least one of instructions, skills and files; files and read come together, and edit needs read.", + "type": "object", + "additionalProperties": false, + "anyOf": [ + {"required": ["instructions"]}, + {"required": ["skills"]}, + {"required": ["files"], "properties": {"files": {"minItems": 1}}} + ], + "dependentRequired": { + "read": ["files"], + "edit": ["read"] + }, + "if": {"required": ["files"], "properties": {"files": {"minItems": 1}}}, + "then": {"required": ["read"]}, + "else": {"properties": {"read": false}}, + "properties": { + "instructions": { + "description": "The Markdown file the CLI reads as the user's own instructions. Core reads and writes it.", + "$ref": "#/$defs/agentConfigurationPath" + }, + "skills": { + "description": "The directory of the CLI's user skills, one directory with a SKILL.md per skill. Core reads it and links library skills into it.", + "$ref": "#/$defs/agentConfigurationPath" + }, + "files": { + "description": "Files in the CLI's own format that hold its MCP servers and hooks. Only the backend reads their format.", + "type": "array", + "maxItems": 8, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["id", "roots"], + "properties": { + "id": { + "description": "Unique in the agent.", + "$ref": "#/$defs/agentID" + }, + "roots": { + "$ref": "#/$defs/agentConfigurationRoots" + } + } + } + }, + "read": { + "description": "Backend function that reports what files hold: {agentID, files: [{id, path, exists}]} to a litheAgentConfiguration answer.", + "$ref": "#/$defs/pluginFunctionID" + }, + "edit": { + "description": "Backend function that applies one change to a staged copy of one file: {agentID, file: {id, staging, exists}, change} to a litheAgentConfigurationEdit answer.", + "$ref": "#/$defs/pluginFunctionID" + } + } + }, + "agentConfigurationPath": { + "type": "object", + "additionalProperties": false, + "required": ["roots"], + "properties": { + "roots": { + "$ref": "#/$defs/agentConfigurationRoots" + } + } + }, + "agentConfigurationRoots": { + "description": "Path candidates written like session roots, each with at least one segment after its variable; the first whose variable resolves is the path.", + "type": "array", + "minItems": 1, + "maxItems": 4, + "items": { + "type": "string", + "pattern": "^(?:\\$\\{userHome\\}|\\$\\{env:[A-Z_][A-Z0-9_]{0,63}\\})(?:/(?!\\.\\.?(?:/|$))[^/$\\\\\\u0000]*)*(?![\\s\\S])", + "not": { + "pattern": "^\\$\\{[^}]*\\}/*(?![\\s\\S])" } } }, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 5cb586c9..3f14ce03 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -61,7 +61,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-38 | 受管网络 | 部分完成 | `network/request`:可取消、有界 HTTP(S) | 下载文件、身份验证会话 | [工作流](../guides/plugin-workflows.md) | | API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | -| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录 | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置 | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | ### 计划中的 API @@ -281,7 +281,7 @@ Status meanings: | API-38 | Managed network | Partial | `network/request`: bounded HTTP(S) with cancellation | File downloads and authentication sessions | [Workflows](../guides/plugin-workflows.md) | | API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | -| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | +| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | ### Planned APIs diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 8637a627..4df91753 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](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.*` 命令 | ✅ | 待宿主接入 | [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 | ✅ | 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 | ✅ | 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 a56c93ac..fc674a85 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?}`,每个插件最多 8 个 | -| 能力版本 | `agents` 0;有 Agent 声明 `native` 或 `sessionSources` 时还需要 `backend` 0。见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`,每个插件最多 8 个 | +| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read` 的 `configuration` 时还需要 `backend` 0。`configuration` 和 `agents.configuration` 是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | API 编号 | API-45 | -| 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | -| 激活事件 | 声明了 `native` 或 `sessionSources` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | +| 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.configuration`(有 `configuration`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | +| 激活事件 | 声明了 `native`、`sessionSources` 或带 `read` 的 `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 版本没有 | -| 安装审查 | 每种运行形式列成一条 `agent` 程序,每个会话来源列成一条 `agentSessions` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录会被读取 | +| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有。`configuration` 的 `read` 和 `edit` 是普通插件函数,任何 SDK 版本都能注册,见各 SDK 的 Agent configuration functions 一节 | +| 安装审查 | 每种运行形式列成一条 `agent` 程序,每个会话来源列成一条 `agentSessions` 程序,声明了 `configuration` 的 Agent 列成一条 `agentConfiguration` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录和文件会被读取或修改 | | Lithe 桌面端 | 接入中,尚未声明 `agents` | ### 运行形式 @@ -34,6 +34,18 @@ - 用户逐个 Agent 同意后,Core 才读取 `sessionSources` 声明的目录:只读匹配 `include` 的普通文件,不跟随符号链接;后端的 `scan` 函数把新增的行变成记录,`read` 函数把记录的范围变成标题或消息。 - Core 缓存记录,负责列表、全文搜索和统计;缓存不存正文,可以删除重建。 - `lithe/host/agents/usage` 按天、Agent 或模型汇总用户已开启记录的 Agent 的用量,并带上最近的额度窗口。它只给数字和模型名,不含对话正文、标题、会话 ID 或工作目录,适合做跨 Agent 的统计和额度面板。 +- `agentSessions.calls` 按时间倒序分页列出 `scan` 报告的每一次调用,带所属 Agent 和调用本身(模型、令牌数等),以及 Core 算出的费用、缓存命中率和速度,供用量页的请求列表和详情使用;不含正文。 + +### 资源库:指令、技能、MCP 服务器与 Hooks + +宿主的 Agent 资源库把指令、技能、MCP 服务器和 Hooks 存一份,用户按 Agent 开关后,Core 写进每个 CLI 自己的配置。插件只声明 `configuration`: + +- `instructions`、`skills`:CLI 读取的用户指令文件和用户技能目录。Core 自己读写它们:跟随资源库的 Agent,指令文件整份写成当前启用的那一套指令加上该 Agent 的附加文字;技能以符号链接放进技能目录,资源库外的技能只显示、不改。 +- `files` 和 `read`、`edit`:保存 MCP 服务器和 Hooks 的 CLI 配置文件。只有后端认识它们的格式:`read` 报告文件里有哪些服务器和 Hooks(环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本,并保留文件里其他内容;Core 校验后用原子替换写回,文件在此期间被改动就拒绝。 +- CLI 自己装的内容(比如 CLI 插件带来的 MCP 服务器、Hooks 和技能)标为 `origin: "agent"`,宿主只显示、不改。 +- 宿主按插件声明的 `displayName` 和 `icon` 显示每个 Agent,不按名字特殊处理。 + +所有改动都只能由用户的操作发起;Core 只读写声明的路径;插件没有获得 `agents.configuration` 授权时,它的 Agent 以 `mayConfigure: false` 列出,Core 什么都不读、不改。命令见 Rust Core API 的 `agentLibrary.*`。 ### 契约章节 @@ -41,19 +53,20 @@ | --- | --- | | [Agents](../../contract/v1/README.md#agents) | 总览和清单示例 | | [Agent declarations](../../contract/v1/README.md#agent-declarations) | 字段、限制、安装审查列出的程序 | -| [Agent permissions and activation](../../contract/v1/README.md#agent-permissions-and-activation) | 四个权限、`onAgent:`、拒绝码 | +| [Agent permissions and activation](../../contract/v1/README.md#agent-permissions-and-activation) | 五个权限、`onAgent:`、拒绝码 | | [Host commands](../../contract/v1/README.md#host-commands) | 宿主调用的 `agents.*` 命令和事件队列 | | [Native sessions](../../contract/v1/README.md#native-sessions) | 启动流程、通知、宿主方法、会话事件 | | [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | +| [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储和命令、`read` 与 `edit` 函数、限制和拒绝码 | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | 日志只记 ID 和元数据,不读凭据文件 | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | 不运行 ACP 客户端,只在可信本地工作区运行 | -| [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*` 与 `agentSessions.*` 命令(Rust Core API 文档) | +| [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*`、`agentSessions.*` 与 `agentLibrary.*` 命令(Rust Core API 文档) | ### 示例与用例 | 文件 | 内容 | | --- | --- | -| [`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/native-session.json`](../../contract/v1/fixtures/agents/native-session.json) | 原生会话通知和每个会话的处理器依次收到的调用、启动或提示失败时报告的 `turnEnded`、`agents` 宿主方法的请求;四个 SDK 的测试都用它 | @@ -66,14 +79,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?}`, at most 8 per plugin | -| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native` or `sessionSources`. See [versions](../capabilities-and-versions.md#capability-versions-requires) | +| Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`, at most 8 per plugin | +| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read`. `configuration` and `agents.configuration` were added within `agents` 0; a Core that does not know them refuses such a manifest. 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.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` or `sessionSources` needs `onAgent:`; other agents may not have one | +| Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.configuration` (with `configuration`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | +| Activation events | An agent that declares `native`, `sessionSources` or a `configuration` with `read` needs `onAgent:`; other agents may not have one | | 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 | -| Install review | Each form is an `agent` program and each session source an `agentSessions` program, so the user sees how the CLI will run and which directories will be read before installing | +| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not. The `read` and `edit` of `configuration` are ordinary plugin functions any SDK version registers; see each SDK's Agent configuration functions section | +| Install review | Each form is an `agent` program, each session source an `agentSessions` program, and each agent that declares `configuration` an `agentConfiguration` program, so the user sees how the CLI will run and which directories and files will be read or changed before installing | | Lithe desktop | Integration in progress; does not declare `agents` yet | ### Forms @@ -92,6 +105,18 @@ The tool always comes from the plugin's `requiresTools`: the host discovers it a - Core reads the directories `sessionSources` declares only after the user consents for that agent. It reads only regular files that match `include` and does not follow symbolic links. The backend's `scan` function turns new lines into records, and its `read` function turns recorded ranges into titles or messages. - Core caches the records and answers lists, full-text search, and statistics. The cache stores no message text and can be deleted and rebuilt. - `lithe/host/agents/usage` sums the usage of the agents whose records the user enabled, by day, agent, or model, with the latest quota windows. It carries only numbers and model names, never conversation text, titles, session IDs, or working directories, so it suits cross-agent statistics and quota panels. +- `agentSessions.calls` pages through every call `scan` reported, most recent first, with its agent and the call itself (model, tokens and so on), plus the cost, cache hit rate and speed Core derives, for the request list and details of a usage page. It carries no message text. + +### The library: instructions, skills, MCP servers and hooks + +The host's agent library keeps one copy of instructions, skills, MCP servers and hooks; once the user turns them on per agent, Core writes them into each CLI's own configuration. The plugin only declares `configuration`: + +- `instructions` and `skills`: the user instruction file and the user skills directory the CLI reads. Core reads and writes them itself: for an agent that follows the library it writes the whole instruction file as the active instruction set followed by that agent's extra text, and it puts skills into the skills directory as symbolic links. Skills outside the library are shown and never changed. +- `files` with `read` and `edit`: the CLI configuration files that hold MCP servers and hooks. Only the backend knows their format. `read` reports the servers and hooks a file holds (names only for environment variables and headers), and `edit` changes only the staged copy Core gives it and keeps everything else in the file. Core checks the copy and replaces the file atomically, refusing when the file changed meanwhile. +- What the CLI installed itself, such as the MCP servers, hooks and skills a CLI plugin brings, has `origin: "agent"`; the host shows it and never changes it. +- The host shows each agent by the `displayName` and `icon` its plugin declares and never special-cases agents by name. + +Every change comes only from a user action. Core reads and writes only the declared paths. An agent whose plugin is not granted `agents.configuration` is listed with `mayConfigure: false`, and Core reads and changes nothing of it. The commands are the `agentLibrary.*` commands of the Rust Core API. ### Contract sections @@ -99,19 +124,20 @@ The tool always comes from the plugin's `requiresTools`: the host discovers it a | --- | --- | | [Agents](../../contract/v1/README.md#agents) | Overview and manifest example | | [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 four permissions, `onAgent:`, and refusal codes | +| [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 | | [Native sessions](../../contract/v1/README.md#native-sessions) | Launch flow, notifications, host methods, session events | | [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | +| [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage and commands, the `read` and `edit` functions, limits, and refusal codes | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | Logs carry only IDs and metadata; no credential file is read | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | No ACP client; trusted local workspaces only | -| [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*` and `agentSessions.*` commands (Rust Core API document) | +| [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*`, `agentSessions.*`, and `agentLibrary.*` commands (Rust Core API document) | ### Examples and cases | 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, and one session source | +| [`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/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/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 | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index e27e62de..179c0f53 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):原生会话可以报告用户可改的会话设置,用户在宿主里切换模型、推理等级或模式。会话事件新增 `configOptions`(对应 ACP 的 session config options,ACP 的 `thought_level` 写作 `thoughtLevel`):最多 16 个 `{id, name, description?, category?, currentValue, options}`,`category` 为 `model`、`thoughtLevel`、`mode` 之一,`options` 为 1–128 个 `{value, name, description?}`;设置 ID 唯一、同一设置的值唯一、`currentValue` 必须在 `options` 里,`thoughtLevel` 的值从低到高排列;每次报告替换上一次,空列表撤回全部设置;这个事件不属于任何回合,随时可以报告。新增宿主命令 `agents.setConfigOption {session, option, value}` → `{}`:只接受用户发起的请求(`agents.userActionRequired`),回合进行中也可以调用;设置或值不在后端最近一次报告里时分别拒绝为新错误码 `agents.unknownConfigOption`、`agents.unknownConfigValue`,后端没有接收时为 `agents.backendUnavailable`。`litheFunctions` 0 内新增通知 `agents/didSetConfigOption {session, option, value}`(`agents.native`),后端在 CLI 能接受时应用,再报告一次 `configOptions`;CLI 拒绝时报告未改变的设置和一条 `notice`。fixture `agents/native-session.json` 补充这条通知和一个 `configOptions` 报告,四种官方 SDK 新增会话处理器方法(Rust `set_config_option`、Go `SetConfigOption`、Node `setConfigOption`、Java `setConfigOption`,默认什么都不做),Go SDK 的宿主通知改为统一走 Agent 通知分发。旧 Core 以未知事件拒绝 `configOptions` 报告(`-32602`),插件在旧宿主上应忽略这次拒绝、照常运行。没有新增能力版本、协议版本或宿主方法。 +- [#222](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/222)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):Agent 资源库与逐条调用列表。清单 `agents[]` 新增可选 `configuration {instructions?, skills?, files?, read?, edit?}`:`instructions`、`skills` 是 CLI 的用户指令文件和用户技能目录,`files` 是最多 8 个保存 MCP 服务器与 Hooks 的 CLI 配置文件(`{id, roots}`),路径写法同会话来源的根目录(每处 1–4 个候选,变量后至少一段);三者至少声明一个,声明了 `files` 就必须有后端函数 `read`,没有 `files` 时不能有 `read`,`edit` 需要 `read`。新增权限 `agents.configuration`(有 `configuration` 时必须声明,没有时声明即拒绝),带 `read` 的 Agent 需要后端和 `onAgent:`。安装审查新增 `agentConfiguration` 程序,列出全部路径和是否可编辑;Agent 目录条目新增 `configuration {instructions, skills, files, editable}` 和 `mayConfigure`,`sessionRootVariables` 也包括配置路径用到的变量。`read`、`edit` 是普通插件函数:`read` 回答 `litheAgentConfiguration` 快照(MCP 服务器、Hooks、Hook 事件、CLI 自带的技能,以及每类改动写进哪个文件;环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本、保留文件里其他内容并回答 `litheAgentConfigurationEdit`,Core 校验后原子替换,文件在此期间被改动就拒绝。Core 新增宿主命令 `agentLibrary.configure`、`read`、`save`、`apply`、`importSkill`、`removeSkill`:资源库(MCP 服务器、Hooks、指令集和技能)存放在平台应用数据目录,`read` 带修订号,`save` 只在修订号未变时替换,`apply` 把用户选中的一项改动写进一个 Agent(指令文件整份写成当前指令集加该 Agent 的附加文字,技能用符号链接),`save`、`apply`、`importSkill`、`removeSkill` 只接受用户发起的请求;新增 `agentLibrary.*` 错误码(逐个见契约 Agent configuration 一节)和日志事件 `agent.library.*`。同一 PR 里新增宿主命令 `agentSessions.calls`:按时间倒序分页列出 `scan` 报告的调用,可按 Agent、会话、时间、模型和成败筛选,每行带 Core 算出的费用、缓存命中率和速度,超出范围的翻页拒绝为 `agentSessions.invalidPage`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `configuration` 或 `agents.configuration` 的清单,也不回答 `agentLibrary.*` 和 `agentSessions.calls`。fixture `agents/agents.plugin.json` 补充配置声明,`manifest/invalid-manifests.json` 新增 10 个拒绝用例,四种官方 SDK 的说明补充配置函数。同一 PR 回填 #220 的合入日期。没有新增宿主方法、通知或能力版本。 - [#207](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/207)(待合入),[@1lck](https://github.com/1lck),`debugAdapters` 0(API-30)增加可选 `launch.executableSetting`。命令型适配器可读取用户全局文件路径,留空沿用原命令查找;旧宿主会拒绝包含该声明的清单。无新增方法、通知或能力版本。 @@ -224,7 +224,7 @@ | API-40 | `workspace/getHostPaths` | 0 | 待合入 | [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151) | | API-45 | `agents/write` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/report` | 0(事件新增 `configOptions`) | 待合入 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | +| API-45 | `agents/report` | 0(事件新增 `configOptions`) | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | | API-45 | `agents/usage` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/usage` | 0(回答新增 `speeds`) | 2026-11-28 | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | | API-45 | `agents/didStart`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | @@ -232,7 +232,7 @@ | API-45 | `agents/didPrompt`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didCancel`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didDecidePermission`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/didSetConfigOption`(通知) | 0 | 待合入 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | +| API-45 | `agents/didSetConfigOption`(通知) | 0 | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | | API-45 | `agents/didExit`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | — | `keymapImport/listInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | — | `keymapImport/readChunk` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -243,6 +243,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 | 原生会话可以报告用户可改的会话设置,用户在宿主里切换模型、推理等级或模式。会话事件新增 `configOptions`(对应 ACP 的 session config options,ACP 的 `thought_level` 写作 `thoughtLevel`):最多 16 个 `{id, name, description?, category?, currentValue, options}`,`category` 为 `model`、`thoughtLevel`、`mode` 之一,`options` 为 1–128 个 `{value, name, description?}`;设置 ID 唯一、同一设置的值唯一、`currentValue` 必须在 `options` 里,`thoughtLevel` 的值从低到高排列;每次报告替换上一次,空列表撤回全部设置;这个事件不属于任何回合,随时可以报告。新增宿主命令 `agents.setConfigOption {session, option, value}` → `{}`:只接受用户发起的请求(`agents.userActionRequired`),回合进行中也可以调用;设置或值不在后端最近一次报告里时分别拒绝为新错误码 `agents.unknownConfigOption`、`agents.unknownConfigValue`,后端没有接收时为 `agents.backendUnavailable`。`litheFunctions` 0 内新增通知 `agents/didSetConfigOption {session, option, value}`(`agents.native`),后端在 CLI 能接受时应用,再报告一次 `configOptions`;CLI 拒绝时报告未改变的设置和一条 `notice`。fixture `agents/native-session.json` 补充这条通知和一个 `configOptions` 报告,四种官方 SDK 新增会话处理器方法(Rust `set_config_option`、Go `SetConfigOption`、Node `setConfigOption`、Java `setConfigOption`,默认什么都不做),Go SDK 的宿主通知改为统一走 Agent 通知分发。旧 Core 以未知事件拒绝 `configOptions` 报告(`-32602`),插件在旧宿主上应忽略这次拒绝、照常运行。没有新增能力版本、协议版本或宿主方法。 | | [#219](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/219) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 | 宿主命令 `agentSessions.list` 新增 `cwdUnder`(最多 64 个目录,会话的 `cwd` 是其中之一或在它下面才保留,末尾的 `/`、`\` 不影响匹配,没有 `cwd` 的会话不在任何目录下)、`order`(`updated` 最近活动在前,默认;`started` 最近开始在前)和 `counts`;`counts: true` 时回答多出 `total`(不受 `offset`、`limit` 影响)、`groups`(每个目录 `{cwd?, count, updatedAtMs?}`,最近活动在前,最多 500 组)和 `groupsTruncated`。每个会话多出 `messageCount`(插件后端在会话自己文件里报的可搜索片段数,子代理文件不计)、`lastMessageRange`(最后一个片段的范围,用 `agentSessions.read` 读出该条消息,Core 不缓存正文)、`subagentCount`(调用里不同 `threadID` 的个数)和 `model`(最近一次主线程调用的 `model`,没有时用 `requestedModel`;全部调用都带 `threadID` 时取最近一次调用的)。旧 Core 以未知字段拒绝三个新参数,也不回答四个新字段,宿主应显示不带它们的列表。没有新增宿主方法、通知、错误码或能力版本。 | | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45、API-23 | `agents` 0 / `commandInstallers` 0 | `agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。契约同时写明 `scan` 的一个既有行为:之后的扫描可以用同一个 `key` 再报一次调用(`range` 在它自己的块里),后报的替换先报的,所以到一轮结束才知道计时的后端可以那时补上 `firstTokenMs` 和 `durationMs`;自 #199 起的 Core 都这样处理。同一 PR 里,会话记录的读取支持分页:`agentSessions.list` 可按 `sessionID` 查找、每个会话带 `readBytes`,`agentSessions.read` 回答 `end`(下一页的起点);读取范围在行中间结束时,Core 只把完整的行交给插件后端的 `read`,并说明后端 `messages` 回答整体不能超过 1 MiB 的函数结果上限。旧 Core 不认 `sessionID`、不回答 `readBytes` 和 `end`,并可能把被截断的行交给后端,后端应跳过不是完整 JSON 的行。同一 PR 里,`commandInstallers` 0 内补充(API-23):[命令安装](../contract/v1/README.md#command-installers)也服务 Agent 的命令行工具:安装声明的 `commands` 可以由本插件某个 Agent 的 `tool` 所指工具定义的 `commands` 提供,`plugins.commandInstallers.requirements` 在 `systemCommand` 启动之后按声明顺序列出 `kind: "agent"`、`id` 为 Agent ID 的使用方;宿主把插件的受管命令目录和记录的默认目录也用于解析 Agent 工具的 `kind: "command"` 候选(先查 `PATH`)。旧 Core 以 `plugin.manifest.invalid`(`commandInstallers[].commands[]`)拒绝只有 Agent 工具用到的安装声明;需要它的插件同时要求 `agents` 0。同一 PR 里,[IDE 连接](../../../rust/contracts/ide-api/v1.md#agent-sessions)新增两个只读 MCP 工具 `lithe_sessions_search`、`lithe_sessions_read`(API-45),让 MCP 客户端搜索和分页读取用户同意读取的 Agent 会话;宿主只在用户打开 IDE 连接、打开“允许 MCP 客户端搜索本地会话”并同意读取至少一个 Agent 的会话时声明它们,没有声明工具清单的宿主不提供这两个工具。它们是 IDE 连接的工具,不是插件宿主方法。没有新增宿主方法、通知或错误码。 | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index 777c5c30..96ffb9c9 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -639,6 +639,29 @@ usage totals. `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. +### Agent configuration functions + +An agent that declares +[`configuration`](../../contract/v1/README.md#agent-configuration) names a +`read` function and, when the library may change its files, an `edit` +function. Both are ordinary plugin functions: register them with +`backend.Function(id, handler)` like any other; this SDK has no separate interface for them, so +every SDK version can serve them. Core calls them only for the agent library +and gives each call 10 seconds. + +- `read` receives `{agentID, files: [{id, path, exists}]}` and answers the + `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and + self-installed skills the files hold, and which declared file takes the + changes of each category. Report environment variable and header names, + never their values. +- `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes + only the file at `staging` in the CLI's own format, keeps everything else + the file holds, and answers + `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks + the staged copy and moves it into place; the backend never writes the real + file. +- Both need `agents.configuration`, and read only the paths Core passes. + ## Testing Run these from this directory: diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 8052d2b8..f58262df 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -607,6 +607,29 @@ backend.onAgentSessions((start, session) -> new AgentSession() { `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. +### Agent configuration functions + +An agent that declares +[`configuration`](../../contract/v1/README.md#agent-configuration) names a +`read` function and, when the library may change its files, an `edit` +function. Both are ordinary plugin functions: register them with +`backend.function(id, handler)` like any other; this SDK has no separate interface for them, so +every SDK version can serve them. Core calls them only for the agent library +and gives each call 10 seconds. + +- `read` receives `{agentID, files: [{id, path, exists}]}` and answers the + `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and + self-installed skills the files hold, and which declared file takes the + changes of each category. Report environment variable and header names, + never their values. +- `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes + only the file at `staging` in the CLI's own format, keeps everything else + the file holds, and answers + `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks + the staged copy and moves it into place; the backend never writes the real + file. +- Both need `agents.configuration`, and read only the paths Core passes. + ## 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 629667dc..36f3f9c1 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -621,6 +621,29 @@ ID, and `usage(params)` for usage totals. `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. +### Agent configuration functions + +An agent that declares +[`configuration`](../../contract/v1/README.md#agent-configuration) names a +`read` function and, when the library may change its files, an `edit` +function. Both are ordinary plugin functions: register them with +`backend.function(id, handler)` like any other; this SDK has no separate interface for them, so +every SDK version can serve them. Core calls them only for the agent library +and gives each call 10 seconds. + +- `read` receives `{agentID, files: [{id, path, exists}]}` and answers the + `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and + self-installed skills the files hold, and which declared file takes the + changes of each category. Report environment variable and header names, + never their values. +- `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes + only the file at `staging` in the CLI's own format, keeps everything else + the file holds, and answers + `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks + the staged copy and moves it into place; the backend never writes the real + file. +- Both need `agents.configuration`, and read only the paths Core passes. + ## 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 bf1dd464..6b33c2c8 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -731,6 +731,29 @@ for any session ID, and `usage(params)` for usage totals. `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. +### Agent configuration functions + +An agent that declares +[`configuration`](../../contract/v1/README.md#agent-configuration) names a +`read` function and, when the library may change its files, an `edit` +function. Both are ordinary plugin functions: register them with +`backend.function(id, handler)` like any other; this SDK has no separate interface for them, so +every SDK version can serve them. Core calls them only for the agent library +and gives each call 10 seconds. + +- `read` receives `{agentID, files: [{id, path, exists}]}` and answers the + `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and + self-installed skills the files hold, and which declared file takes the + changes of each category. Report environment variable and header names, + never their values. +- `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes + only the file at `staging` in the CLI's own format, keeps everything else + the file holds, and answers + `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks + the staged copy and moves it into place; the backend never writes the real + file. +- Both need `agents.configuration`, and read only the paths Core passes. + ## Testing Run these from the root of this repository: From 23331dc9212eecd16ef9ae9c7414db6822af513f Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 29 Nov 2026 00:32:24 +0800 Subject: [PATCH 3/4] =?UTF-8?q?docs(plugins):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E9=87=8C=E6=9C=AC=20PR=20=E7=9A=84=E7=BC=96?= =?UTF-8?q?=E5=8F=B7=E6=94=B9=E4=B8=BA=20#223?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 179c0f53..51cf378c 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#222](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/222)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):Agent 资源库与逐条调用列表。清单 `agents[]` 新增可选 `configuration {instructions?, skills?, files?, read?, edit?}`:`instructions`、`skills` 是 CLI 的用户指令文件和用户技能目录,`files` 是最多 8 个保存 MCP 服务器与 Hooks 的 CLI 配置文件(`{id, roots}`),路径写法同会话来源的根目录(每处 1–4 个候选,变量后至少一段);三者至少声明一个,声明了 `files` 就必须有后端函数 `read`,没有 `files` 时不能有 `read`,`edit` 需要 `read`。新增权限 `agents.configuration`(有 `configuration` 时必须声明,没有时声明即拒绝),带 `read` 的 Agent 需要后端和 `onAgent:`。安装审查新增 `agentConfiguration` 程序,列出全部路径和是否可编辑;Agent 目录条目新增 `configuration {instructions, skills, files, editable}` 和 `mayConfigure`,`sessionRootVariables` 也包括配置路径用到的变量。`read`、`edit` 是普通插件函数:`read` 回答 `litheAgentConfiguration` 快照(MCP 服务器、Hooks、Hook 事件、CLI 自带的技能,以及每类改动写进哪个文件;环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本、保留文件里其他内容并回答 `litheAgentConfigurationEdit`,Core 校验后原子替换,文件在此期间被改动就拒绝。Core 新增宿主命令 `agentLibrary.configure`、`read`、`save`、`apply`、`importSkill`、`removeSkill`:资源库(MCP 服务器、Hooks、指令集和技能)存放在平台应用数据目录,`read` 带修订号,`save` 只在修订号未变时替换,`apply` 把用户选中的一项改动写进一个 Agent(指令文件整份写成当前指令集加该 Agent 的附加文字,技能用符号链接),`save`、`apply`、`importSkill`、`removeSkill` 只接受用户发起的请求;新增 `agentLibrary.*` 错误码(逐个见契约 Agent configuration 一节)和日志事件 `agent.library.*`。同一 PR 里新增宿主命令 `agentSessions.calls`:按时间倒序分页列出 `scan` 报告的调用,可按 Agent、会话、时间、模型和成败筛选,每行带 Core 算出的费用、缓存命中率和速度,超出范围的翻页拒绝为 `agentSessions.invalidPage`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `configuration` 或 `agents.configuration` 的清单,也不回答 `agentLibrary.*` 和 `agentSessions.calls`。fixture `agents/agents.plugin.json` 补充配置声明,`manifest/invalid-manifests.json` 新增 10 个拒绝用例,四种官方 SDK 的说明补充配置函数。同一 PR 回填 #220 的合入日期。没有新增宿主方法、通知或能力版本。 +- [#223](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/223)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):Agent 资源库与逐条调用列表。清单 `agents[]` 新增可选 `configuration {instructions?, skills?, files?, read?, edit?}`:`instructions`、`skills` 是 CLI 的用户指令文件和用户技能目录,`files` 是最多 8 个保存 MCP 服务器与 Hooks 的 CLI 配置文件(`{id, roots}`),路径写法同会话来源的根目录(每处 1–4 个候选,变量后至少一段);三者至少声明一个,声明了 `files` 就必须有后端函数 `read`,没有 `files` 时不能有 `read`,`edit` 需要 `read`。新增权限 `agents.configuration`(有 `configuration` 时必须声明,没有时声明即拒绝),带 `read` 的 Agent 需要后端和 `onAgent:`。安装审查新增 `agentConfiguration` 程序,列出全部路径和是否可编辑;Agent 目录条目新增 `configuration {instructions, skills, files, editable}` 和 `mayConfigure`,`sessionRootVariables` 也包括配置路径用到的变量。`read`、`edit` 是普通插件函数:`read` 回答 `litheAgentConfiguration` 快照(MCP 服务器、Hooks、Hook 事件、CLI 自带的技能,以及每类改动写进哪个文件;环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本、保留文件里其他内容并回答 `litheAgentConfigurationEdit`,Core 校验后原子替换,文件在此期间被改动就拒绝。Core 新增宿主命令 `agentLibrary.configure`、`read`、`save`、`apply`、`importSkill`、`removeSkill`:资源库(MCP 服务器、Hooks、指令集和技能)存放在平台应用数据目录,`read` 带修订号,`save` 只在修订号未变时替换,`apply` 把用户选中的一项改动写进一个 Agent(指令文件整份写成当前指令集加该 Agent 的附加文字,技能用符号链接),`save`、`apply`、`importSkill`、`removeSkill` 只接受用户发起的请求;新增 `agentLibrary.*` 错误码(逐个见契约 Agent configuration 一节)和日志事件 `agent.library.*`。同一 PR 里新增宿主命令 `agentSessions.calls`:按时间倒序分页列出 `scan` 报告的调用,可按 Agent、会话、时间、模型和成败筛选,每行带 Core 算出的费用、缓存命中率和速度,超出范围的翻页拒绝为 `agentSessions.invalidPage`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `configuration` 或 `agents.configuration` 的清单,也不回答 `agentLibrary.*` 和 `agentSessions.calls`。fixture `agents/agents.plugin.json` 补充配置声明,`manifest/invalid-manifests.json` 新增 10 个拒绝用例,四种官方 SDK 的说明补充配置函数。同一 PR 回填 #220 的合入日期。没有新增宿主方法、通知或能力版本。 - [#207](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/207)(待合入),[@1lck](https://github.com/1lck),`debugAdapters` 0(API-30)增加可选 `launch.executableSetting`。命令型适配器可读取用户全局文件路径,留空沿用原命令查找;旧宿主会拒绝包含该声明的清单。无新增方法、通知或能力版本。 From ae12ce04e7f27305b74ebac4f5fd4579a02c819d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 29 Nov 2026 00:38:36 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(agents):=20hookEvents=20=E4=B8=8A?= =?UTF-8?q?=E9=99=90=E6=94=B9=E4=B8=BA=2064=EF=BC=88Claude=20Code=202.1=20?= =?UTF-8?q?=E6=9C=89=2034=20=E4=B8=AA=E4=BA=8B=E4=BB=B6=EF=BC=89=EF=BC=8CS?= =?UTF-8?q?DK=20=E8=AF=B4=E6=98=8E=E5=86=99=E5=87=86=20read=20=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E8=AF=BB=20CLI=20=E8=87=AA=E5=B7=B1=E8=A3=85=E7=9A=84?= =?UTF-8?q?=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/crates/agent-runtime/src/library.rs | 2 +- shared/plugins/contract/v1/README.md | 2 +- shared/plugins/sdk/go/README.md | 6 +++++- shared/plugins/sdk/java/README.md | 6 +++++- shared/plugins/sdk/node/README.md | 6 +++++- shared/plugins/sdk/rust/README.md | 6 +++++- 6 files changed, 22 insertions(+), 6 deletions(-) diff --git a/rust/crates/agent-runtime/src/library.rs b/rust/crates/agent-runtime/src/library.rs index 911f4c75..f6f47665 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -63,7 +63,7 @@ const FUNCTION_TIMEOUT: Duration = Duration::from_secs(10); const MAX_SERVERS: usize = 256; const MAX_HOOKS: usize = 256; -const MAX_HOOK_EVENTS: usize = 32; +const MAX_HOOK_EVENTS: usize = 64; const MAX_EVENT_BYTES: usize = 64; const MAX_SKILLS: usize = 512; const MAX_NAME_CHARS: usize = 128; diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 7abec129..8af93cf0 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4329,7 +4329,7 @@ for the file, with the same extension; `exists` says whether anything is at `provider` (1–128 characters) names and Lithe only shows; - `hooks`: at most 256 `{event, matcher?, command, timeoutSeconds?, origin, provider?}`; -- `hookEvents`: at most 32 distinct events the CLI runs hooks for; empty +- `hookEvents`: at most 64 distinct events the CLI runs hooks for; empty when the plugin does not say, and then every event is allowed; - `skills`: at most 512 `{name, description?, provider?}`, skills the CLI installed itself outside the skills directory, `description` at most 1024 diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index 96ffb9c9..7bcecc85 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -660,7 +660,11 @@ and gives each call 10 seconds. `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file. -- Both need `agents.configuration`, and read only the paths Core passes. +- Both need `agents.configuration`. `read` reads the declared files at the + paths Core passes, which may be staged copies, and may also read what the + CLI installed itself, such as its plugins, to report it with + `origin: "agent"`; it never opens credential files. `edit` writes only + the file at `staging`. ## Testing diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index f58262df..de7ec881 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -628,7 +628,11 @@ and gives each call 10 seconds. `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file. -- Both need `agents.configuration`, and read only the paths Core passes. +- Both need `agents.configuration`. `read` reads the declared files at the + paths Core passes, which may be staged copies, and may also read what the + CLI installed itself, such as its plugins, to report it with + `origin: "agent"`; it never opens credential files. `edit` writes only + the file at `staging`. ## Testing diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 36f3f9c1..79e14de8 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -642,7 +642,11 @@ and gives each call 10 seconds. `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file. -- Both need `agents.configuration`, and read only the paths Core passes. +- Both need `agents.configuration`. `read` reads the declared files at the + paths Core passes, which may be staged copies, and may also read what the + CLI installed itself, such as its plugins, to report it with + `origin: "agent"`; it never opens credential files. `edit` writes only + the file at `staging`. ## Testing diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 6b33c2c8..986f1e27 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -752,7 +752,11 @@ and gives each call 10 seconds. `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file. -- Both need `agents.configuration`, and read only the paths Core passes. +- Both need `agents.configuration`. `read` reads the declared files at the + paths Core passes, which may be staged copies, and may also read what the + CLI installed itself, such as its plugins, to report it with + `origin: "agent"`; it never opens credential files. `edit` writes only + the file at `staging`. ## Testing