diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2a32a3cd..34d8b178 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -492,7 +492,7 @@ 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, or find one by its ID | +| `agentSessions.list` | List a page of recorded agent sessions by directory and order, with their activity and the whole list's counts, or find one by its ID | | `agentSessions.search` | Search recorded agent session text | | `agentSessions.read` | Read one recorded range as messages and where the next page starts | | `agentSessions.stats` | Sum recorded agent usage with the latest rate limits | diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 53fd5581..0eadbeed 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -22,7 +22,8 @@ use lithe_agent_sessions::pricing::PriceTable; 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, + SessionOrder, SessionParser, SessionSource, SessionStore, MAX_FILTER_DIRECTORIES, + MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, }; use lithe_lsp_engine::agent_host::AgentHostFailure; use lithe_plugin_agents::SessionSourceDeclaration; @@ -54,6 +55,9 @@ const MAX_MESSAGE_TEXT_BYTES: usize = 1024 * 1024; /// Longest range `lithe/host/agents/usage` sums, in days. const MAX_USAGE_DAYS: i64 = 366; +/// Longest directory `agentSessions.list`'s `cwdUnder` takes, in bytes. +const MAX_FILTER_DIRECTORY_BYTES: usize = 4096; + /// Largest `rate-limits.json` Core loads. const MAX_RATE_FILE_BYTES: u64 = 1024 * 1024; @@ -340,9 +344,17 @@ impl Records { Ok(json!({ "files": files })) } - /// `agentSessions.list`: the sessions of the readable agents, newest - /// first, with their titles when asked. + /// `agentSessions.list`: a page of the readable agents' sessions, most + /// recently active or started first, with their titles and the counts of + /// the whole list when asked. pub fn list(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize, Default, PartialEq, Eq)] + #[serde(rename_all = "camelCase")] + enum ListOrder { + #[default] + Updated, + Started, + } #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ListRequest { @@ -351,32 +363,67 @@ impl Records { #[serde(default)] cwd: Option, #[serde(default)] + cwd_under: Vec, + #[serde(default)] active_since_ms: Option, #[serde(rename = "sessionID", default)] session_id: Option, #[serde(default)] + order: ListOrder, + #[serde(default)] offset: u64, #[serde(default)] limit: Option, #[serde(default)] titles: bool, + #[serde(default)] + counts: bool, } let request: ListRequest = crate::decode(payload)?; + if request.cwd_under.len() > MAX_FILTER_DIRECTORIES + || request.cwd_under.iter().any(|directory| { + directory.is_empty() + || directory.len() > MAX_FILTER_DIRECTORY_BYTES + || directory.chars().any(char::is_control) + }) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid agent command payload: cwdUnder", + ) + .with_details("agents.invalidPayload")); + } let Some(agents) = allowed_agents(runtime, request.agents) else { - return Ok(json!({ "sessions": [] })); + let mut answer = json!({ "sessions": [] }); + if request.counts { + answer["total"] = json!(0); + answer["groups"] = json!([]); + answer["groupsTruncated"] = json!(false); + } + return Ok(answer); }; let filter = SessionFilter { agents, cwd: request.cwd, + cwd_under: request.cwd_under, active_since_ms: request.active_since_ms, session_id: request.session_id, + order: match request.order { + ListOrder::Updated => SessionOrder::Updated, + ListOrder::Started => SessionOrder::Started, + }, offset: request.offset, limit: request.limit.unwrap_or(100).clamp(1, MAX_SESSIONS_PAGE), }; - let (entries, title_bytes) = { + let (entries, title_bytes, counts) = { let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; let entries = store.sessions(&filter)?; + let counts = if request.counts { + Some(store.session_counts(&filter)?) + } else { + None + }; let mut title_bytes = Vec::with_capacity(entries.len()); for entry in &entries { let bytes = match (request.titles, entry.title_range) { @@ -388,7 +435,7 @@ impl Records { }; title_bytes.push(bytes); } - (entries, title_bytes) + (entries, title_bytes, counts) }; let mut titles: Vec> = vec![None; entries.len()]; @@ -455,7 +502,13 @@ impl Records { value }) .collect(); - Ok(json!({ "sessions": sessions })) + let mut answer = json!({ "sessions": sessions }); + if let Some(counts) = counts { + answer["total"] = json!(counts.total); + answer["groups"] = serde_json::to_value(&counts.groups).unwrap_or_else(|_| json!([])); + answer["groupsTruncated"] = json!(counts.groups_truncated); + } + Ok(answer) } /// `agentSessions.search`: where the readable agents' sessions contain diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 1c49327f..f4bd5117 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1232,6 +1232,64 @@ fn write_session_file(harness: &Harness, now: i64) -> PathBuf { path } +#[test] +fn records_list_filters_under_directories_counts_and_describes_activity() { + let harness = Harness::new("records-list", ALL_GRANTS); + let now = crate::now_ms(); + write_session_file(&harness, now); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + + let answer = harness.run( + "agentSessions.list", + json!({ "cwdUnder": ["/work/"], "order": "started", "counts": true, "limit": 1 }), + ); + assert_eq!(answer["total"], 1, "{answer}"); + assert_eq!(answer["groupsTruncated"], false, "{answer}"); + assert_eq!( + answer["groups"], + json!([{ "cwd": "/work/project", "count": 1, "updatedAtMs": now }]) + ); + let session = &answer["sessions"][0]; + assert_eq!(session["messageCount"], 1, "{answer}"); + assert_eq!(session["subagentCount"], 0, "{answer}"); + assert_eq!(session["model"], "sample-model", "{answer}"); + // The last message's range reads back the message itself. + let read = harness.run( + "agentSessions.read", + json!({ "agent": AGENT_KEY, "path": session["path"], "range": session["lastMessageRange"] }), + ); + assert_eq!(read["messages"][0]["text"], "hello from the user", "{read}"); + + // Without `counts` the answer keeps its old shape; a directory that holds + // none of the sessions lists none and counts none. + let plain = harness.run("agentSessions.list", json!({})); + assert!(plain.get("total").is_none(), "{plain}"); + let elsewhere = harness.run( + "agentSessions.list", + json!({ "cwdUnder": ["/work/project-two"], "counts": true }), + ); + assert_eq!( + (elsewhere["sessions"].clone(), elsewhere["total"].clone()), + (json!([]), json!(0)) + ); + + for payload in [ + json!({ "cwdUnder": [""] }), + json!({ "cwdUnder": ["/work\nproject"] }), + json!({ "cwdUnder": ["/w".repeat(2_049)] }), + json!({ "cwdUnder": vec!["/work"; 65] }), + json!({ "order": "title" }), + ] { + assert_eq!( + harness.refused("agentSessions.list", payload), + "agents.invalidPayload" + ); + } +} + #[test] fn records_sync_list_search_read_and_sum_through_the_plugin() { let harness = Harness::new("records", ALL_GRANTS); diff --git a/rust/crates/agent-sessions/src/lib.rs b/rust/crates/agent-sessions/src/lib.rs index 9fda99fb..e4be4c46 100644 --- a/rust/crates/agent-sessions/src/lib.rs +++ b/rust/crates/agent-sessions/src/lib.rs @@ -39,8 +39,9 @@ pub use model::{ ByteRange, CallRecord, IndexSpan, ScanChunk, ScanOutput, SessionMeta, SessionParser, Tokens, }; pub use store::{ - database_file_name, CallEntry, CallFilter, FileFailure, SearchHit, SearchQuery, SessionEntry, - SessionFilter, SessionStore, SyncReport, MAX_ID_BYTES, MAX_INDEXED_SPAN_BYTES, MAX_LABEL_BYTES, - MAX_READ_BYTES, MAX_RECORDS_PER_CHUNK, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, MAX_STATE_BYTES, + database_file_name, CallEntry, CallFilter, FileFailure, SearchHit, SearchQuery, SessionCounts, + SessionEntry, SessionFilter, SessionGroup, SessionOrder, SessionStore, SyncReport, + MAX_FILTER_DIRECTORIES, MAX_ID_BYTES, MAX_INDEXED_SPAN_BYTES, MAX_LABEL_BYTES, MAX_READ_BYTES, + MAX_RECORDS_PER_CHUNK, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, MAX_SESSION_GROUPS, MAX_STATE_BYTES, SCHEMA_VERSION, }; diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs index c637e356..832e149b 100644 --- a/rust/crates/agent-sessions/src/store.rs +++ b/rust/crates/agent-sessions/src/store.rs @@ -57,6 +57,12 @@ pub const MAX_SEARCH_HITS: usize = 200; /// Most sessions one page of [`SessionStore::sessions`] lists. pub const MAX_SESSIONS_PAGE: usize = 500; +/// Most directories one [`SessionFilter::cwd_under`] names. +pub const MAX_FILTER_DIRECTORIES: usize = 64; + +/// Most working directories [`SessionStore::session_counts`] counts apart. +pub const MAX_SESSION_GROUPS: usize = 500; + /// Most bytes [`SessionStore::read_range`] returns at once. pub const MAX_READ_BYTES: u64 = 16 * 1024 * 1024; @@ -237,16 +243,62 @@ pub struct SessionFilter { pub agents: Vec, /// Only sessions that ran in this working directory. pub cwd: Option, + /// Only sessions that ran in one of these directories or below one; empty + /// does not filter. A directory matches its own path and the paths that + /// continue it after a `/` or `\`; trailing separators are ignored. At + /// most [`MAX_FILTER_DIRECTORIES`]. + pub cwd_under: Vec, /// 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, + /// Which sessions come first. + pub order: SessionOrder, /// Sessions to skip, for the next page. pub offset: u64, /// Sessions to list, at most [`MAX_SESSIONS_PAGE`]. pub limit: usize, } +/// The order of [`SessionStore::sessions`]. Sessions without the time come +/// last; ties go by agent and session ID. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum SessionOrder { + /// Most recently active first: by the latest change, or the start when no + /// file records a change. + #[default] + Updated, + /// Most recently started first. + Started, +} + +/// How many sessions a [`SessionFilter`] selects, ignoring its page. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionCounts { + /// Every session the filter selects. + pub total: u64, + /// The sessions of each working directory, most recently active first, at + /// most [`MAX_SESSION_GROUPS`]. + pub groups: Vec, + /// Whether directories were left out of `groups`. + pub groups_truncated: bool, +} + +/// The sessions of one working directory. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionGroup { + /// The directory; absent for sessions whose directory is not known. + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// Sessions that ran in it. + pub count: u64, + /// The latest activity of those sessions, in Unix milliseconds. + #[serde(skip_serializing_if = "Option::is_none")] + pub updated_at_ms: Option, +} + /// A session, merged from every file that describes it. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] @@ -283,6 +335,56 @@ pub struct SessionEntry { /// 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, + /// The session's messages in `path`: the prompts and replies its plugin + /// reported as searchable text. Tool output and other files' copies are + /// not counted. + pub message_count: u64, + /// Threads besides the main one that made model calls in the session, in + /// any of its files: the agent's subagents. + pub subagent_count: u64, + /// The model of the session's latest call: the main thread's when it made + /// one, otherwise a subagent's; the requested model when the response + /// named none. + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, + /// The bytes of `path` that hold the session's last message. + #[serde(skip_serializing_if = "Option::is_none")] + pub last_message_range: Option, +} + +/// The sessions a [`SessionFilter`] selects, before its order and page, one +/// row per session: the copy the other fields come from. Parameters: `?1` +/// agents, `?2` cwd, `?3` active since, `?4` session ID, `?5` the +/// directories of `cwd_under`. +macro_rules! selected_sessions { + () => { + "WITH ranked AS ( + 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 + ) AS copy_rank, + COUNT(*) OVER whole AS file_count, + 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))) + AND (?4 IS NULL OR s.session_id = ?4) + WINDOW whole AS (PARTITION BY f.agent, s.session_id) + ), + selected AS ( + SELECT * FROM ranked + WHERE copy_rank = 1 + AND (?2 IS NULL OR cwd = ?2) + AND (?3 IS NULL OR COALESCE(last_updated_ms, first_started_ms) >= ?3) + AND (json_array_length(?5) = 0 + OR EXISTS (SELECT 1 FROM json_each(?5) d + WHERE cwd = d.value + OR substr(cwd, 1, length(d.value) + 1) + IN (d.value || '/', d.value || char(92)))) + )" + }; } /// A full-text search. @@ -504,68 +606,176 @@ impl SessionStore { Ok(visited) } - /// Lists sessions, most recently active first. + /// Lists a page of sessions in the filter's order. pub fn sessions(&self, filter: &SessionFilter) -> Result, CoreError> { - const SQL: &str = " - WITH ranked AS ( - 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 - ) AS copy_rank, - COUNT(*) OVER whole AS file_count, - 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))) - AND (?6 IS NULL OR s.session_id = ?6) - WINDOW whole AS (PARTITION BY f.agent, s.session_id) - ) + const SQL: &str = concat!( + selected_sessions!(), + " SELECT agent, session_id, path, file_count, parent_session_id, cwd, 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) - AND (?3 IS NULL OR COALESCE(last_updated_ms, first_started_ms) >= ?3) - ORDER BY COALESCE(last_updated_ms, first_started_ms) DESC NULLS LAST, + cursor_offset, file_id + FROM selected + ORDER BY CASE WHEN ?6 = 1 THEN first_started_ms + ELSE COALESCE(last_updated_ms, first_started_ms) END DESC NULLS LAST, agent, session_id - LIMIT ?4 OFFSET ?5"; + LIMIT ?7 OFFSET ?8" + ); + let list = |error| sql_error("Could not list agent sessions", error); let limit = filter.limit.min(MAX_SESSIONS_PAGE); - let mut statement = self + let mut entries = { + let mut statement = self.connection.prepare_cached(SQL).map_err(list)?; + let rows = statement + .query_map( + params![ + agents_json(&filter.agents)?, + filter.cwd, + filter.active_since_ms, + filter.session_id, + directories_json(&filter.cwd_under)?, + i64::from(filter.order == SessionOrder::Started), + limit, + filter.offset + ], + |row| { + let entry = SessionEntry { + agent: row.get(0)?, + session_id: row.get(1)?, + path: row.get(2)?, + file_count: row.get(3)?, + parent_session_id: row.get(4)?, + cwd: row.get(5)?, + started_at_ms: row.get(6)?, + 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)?, + message_count: 0, + subagent_count: 0, + model: None, + last_message_range: None, + }; + Ok((row.get::<_, i64>(12)?, entry)) + }, + ) + .map_err(list)?; + rows.collect::, _>>().map_err(list)? + }; + for (file_id, entry) in &mut entries { + cancellation::check()?; + self.describe_activity(*file_id, entry).map_err(list)?; + } + Ok(entries.into_iter().map(|(_, entry)| entry).collect()) + } + + /// Fills in the messages, subagents and model of a listed session. + fn describe_activity(&self, file_id: i64, entry: &mut SessionEntry) -> rusqlite::Result<()> { + // The count is taken over every span before the limit keeps the last. + const MESSAGES: &str = " + SELECT range_start, range_end, COUNT(*) OVER () + FROM spans WHERE file_id = ?1 AND session_id = ?2 + ORDER BY range_start DESC LIMIT 1"; + // Every file that records calls of the session has a row in sessions. + const THREADS: &str = " + SELECT COUNT(DISTINCT c.thread_id) + FROM sessions s + JOIN files f ON f.id = s.file_id + JOIN calls c ON c.file_id = s.file_id AND c.session_id = s.session_id + WHERE s.session_id = ?1 AND f.agent = ?2"; + const MODEL: &str = " + SELECT COALESCE(c.model, c.requested_model) + FROM sessions s + JOIN files f ON f.id = s.file_id + JOIN calls c ON c.file_id = s.file_id AND c.session_id = s.session_id + WHERE s.session_id = ?1 AND f.agent = ?2 + AND COALESCE(c.model, c.requested_model) IS NOT NULL + ORDER BY c.thread_id IS NOT NULL, c.started_at_ms DESC, c.call_key DESC + LIMIT 1"; + let last = self .connection - .prepare_cached(SQL) - .map_err(|error| sql_error("Could not list agent sessions", error))?; + .prepare_cached(MESSAGES)? + .query_row(params![file_id, entry.session_id], |row| { + Ok(( + row.get::<_, u64>(0)?, + row.get::<_, u64>(1)?, + row.get::<_, u64>(2)?, + )) + }) + .optional()?; + if let Some((start, end, count)) = last { + entry.message_count = count; + entry.last_message_range = Some(ByteRange { start, end }); + } + entry.subagent_count = self + .connection + .prepare_cached(THREADS)? + .query_row(params![entry.session_id, entry.agent], |row| row.get(0))?; + entry.model = self + .connection + .prepare_cached(MODEL)? + .query_row(params![entry.session_id, entry.agent], |row| row.get(0)) + .optional()?; + Ok(()) + } + + /// Counts the sessions `filter` selects, in all and by working directory, + /// ignoring its order and page. + pub fn session_counts(&self, filter: &SessionFilter) -> Result { + const TOTAL: &str = concat!(selected_sessions!(), " SELECT COUNT(*) FROM selected"); + const GROUPS: &str = concat!( + selected_sessions!(), + " + SELECT cwd, COUNT(*), MAX(COALESCE(last_updated_ms, first_started_ms)) AS active + FROM selected + GROUP BY cwd + ORDER BY active DESC NULLS LAST, cwd + LIMIT ?6" + ); + let count = |error| sql_error("Could not count agent sessions", error); + let agents = agents_json(&filter.agents)?; + let directories = directories_json(&filter.cwd_under)?; + let total = self + .connection + .prepare_cached(TOTAL) + .map_err(count)? + .query_row( + params![ + agents, + filter.cwd, + filter.active_since_ms, + filter.session_id, + directories + ], + |row| row.get(0), + ) + .map_err(count)?; + let mut statement = self.connection.prepare_cached(GROUPS).map_err(count)?; let rows = statement .query_map( params![ - agents_json(&filter.agents)?, + agents, filter.cwd, filter.active_since_ms, - limit, - filter.offset, - filter.session_id + filter.session_id, + directories, + MAX_SESSION_GROUPS + 1 ], |row| { - Ok(SessionEntry { - agent: row.get(0)?, - session_id: row.get(1)?, - path: row.get(2)?, - file_count: row.get(3)?, - parent_session_id: row.get(4)?, - cwd: row.get(5)?, - started_at_ms: row.get(6)?, - 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)?, + Ok(SessionGroup { + cwd: row.get(0)?, + count: row.get(1)?, + updated_at_ms: row.get(2)?, }) }, ) - .map_err(|error| sql_error("Could not list agent sessions", error))?; - rows.collect::, _>>() - .map_err(|error| sql_error("Could not list agent sessions", error)) + .map_err(count)?; + let mut groups = rows.collect::, _>>().map_err(count)?; + let groups_truncated = groups.len() > MAX_SESSION_GROUPS; + groups.truncate(MAX_SESSION_GROUPS); + Ok(SessionCounts { + total, + groups, + groups_truncated, + }) } /// Finds the spans that contain every term of `query.text`, newest first. @@ -1331,6 +1541,24 @@ fn agents_json(agents: &[String]) -> Result { .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "The agent filter is not valid")) } +/// The directories of [`SessionFilter::cwd_under`] as a JSON array, without +/// trailing separators: a root becomes the empty string, which every +/// absolute path continues after its separator. +fn directories_json(directories: &[String]) -> Result { + if directories.len() > MAX_FILTER_DIRECTORIES { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Too many directories in one session filter", + )); + } + let trimmed: Vec<&str> = directories + .iter() + .map(|directory| directory.trim_end_matches(['/', '\\'])) + .collect(); + serde_json::to_string(&trimmed) + .map_err(|_| CoreError::new(ErrorCode::Unknown, "Could not encode the directory filter")) +} + fn optional_range(start: Option, end: Option) -> Option { start.zip(end).map(|(start, end)| ByteRange { start, end }) } diff --git a/rust/crates/agent-sessions/src/tests/mod.rs b/rust/crates/agent-sessions/src/tests/mod.rs index eb6ce69f..c7b6a21a 100644 --- a/rust/crates/agent-sessions/src/tests/mod.rs +++ b/rust/crates/agent-sessions/src/tests/mod.rs @@ -102,7 +102,10 @@ impl SessionParser for LinesParser { parent_session_id: text("parent"), cwd: text("cwd"), started_at_ms: value.get("at").and_then(Value::as_i64), - updated_at_ms: value.get("at").and_then(Value::as_i64), + updated_at_ms: value + .get("updated") + .or_else(|| value.get("at")) + .and_then(Value::as_i64), agent_version: text("version"), title_range: value.get("title").map(|_| range), }); @@ -113,7 +116,7 @@ impl SessionParser for LinesParser { Some("call") => output.calls.push(CallRecord { key: text("key").expect("call key"), session_id: session.clone().expect("a session line first"), - thread_id: None, + thread_id: text("thread"), started_at_ms: value.get("at").and_then(Value::as_i64).expect("call time"), requested_model: text("requested"), model: text("model"), diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs index d90f4f56..8fbdfc02 100644 --- a/rust/crates/agent-sessions/src/tests/store.rs +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -10,8 +10,8 @@ use super::{append, call_line, session_line, text_line, LinesParser, TempDir}; use crate::ingest::ChunkLimits; use crate::model::ByteRange; use crate::store::{ - database_file_name, CallEntry, CallFilter, SearchHit, SearchQuery, SessionEntry, SessionFilter, - SessionStore, SyncReport, + database_file_name, CallEntry, CallFilter, SearchHit, SearchQuery, SessionCounts, SessionEntry, + SessionFilter, SessionGroup, SessionOrder, SessionStore, SyncReport, MAX_FILTER_DIRECTORIES, }; use crate::{MAX_CHUNK_BYTES, MAX_LINE_BYTES}; @@ -871,3 +871,205 @@ fn old_and_damaged_caches_are_rebuilt() { sync_as(&mut store, AGENT, &[session]); assert_eq!(keys(&calls(&store, &CallFilter::default())), ["c1"]); } + +fn thread_call_line(key: &str, at: i64, model: &str, thread: &str) -> String { + format!( + "{}\n", + json!({ "type": "call", "key": key, "at": at, "model": model, "thread": thread }) + ) +} + +fn session_at(id: &str, cwd: Option<&str>, started: i64, updated: i64) -> String { + let mut line = json!({ "type": "session", "id": id, "at": started, "updated": updated }); + if let Some(cwd) = cwd { + line["cwd"] = json!(cwd); + } + format!("{line}\n") +} + +#[test] +fn listed_sessions_count_messages_and_subagents_and_name_the_main_model() { + let mut fixture = Fixture::new("activity"); + let main = fixture.file("a.jsonl"); + let subagent = fixture.file("b.jsonl"); + let only_subagents = fixture.file("c.jsonl"); + let quiet = fixture.file("d.jsonl"); + let opening = session_line("s1", "/w", 1_000) + + &text_line(1_000, "the prompt") + + &call_line("c1", 1_100, "main-old", 1, 2) + + &call_line("c2", 1_300, "main-new", 1, 2); + let reply = text_line(1_350, "the reply"); + append( + &main, + &(opening.clone() + &reply + &thread_call_line("c3", 1_400, "sub-model", "t1")), + ); + // A subagent's own file: its calls and text belong to the session, but + // only the session's own file counts messages. + append( + &subagent, + &(use_line("s1") + + &thread_call_line("c4", 1_500, "sub-model", "t2") + + &thread_call_line("c5", 1_600, "sub-model", "t2") + + &text_line(1_600, "the subagent's report")), + ); + append( + &only_subagents, + &(session_line("s2", "/w", 900) + &thread_call_line("c6", 950, "sub-only", "t3")), + ); + append(&quiet, &session_line("s3", "/w", 800)); + fixture.sync(&[main.clone(), subagent, only_subagents, quiet]); + + let listed = sessions(&fixture.store, every_session()); + assert_eq!(session_ids(&listed), ["s1", "s2", "s3"]); + let busy = &listed[0]; + assert_eq!(busy.path, path_text(&main)); + assert_eq!(busy.message_count, 2); + let start = opening.len() as u64; + assert_eq!( + busy.last_message_range, + Some(ByteRange { + start, + end: start + reply.len() as u64 + }) + ); + assert_eq!(busy.subagent_count, 2); + // The main thread's latest call names the model, though a subagent + // called later. + assert_eq!(busy.model.as_deref(), Some("main-new")); + + assert_eq!(listed[1].model.as_deref(), Some("sub-only")); + assert_eq!(listed[1].subagent_count, 1); + assert_eq!(listed[1].message_count, 0); + + let quiet = &listed[2]; + assert_eq!( + ( + quiet.message_count, + quiet.subagent_count, + quiet.model.as_deref(), + quiet.last_message_range + ), + (0, 0, None, None) + ); + let serialized = serde_json::to_value(busy).expect("serialize the entry"); + assert_eq!(serialized["messageCount"], 2); + assert_eq!(serialized["subagentCount"], 2); + assert_eq!(serialized["model"], "main-new"); + assert_eq!(serialized["lastMessageRange"]["start"], start); + let serialized = serde_json::to_value(quiet).expect("serialize the entry"); + assert!(serialized.get("model").is_none()); + assert!(serialized.get("lastMessageRange").is_none()); +} + +#[test] +fn sessions_filter_under_directories_and_order_by_start() { + let mut fixture = Fixture::new("under"); + let files: Vec = [ + ("s1", Some("/w"), 1_000, 9_000), + ("s2", Some("/w/app"), 3_000, 3_000), + ("s3", Some("/wx"), 4_000, 4_000), + ("s4", Some(r"C:\w\y"), 5_000, 5_000), + ("s5", None, 6_000, 6_000), + ] + .iter() + .map(|(id, cwd, started, updated)| { + let path = fixture.file(&format!("{id}.jsonl")); + append(&path, &session_at(id, *cwd, *started, *updated)); + path + }) + .collect(); + fixture.sync(&files); + + let only = |filter: SessionFilter| session_ids(&sessions(&fixture.store, filter)).join(","); + let under = |directories: &[&str]| SessionFilter { + cwd_under: directories + .iter() + .map(|directory| directory.to_string()) + .collect(), + ..every_session() + }; + // A directory matches itself and what lies below it, not a sibling that + // shares its start; a trailing separator changes nothing. + assert_eq!(only(under(&["/w"])), "s1,s2"); + assert_eq!(only(under(&["/w/"])), "s1,s2"); + assert_eq!(only(under(&["/w/app", r"C:\w"])), "s4,s2"); + assert_eq!(only(under(&[r"C:\"])), "s4"); + // A root holds every path below it; sessions without a directory are + // under none. + assert_eq!(only(under(&["/"])), "s1,s3,s2"); + assert_eq!(only(under(&["/elsewhere"])), ""); + assert_eq!(only(every_session()), "s1,s5,s4,s3,s2"); + assert_eq!( + only(SessionFilter { + order: SessionOrder::Started, + ..every_session() + }), + "s5,s4,s3,s2,s1" + ); + + let too_many = SessionFilter { + cwd_under: vec!["/w".to_string(); MAX_FILTER_DIRECTORIES + 1], + ..every_session() + }; + let error = fixture + .store + .sessions(&too_many) + .expect_err("too many directories"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); +} + +#[test] +fn session_counts_ignore_the_page_and_group_by_directory() { + let mut fixture = Fixture::new("counts"); + let files: Vec = [ + ("s1", Some("/w"), 1_000), + ("s2", Some("/w"), 2_000), + ("s3", Some("/w/app"), 3_000), + ("s4", None, 500), + ] + .iter() + .map(|(id, cwd, at)| { + let path = fixture.file(&format!("{id}.jsonl")); + append(&path, &session_at(id, *cwd, *at, *at)); + path + }) + .collect(); + fixture.sync(&files); + + let page = SessionFilter { + limit: 1, + ..every_session() + }; + assert_eq!(sessions(&fixture.store, page.clone()).len(), 1); + let group = |cwd: Option<&str>, count, updated| SessionGroup { + cwd: cwd.map(str::to_string), + count, + updated_at_ms: Some(updated), + }; + assert_eq!( + fixture.store.session_counts(&page).expect("count"), + SessionCounts { + total: 4, + groups: vec![ + group(Some("/w/app"), 1, 3_000), + group(Some("/w"), 2, 2_000), + group(None, 1, 500), + ], + groups_truncated: false, + } + ); + let counts = fixture + .store + .session_counts(&SessionFilter { + cwd: Some("/w".to_string()), + ..every_session() + }) + .expect("count"); + assert_eq!((counts.total, counts.groups.len()), (2, 1)); + let serialized = serde_json::to_value(&counts).expect("serialize the counts"); + assert_eq!( + serialized, + json!({ "total": 2, "groups": [{ "cwd": "/w", "count": 2, "updatedAtMs": 2_000 }], + "groupsTruncated": false }) + ); +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 2721aacc..41364cbc 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3957,8 +3957,8 @@ 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?, sessionID?, activeSinceMs?, offset, - limit, titles}` (at most 500), `agentSessions.search {text, agents?, +- `agentSessions.list {agents?, cwd?, cwdUnder?, sessionID?, activeSinceMs?, + order?, offset, limit, titles, counts?}` (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 @@ -3978,6 +3978,27 @@ Lithe list, search and sum them without the CLI running: 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. +- `cwdUnder` keeps the sessions whose `cwd` is one of at most 64 directories + or lies below one; each is 1–4096 bytes without control characters, and a + trailing `/` or `\` changes nothing. A session without `cwd` is under none. + `order` is `updated` (the default: most recently active first) or + `started` (most recently started first). With `counts: true` the answer + also gives `total`, how many sessions the filter keeps regardless of + `offset` and `limit`, and `groups`: `{cwd?, count, updatedAtMs?}` per + directory, most recently active first, at most 500, with + `groupsTruncated` true when more exist. +- A listed session also gives `messageCount`, how many searchable spans the + backend reported for the session in its own file (a subagent's file counts + toward neither); `lastMessageRange`, the range of the last of them, which + `agentSessions.read` turns into that message; `subagentCount`, how many + distinct `threadID`s its calls carry; and `model`, the `model` or else + `requestedModel` of its latest main-thread call, or of its latest call + when every call carries a `threadID`. Core keeps no conversation text for + them: the message is read from the file on request. +- `cwdUnder`, `order`, `counts` and the four session fields above were added + within `agents` 0. A Core that predates them refuses the three fields as + unknown and answers none of the four session fields; a host shows the list + without them. `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 bc51d9bc..b3b67b62 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,11 +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 的说明同步。旧宿主不返回该字段,插件应按缺失处理。契约同时写明 `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 客户端,会话只在可信的本地工作区运行。 - -- [#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 版本。 +- [#219](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/219)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):宿主命令 `agentSessions.list` 新增 `cwdUnder`(最多 64 个目录,会话的 `cwd` 是其中之一或在它下面才保留,末尾的 `/`、`\` 不影响匹配,没有 `cwd` 的会话不在任何目录下)、`order`(`updated` 最近活动在前,默认;`started` 最近开始在前)和 `counts`;`counts: true` 时回答多出 `total`(不受 `offset`、`limit` 影响)、`groups`(每个目录 `{cwd?, count, updatedAtMs?}`,最近活动在前,最多 500 组)和 `groupsTruncated`。每个会话多出 `messageCount`(插件后端在会话自己文件里报的可搜索片段数,子代理文件不计)、`lastMessageRange`(最后一个片段的范围,用 `agentSessions.read` 读出该条消息,Core 不缓存正文)、`subagentCount`(调用里不同 `threadID` 的个数)和 `model`(最近一次主线程调用的 `model`,没有时用 `requestedModel`;全部调用都带 `threadID` 时取最近一次调用的)。旧 Core 以未知字段拒绝三个新参数,也不回答四个新字段,宿主应显示不带它们的列表。没有新增宿主方法、通知、错误码或能力版本。 - [#207](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/207)(待合入),[@1lck](https://github.com/1lck),`debugAdapters` 0(API-30)增加可选 `launch.executableSetting`。命令型适配器可读取用户全局文件路径,留空沿用原命令查找;旧宿主会拒绝包含该声明的清单。无新增方法、通知或能力版本。 @@ -75,7 +71,7 @@ | 能力 | 版本 | 日期 | PR | | --- | --- | --- | --- | | `backend` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | -| `agents` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| `agents` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | `buildModelInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 1 | 2026-11-18 | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | @@ -139,8 +135,8 @@ | API-05 | `workspace/listContexts` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-05 | `workspace/getContext` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-05 | `workspace/getFolders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | -| API-05 | `workspace/setDirectoryTypes` | 0 | 待合入 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | -| API-05 | `workspace/setDirectoryMarks` | 0 | 待合入 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | +| API-05 | `workspace/setDirectoryTypes` | 0 | 2026-11-27 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | +| API-05 | `workspace/setDirectoryMarks` | 0 | 2026-11-27 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | | API-06 | `workspace/readDirectory` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-06 | `workspace/readDirectory` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-06 | `workspace/stat` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -226,21 +222,34 @@ | API-35 | `functions/invoke` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-38 | `network/request` | 0 | 2026-11-23 | [#193](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/193) | | API-40 | `workspace/getHostPaths` | 0 | 待合入 | [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151) | -| 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`) | 待合入 | [#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) | -| API-45 | `agents/didCancel`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/didDecidePermission`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/didExit`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/write` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/report` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/usage` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/usage` | 0(回答新增 `speeds`) | 2026-11-28 | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | +| API-45 | `agents/didStart`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didOutput`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didPrompt`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didCancel`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didDecidePermission`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didExit`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | — | `keymapImport/listInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | — | `keymapImport/readChunk` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | ## 时间线(新的在上) +### 2026-11-28 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | +| --- | --- | --- | --- | --- | +| [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45、API-23 | `agents` 0 / `commandInstallers` 0 | `agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。契约同时写明 `scan` 的一个既有行为:之后的扫描可以用同一个 `key` 再报一次调用(`range` 在它自己的块里),后报的替换先报的,所以到一轮结束才知道计时的后端可以那时补上 `firstTokenMs` 和 `durationMs`;自 #199 起的 Core 都这样处理。同一 PR 里,会话记录的读取支持分页:`agentSessions.list` 可按 `sessionID` 查找、每个会话带 `readBytes`,`agentSessions.read` 回答 `end`(下一页的起点);读取范围在行中间结束时,Core 只把完整的行交给插件后端的 `read`,并说明后端 `messages` 回答整体不能超过 1 MiB 的函数结果上限。旧 Core 不认 `sessionID`、不回答 `readBytes` 和 `end`,并可能把被截断的行交给后端,后端应跳过不是完整 JSON 的行。同一 PR 里,`commandInstallers` 0 内补充(API-23):[命令安装](../contract/v1/README.md#command-installers)也服务 Agent 的命令行工具:安装声明的 `commands` 可以由本插件某个 Agent 的 `tool` 所指工具定义的 `commands` 提供,`plugins.commandInstallers.requirements` 在 `systemCommand` 启动之后按声明顺序列出 `kind: "agent"`、`id` 为 Agent ID 的使用方;宿主把插件的受管命令目录和记录的默认目录也用于解析 Agent 工具的 `kind: "command"` 候选(先查 `PATH`)。旧 Core 以 `plugin.manifest.invalid`(`commandInstallers[].commands[]`)拒绝只有 Agent 工具用到的安装声明;需要它的插件同时要求 `agents` 0。同一 PR 里,[IDE 连接](../../../rust/contracts/ide-api/v1.md#agent-sessions)新增两个只读 MCP 工具 `lithe_sessions_search`、`lithe_sessions_read`(API-45),让 MCP 客户端搜索和分页读取用户同意读取的 Agent 会话;宿主只在用户打开 IDE 连接、打开“允许 MCP 客户端搜索本地会话”并同意读取至少一个 Agent 的会话时声明它们,没有声明工具清单的宿主不提供这两个工具。它们是 IDE 连接的工具,不是插件宿主方法。没有新增宿主方法、通知或错误码。 | + +### 2026-11-27 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | +| --- | --- | --- | --- | --- | +| [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | **`agents` 0** | 清单 `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) | API-05 | `pluginAPIVersion` 0 / `litheFunctions` 0 | 新增宿主方法 `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 版本。 | + ### 2026-11-23 | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 |