From 85425cc8bd2e5ab789660b0cb7b4c62ba7965ffc Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 06:30:00 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat(agents):=20usage=20=E4=B8=8E=20stats?= =?UTF-8?q?=20=E5=9B=9E=E7=AD=94=E5=B8=A6=E6=8C=89=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E6=8E=92=E5=88=97=E7=9A=84=E8=BE=93=E5=87=BA=E9=80=9F=E5=BA=A6?= =?UTF-8?q?=E4=B8=AD=E4=BD=8D=E6=95=B0=20speeds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 速度排行改成逐条累加的 SpeedRanker,只保留每个模型的速度值,大量历史不必一次读进内存。lithe/host/agents/usage 和 agentSessions.stats 都返回 speeds,契约、更新记录与四种 SDK 的说明同步。 --- rust/crates/agent-runtime/src/records.rs | 26 +++++--- rust/crates/agent-runtime/src/tests.rs | 8 ++- rust/crates/agent-sessions/src/stats.rs | 60 ++++++++++++------- shared/plugins/contract/v1/README.md | 14 ++++- .../plugins/reference/protocol-changelog.md | 3 + shared/plugins/sdk/go/README.md | 2 +- shared/plugins/sdk/go/lithe/agents.go | 2 +- shared/plugins/sdk/java/README.md | 2 +- .../io/github/litheidea/plugin/sdk/Host.java | 2 +- shared/plugins/sdk/node/README.md | 2 +- shared/plugins/sdk/node/src/host.mjs | 2 +- shared/plugins/sdk/rust/README.md | 2 +- .../plugins/sdk/rust/plugin-sdk/src/agents.rs | 2 +- 13 files changed, 87 insertions(+), 40 deletions(-) diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index b095b319..8d843e6d 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -19,7 +19,7 @@ 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, Summarizer}; +use lithe_agent_sessions::stats::{GroupBy, SpeedRanker, Summarizer}; use lithe_agent_sessions::{ discover, ByteRange, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, SessionParser, SessionSource, SessionStore, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, @@ -573,8 +573,8 @@ impl Records { "Group by day, agent, model, session or cwd.", ) })?; - let summaries = match allowed_agents(runtime, request.agents) { - None => json!([]), + let (summaries, speeds) = match allowed_agents(runtime, request.agents) { + None => (json!([]), json!([])), Some(agents) => { let filter = CallFilter { agents, @@ -589,28 +589,37 @@ impl Records { }; Ok(json!({ "summaries": summaries, + "speeds": speeds, "rateLimits": self.rate_limit_entries(runtime), })) } + /// 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( &self, store: &SessionStore, filter: &CallFilter, group_by: GroupBy, - ) -> Result { + ) -> Result<(Value, Value), CoreError> { let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); let mut summarizer = Summarizer::new(group_by, prices.as_ref()); + let mut speeds = SpeedRanker::default(); store.for_each_call(filter, |entry| { summarizer.add(&entry); + speeds.add(&entry.call); Ok(()) })?; - Ok(serde_json::to_value(summarizer.finish()).unwrap_or_else(|_| json!([]))) + Ok(( + serde_json::to_value(summarizer.finish()).unwrap_or_else(|_| json!([])), + serde_json::to_value(speeds.finish()).unwrap_or_else(|_| json!([])), + )) } /// Answers `lithe/host/agents/usage` for a plugin granted /// `agents.usage.read`: totals of the readable agents, grouped by day, - /// agent or model, and their rate limits. It carries no conversation text, + /// agent or model, the models' median output speeds, and the agents' + /// rate limits. It carries no conversation text, /// titles, session IDs or directories. Runs with the asking backend's /// session lock held, so it never waits for the cache. pub fn usage(&self, runtime: &Runtime, params: &Value) -> Result { @@ -645,8 +654,8 @@ impl Records { .iter() .map(CatalogAgent::record_key) .collect(); - let summaries = if agents.is_empty() { - json!([]) + let (summaries, speeds) = if agents.is_empty() { + (json!([]), json!([])) } else { let reader = match self.reader.try_lock() { Ok(reader) => reader, @@ -678,6 +687,7 @@ impl Records { "sinceMs": since_ms, "untilMs": until_ms, "summaries": summaries, + "speeds": speeds, "rateLimits": self.rate_limit_entries(runtime), })) } diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index b4b02ba7..eb8cb284 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -174,6 +174,8 @@ fn scan(params: &Value) -> Value { "startedAtMs": record["at"], "model": record["model"], "tokens": { "input": record["input"], "output": record["output"] }, + "firstTokenMs": record["first"], + "durationMs": record["duration"], "range": range, })), Some("limits") => { @@ -1222,7 +1224,7 @@ fn write_session_file(harness: &Harness, now: i64) -> PathBuf { let lines = [ json!({ "type": "session", "id": "s1", "cwd": "/work/project", "at": now }), json!({ "type": "user", "session": "s1", "text": "hello from the user", "at": now }), - json!({ "type": "call", "session": "s1", "key": "c1", "model": "sample-model", "input": 100, "output": 20, "at": now }), + json!({ "type": "call", "session": "s1", "key": "c1", "model": "sample-model", "input": 100, "output": 300, "first": 500, "duration": 2500, "at": now }), json!({ "type": "limits", "at": now, "used": 40.0 }), ]; let text: String = lines.iter().map(|line| format!("{line}\n")).collect(); @@ -1287,6 +1289,9 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() { let stats = harness.run("agentSessions.stats", json!({ "groupBy": "model" })); assert_eq!(stats["summaries"][0]["calls"], 1, "{stats}"); assert_eq!(stats["summaries"][0]["tokens"]["input"], 100, "{stats}"); + // 300 output tokens in the 2 seconds after the first token. + let speed = json!([{ "model": "sample-model", "calls": 1, "medianTokensPerSecond": 150.0, "lowerBound": false }]); + assert_eq!(stats["speeds"], speed, "{stats}"); assert_eq!( stats["rateLimits"][0]["windows"][0]["usedPercent"], 40.0, "{stats}" @@ -1299,6 +1304,7 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() { .answer(AGENTS_USAGE, json!({ "groupBy": "agent" })) .expect("usage"); assert_eq!(usage["summaries"][0]["calls"], 1, "{usage}"); + assert_eq!(usage["speeds"], speed, "{usage}"); let text = usage.to_string(); for private in ["\"s1\"", "/work/project", "hello", "s1.jsonl"] { assert!(!text.contains(private), "usage carries {private}: {text}"); diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs index da658894..615dcc6d 100644 --- a/rust/crates/agent-sessions/src/stats.rs +++ b/rust/crates/agent-sessions/src/stats.rs @@ -344,34 +344,54 @@ pub struct SpeedRank { /// Ranks models by median speed, fastest first, over calls with at least /// [`MIN_RANKED_OUTPUT_TOKENS`] output tokens and a speed. pub fn rank_speed<'c>(calls: impl IntoIterator) -> Vec { - let mut by_model: BTreeMap<&str, (Vec, bool)> = BTreeMap::new(); + let mut ranker = SpeedRanker::default(); for call in calls { + ranker.add(call); + } + ranker.finish() +} + +/// Adds calls into a [`rank_speed`] ranking one at a time, keeping only each +/// model's speeds, so a large history never has to be in memory at once. +#[derive(Debug, Default)] +pub struct SpeedRanker { + by_model: BTreeMap, bool)>, +} + +impl SpeedRanker { + /// Adds a call; one too short or without a speed is left out. + pub fn add(&mut self, call: &CallRecord) { if call.tokens.output.unwrap_or(0) < MIN_RANKED_OUTPUT_TOKENS { - continue; + return; } let (Some(model), Some(speed)) = (model_name(call), call_speed(call)) else { - continue; + return; }; - let (speeds, lower_bound) = by_model.entry(model).or_default(); + let (speeds, lower_bound) = self.by_model.entry(model.to_string()).or_default(); speeds.push(speed.tokens_per_second()); *lower_bound |= matches!(speed, Speed::AtLeast(_)); } - let mut ranks: Vec = by_model - .into_iter() - .map(|(model, (mut speeds, lower_bound))| SpeedRank { - model: model.to_string(), - calls: speeds.len() as u64, - median_tokens_per_second: median(&mut speeds), - lower_bound, - }) - .collect(); - ranks.sort_by(|left, right| { - right - .median_tokens_per_second - .total_cmp(&left.median_tokens_per_second) - .then_with(|| left.model.cmp(&right.model)) - }); - ranks + + /// The ranking, fastest first; models tie by name. + pub fn finish(self) -> Vec { + let mut ranks: Vec = self + .by_model + .into_iter() + .map(|(model, (mut speeds, lower_bound))| SpeedRank { + calls: speeds.len() as u64, + median_tokens_per_second: median(&mut speeds), + model, + lower_bound, + }) + .collect(); + ranks.sort_by(|left, right| { + right + .median_tokens_per_second + .total_cmp(&left.median_tokens_per_second) + .then_with(|| left.model.cmp(&right.model)) + }); + ranks + } } /// The model a call is counted under: the one that answered, or the one asked diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 8d2766ae..222ffa9f 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3867,7 +3867,7 @@ host never sees them): | --- | --- | --- | --- | | `lithe/host/agents/write` | `agents.native` | `{session, lines}` | `{}` | | `lithe/host/agents/report` | `agents.native` | `{session, events}` | `{}` | -| `lithe/host/agents/usage` | `agents.usage.read` | `{sinceMs?, untilMs?, groupBy, utcOffsetSeconds?}` | `{sinceMs, untilMs, summaries, rateLimits}` | +| `lithe/host/agents/usage` | `agents.usage.read` | `{sinceMs?, untilMs?, groupBy, utcOffsetSeconds?}` | `{sinceMs, untilMs, summaries, speeds, rateLimits}` | - `write` takes 1–256 lines of at most 16 MiB together, none with a line break; Core adds the newline. More than 64 writes waiting for the CLI is @@ -3880,6 +3880,7 @@ host never sees them): records the user enabled, grouped by `day`, `agent` or `model`, between `sinceMs` and `untilMs` (default the 30 days before tomorrow, at most 366 days; `utcOffsetSeconds` within ±14 hours sets the day boundary). + `speeds` ranks the models of the same calls by median output speed. `rateLimits` holds the latest quota windows of the agents the user may run or read. While the records are being written the answer is `-32020`; before they are opened, `-32601`; a failed read, `-32603`. It never carries @@ -3981,8 +3982,15 @@ cost?, firstStartedAtMs, lastStartedAtMs}`. `key` is `{kind: "day", date}`, agent, sessionID}` or `{kind: "cwd", cwd?}`. `cost` is `{usd, basis: "apiPriceEquivalent", pricedCalls, unpricedCalls, approximateCalls}`: what the tokens would cost at the API prices of `pricesFile`, not what the user -paid. Rate limits are `{atMs, windows, plan?, pluginID, agentID}`; Core keeps -the latest per agent in `rate-limits.json` in the cache directory. +paid. `stats` and `usage` also answer `speeds`, the models ranked fastest +first by the median output speed of their calls, each `{model, calls, +medianTokensPerSecond, lowerBound}`. A call's speed is its output tokens per +second after the first token; a call without a first-token time counts only +with at least 1000 output tokens over at least a second, as a lower bound, and +then `lowerBound` is true. Calls with fewer than 100 output tokens, failed +calls and speeds above 10000 tokens per second are left out. Rate limits are +`{atMs, windows, plan?, pluginID, agentID}`; Core keeps the latest per agent +in `rate-limits.json` in the cache directory. `agentSessions.*` refusals: `agentSessions.notConfigured`, `agentSessions.invalidDirectory`, `agentSessions.invalidEnvironment`, diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index a517c02d..5a8e5c15 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,8 @@ ## 待合入 +- [#SPEEDS](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/SPEEDS)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。 + - [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 - [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 / `litheFunctions` 0 内补充(API-05):新增宿主方法 `workspace/setDirectoryTypes` 与 `workspace/setDirectoryMarks`(新权限 `workspace.directoryMarks`),允许插件后端在当前工作区上下文注册自定义目录类型(最多 32 个,`id` 以 `plugin.` 开头)与动态目录标记(最多 500 条);`workspace.resolveDirectoryPresentation` 新增可选 `pluginTypes` 与 `pluginMarks` 字段及输出可选 `pluginId`,按 `user > shared > plugin > glob > vcs > plain` 确定性合并呈现与索引排除,并允许用户手动分配 `plugin.*` 角色;插件提交时的校验与解析器一致,宿主保存下来的登记不会让整次解析失败;清单 schema 与四种官方 SDK(Rust、Go、Node、Java)同步补齐。无新增能力版本、协议版本或 SDK 版本。 @@ -227,6 +229,7 @@ | API-45 | `agents/write` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/usage` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/usage` | 0(回答新增 `speeds`) | 待合入 | [#SPEEDS](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/SPEEDS) | | API-45 | `agents/didStart`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didOutput`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index e2b8bb5f..12c6159d 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -635,7 +635,7 @@ usage totals. registering one with `OnHostNotification` fails with `sdk.method.reserved`. - `write` and `report` need `agents.native` and act only on the plugin's own sessions. `usage` needs `agents.usage.read` and answers - `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. ## Testing diff --git a/shared/plugins/sdk/go/lithe/agents.go b/shared/plugins/sdk/go/lithe/agents.go index 74ca3551..4994ffdf 100644 --- a/shared/plugins/sdk/go/lithe/agents.go +++ b/shared/plugins/sdk/go/lithe/agents.go @@ -131,7 +131,7 @@ func (a *Agents) Report(session string, events any) error { return err } -// Usage answers { sinceMs, untilMs, summaries, rateLimits } for +// Usage answers { sinceMs, untilMs, summaries, speeds, rateLimits } for // { groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }. func (a *Agents) Usage(params any) (json.RawMessage, error) { value, err := toValue(params) diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 686d312b..98686e29 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -603,7 +603,7 @@ backend.onAgentSessions((start, session) -> new AgentSession() { registering one with `onHostNotification` fails with `sdk.method.reserved`. - `write` and `report` need `agents.native` and act only on the plugin's own sessions. `usage` needs `agents.usage.read` and answers - `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. ## Testing diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java index b3cfa0fb..86c80b1b 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -1037,7 +1037,7 @@ public CompletableFuture report(String session, List events) { } /** - * {@code { sinceMs, untilMs, summaries, rateLimits }} for + * {@code { sinceMs, untilMs, summaries, speeds, rateLimits }} for * {@code { groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }}. */ public CompletableFuture> usage(Map params) { diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 2f3af9ed..fa010501 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -616,7 +616,7 @@ ID, and `usage(params)` for usage totals. registering one with `onHostNotification` fails with `sdk.method.reserved`. - `write` and `report` need `agents.native` and act only on the plugin's own sessions. `usage` needs `agents.usage.read` and answers - `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. ## Testing diff --git a/shared/plugins/sdk/node/src/host.mjs b/shared/plugins/sdk/node/src/host.mjs index dda61c20..f5d53acb 100644 --- a/shared/plugins/sdk/node/src/host.mjs +++ b/shared/plugins/sdk/node/src/host.mjs @@ -325,7 +325,7 @@ export function createHost(channel, callSignal, parentOperationId) { report: async (session, events, options) => { await request(HOST_METHODS.agentsReport, { session, events }, options); }, - /** `{ sinceMs, untilMs, summaries, rateLimits }` for `{ groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }`. */ + /** `{ sinceMs, untilMs, summaries, speeds, rateLimits }` for `{ groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }`. */ usage: async (params, options) => { const result = await request(HOST_METHODS.agentsUsage, params, options); if (typeof result !== 'object' || result === null || Array.isArray(result)) { diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 8d8ea037..22c5bceb 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -727,7 +727,7 @@ for any session ID, and `usage(params)` for usage totals. registering one with `on_host_notification` fails with `sdk.method.reserved`. - `write` and `report` need `agents.native` and act only on the plugin's own sessions. `usage` needs `agents.usage.read` and answers - `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + `{sinceMs, untilMs, summaries, speeds, rateLimits}`: numbers and model names only, never conversation text, titles, session IDs or directories. ## Testing diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs index 3c771f3c..6670d694 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs @@ -120,7 +120,7 @@ impl Agents { .map(drop) } - /// The usage totals `{ sinceMs, untilMs, summaries, rateLimits }` for + /// The usage totals `{ sinceMs, untilMs, summaries, speeds, rateLimits }` for /// `{ groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }`. pub fn usage(&self, params: Value) -> Result { match self.host.request(methods::AGENTS_USAGE, params)? { From 203c58933a6f589f9a5792a80b9cb17cc1e0d523 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 06:33:10 +0800 Subject: [PATCH 2/7] =?UTF-8?q?docs(plugins):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E5=86=99=E4=B8=8A=20#217=20=E7=BC=96?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 5a8e5c15..9c10dacb 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#SPEEDS](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/SPEEDS)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。 +- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。 - [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 @@ -229,7 +229,7 @@ | API-45 | `agents/write` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/usage` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/usage` | 0(回答新增 `speeds`) | 待合入 | [#SPEEDS](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/SPEEDS) | +| API-45 | `agents/usage` | 0(回答新增 `speeds`) | 待合入 | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | | API-45 | `agents/didStart`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didOutput`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | From 4e864f76fe93c45c904df415e01194b8635625f5 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 09:56:47 +0800 Subject: [PATCH 3/7] =?UTF-8?q?feat(agents):=20=E4=BC=9A=E8=AF=9D=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E5=88=86=E9=A1=B5=E8=AF=BB=E5=8F=96=EF=BC=9Alist=20?= =?UTF-8?q?=E6=8C=89=20sessionID=20=E6=9F=A5=E6=89=BE=E5=B9=B6=E5=B8=A6=20?= =?UTF-8?q?readBytes=EF=BC=8Cread=20=E5=9B=9E=E7=AD=94=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E9=A1=B5=E8=B5=B7=E7=82=B9=20end?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 读取范围在行中间结束时只把完整的行交给插件后端,范围落在一行之内时回答 end 等于起点、不调用后端。契约 README、Core API 表和更新记录同步;新字段都是 agents 0 内的补充。 --- rust/contracts/rust-core-api.md | 4 +- rust/crates/agent-runtime/src/records.rs | 50 ++++++++++++++++-- rust/crates/agent-runtime/src/tests.rs | 52 ++++++++++++++++++- rust/crates/agent-sessions/src/store.rs | 19 +++++-- rust/crates/agent-sessions/src/tests/store.rs | 12 +++++ shared/plugins/contract/v1/README.md | 24 +++++++-- .../plugins/reference/protocol-changelog.md | 2 +- 7 files changed, 144 insertions(+), 19 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 3d057271..d402582a 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -492,9 +492,9 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.configure` | Open the agent session record cache | | `agentSessions.sync` | Read one agent's changed session files through its plugin | | `agentSessions.forget` | Drop one agent's cached session records | -| `agentSessions.list` | List recorded agent sessions | +| `agentSessions.list` | List recorded agent sessions, or find one by its ID | | `agentSessions.search` | Search recorded agent session text | -| `agentSessions.read` | Read one recorded range as messages | +| `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 | | `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 | diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 8d843e6d..53fd5581 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -352,6 +352,8 @@ impl Records { cwd: Option, #[serde(default)] active_since_ms: Option, + #[serde(rename = "sessionID", default)] + session_id: Option, #[serde(default)] offset: u64, #[serde(default)] @@ -367,6 +369,7 @@ impl Records { agents, cwd: request.cwd, active_since_ms: request.active_since_ms, + session_id: request.session_id, offset: request.offset, limit: request.limit.unwrap_or(100).clamp(1, MAX_SESSIONS_PAGE), }; @@ -495,7 +498,9 @@ impl Records { } /// `agentSessions.read`: the messages of a byte range of a session file, - /// as the agent's plugin reads them. + /// as the agent's plugin reads them. A range that ends inside a line is + /// read up to its last whole line, and `end` says where that is, so a host + /// reads a long session a page at a time and no line is cut in two. pub fn read(&self, runtime: &Runtime, payload: Value) -> Result { #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -522,14 +527,40 @@ impl Records { "The file is not in a session directory of the agent.", ) })?; - let bytes = { + let (bytes, ends_line) = { let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; - store.read_range(&request.agent, &request.path, request.range)? + let bytes = store.read_range(&request.agent, &request.path, request.range)?; + // A range ends a line when its last byte is a newline or the byte + // after it begins one; a span a plugin recorded without its + // newline is read whole. + let ends_line = match &bytes { + Some(bytes) if bytes.last() != Some(&b'\n') => { + let next = ByteRange { + start: request.range.end, + end: request.range.end.saturating_add(1), + }; + !matches!( + store.read_range(&request.agent, &request.path, next), + Ok(Some(byte)) if byte != b"\n" && byte != b"\r" + ) + } + _ => true, + }; + (bytes, ends_line) }; - let Some(bytes) = bytes else { + let Some(mut bytes) = bytes else { return Ok(json!({ "changed": true, "messages": [] })); }; + if !ends_line { + bytes.truncate(whole_lines(&bytes)); + } + // A range inside one line reads nothing and answers its own start, so + // the caller asks again with a larger range. + let end = request.range.start + bytes.len() as u64; + if bytes.is_empty() { + return Ok(json!({ "changed": false, "messages": [], "end": end })); + } let items = vec![json!({ "path": request.path, "lines": text_lines(&bytes) })]; let answers = call_read( &*runtime.link, @@ -544,7 +575,7 @@ impl Records { .map(decode_messages) .transpose()? .unwrap_or_default(); - Ok(json!({ "changed": false, "messages": messages })) + Ok(json!({ "changed": false, "messages": messages, "end": end })) } /// `agentSessions.stats`: usage of the readable agents for the host. @@ -911,6 +942,15 @@ fn backend_for( }) } +/// How many of `bytes`, which end inside a line, make whole lines: up to the +/// last newline, none when they hold no newline. +fn whole_lines(bytes: &[u8]) -> usize { + bytes + .iter() + .rposition(|byte| *byte == b'\n') + .map_or(0, |index| index + 1) +} + /// The lines of `bytes` as text, without their line breaks. fn text_lines(bytes: &[u8]) -> Vec { if bytes.is_empty() { diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index eb8cb284..1c49327f 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1276,8 +1276,58 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() { ); assert_eq!( read, - json!({ "changed": false, "messages": [{ "role": "user", "text": "hello from the user" }] }) + json!({ + "changed": false, + "messages": [{ "role": "user", "text": "hello from the user" }], + "end": hits[0]["range"]["end"], + }) + ); + + // The list gives how much of the file the cache has read and finds one + // session by its ID, so a viewer can page through a whole record. + let size = fs::metadata(&file).unwrap().len(); + assert_eq!(sessions[0]["readBytes"], size, "{sessions}"); + let found = harness.run("agentSessions.list", json!({ "sessionID": "s1" }))["sessions"].clone(); + assert_eq!(found.as_array().map(Vec::len), Some(1), "{found}"); + let none = harness.run("agentSessions.list", json!({ "sessionID": "s9" }))["sessions"].clone(); + assert_eq!(none.as_array().map(Vec::len), Some(0), "{none}"); + let whole = harness.run( + "agentSessions.read", + json!({ "agent": AGENT_KEY, "path": path_text(&file), "range": { "start": 0, "end": size } }), + ); + assert_eq!(whole["end"], size, "{whole}"); + assert_eq!( + whole["messages"].as_array().map(Vec::len), + Some(1), + "{whole}" + ); + // A page that ends inside a line stops at the line before it, and the + // plugin never sees the cut line. + let text = fs::read_to_string(&file).unwrap(); + let second = text.find('\n').unwrap() as u64 + 1; + let third = second + text[second as usize..].find('\n').unwrap() as u64 + 1; + let page = harness.run( + "agentSessions.read", + json!({ "agent": AGENT_KEY, "path": path_text(&file), "range": { "start": 0, "end": third + 5 } }), + ); + assert_eq!(page["end"], third, "{page}"); + assert_eq!(page["messages"].as_array().map(Vec::len), Some(1), "{page}"); + let last = harness + .link + .calls_of("sessions.read") + .last() + .cloned() + .unwrap(); + let sent = last["items"][0]["lines"].as_array().map(Vec::len); + assert_eq!(sent, Some(2), "{last}"); + let calls = harness.link.calls_of("sessions.read").len(); + let inside = harness.run( + "agentSessions.read", + json!({ "agent": AGENT_KEY, "path": path_text(&file), "range": { "start": second + 1, "end": second + 5 } }), ); + let expected = json!({ "changed": false, "messages": [], "end": second + 1 }); + assert_eq!(inside, expected); + assert_eq!(harness.link.calls_of("sessions.read").len(), calls); assert_eq!( harness.refused( "agentSessions.read", diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs index 51d25337..c637e356 100644 --- a/rust/crates/agent-sessions/src/store.rs +++ b/rust/crates/agent-sessions/src/store.rs @@ -239,6 +239,8 @@ pub struct SessionFilter { pub cwd: Option, /// Only sessions last active at or after this time, in Unix milliseconds. pub active_since_ms: Option, + /// Only the session with this ID, in the agent's own ID format. + pub session_id: Option, /// Sessions to skip, for the next page. pub offset: u64, /// Sessions to list, at most [`MAX_SESSIONS_PAGE`]. @@ -278,6 +280,9 @@ pub struct SessionEntry { /// The bytes of `path` that hold the title. #[serde(skip_serializing_if = "Option::is_none")] pub title_range: Option, + /// How many bytes of `path` the cache has read: every whole line up to + /// here, so [`SessionStore::read_range`] takes any range that ends by it. + pub read_bytes: u64, } /// A full-text search. @@ -503,7 +508,7 @@ impl SessionStore { pub fn sessions(&self, filter: &SessionFilter) -> Result, CoreError> { const SQL: &str = " WITH ranked AS ( - SELECT f.agent, f.path, s.*, + SELECT f.agent, f.path, f.cursor_offset, s.*, ROW_NUMBER() OVER ( PARTITION BY f.agent, s.session_id ORDER BY s.described DESC, f.path @@ -512,12 +517,14 @@ impl SessionStore { MIN(s.started_at_ms) OVER whole AS first_started_ms, MAX(s.updated_at_ms) OVER whole AS last_updated_ms FROM sessions s JOIN files f ON f.id = s.file_id - WHERE json_array_length(?1) = 0 - OR f.agent IN (SELECT value FROM json_each(?1)) + WHERE (json_array_length(?1) = 0 + OR f.agent IN (SELECT value FROM json_each(?1))) + AND (?6 IS NULL OR s.session_id = ?6) WINDOW whole AS (PARTITION BY f.agent, s.session_id) ) SELECT agent, session_id, path, file_count, parent_session_id, cwd, - first_started_ms, last_updated_ms, agent_version, title_start, title_end + first_started_ms, last_updated_ms, agent_version, title_start, title_end, + cursor_offset FROM ranked WHERE copy_rank = 1 AND (?2 IS NULL OR cwd = ?2) @@ -537,7 +544,8 @@ impl SessionStore { filter.cwd, filter.active_since_ms, limit, - filter.offset + filter.offset, + filter.session_id ], |row| { Ok(SessionEntry { @@ -551,6 +559,7 @@ impl SessionStore { updated_at_ms: row.get(7)?, agent_version: row.get(8)?, title_range: optional_range(row.get(9)?, row.get(10)?), + read_bytes: row.get(11)?, }) }, ) diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs index b370e209..166e283d 100644 --- a/rust/crates/agent-sessions/src/tests/store.rs +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -513,8 +513,20 @@ fn sessions_merge_their_files_and_filter() { (Some(1_000), Some(1_000)) ); assert!(merged.title_range.is_some()); + // The cache has read every whole line of the file the entry names. + assert_eq!( + merged.read_bytes, + std::fs::metadata(&described).expect("stat the file").len() + ); let only = |filter: SessionFilter| session_ids(&sessions(&fixture.store, filter)).join(","); + assert_eq!( + only(SessionFilter { + session_id: Some("s3".to_string()), + ..every_session() + }), + "s3" + ); assert_eq!( only(SessionFilter { agents: vec![AGENT.to_string()], diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 222ffa9f..eecf2dac 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3944,13 +3944,27 @@ Lithe list, search and sum them without the CLI running: `unreadableEntries`. Lines reach `scan` in chunks of at most 4 MiB; a line longer than 16 MiB is skipped. `agentSessions.forget {pluginID, agentID}` drops the agent's records and answers `{files}`. -- `agentSessions.list {agents?, cwd?, activeSinceMs?, offset, limit, - titles}` (at most 500), `agentSessions.search {text, agents?, sessionID?, - limit}` (at most 200), `agentSessions.read {agent, path, range}` and - `agentSessions.stats {agents?, sessionID?, sinceMs?, untilMs?, groupBy, - utcOffsetSeconds}` serve the host's own views; `agent` is +- `agentSessions.list {agents?, cwd?, sessionID?, activeSinceMs?, offset, + limit, titles}` (at most 500), `agentSessions.search {text, agents?, + sessionID?, limit}` (at most 200), `agentSessions.read {agent, path, + range}` and `agentSessions.stats {agents?, sessionID?, sinceMs?, untilMs?, + groupBy, utcOffsetSeconds}` serve the host's own views; `agent` is `/`, and `stats` groups by `day`, `agent`, `model`, `session` or `cwd`. +- 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 + range end when the range ends a line, otherwise the start of the line the + range cuts, whose bytes the backend never sees. A range inside one line + answers `end` equal to its start and no messages; ask again with a larger + range. `changed` is true, with no messages and no `end`, when the file + changed since the cache read it; sync and list again. A backend's whole + `messages` answer must fit the 1 MiB function result bound, so a host pages + a long record with ranges well below it. +- `sessionID`, `readBytes` and `end` were added within `agents` 0. A Core + that predates them refuses `sessionID` as an unknown field, answers neither + `readBytes` nor `end`, and may hand `read` a range that ends inside a line; + the backend skips a line that is not a whole JSON value. `scan` receives `{agentID, sourceID, path, lines: [{offset, length, text}], state?}` and has 30 seconds. It answers: diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 9c10dacb..e2fa7960 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。 +- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。同一 PR 里,会话记录的读取支持分页:`agentSessions.list` 可按 `sessionID` 查找、每个会话带 `readBytes`,`agentSessions.read` 回答 `end`(下一页的起点);读取范围在行中间结束时,Core 只把完整的行交给插件后端的 `read`,并说明后端 `messages` 回答整体不能超过 1 MiB 的函数结果上限。旧 Core 不认 `sessionID`、不回答 `readBytes` 和 `end`,并可能把被截断的行交给后端,后端应跳过不是完整 JSON 的行。 - [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 From 8a8d13c7996ee0f97884a92e8178d72dde368dbb Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 10:19:26 +0800 Subject: [PATCH 4/7] =?UTF-8?q?feat(command-installers):=20=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E5=AE=89=E8=A3=85=E4=B9=9F=E6=9C=8D=E5=8A=A1=20Agent?= =?UTF-8?q?=20=E7=9A=84=E5=91=BD=E4=BB=A4=E8=A1=8C=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=EF=BC=88commandInstallers=200=20=E5=86=85=E8=A1=A5=E5=85=85?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 安装声明的 commands 可以由本插件某个 Agent 的 tool 所指工具定义的 commands 提供;requirements 在 systemCommand 启动之后按声明顺序列出 kind 为 agent、 id 为 Agent ID 的使用方。新增 fixture command-installer-agent.plugin.json 和 三个计划用例(列出使用方、受管目录计划、拒绝没有启动或 Agent 工具用到的命令), 契约 README、工具链参考页、能力版本表和协议更新记录同步。 --- .../core/src/tests/declarative_plugins.rs | 4 + .../plugin-manifest/src/command_installers.rs | 52 ++++++++++- shared/plugins/contract/v1/README.md | 29 ++++-- .../command-installer-agent.plugin.json | 72 +++++++++++++++ .../command-installer-plans.json | 89 +++++++++++++++++++ .../reference/capabilities-and-versions.md | 4 +- .../plugins/reference/domains/toolchains.md | 5 +- .../plugins/reference/protocol-changelog.md | 2 +- 8 files changed, 240 insertions(+), 17 deletions(-) create mode 100644 shared/plugins/contract/v1/fixtures/command-installers/command-installer-agent.plugin.json diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 990e9c82..c177a91c 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -71,6 +71,8 @@ const COMMAND_INSTALLER_FIXTURE: &str = contract_file!("fixtures/command-installers/command-installer.plugin.json"); const COMMAND_INSTALLER_DOWNLOAD_FIXTURE: &str = contract_file!("fixtures/command-installers/command-installer-download.plugin.json"); +const COMMAND_INSTALLER_AGENT_FIXTURE: &str = + contract_file!("fixtures/command-installers/command-installer-agent.plugin.json"); const COMMAND_INSTALLER_PLANS: &str = contract_file!("fixtures/command-installers/command-installer-plans.json"); const RUN_CONFIGURATION_TYPES_FIXTURE: &str = @@ -114,6 +116,7 @@ fn fixture(name: &str) -> Value { "project-generator-tool-field.plugin.json" => PROJECT_GENERATOR_TOOL_FIXTURE, "command-installer.plugin.json" => COMMAND_INSTALLER_FIXTURE, "command-installer-download.plugin.json" => COMMAND_INSTALLER_DOWNLOAD_FIXTURE, + "command-installer-agent.plugin.json" => COMMAND_INSTALLER_AGENT_FIXTURE, "run-configuration-types.plugin.json" => RUN_CONFIGURATION_TYPES_FIXTURE, "before-launch-tasks.plugin.json" => BEFORE_LAUNCH_TASKS_FIXTURE, "agents.plugin.json" => AGENTS_FIXTURE, @@ -152,6 +155,7 @@ fn contract_fixtures_and_official_plugins_validate() { PROJECT_GENERATOR_TOOL_FIXTURE, COMMAND_INSTALLER_FIXTURE, COMMAND_INSTALLER_DOWNLOAD_FIXTURE, + COMMAND_INSTALLER_AGENT_FIXTURE, RUN_CONFIGURATION_TYPES_FIXTURE, BEFORE_LAUNCH_TASKS_FIXTURE, AGENTS_FIXTURE, diff --git a/rust/crates/plugin-manifest/src/command_installers.rs b/rust/crates/plugin-manifest/src/command_installers.rs index b0a827a4..e61ebe9e 100644 --- a/rust/crates/plugin-manifest/src/command_installers.rs +++ b/rust/crates/plugin-manifest/src/command_installers.rs @@ -1,5 +1,6 @@ //! `commandInstallers[]`: how the host installs a bare command that one of the -//! plugin's `systemCommand` launches needs and the machine lacks. +//! plugin's `systemCommand` launches, or the CLI of one of its agents, needs +//! and the machine lacks. //! //! The host never installs on its own. It shows the user what the //! installation runs or downloads, whether it uses the network and where the @@ -69,6 +70,9 @@ const SYSTEM_COMMAND_PROGRAMS: &[(&str, &str, Option<&str>)] = &[ ("systemVcsProvider", "vcsProvider", Some("vcs")), ]; +/// The consumer kind of an agent's CLI, keyed by the agent's ID. +const AGENT_CONSUMER: &str = "agent"; + /// One way to install bare commands the plugin's launches name: a run of a /// tool (`tool` and `arguments`) or a pinned download (`download`), never /// both. @@ -78,7 +82,8 @@ pub(crate) struct CommandInstallerDeclaration { /// Lowercase letters, digits, and hyphens; unique within the plugin. pub(crate) id: String, /// Bare commands the installation provides. Each is named by a - /// `systemCommand` launch of this manifest and by no other installer. + /// `systemCommand` launch of this manifest, or by the `commands` of the + /// tool definition of one of its agents, and by no other installer. pub(crate) commands: Vec, /// Tool-definition ID, listed in `requiresTools`, whose executable runs /// the installation. Required unless the installer downloads. @@ -324,7 +329,9 @@ impl CommandInstallerDeclaration { if !launched.contains(command) { return Err(invalid( entry, - format!("No systemCommand launch of this plugin names {command}."), + format!( + "No systemCommand launch or agent tool of this plugin names {command}." + ), )); } } @@ -644,8 +651,40 @@ impl DeclarativePluginManifest { } /// Every `systemCommand` launch the host may start, in the order of the - /// reviewed program list. + /// reviewed program list, then every agent whose tool this plugin defines, + /// in declaration order, with the commands of that definition. The host + /// finds an agent's CLI through the tool definition, whose `commands` are + /// the bare names it looks up; an agent whose tool another plugin defines + /// names no command here. fn command_consumers(&self) -> Vec { + let mut consumers = self.system_command_consumers(); + for agent in &self.agents { + let Some(definition) = self + .tool_definitions + .iter() + .find(|definition| definition["id"] == agent.tool.as_str()) + else { + continue; + }; + let commands: Vec = definition["commands"] + .as_array() + .into_iter() + .flatten() + .filter_map(|command| command.as_str().map(str::to_string)) + .collect(); + if !commands.is_empty() { + consumers.push(CommandConsumer { + kind: AGENT_CONSUMER, + id: Some(agent.id.clone()), + commands, + }); + } + } + consumers + } + + /// The `systemCommand` launches of the reviewed program list, in its order. + fn system_command_consumers(&self) -> Vec { self.programs() .iter() .filter_map(|program| { @@ -1083,6 +1122,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer-download.plugin.json" )); + const AGENT_PLUGIN: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer-agent.plugin.json" + )); const PLANS: &str = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json" @@ -1104,6 +1147,7 @@ mod tests { let plugin: Value = serde_json::from_str(match file { "command-installer.plugin.json" => PLUGIN, "command-installer-download.plugin.json" => DOWNLOAD_PLUGIN, + "command-installer-agent.plugin.json" => AGENT_PLUGIN, other => panic!("unknown plugin fixture {other}"), }) .unwrap(); diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index eecf2dac..b0420b4a 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -182,7 +182,7 @@ symbolic links. A host treats an installed package as read-only. | `settings` | User-adjustable plugin options. | | `ui` | Host-rendered tool windows and commands. | | `buildSystems` | Project-level build tools. | -| `commandInstallers` | How the host installs a bare command a `systemCommand` launch needs; requires `commandInstallers: 0` and `commands.install`; see [Command installers](#command-installers). | +| `commandInstallers` | How the host installs a bare command a `systemCommand` launch or an agent's CLI needs; requires `commandInstallers: 0` and `commands.install`; see [Command installers](#command-installers). | | `managedRuntimes` | Pinned dependencies qualified by a packaged backend and installed in host-owned storage independent of plugin version; requires `managedRuntimes: 0` and `runtimes.install`; see [Managed runtimes](#managed-runtimes). | | `toolDefinitions` | Plugin-owned tool policy ([Core foundation](toolchains/README.md)); requires `toolDefinitions: 0`, or `1` when a definition sets the settings-list `category` or `audience`; a host may offer read-only discovery and resolve Build and run tools. | | `toolchainProviders` | Backend fact-provider declarations ([Core foundation](toolchains/README.md)); requires `toolchainProviders: 0` or `1`, `backend: 0` and `toolchains.provide`. Version 1 uses distinct permission and authority error numbers. | @@ -1069,7 +1069,7 @@ belongs to one capability: | `debugAdapters` | [`debugAdapters[]`](#debug-adapters) | — | Starts the adapter and applies its [declared features and defaults](#adapter-features-and-defaults). | | `outputLinkMatchers` | [`outputLinkMatchers[]`](#output-link-matchers) | — | Turns Run and Test console text into links through the declared patterns. | | `projectGenerators` | [`projectGenerators[]`](#project-generators), including [`tool` fields](#tool-fields) | — | Lists the entries in the New Project window and generates the project. | -| `commandInstallers` | [`commandInstallers[]`](#command-installers) | — | Reports missing commands of `systemCommand` launches and installs them after the user confirms the command line, the network use and the target. | +| `commandInstallers` | [`commandInstallers[]`](#command-installers) | — | Reports missing commands of `systemCommand` launches and of agents' tools, and installs them after the user confirms the command line, the network use and the target. | | `managedRuntimes` | [`managedRuntimes`](#managed-runtimes) | Existing backend functions | Qualifies external and cached dependencies before committing an approved install/update, downloads only missing pinned artifacts, and repairs missing state before a server starts. | | `backend` | [`backend`](#plugin-backend): the plugin's own long-lived process | `litheFunctions` | Starts the backend with or without a page, serves the host services its permissions grant, and speaks `litheFunctions`. | | `toolDefinitions` | `toolDefinitions[]`: [tool identities, layouts, discovery and four-layer candidates](toolchains/README.md) | — | Resolves the definitions through the four layers. | @@ -1481,7 +1481,7 @@ downloads a pinned archive (a **download installer**). The section requires | Field | Meaning | | --- | --- | | `id` | Lowercase letters, digits and `-`, at most 64 characters; unique within the plugin. | -| `commands` | 1 to 8 bare command names the installation provides. Each one is named by a `systemCommand` launch of this manifest (a language server, build provider, VCS provider, debug adapter or the backend) and by no other installer. | +| `commands` | 1 to 8 bare command names the installation provides. Each one is named by a `systemCommand` launch of this manifest (a language server, build provider, VCS provider, debug adapter or the backend), or by the `commands` of the tool definition of one of its [agents](#agents), and by no other installer. | | `tool` | Tool installer: the tool-definition ID, listed in `requiresTools`, whose executable runs the installation and the directory probes. | | `minimumVersion` | Tool installer, optional: lowest version of `tool`, one to three dotted numbers. | | `arguments` | Tool installer: arguments after the tool's executable, used by a target that does not replace them. Literal: no template variables. | @@ -1513,8 +1513,16 @@ The user chooses the target when installing: At most 16 installers, 64 arguments per list, 16 environment variables per target, and 4096 bytes per argument or value. An environment name is uppercase letters, digits and `_`, not starting with a digit. Only `systemCommand` -launches are served: a build system's or execution provider's executable -resolved through `invocation.executables` is not. +launches and the CLIs of agents are served: a build system's or execution +provider's executable resolved through `invocation.executables` is not. An +agent is served when this manifest defines its `tool`; the installer then +installs the `commands` of that tool definition. + +Agent CLIs are an addition within `commandInstallers: 0`. A Core that predates +it refuses an installer whose commands only an agent's tool names, with +`plugin.manifest.invalid` on `commandInstallers[].commands[]`; a plugin that +needs it also requires `agents: 0`, which no host offers without it. See +[`command-installer-agent.plugin.json`](fixtures/command-installers/command-installer-agent.plugin.json). ### Download installers @@ -1579,7 +1587,9 @@ The host never installs on its own: 1. `plugins.commandInstallers.requirements` accepts `{manifest, platform?}` and lists each `systemCommand` launch with its commands and their - installer, `null` when none provides it, and the installers offered. Each + installer, `null` when none provides it, then each agent whose `tool` this + manifest defines (`kind: "agent"`, `id` the agent ID) with the `commands` + of that definition, and the installers offered. Each installer entry has `id`, `commands`, `tool`, `minimumVersion`, `download` (`null` for a tool installer, `{version}` for a download installer), `mayUseNetwork` and `targets`. With `platform: {os, arch}` a @@ -1618,7 +1628,9 @@ The host never installs on its own: `download.commandDirectory` below the extracted root. 5. Later launches of the plugin find the commands there: the host adds the plugin's managed command directories and the default directories it - recorded to the lookup of that plugin's `systemCommand` launches. + recorded to the lookup of that plugin's `systemCommand` launches, and + resolves the `kind: "command"` executables of its agents' tools in them + when the command is not on `PATH`. Every installer is a program of the [install review](#trust-and-install-review) (`kind: "commandInstaller"` with its fields), so a change to what it runs is @@ -1628,7 +1640,8 @@ mirror, digest or version is approved again too. A host that declares only `commandInstallers: 0` refuses a plugin with a download installer before installing it. See [`command-installer.plugin.json`](fixtures/command-installers/command-installer.plugin.json), -[`command-installer-download.plugin.json`](fixtures/command-installers/command-installer-download.plugin.json) +[`command-installer-download.plugin.json`](fixtures/command-installers/command-installer-download.plugin.json), +[`command-installer-agent.plugin.json`](fixtures/command-installers/command-installer-agent.plugin.json) and the golden cases in [`command-installer-plans.json`](fixtures/command-installers/command-installer-plans.json). diff --git a/shared/plugins/contract/v1/fixtures/command-installers/command-installer-agent.plugin.json b/shared/plugins/contract/v1/fixtures/command-installers/command-installer-agent.plugin.json new file mode 100644 index 00000000..98f5914c --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/command-installers/command-installer-agent.plugin.json @@ -0,0 +1,72 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.agent-installer", + "displayName": "Agent Installer Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { + "agents": 0, + "commandInstallers": 0, + "toolDefinitions": 0 + }, + "requiresTools": [ + "dev.lithe.fixture.agent-installer:example-agent", + "dev.lithe.fixture.agent-installer:packages" + ], + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "agents.run", + "commands.install" + ], + "activationEvents": [], + "agents": [ + { + "id": "example", + "displayName": "Example Agent", + "tool": "dev.lithe.fixture.agent-installer:example-agent", + "terminal": { "arguments": [] } + } + ], + "toolDefinitions": [ + { + "id": "dev.lithe.fixture.agent-installer:example-agent", + "displayName": "Example Agent", + "executableLayouts": [{ "path": "bin/example-agent" }], + "executables": [{ "id": "shell", "kind": "command", "command": "example-agent" }], + "version": { "arguments": ["--version"], "pattern": "(\\d+(?:\\.\\d+)*)" }, + "commands": ["example-agent"], + "launch": ["${executable}", "${arguments}"] + }, + { + "id": "dev.lithe.fixture.agent-installer:packages", + "displayName": "Package Tool", + "executableLayouts": [{ "path": "bin/packages" }], + "executables": [{ "id": "shell", "kind": "command", "command": "packages" }], + "version": { "arguments": ["--version"], "pattern": "(\\d+(?:\\.\\d+)*)" }, + "commands": ["packages"], + "launch": ["${executable}", "${arguments}"] + } + ], + "commandInstallers": [ + { + "id": "example-agent", + "commands": ["example-agent"], + "tool": "dev.lithe.fixture.agent-installer:packages", + "arguments": ["install", "--global", "example-agent"], + "mayUseNetwork": true, + "targets": { + "managed": { + "arguments": ["install", "--prefix", "${installDirectory}", "example-agent"], + "commandDirectory": "bin" + }, + "toolDefault": { + "directory": [{ "arguments": ["prefix", "--global"], "append": "bin" }] + } + } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json b/shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json index bd3eaccf..c831999b 100644 --- a/shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json +++ b/shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json @@ -92,6 +92,95 @@ } } }, + { + "name": "an agent whose tool the plugin defines lists the commands of that definition", + "plugin": "command-installer-agent.plugin.json", + "operation": "requirements", + "payload": {}, + "expected": { + "status": "ok", + "requirements": { + "consumers": [ + { + "kind": "agent", + "id": "example", + "commands": [{ "command": "example-agent", "installer": "example-agent" }] + } + ], + "installers": [ + { + "id": "example-agent", + "commands": ["example-agent"], + "tool": "dev.lithe.fixture.agent-installer:packages", + "minimumVersion": null, + "download": null, + "mayUseNetwork": true, + "targets": ["managed", "toolDefault"] + } + ] + } + } + }, + { + "name": "an agent plan installs the CLI into the managed directory", + "plugin": "command-installer-agent.plugin.json", + "operation": "plan", + "payload": { "installerID": "example-agent", "target": "managed" }, + "platforms": { + "unix": { + "payload": { "installDirectory": "/data/lithe/commands/example-agent" }, + "expected": { + "status": "ok", + "plan": { + "installer": "example-agent", + "target": "managed", + "commands": ["example-agent"], + "tool": "dev.lithe.fixture.agent-installer:packages", + "minimumVersion": null, + "mayUseNetwork": true, + "timeoutMilliseconds": 600000, + "arguments": ["install", "--prefix", "/data/lithe/commands/example-agent", "example-agent"], + "environment": {}, + "commandDirectory": "/data/lithe/commands/example-agent/bin", + "directoryProbes": [], + "download": null + } + } + }, + "windows": { + "payload": { "installDirectory": "C:\\Lithe\\commands\\example-agent" }, + "expected": { + "status": "ok", + "plan": { + "installer": "example-agent", + "target": "managed", + "commands": ["example-agent"], + "tool": "dev.lithe.fixture.agent-installer:packages", + "minimumVersion": null, + "mayUseNetwork": true, + "timeoutMilliseconds": 600000, + "arguments": ["install", "--prefix", "C:\\Lithe\\commands\\example-agent", "example-agent"], + "environment": {}, + "commandDirectory": "C:\\Lithe\\commands\\example-agent\\bin", + "directoryProbes": [], + "download": null + } + } + } + } + }, + { + "name": "an installer for a command no launch or agent tool names is refused", + "plugin": "command-installer-agent.plugin.json", + "operation": "requirements", + "payload": {}, + "manifestEdits": [{ "path": "/commandInstallers/0/commands", "value": ["other-agent"] }], + "expected": { + "status": "rejected", + "code": "plugin.manifest.invalid", + "field": "commandInstallers[0].commands[0]" + } + }, { "name": "a managed plan passes the install directory through the environment", "operation": "plan", diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index cd629fe1..8637a627 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -62,7 +62,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters):独立适配器、语言服务器内的适配器、[远程附加](../contract/v1/README.md#remote-attach)、参数和环境变量、[`features` 与 `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [调试适配器](domains/debug-adapters.md) | | `managedRuntimes` `0` | 固定归档、插件后端资格检查、跨版本缓存与安装前准备;权限 `runtimes.install` | ✅ | ✅ | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `managedRuntimes` `1` | 在 `0` 基础上允许每个平台归档声明最多 8 个 HTTPS `mirrors` 镜像地址,不改变 `cacheKey` | ✅ | 配套宿主接入后声明 | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | -| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers):用插件已依赖的工具安装 `systemCommand` 启动缺的裸命令,装到 Lithe 管理的目录(`managed`)或工具默认位置(`toolDefault`),用户确认后才运行 | ✅ | ✅ | [工具链](domains/toolchains.md#安装缺失的命令) | +| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers):用插件已依赖的工具安装 `systemCommand` 启动或 Agent 工具缺的裸命令(Agent 工具为 0 内的补充),装到 Lithe 管理的目录(`managed`)或工具默认位置(`toolDefault`),用户确认后才运行 | ✅ | ✅ | [工具链](domains/toolchains.md#安装缺失的命令) | | `commandInstallers` `1` | 在 `0` 基础上新增[下载安装](../contract/v1/README.md#download-installers):`download` 固定上游版本和每个平台的 HTTPS 归档(SHA-256、`zip`/`tar.gz`、可选镜像和 `stripPrefix`),宿主下载、校验、解压到 Lithe 管理的目录,用户确认版本和地址后才下载;没有当前平台归档的安装不提供 | ✅ | 配套宿主接入后声明 | [工具链](domains/toolchains.md#安装缺失的命令) | | `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) | @@ -183,7 +183,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters): standalone adapters, adapters inside a language server, [remote attach](../contract/v1/README.md#remote-attach), arguments and environment, [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [Debug adapters](domains/debug-adapters.md) | | `managedRuntimes` `0` | Pinned archives, plugin-owned qualification, version-independent cache and install preflight; permission `runtimes.install` | ✅ | ✅ | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `managedRuntimes` `1` | Extends `0` with up to 8 optional HTTPS `mirrors` URLs per platform artifact without changing `cacheKey` | ✅ | Declared with companion host integration | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | -| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers): install a bare command a `systemCommand` launch lacks with a tool the plugin already requires, into a directory Lithe manages (`managed`) or the tool's default location (`toolDefault`), only after the user confirms | ✅ | ✅ | [Toolchains](domains/toolchains.md#installing-missing-commands) | +| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers): install a bare command a `systemCommand` launch or an agent's tool lacks (agent tools are an addition within 0) with a tool the plugin already requires, into a directory Lithe manages (`managed`) or the tool's default location (`toolDefault`), only after the user confirms | ✅ | ✅ | [Toolchains](domains/toolchains.md#installing-missing-commands) | | `commandInstallers` `1` | Extends `0` with [download installers](../contract/v1/README.md#download-installers): `download` pins an upstream version and an HTTPS archive per platform (SHA-256, `zip`/`tar.gz`, optional mirrors and `stripPrefix`); the host downloads, checks and extracts it into a directory Lithe manages, only after the user confirms the version and URL; an installer without an archive for the platform is not offered | ✅ | Declared with companion host integration | [Toolchains](domains/toolchains.md#installing-missing-commands) | | `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) | diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index 686b4d78..f3ab4569 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -123,12 +123,13 @@ | 项目 | 规则 | | --- | --- | -| 声明 | `id`、`commands`(1–8 个本清单 `systemCommand` 启动用到的裸命令,一个命令只归一个安装)、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)、`targets`;工具安装另有 `tool`、`minimumVersion?`、字面量 `arguments`,下载安装另有 `download` | +| 声明 | `id`、`commands`(1–8 个本清单 `systemCommand` 启动或本插件 Agent 工具定义的 `commands` 用到的裸命令,一个命令只归一个安装)、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)、`targets`;工具安装另有 `tool`、`minimumVersion?`、字面量 `arguments`,下载安装另有 `download` | | 下载安装 | `download.version` 是上游版本;`download.artifacts` 1–6 个归档,每个 `os`/`arch` 最多一个,各有 HTTPS `url`、可选 `mirrors`(最多 8 个)、完整 `sha256`、`archive`(`zip` 或 `tar.gz`)、可选 `stripPrefix`。只能用 `managed` 目标,不带 `arguments`、`environment`;`commandDirectory` 相对解压根目录。`mayUseNetwork` 必须为 `true`。没有当前平台归档时不提供这个安装 | | `managed` 目标 | 装进宿主为插件管理的目录(应用数据目录,不在应用包、安装目录或插件包里,卸载插件时删除)。`arguments`(替换安装的参数)或 `environment` 必须用唯一的模板变量 `${installDirectory}`;`commandDirectory` 是命令所在的子目录 | | `toolDefault` 目标 | 装到工具默认位置,值都是字面量。`directory` 最多 4 个探针,按顺序用同一工具运行,第一个输出绝对目录的探针决定位置;`pathList` 取路径列表第一项,`append` 拼接子目录 | | 宿主做什么 | `plugins.commandInstallers.requirements` 带上本机 `platform`,列出每个启动缺哪些命令、由哪个安装提供;`toolDefault` 先运行探针,把输出交给 `defaultDirectory`;向用户展示工具和完整命令行(下载安装展示版本和下载地址)、是否联网和每个目标的目录,用户选定后用 `plan` 展开并运行,显示输出、可取消、超时停止,结束后确认命令确实在目录里。下载安装的 `plan` 带 `platform`,返回 `download`(选中平台的归档和 `cacheKey`);宿主依次尝试 `url` 和镜像下载,解压前校验 SHA-256,安全解压到受管目录下自己的子目录,保留文件权限 | -| 之后的启动 | 宿主查找这个插件的 `systemCommand` 时,除 `PATH` 外还查插件的受管命令目录和记录下来的默认目录 | +| 之后的启动 | 宿主查找这个插件的 `systemCommand`、解析它的 Agent 工具的 `kind: "command"` 候选时,除 `PATH` 外还查插件的受管命令目录和记录下来的默认目录 | +| Agent 命令行工具 | `commandInstallers` 0 内的补充:Agent 的 `tool` 是本插件定义的工具时,`requirements` 在 `systemCommand` 启动之后列出 `kind: "agent"`、`id` 为 Agent ID 的使用方,例如用 npm 安装 Agent 的命令行工具;旧 Core 以 `plugin.manifest.invalid` 拒绝只有 Agent 工具用到的安装,需要它的插件同时要求 `agents` 0 | | 不覆盖 | 构建系统和执行提供者通过 `invocation.executables` 解析的可执行文件 | | 安装审查 | 每个安装都是审查里的程序(`kind: "commandInstaller"`),改了要运行的内容需要重新批准;下载安装的程序列出全部归档,改地址、镜像、摘要或版本也要重新批准 | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index e2fa7960..c1ae84f3 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。同一 PR 里,会话记录的读取支持分页:`agentSessions.list` 可按 `sessionID` 查找、每个会话带 `readBytes`,`agentSessions.read` 回答 `end`(下一页的起点);读取范围在行中间结束时,Core 只把完整的行交给插件后端的 `read`,并说明后端 `messages` 回答整体不能超过 1 MiB 的函数结果上限。旧 Core 不认 `sessionID`、不回答 `readBytes` 和 `end`,并可能把被截断的行交给后端,后端应跳过不是完整 JSON 的行。 +- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。同一 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。没有新增宿主方法、通知或错误码。 - [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 From 08ba94e6be3c4256c45db517ad75fd14c7226fb3 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 10:59:38 +0800 Subject: [PATCH 5/7] =?UTF-8?q?feat(ide-host):=20IDE=20=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8F=AA=E8=AF=BB=E7=9A=84=20Agent=20?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E6=90=9C=E7=B4=A2=E5=92=8C=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=EF=BC=88API-45=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - lithe_sessions_search(query、可选 agent)和 lithe_sessions_read(sessionID、可选 agent、可选 cursor),权限都是 read,参数里没有路径 - 这两个工具只在宿主声明时提供:没有声明工具清单的宿主照旧提供其余全部工具,但不提供它们;宿主只在用户打开 IDE 连接、打开“允许 MCP 客户端搜索本地会话”并同意读取至少一个 Agent 的会话时声明 - 调用 fixture 加上接受和拒绝的会话工具调用,产品工具清单 fixture 加上两个工具;单测核对只读、无路径参数、撤回声明后拒绝调用 - 新日志事件 agent.records.inspected(由 Lithe 记):只记工具名、结果条数和耗时,不记查询词、会话 ID 和内容 - ide-api v1 契约写明三个条件、结果和字节上限、错误码、不返回路径、不触发同步;更新记录在 #217 条目里补一句 --- rust/contracts/ide-api/v1.md | 43 +++++++++++ .../diagnostics/src/catalog_generated.rs | 14 ++++ rust/crates/ide-host/src/catalog.rs | 73 ++++++++++++++++++- rust/crates/ide-host/src/lib.rs | 29 +++++++- rust/fixtures/ide-api/calls.json | 46 ++++++++++++ rust/fixtures/ide-api/host-tool-exposure.json | 12 +++ rust/logging/events/agent.json | 13 ++++ .../plugins/reference/protocol-changelog.md | 2 +- 8 files changed, 226 insertions(+), 6 deletions(-) diff --git a/rust/contracts/ide-api/v1.md b/rust/contracts/ide-api/v1.md index 8645cac6..6c714b1a 100644 --- a/rust/contracts/ide-api/v1.md +++ b/rust/contracts/ide-api/v1.md @@ -118,6 +118,8 @@ configuration values, never portable workspace identifiers. | `lithe_operations_list` | none | read | retained Build/Run operations and status, without log bodies | | `lithe_operation_output` | `operationID`, optional opaque `cursor` | read | state, nullable exitCode, bounded output and cursor | | `lithe_operation_stop` | `operationID` | execute | stop request for that exact execution | +| `lithe_sessions_search` | `query`, optional `agent` | read | at most 20 hits with agent, session ID, time and a bounded excerpt; served only when declared | +| `lithe_sessions_read` | `sessionID`, optional `agent`, optional `cursor` | read | one bounded page of the session's recorded messages and its cursor; served only when declared | The catalog has no language- or tool-specific capability. Toolchains and build tools belong to plugins, so an agent reads and sets their options through @@ -174,6 +176,44 @@ silently answers them. Output is retained only as long as its existing IDE outpu slot: replacing a run, removing its tab, or closing the workspace may expire an operation. Callers receive `OPERATION_EXPIRED`, never another run's output. +## Agent sessions + +`lithe_sessions_search` and `lithe_sessions_read` let an MCP client search and read +the local session records of the user's coding agents (API-45). They are the only +tools a host serves only when it declares them: a host that declares no selection +serves every other tool and never these two. A host declares them only while all +three hold: the user enabled the IDE connection for this project, turned on the +separate "Allow MCP clients to search local sessions" switch, and allowed Lithe to +read at least one agent's sessions. The host checks the switch and the per-agent +consent again on every call, so a client that listed the tools earlier is refused +once the user withdraws either one. Turning the switch on or off reopens the +connection with the new declaration; the descriptor path and client configuration +do not change. + +Both tools read only agents whose sessions the user allowed; an `agent` argument +names one of them as `/`, and an agent the user did not allow +returns `PERMISSION_DENIED`. They cover every allowed agent's sessions, not only +sessions started in this project. They search what Lithe has already indexed and +do not start a sync; a session updated after Lithe's last sync appears once the +user next opens the agent history. Remote workspaces return `NOT_AVAILABLE`. + +Search requires every word of `query` and returns at most 20 hits. Each hit has +`agent`, `agentName`, `sessionID`, `atMs` and an `excerpt` of at most 1,024 UTF-8 +bytes re-read from the session file, with `excerptTruncated` when cut and +`changed` when the file no longer holds the indexed text. The excerpts of one +answer total at most 32,768 bytes; `truncated: true` reports that hits were left +out. Read returns `agent`, `agentName`, `sessionID`, `title`, `messages` +(`role`, `text`, `atMs`, optional `toolName`, `truncated` when a message was cut +to 4,096 bytes), `nextCursor`, `hasMore` and `changed`. A page holds at most +65,536 bytes of message text. The cursor is the opaque `nextCursor` of the +previous page of the same session; any other value returns `INVALID_ARGUMENTS`. +A session ID that two allowed agents share returns `INVALID_ARGUMENTS` until +`agent` names one; an unknown session returns `NOT_FOUND`. + +Neither tool returns a file path, working directory, account or credential. The +host logs `agent.records.inspected` with the tool name, the number of hits or +messages and the duration; never the query, session ID or content. + ## Output and errors Operation IDs identify executions, not reusable UI slots. Copying/updating a run @@ -221,3 +261,6 @@ surface; it does not introduce a new plugin marketplace, sandbox or UI extension - Both platforms: configure a plugin Build option, reload, execute a Build task, start a configuration, read incremental output, restart, reject the old ID, stop, revoke, and close the project. Confirm installed resource manifests/hashes remain unchanged. +- Agent sessions: with the switch off or no agent allowed, `tools/list` omits both + session tools and a direct call returns `NOT_SUPPORTED`; with both on, search and + read stay within their bounds, return no path and log no query. diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 1da75087..379f5f78 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -6,6 +6,20 @@ use super::{EventMetadata, FieldMetadata, FieldType, LogLevel, SpanPhase}; /// Sorted, immutable metadata for every expanded catalog event. #[rustfmt::skip] pub static EVENTS: &[EventMetadata] = &[ + EventMetadata { + id: "agent.records.inspected", + channel: "agent", + level: LogLevel::Info, + message: "An MCP client searched or read agent session records", + fields: &[ + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the call took", reason: None }, + FieldMetadata { name: "results", field_type: FieldType::Int, required: true, description: "Hits or messages answered", reason: None }, + FieldMetadata { name: "tool", field_type: FieldType::Token, required: true, description: "IDE tool the MCP client called, lithe_sessions_search or lithe_sessions_read; never the query, session ID or content", reason: None }, + ], + span: None, + rate: 60, + owner: "Lithe", + }, EventMetadata { id: "agent.records.removed", channel: "agent", diff --git a/rust/crates/ide-host/src/catalog.rs b/rust/crates/ide-host/src/catalog.rs index 2f9126db..0f5ecc6e 100644 --- a/rust/crates/ide-host/src/catalog.rs +++ b/rust/crates/ide-host/src/catalog.rs @@ -64,10 +64,22 @@ pub fn exposed_tools(exposure: &[ToolExposure]) -> Result, String> { Ok(result) } +/// Tools a host serves only when it declares them. They read the local session records +/// of the user's coding agents, which a host offers only while the user allows MCP +/// clients to search them, so a host that declares nothing never serves them. +pub const DECLARED_ONLY: [&str; 2] = ["lithe_sessions_search", "lithe_sessions_read"]; + /// The tools a host serves. A host that declares no selection serves the whole -/// catalog, so a platform keeps its tools until it declares what it implements. +/// catalog except [`DECLARED_ONLY`], so a platform keeps its workflow tools until it +/// declares what it implements. pub fn served_tools(exposure: Option<&[ToolExposure]>) -> Result, String> { - exposure.map_or_else(|| Ok(tools()), exposed_tools) + match exposure { + Some(exposure) => exposed_tools(exposure), + None => Ok(tools() + .into_iter() + .filter(|tool| !DECLARED_ONLY.iter().any(|name| tool["name"] == *name)) + .collect()), + } } /// Authorization is granted by the IDE settings UI, never by tool arguments. @@ -112,6 +124,8 @@ pub fn tools() -> Vec { ("lithe_operations_list", "List retained IDE executions with their operationID, state and exit code.", "read", schema(json!({}), &[])), ("lithe_operation_output", "Read bounded output and state for one exact execution. Pass nextCursor to read incrementally. reset=true means output was cleared or truncated; never treats another execution as the same operation.", "read", schema(json!({"operationID":string(),"cursor":string()}), &["operationID"])), ("lithe_operation_stop", "Stop one exact execution. Never stops a newer execution occupying the same UI output slot. Requires execute permission.", "execute", schema(json!({"operationID":string()}), &["operationID"])), + ("lithe_sessions_search", "Search the local session records of the coding agents whose sessions the user lets Lithe read. Every word of the query must appear. Returns at most 20 hits, each with the agent, session ID, time and a bounded excerpt, never a file path. Searches what Lithe has already indexed. Pass agent to search one agent's sessions. Served only while the user allows MCP clients to search local sessions.", "read", schema(json!({"query":string(),"agent":string()}), &["query"])), + ("lithe_sessions_read", "Read the recorded messages of one local agent session, a bounded page at a time, from its start. Pass nextCursor to continue; hasMore=false ends the session. changed=true means the session file no longer holds what Lithe recorded. Pass agent when two agents have the session ID. Served only while the user allows MCP clients to search local sessions.", "read", schema(json!({"sessionID":string(),"agent":string(),"cursor":string()}), &["sessionID"])), ]; definitions.into_iter().map(|(name, description, permission, input)| json!({ "name":name,"description":description,"inputSchema":input, @@ -430,6 +444,61 @@ mod tests { .is_err()); } #[test] + fn session_tools_are_read_only_served_only_when_declared_and_take_no_path() { + let catalog = tools(); + for name in DECLARED_ONLY { + let tool = catalog.iter().find(|tool| tool["name"] == name).unwrap(); + assert_eq!(tool["_meta"]["lithe/permission"], "read"); + assert_eq!(tool["annotations"]["readOnlyHint"], true); + let properties = tool["inputSchema"]["properties"].as_object().unwrap(); + assert!(properties.keys().all(|key| !key.contains("path")), "{name}"); + } + let declared = DECLARED_ONLY.map(|name| ToolExposure { + name: name.into(), + arguments: None, + }); + let none = Permissions::default(); + assert!(validate_exposed( + "lithe_sessions_search", + &json!({"query":"retry"}), + &none, + &declared + ) + .is_ok()); + assert!(validate_exposed( + "lithe_sessions_read", + &json!({"sessionID":"fixture-session","agent":"fixture.plugin/agent","cursor":"0"}), + &none, + &declared + ) + .is_ok()); + // A host that withdraws the declaration, as when the user turns the switch off, + // refuses the call even from a client that listed the tool earlier. + let workflow = [ToolExposure { + name: "lithe_run_list".into(), + arguments: None, + }]; + assert_eq!( + validate_exposed( + "lithe_sessions_search", + &json!({"query":"retry"}), + &none, + &workflow + ) + .unwrap_err()["error"]["code"], + "NOT_SUPPORTED" + ); + for arguments in [ + json!({"query":"retry","limit":500}), + json!({"query":["retry"]}), + json!({"query":"x".repeat(4097)}), + ] { + assert!( + validate_exposed("lithe_sessions_search", &arguments, &none, &declared).is_err() + ); + } + } + #[test] fn output_cursor_detects_clear_and_truncation_and_preserves_unicode() { let first = output_page(json!({"output":"你好\n"}), None); let cursor = first["nextCursor"].as_str().unwrap(); diff --git a/rust/crates/ide-host/src/lib.rs b/rust/crates/ide-host/src/lib.rs index a9ec9b45..88343448 100644 --- a/rust/crates/ide-host/src/lib.rs +++ b/rust/crates/ide-host/src/lib.rs @@ -748,7 +748,7 @@ mod tests { } #[test] - fn a_host_without_a_declaration_opens_and_serves_the_whole_catalog() { + fn a_host_without_a_declaration_opens_and_serves_the_catalog_except_session_tools() { let root = std::env::temp_dir().join(format!("lithe-ide-undeclared-{}", Uuid::new_v4())); std::fs::create_dir_all(&root).unwrap(); let helper = root.join("helper"); @@ -774,15 +774,38 @@ mod tests { serde_json::from_slice(&std::fs::read(connection).unwrap()).unwrap(); assert!(descriptor.get("toolExposure").is_none()); let served: Connection = serde_json::from_value(descriptor).unwrap(); + let tools = catalog::served_tools(served.tool_exposure.as_deref()).unwrap(); + let mut expected = catalog::tools(); + expected.retain(|tool| { + !catalog::DECLARED_ONLY + .iter() + .any(|name| tool["name"] == *name) + }); + assert_eq!(tools, expected); assert_eq!( - catalog::served_tools(served.tool_exposure.as_deref()).unwrap(), - catalog::tools() + tools.len() + catalog::DECLARED_ONLY.len(), + catalog::tools().len() ); let permissions = catalog::Permissions { configure: true, execute: true, }; assert!(catalog::validate_served("lithe_run_list", &json!({}), &permissions, None).is_ok()); + // The session tools read the user's agent sessions; a host that declares + // nothing has not said the user allows it, so they are refused. + for (name, arguments) in [ + ("lithe_sessions_search", json!({"query":"retry"})), + ( + "lithe_sessions_read", + json!({"sessionID":"fixture-session"}), + ), + ] { + assert_eq!( + catalog::validate_served(name, &arguments, &permissions, None).unwrap_err() + ["error"]["code"], + "NOT_SUPPORTED" + ); + } } async fn notification(rx: &mut tokio::sync::mpsc::UnboundedReceiver) -> Option { diff --git a/rust/fixtures/ide-api/calls.json b/rust/fixtures/ide-api/calls.json index 98d0f499..cf687b57 100644 --- a/rust/fixtures/ide-api/calls.json +++ b/rust/fixtures/ide-api/calls.json @@ -38,6 +38,26 @@ "arguments": { "instanceID": "fixture@." } + }, + { + "name": "lithe_sessions_search", + "arguments": { + "query": "retry policy" + } + }, + { + "name": "lithe_sessions_search", + "arguments": { + "query": "重试", + "agent": "fixture.plugin/agent" + } + }, + { + "name": "lithe_sessions_read", + "arguments": { + "sessionID": "fixture-session", + "cursor": "4096" + } } ], "rejected": [ @@ -79,6 +99,32 @@ "arguments": { "sessionID": "ambiguous-output-slot" } + }, + { + "name": "lithe_sessions_search", + "arguments": { + "query": "retry", + "path": "/fixture/sessions" + } + }, + { + "name": "lithe_sessions_search", + "arguments": { + "agent": "fixture.plugin/agent" + } + }, + { + "name": "lithe_sessions_read", + "arguments": { + "agent": "fixture.plugin/agent" + } + }, + { + "name": "lithe_sessions_read", + "arguments": { + "sessionID": "fixture-session", + "limit": 500 + } } ] } diff --git a/rust/fixtures/ide-api/host-tool-exposure.json b/rust/fixtures/ide-api/host-tool-exposure.json index 39fc5442..a7d7a00b 100644 --- a/rust/fixtures/ide-api/host-tool-exposure.json +++ b/rust/fixtures/ide-api/host-tool-exposure.json @@ -33,6 +33,12 @@ }, { "name": "lithe_build_execute" + }, + { + "name": "lithe_sessions_search" + }, + { + "name": "lithe_sessions_read" } ], "windows": [ @@ -68,6 +74,12 @@ }, { "name": "lithe_build_execute" + }, + { + "name": "lithe_sessions_search" + }, + { + "name": "lithe_sessions_read" } ] } diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 5ec47cd8..6c88e27e 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -95,6 +95,19 @@ }, "rate": 60, "owner": "lithe-core" + }, + { + "id": "agent.records.inspected", + "channel": "agent", + "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"} + }, + "rate": 60, + "owner": "Lithe" } ] } diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index c1ae84f3..5391102a 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。同一 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。没有新增宿主方法、通知或错误码。 +- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。同一 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 连接的工具,不是插件宿主方法。没有新增宿主方法、通知或错误码。 - [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 From 1cfc556ea66649b7e072533d6e0e4f5128aacaee Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 11:13:03 +0800 Subject: [PATCH 6/7] =?UTF-8?q?docs(ide-api):=20=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E6=B8=B8=E6=A0=87=E5=8F=AA=E5=9C=A8=E5=8F=91?= =?UTF-8?q?=E5=87=BA=E5=AE=83=E7=9A=84=E8=BF=9E=E6=8E=A5=E4=B8=8A=E6=9C=89?= =?UTF-8?q?=E6=95=88=EF=BC=8C=E8=A1=A5=20tooLong=E3=80=81omitted=20?= =?UTF-8?q?=E5=92=8C=E6=B6=88=E6=81=AF=E6=9D=A1=E6=95=B0=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 游标用连接的密钥签名,重连后旧游标返回 INVALID_ARGUMENTS,从头读取 - 页面最多 65,536 字节文字、2,000 条消息;tooLong 表示单行超过 16 MiB;omitted 表示为长行放大的一次读取里放不下的消息条数 - lithe_sessions_read 的工具说明写明游标只在本连接有效 --- rust/contracts/ide-api/v1.md | 22 ++++++++++++++++------ rust/crates/ide-host/src/catalog.rs | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/rust/contracts/ide-api/v1.md b/rust/contracts/ide-api/v1.md index 6c714b1a..2f63a8ce 100644 --- a/rust/contracts/ide-api/v1.md +++ b/rust/contracts/ide-api/v1.md @@ -203,12 +203,22 @@ bytes re-read from the session file, with `excerptTruncated` when cut and `changed` when the file no longer holds the indexed text. The excerpts of one answer total at most 32,768 bytes; `truncated: true` reports that hits were left out. Read returns `agent`, `agentName`, `sessionID`, `title`, `messages` -(`role`, `text`, `atMs`, optional `toolName`, `truncated` when a message was cut -to 4,096 bytes), `nextCursor`, `hasMore` and `changed`. A page holds at most -65,536 bytes of message text. The cursor is the opaque `nextCursor` of the -previous page of the same session; any other value returns `INVALID_ARGUMENTS`. -A session ID that two allowed agents share returns `INVALID_ARGUMENTS` until -`agent` names one; an unknown session returns `NOT_FOUND`. +(`role`, `text`, `atMs`, optional `toolName` of at most 128 bytes, `truncated` +when a message was cut to 4,096 bytes or by the page bound), `hasMore`, +`changed` and, while `hasMore` is true, `nextCursor`. A page holds at most +65,536 bytes of message text and at most 2,000 messages. `tooLong: true` reports +a record line longer than the 16 MiB Lithe reads at once: the page ends before +it and `hasMore` is false. `omitted: n` reports that the page met its bound +inside one read made larger for a long line and left out the `n` messages after +it; the next page starts after them. + +The cursor is the opaque `nextCursor` of the previous page of the same session, +answered on the same connection. The host signs it with a key of the +connection, so a cursor from another connection, including the one before a +reopen, returns `INVALID_ARGUMENTS`, as does any other value; read the session +again from its start without a cursor. A session ID that two allowed agents +share returns `INVALID_ARGUMENTS` until `agent` names one; an unknown session +returns `NOT_FOUND`. Neither tool returns a file path, working directory, account or credential. The host logs `agent.records.inspected` with the tool name, the number of hits or diff --git a/rust/crates/ide-host/src/catalog.rs b/rust/crates/ide-host/src/catalog.rs index 0f5ecc6e..64bb10a7 100644 --- a/rust/crates/ide-host/src/catalog.rs +++ b/rust/crates/ide-host/src/catalog.rs @@ -125,7 +125,7 @@ pub fn tools() -> Vec { ("lithe_operation_output", "Read bounded output and state for one exact execution. Pass nextCursor to read incrementally. reset=true means output was cleared or truncated; never treats another execution as the same operation.", "read", schema(json!({"operationID":string(),"cursor":string()}), &["operationID"])), ("lithe_operation_stop", "Stop one exact execution. Never stops a newer execution occupying the same UI output slot. Requires execute permission.", "execute", schema(json!({"operationID":string()}), &["operationID"])), ("lithe_sessions_search", "Search the local session records of the coding agents whose sessions the user lets Lithe read. Every word of the query must appear. Returns at most 20 hits, each with the agent, session ID, time and a bounded excerpt, never a file path. Searches what Lithe has already indexed. Pass agent to search one agent's sessions. Served only while the user allows MCP clients to search local sessions.", "read", schema(json!({"query":string(),"agent":string()}), &["query"])), - ("lithe_sessions_read", "Read the recorded messages of one local agent session, a bounded page at a time, from its start. Pass nextCursor to continue; hasMore=false ends the session. changed=true means the session file no longer holds what Lithe recorded. Pass agent when two agents have the session ID. Served only while the user allows MCP clients to search local sessions.", "read", schema(json!({"sessionID":string(),"agent":string(),"cursor":string()}), &["sessionID"])), + ("lithe_sessions_read", "Read the recorded messages of one local agent session, a bounded page at a time, from its start. Pass nextCursor to continue; it is valid only on this connection, so after a reconnect read from the start. hasMore=false ends the session. changed=true means the session file no longer holds what Lithe recorded. Pass agent when two agents have the session ID. Served only while the user allows MCP clients to search local sessions.", "read", schema(json!({"sessionID":string(),"agent":string(),"cursor":string()}), &["sessionID"])), ]; definitions.into_iter().map(|(name, description, permission, input)| json!({ "name":name,"description":description,"inputSchema":input, From b801e8fcc51146ee0f891ba9d89247c7827de741 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 11:51:21 +0800 Subject: [PATCH 7/7] =?UTF-8?q?docs(agents):=20=E5=86=99=E6=98=8E=20scan?= =?UTF-8?q?=20=E4=B9=8B=E5=90=8E=E7=9A=84=E6=89=AB=E6=8F=8F=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E7=94=A8=E5=90=8C=E4=B8=80=E4=B8=AA=20key=20=E9=87=8D?= =?UTF-8?q?=E6=8A=A5=E8=B0=83=E7=94=A8=E5=B9=B6=E6=9B=BF=E6=8D=A2=E5=85=88?= =?UTF-8?q?=E6=8A=A5=E7=9A=84=EF=BC=8C=E8=A1=A5=20store=20=E6=B5=8B?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/crates/agent-sessions/src/tests/store.rs | 35 +++++++++++++++++++ shared/plugins/contract/v1/README.md | 5 ++- .../plugins/reference/protocol-changelog.md | 2 +- 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs index 166e283d..d90f4f56 100644 --- a/rust/crates/agent-sessions/src/tests/store.rs +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -170,6 +170,41 @@ fn appended_lines_are_read_from_the_cursor() { ); } +#[test] +fn a_later_report_of_a_call_replaces_it() { + let mut fixture = Fixture::new("re-report"); + let path = fixture.file("a.jsonl"); + append( + &path, + &(session_line("s1", "/work/app", 1_000) + &call_line("c1", 1_100, "model-a", 10, 20)), + ); + fixture.sync(std::slice::from_ref(&path)); + let first_size = size(&path); + + // A parser that learns a call's timing only later reports the call + // again under its key, in the chunk it learned it from. + let timed = json!({ "type": "call", "key": "c1", "at": 1_100, "model": "model-a", + "input": 10, "output": 20, "firstTokenMs": 500, "durationMs": 2_000 }); + append(&path, &format!("{timed}\n")); + let report = fixture.sync(std::slice::from_ref(&path)); + assert_eq!((report.files_read, report.files_failed), (1, 0)); + let entries = fixture.calls(); + assert_eq!(keys(&entries), ["c1"]); + let call = &entries[0].call; + assert_eq!( + (call.first_token_ms, call.duration_ms), + (Some(500), Some(2_000)) + ); + assert_eq!(call.tokens.output, Some(20)); + assert_eq!( + call.range, + ByteRange { + start: first_size, + end: size(&path) + } + ); +} + #[test] fn rewritten_and_truncated_files_are_read_again() { let mut fixture = Fixture::new("rewrite"); diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index b0420b4a..2721aacc 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3988,7 +3988,10 @@ state?}` and has 30 seconds. It answers: requestedModel?, model?, contextWindow?, effort?, provider?, tokens: {input?, output?, cacheRead?, cacheWrite5m?, cacheWrite1h?, reasoning?}, firstTokenMs?, durationMs?, compaction, requestID?, errorCategory?, range: - {start, end}}`, `key` unique in the file; + {start, end}}`, `key` unique in the file. A later scan of the file may + report a call again under its key, with a range in its own chunk, and the + later report replaces the earlier one: a backend that learns a call's + timing only when the turn ends reports the call again then; - `spans`: `{sessionID, atMs?, range, text}`, the searchable text, of which Core indexes at most 256 KiB per span; - `state`: at most 64 KiB the next scan of the file receives, never diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 5391102a..bc51d9bc 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。同一 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 连接的工具,不是插件宿主方法。没有新增宿主方法、通知或错误码。 +- [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):`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 连接的工具,不是插件宿主方法。没有新增宿主方法、通知或错误码。 - [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。