From b34dbc47310121d8cf389c44e97add84248140d2 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 20:48:26 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(agents):=20=E7=BB=9F=E8=AE=A1=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8C=89=E7=AC=AC=E4=BA=8C=E4=B8=AA=E7=BB=B4=E5=BA=A6?= =?UTF-8?q?=E6=8B=86=E5=88=86=E3=80=81=E6=8C=89=E6=A8=A1=E5=9E=8B/?= =?UTF-8?q?=E4=BE=9B=E5=BA=94=E5=95=86/=E6=88=90=E8=B4=A5/=E6=96=87?= =?UTF-8?q?=E5=AD=97=E7=AD=9B=E9=80=89=EF=BC=8C=E5=B9=B6=E7=BB=99=E5=87=BA?= =?UTF-8?q?=E6=AF=8F=E7=BB=84=E7=9A=84=E9=80=9F=E5=BA=A6=E4=B8=AD=E4=BD=8D?= =?UTF-8?q?=E6=95=B0=E4=B8=8E=E9=A6=96=E5=AD=97=E5=B9=B3=E5=9D=87=E8=80=97?= =?UTF-8?q?=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit agentSessions.stats 新增可选 splitBy(agent/model/provider/modelProvider)、models、providers、failed、search、detail,groupBy 新增 provider、modelProvider、all;agentSessions.calls 新增 models、providers、search。agents/usage 的分组和回答保持不变。 --- rust/crates/agent-runtime/src/records.rs | 147 ++++++++++- rust/crates/agent-runtime/src/tests.rs | 115 +++++++++ rust/crates/agent-sessions/src/stats.rs | 228 ++++++++++++++++- rust/crates/agent-sessions/src/tests/stats.rs | 230 +++++++++++++++++- shared/plugins/contract/v1/README.md | 38 ++- 5 files changed, 732 insertions(+), 26 deletions(-) diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index beed2700..8be19219 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -19,7 +19,9 @@ 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::{call_cost, PriceTable}; -use lithe_agent_sessions::stats::{call_speed, model_name, GroupBy, SpeedRanker, Summarizer}; +use lithe_agent_sessions::stats::{ + call_speed, model_name, CallSelector, GroupBy, SpeedRanker, Summarizer, +}; use lithe_agent_sessions::{ discover, ByteRange, CallEntry, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, SessionOrder, SessionParser, SessionSource, SessionStore, MAX_FILTER_DIRECTORIES, @@ -887,9 +889,21 @@ impl Records { until_ms: Option, group_by: String, #[serde(default)] + split_by: Option, + #[serde(default)] utc_offset_seconds: i32, #[serde(default)] hour_anchor_ms: Option, + #[serde(default)] + models: Vec, + #[serde(default)] + providers: Vec, + #[serde(default)] + failed: Option, + #[serde(default)] + search: Option, + #[serde(default)] + detail: bool, } let request: StatsRequest = crate::decode(payload)?; let group_by = parse_group_by( @@ -902,9 +916,28 @@ impl Records { refusal( ErrorCode::InvalidRequest, "agentSessions.invalidGroup", - "Group by hour, day, agent, model, session or cwd. Only hour accepts hourAnchorMs.", + "Group by hour, day, agent, model, provider, modelProvider, session, cwd or all. Only hour accepts hourAnchorMs.", ) })?; + let split_by = request + .split_by + .as_deref() + .map(|name| { + parse_split_by(name).ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidSplit", + "Split by agent, model, provider or modelProvider.", + ) + }) + }) + .transpose()?; + let selector = call_selector( + request.models, + request.providers, + request.failed, + request.search.as_deref(), + )?; let (summaries, speeds) = match allowed_agents(runtime, request.agents) { None => (json!([]), json!([])), Some(agents) => { @@ -916,7 +949,14 @@ impl Records { }; let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; - self.summarize(store, &filter, group_by)? + self.summarize( + store, + &filter, + group_by, + split_by, + &selector, + request.detail, + )? } }; Ok(json!({ @@ -945,8 +985,14 @@ impl Records { #[serde(default)] model: Option, #[serde(default)] + models: Vec, + #[serde(default)] + providers: Vec, + #[serde(default)] failed: Option, #[serde(default)] + search: Option, + #[serde(default)] offset: usize, limit: usize, } @@ -959,6 +1005,13 @@ impl Records { "Ask for 1 to 500 calls at an offset of at most 50000.", )); } + // `model` is the one-model form of `models`; both must hold. + let selector = call_selector( + request.models, + request.providers, + request.failed, + request.search.as_deref(), + )?; let Some(agents) = allowed_agents(runtime, request.agents) else { return Ok(json!({ "calls": [], "total": 0 })); }; @@ -982,12 +1035,7 @@ impl Records { .model .as_deref() .is_some_and(|model| model_name(call) != Some(model)) - { - return Ok(()); - } - if request - .failed - .is_some_and(|failed| call.error_category.is_some() != failed) + || !selector.keeps(&entry) { return Ok(()); } @@ -1009,18 +1057,32 @@ impl Records { Ok(json!({ "calls": calls, "total": total })) } - /// The summaries of the calls `filter` selects, grouped by `group_by`, - /// and the models ranked by median output speed over the same calls. + /// The summaries of the calls `filter` and `selector` keep, grouped by + /// `group_by` and split by `split_by`, with each group's median speed and + /// first-token average when `detailed`, and the models ranked by median + /// output speed over the same calls. fn summarize( &self, store: &SessionStore, filter: &CallFilter, group_by: GroupBy, + split_by: Option, + selector: &CallSelector, + detailed: bool, ) -> 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()); + if let Some(split_by) = split_by { + summarizer = summarizer.split_by(split_by); + } + if detailed { + summarizer = summarizer.detailed(); + } let mut speeds = SpeedRanker::default(); store.for_each_call(filter, |entry| { + if !selector.keeps(&entry) { + return Ok(()); + } summarizer.add(&entry); speeds.add(&entry.call); Ok(()) @@ -1105,7 +1167,15 @@ impl Records { since_ms: Some(since_ms), until_ms: Some(until_ms), }; - self.summarize(store, &filter, group_by).map_err(|_| { + self.summarize( + store, + &filter, + group_by, + None, + &CallSelector::default(), + false, + ) + .map_err(|_| { AgentHostFailure::new(codes::HOST_FAILED, "Could not sum the session records.") })? }; @@ -1338,10 +1408,63 @@ fn parse_group_by( "model" => Some(GroupBy::Model), "session" if host => Some(GroupBy::Session), "cwd" if host => Some(GroupBy::Cwd), + "provider" if host => Some(GroupBy::Provider), + "modelProvider" if host => Some(GroupBy::ModelProvider), + "all" if host => Some(GroupBy::All), _ => None, } } +/// What a statistics request can split each group by. +fn parse_split_by(name: &str) -> Option { + match name { + "agent" => Some(GroupBy::Agent), + "model" => Some(GroupBy::Model), + "provider" => Some(GroupBy::Provider), + "modelProvider" => Some(GroupBy::ModelProvider), + _ => None, + } +} + +/// Most models or providers a request may filter by, and the longest name or +/// search text. +const MAX_FILTER_NAMES: usize = 64; +const MAX_FILTER_TEXT_BYTES: usize = 256; + +/// The selector of a statistics or calls request, or a refusal when a filter +/// is too long. +fn call_selector( + models: Vec, + providers: Vec, + failed: Option, + search: Option<&str>, +) -> Result { + let too_long = |names: &[String]| { + names.len() > MAX_FILTER_NAMES + || names.iter().any(|name| name.len() > MAX_FILTER_TEXT_BYTES) + }; + if too_long(&models) + || too_long(&providers) + || search.is_some_and(|text| text.len() > MAX_FILTER_TEXT_BYTES) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidFilter", + "Filter by at most 64 models and 64 providers, each name and the search text at most 256 bytes.", + )); + } + let selector = CallSelector { + models, + providers, + failed, + words: Vec::new(), + }; + Ok(match search { + Some(text) => selector.with_search(text), + None => selector, + }) +} + /// A session source with its root resolved. struct RootedSource { root: PathBuf, diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 38ff9407..27f2eb79 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1765,6 +1765,121 @@ fn hourly_stats_match_the_shared_desktop_fixture() { ); } +#[test] +fn stats_split_filter_and_detail_the_calls() { + let harness = Harness::new("stats-split", ALL_GRANTS); + write_session_file(&harness, crate::now_ms()); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + + // A day split by model carries the split key and, on request, the group's + // median speed and first-token average. + let detailed = harness.run( + "agentSessions.stats", + json!({ "groupBy": "day", "splitBy": "model", "detail": true }), + ); + let summary = &detailed["summaries"][0]; + assert_eq!(summary["calls"], 1, "{detailed}"); + assert_eq!( + summary["split"], + json!({ "kind": "model", "model": "sample-model" }), + "{detailed}" + ); + assert_eq!( + summary["speed"], + json!({ "calls": 1, "medianTokensPerSecond": 150.0, "lowerBound": false }), + "{detailed}" + ); + assert_eq!( + summary["firstToken"], + json!({ "calls": 1, "averageMs": 500.0 }), + "{detailed}" + ); + let plain = harness.run("agentSessions.stats", json!({ "groupBy": "day" })); + assert!(plain["summaries"][0].get("split").is_none(), "{plain}"); + assert!(plain["summaries"][0].get("speed").is_none(), "{plain}"); + assert!(plain["summaries"][0].get("firstToken").is_none(), "{plain}"); + + for (group, key) in [ + ("all", json!({ "kind": "all" })), + ("provider", json!({ "kind": "provider" })), + ( + "modelProvider", + json!({ "kind": "modelProvider", "model": "sample-model" }), + ), + ] { + let stats = harness.run("agentSessions.stats", json!({ "groupBy": group })); + assert_eq!(stats["summaries"][0]["key"], key, "{stats}"); + } + + // Filters narrow what is summed and what the request table lists. + for (filter, kept) in [ + (json!({ "models": ["sample-model"] }), 1), + (json!({ "models": ["other-model"] }), 0), + (json!({ "providers": [""] }), 1), + (json!({ "providers": ["p1"] }), 0), + (json!({ "failed": false }), 1), + (json!({ "failed": true }), 0), + (json!({ "search": "SAMPLE" }), 1), + (json!({ "search": "sample nothing" }), 0), + (json!({ "search": "/work/project" }), 1), + ] { + let mut stats_query = filter.clone(); + stats_query["groupBy"] = json!("all"); + let stats = harness.run("agentSessions.stats", stats_query); + let counted = stats["summaries"][0]["calls"].as_u64().unwrap_or(0); + assert_eq!(counted, kept, "stats {filter} {stats}"); + let mut calls_query = filter.clone(); + calls_query["limit"] = json!(10); + let calls = harness.run("agentSessions.calls", calls_query); + assert_eq!(calls["total"], kept, "calls {filter} {calls}"); + } + let narrowed = harness.run( + "agentSessions.stats", + json!({ "groupBy": "model", "models": ["other-model"], "detail": true }), + ); + assert_eq!(narrowed["summaries"], json!([]), "{narrowed}"); + assert_eq!(narrowed["speeds"], json!([]), "{narrowed}"); + + for (query, code) in [ + ( + json!({ "groupBy": "day", "splitBy": "day" }), + "agentSessions.invalidSplit", + ), + ( + json!({ "groupBy": "day", "search": "x".repeat(257) }), + "agentSessions.invalidFilter", + ), + ( + json!({ "groupBy": "day", "models": vec!["m"; 65] }), + "agentSessions.invalidFilter", + ), + ] { + assert_eq!(harness.refused("agentSessions.stats", query.clone()), code); + } + assert_eq!( + harness.refused( + "agentSessions.calls", + json!({ "limit": 1, "providers": vec!["p"; 65] }) + ), + "agentSessions.invalidFilter" + ); + + // Plugins keep the grouping and the answer they had. + for group in ["provider", "modelProvider", "all"] { + let refusal = harness + .answer(AGENTS_USAGE, json!({ "groupBy": group })) + .expect_err("plugins cannot group by this"); + assert_eq!(refusal.code, codes::HOST_INVALID_PARAMS); + } + let usage = harness + .answer(AGENTS_USAGE, json!({ "groupBy": "model" })) + .expect("usage"); + assert!(usage["summaries"][0].get("speed").is_none(), "{usage}"); +} + #[test] fn rate_limits_survive_a_restart() { let dir; diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs index 03c78524..b9a332e2 100644 --- a/rust/crates/agent-sessions/src/stats.rs +++ b/rust/crates/agent-sessions/src/stats.rs @@ -8,7 +8,10 @@ //! - cost is what the tokens would cost at API prices ([`CostBasis`]); calls //! without a price are counted apart, never as free; //! - speed is output tokens per second after the first token; without the -//! time of the first token, a long call gives a lower bound. +//! time of the first token, a long call gives a lower bound; +//! - a group's speed is the median over its calls with a speed and at least +//! [`MIN_RANKED_OUTPUT_TOKENS`] output tokens, like a model's rank; its +//! first-token time is the mean over its successful calls that report one. use std::collections::BTreeMap; @@ -55,6 +58,14 @@ pub enum GroupBy { Session, /// By the working directory of the session. Cwd, + /// By the provider that served the call, when the session file names it. + Provider, + /// By model and provider together, so one model served by two providers + /// counts as two groups. + ModelProvider, + /// All calls as one group, for totals that are not sums of other groups + /// (a median speed, a hit rate). + All, } /// The group a [`Summary`] covers. @@ -97,6 +108,23 @@ pub enum GroupKey { #[serde(skip_serializing_if = "Option::is_none")] cwd: Option, }, + /// A provider; absent for calls whose session file does not name it. + Provider { + /// The provider, as a models.dev provider ID. + #[serde(skip_serializing_if = "Option::is_none")] + provider: Option, + }, + /// A model served by a provider; either is absent when the call names none. + ModelProvider { + /// The model. + #[serde(skip_serializing_if = "Option::is_none")] + model: Option, + /// The provider. + #[serde(skip_serializing_if = "Option::is_none")] + provider: Option, + }, + /// Every call. + All, } /// Sums of the token counts calls report. @@ -144,12 +172,39 @@ pub struct CostTotal { pub approximate_calls: u64, } +/// The median output speed of a group of calls, over the calls a speed +/// ranking uses (see [`MIN_RANKED_OUTPUT_TOKENS`]). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SpeedSummary { + /// Calls the median covers. + pub calls: u64, + /// The median, in tokens per second. + pub median_tokens_per_second: f64, + /// Whether a lower bound is among the speeds, so the median may be low. + pub lower_bound: bool, +} + +/// The average wait for the first output token of a group of calls. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FirstTokenSummary { + /// Successful calls that report the time of their first token. + pub calls: u64, + /// The mean of those times, in milliseconds. + pub average_ms: f64, +} + /// Statistics of one group of calls. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Summary { /// The group. pub key: GroupKey, + /// The second key of a group that [`Summarizer::split_by`] splits further; + /// absent otherwise. + #[serde(skip_serializing_if = "Option::is_none")] + pub split: Option, /// Calls in the group. pub calls: u64, /// Calls that failed. @@ -169,6 +224,14 @@ pub struct Summary { pub first_started_at_ms: i64, /// The start of the last call, in Unix milliseconds. pub last_started_at_ms: i64, + /// The median output speed; only [`Summarizer::detailed`] summaries carry + /// it, and only when a call of the group has a speed. + #[serde(skip_serializing_if = "Option::is_none")] + pub speed: Option, + /// The average wait for the first token; only [`Summarizer::detailed`] + /// summaries carry it, and only when a call of the group reports one. + #[serde(skip_serializing_if = "Option::is_none")] + pub first_token: Option, } /// Adds calls into groups one at a time, so a large history never has to be @@ -176,8 +239,10 @@ pub struct Summary { #[derive(Debug)] pub struct Summarizer<'a> { group_by: GroupBy, + split_by: Option, + detailed: bool, prices: Option<&'a PriceTable>, - groups: BTreeMap, + groups: BTreeMap<(GroupKey, Option), Accumulator>, } #[derive(Debug)] @@ -185,6 +250,10 @@ struct Accumulator { summary: Summary, cache_read: u64, cache_input: u64, + speeds: Vec, + lower_bound: bool, + first_token_total_ms: u128, + first_token_calls: u64, } impl<'a> Summarizer<'a> { @@ -192,21 +261,39 @@ impl<'a> Summarizer<'a> { pub fn new(group_by: GroupBy, prices: Option<&'a PriceTable>) -> Self { Self { group_by, + split_by: None, + detailed: false, prices, groups: BTreeMap::new(), } } + /// Splits every group further by `split_by`: one summary per pair of keys, + /// the second in [`Summary::split`]. + pub fn split_by(mut self, split_by: GroupBy) -> Self { + self.split_by = Some(split_by); + self + } + + /// Also works out each group's median speed and average wait for the first + /// token, which needs every speed of the group kept until the end. + pub fn detailed(mut self) -> Self { + self.detailed = true; + self + } + /// Adds a call. pub fn add(&mut self, entry: &CallEntry) { let call = &entry.call; let key = group_key(self.group_by, entry); + let split = self.split_by.map(|split_by| group_key(split_by, entry)); let accumulator = self .groups - .entry(key.clone()) + .entry((key.clone(), split.clone())) .or_insert_with(|| Accumulator { summary: Summary { key, + split, calls: 0, failed_calls: 0, compaction_calls: 0, @@ -221,9 +308,15 @@ impl<'a> Summarizer<'a> { }), first_started_at_ms: call.started_at_ms, last_started_at_ms: call.started_at_ms, + speed: None, + first_token: None, }, cache_read: 0, cache_input: 0, + speeds: Vec::new(), + lower_bound: false, + first_token_total_ms: 0, + first_token_calls: 0, }); let summary = &mut accumulator.summary; summary.calls += 1; @@ -271,16 +364,41 @@ impl<'a> Summarizer<'a> { None => cost.unpriced_calls += 1, } } + + if self.detailed { + if let Some(speed) = ranked_speed(call) { + accumulator.speeds.push(speed.tokens_per_second()); + accumulator.lower_bound |= matches!(speed, Speed::AtLeast(_)); + } + if let (None, Some(first)) = (&call.error_category, call.first_token_ms) { + accumulator.first_token_total_ms += u128::from(first); + accumulator.first_token_calls += 1; + } + } } - /// The groups, in order of their keys. + /// The groups, in order of their keys, then of their second keys. pub fn finish(self) -> Vec { self.groups .into_values() - .map(|accumulator| { + .map(|mut accumulator| { let mut summary = accumulator.summary; summary.cache_hit_rate = (accumulator.cache_input > 0) .then(|| accumulator.cache_read as f64 / accumulator.cache_input as f64); + if !accumulator.speeds.is_empty() { + summary.speed = Some(SpeedSummary { + calls: accumulator.speeds.len() as u64, + median_tokens_per_second: median(&mut accumulator.speeds), + lower_bound: accumulator.lower_bound, + }); + } + if accumulator.first_token_calls > 0 { + summary.first_token = Some(FirstTokenSummary { + calls: accumulator.first_token_calls, + average_ms: accumulator.first_token_total_ms as f64 + / accumulator.first_token_calls as f64, + }); + } summary }) .collect() @@ -338,6 +456,15 @@ pub fn call_speed(call: &CallRecord) -> Option { (speed.tokens_per_second() <= MAX_TOKENS_PER_SECOND).then_some(speed) } +/// The speed of a call a ranking or a group median uses: one with at least +/// [`MIN_RANKED_OUTPUT_TOKENS`] output tokens and a [`call_speed`]. +fn ranked_speed(call: &CallRecord) -> Option { + if call.tokens.output.unwrap_or(0) < MIN_RANKED_OUTPUT_TOKENS { + return None; + } + call_speed(call) +} + /// The median speed of a model. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -372,10 +499,7 @@ pub struct SpeedRanker { 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 { - return; - } - let (Some(model), Some(speed)) = (model_name(call), call_speed(call)) else { + let (Some(model), Some(speed)) = (model_name(call), ranked_speed(call)) else { return; }; let (speeds, lower_bound) = self.by_model.entry(model.to_string()).or_default(); @@ -453,6 +577,92 @@ fn group_key(group_by: GroupBy, entry: &CallEntry) -> GroupKey { GroupBy::Cwd => GroupKey::Cwd { cwd: entry.cwd.clone(), }, + GroupBy::Provider => GroupKey::Provider { + provider: entry.call.provider.clone(), + }, + GroupBy::ModelProvider => GroupKey::ModelProvider { + model: model_name(&entry.call).map(str::to_string), + provider: entry.call.provider.clone(), + }, + GroupBy::All => GroupKey::All, + } +} + +/// Which calls a statistics request keeps beyond what the store filters by +/// agent, session and time. Every filter given must hold. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CallSelector { + /// Models that answered ([`model_name`]); the empty name stands for calls + /// that name none. Empty keeps every model. + pub models: Vec, + /// Providers; the empty name stands for calls whose session file names + /// none. Empty keeps every provider. + pub providers: Vec, + /// `true` keeps only failed calls, `false` only successful ones. + pub failed: Option, + /// Words that must each appear, ignoring case, in the model, requested + /// model, provider, agent, session or directory of the call. + pub words: Vec, +} + +impl CallSelector { + /// A selector that keeps calls whose text holds every word of `search`. + pub fn with_search(mut self, search: &str) -> Self { + self.words = search.split_whitespace().map(str::to_lowercase).collect(); + self + } + + /// Whether the selector keeps every call. + pub fn is_open(&self) -> bool { + self.models.is_empty() + && self.providers.is_empty() + && self.failed.is_none() + && self.words.is_empty() + } + + /// Whether the selector keeps `entry`. + pub fn keeps(&self, entry: &CallEntry) -> bool { + let call = &entry.call; + if !self.models.is_empty() + && !self + .models + .iter() + .any(|model| model == model_name(call).unwrap_or("")) + { + return false; + } + if !self.providers.is_empty() + && !self + .providers + .iter() + .any(|provider| provider == call.provider.as_deref().unwrap_or("")) + { + return false; + } + if self + .failed + .is_some_and(|failed| call.error_category.is_some() != failed) + { + return false; + } + if self.words.is_empty() { + return true; + } + let fields = [ + call.model.as_deref(), + call.requested_model.as_deref(), + call.provider.as_deref(), + Some(entry.agent.as_str()), + Some(call.session_id.as_str()), + entry.cwd.as_deref(), + ] + .map(|field| field.map(str::to_lowercase)); + self.words.iter().all(|word| { + fields + .iter() + .flatten() + .any(|field| field.contains(word.as_str())) + }) } } diff --git a/rust/crates/agent-sessions/src/tests/stats.rs b/rust/crates/agent-sessions/src/tests/stats.rs index 74c739f0..f7c90f15 100644 --- a/rust/crates/agent-sessions/src/tests/stats.rs +++ b/rust/crates/agent-sessions/src/tests/stats.rs @@ -3,8 +3,8 @@ use crate::model::{ByteRange, CallRecord, Tokens}; use crate::pricing::PriceTable; use crate::stats::{ - call_speed, civil_date, rank_speed, summarize, CostBasis, CostTotal, GroupBy, GroupKey, Speed, - Summarizer, TokenTotals, + call_speed, civil_date, rank_speed, summarize, CallSelector, CostBasis, CostTotal, GroupBy, + GroupKey, Speed, Summarizer, TokenTotals, }; use crate::store::CallEntry; @@ -373,3 +373,229 @@ fn models_rank_by_median_speed() { .collect(); assert_eq!(models, ["a", "b"]); } + +const DAY_MS: i64 = 86_400_000; + +fn served(model: &str, provider: Option<&str>, at: i64) -> CallRecord { + CallRecord { + model: Some(model.to_string()), + provider: provider.map(str::to_string), + started_at_ms: at, + ..record("c", at) + } +} + +#[test] +fn groups_split_by_a_second_key() { + let entries: Vec = [ + served("m-a", Some("p1"), 1_000), + served("m-b", Some("p1"), 2_000), + served("m-a", Some("p2"), 3_000), + served("m-a", Some("p1"), DAY_MS + 1_000), + ] + .into_iter() + .map(entry) + .collect(); + + let summaries = Summarizer::new( + GroupBy::Day { + utc_offset_seconds: 0, + }, + None, + ) + .split_by(GroupBy::Model) + .tap(&entries); + let pairs: Vec<(String, Option, u64)> = summaries + .iter() + .map(|summary| { + let GroupKey::Day { date } = &summary.key else { + panic!("not a day: {:?}", summary.key); + }; + let split = summary + .split + .as_ref() + .map(|key| model_of(key).unwrap_or("").to_string()); + (date.clone(), split, summary.calls) + }) + .collect(); + assert_eq!( + pairs, + [ + ("1970-01-01".to_string(), Some("m-a".to_string()), 2), + ("1970-01-01".to_string(), Some("m-b".to_string()), 1), + ("1970-01-02".to_string(), Some("m-a".to_string()), 1), + ] + ); + + // Without a split the second key is absent, as before. + let plain = summarize(&entries, GroupBy::Model, None); + assert!(plain.iter().all(|summary| summary.split.is_none())); +} + +#[test] +fn providers_group_alone_and_with_the_model() { + let entries: Vec = [ + served("m-a", Some("p1"), 0), + served("m-a", Some("p2"), 0), + served("m-a", None, 0), + served("m-b", Some("p1"), 0), + ] + .into_iter() + .map(entry) + .collect(); + + let by_provider = summarize(&entries, GroupBy::Provider, None); + let providers: Vec<(Option<&str>, u64)> = by_provider + .iter() + .map(|summary| match &summary.key { + GroupKey::Provider { provider } => (provider.as_deref(), summary.calls), + other => panic!("not a provider: {other:?}"), + }) + .collect(); + assert_eq!(providers, [(None, 1), (Some("p1"), 2), (Some("p2"), 1)]); + + let both = summarize(&entries, GroupBy::ModelProvider, None); + assert_eq!(both.len(), 4); + assert_eq!( + both[1].key, + GroupKey::ModelProvider { + model: Some("m-a".to_string()), + provider: Some("p1".to_string()), + } + ); + + let all = summarize(&entries, GroupBy::All, None); + assert_eq!(all.len(), 1); + assert_eq!((all[0].key.clone(), all[0].calls), (GroupKey::All, 4)); +} + +#[test] +fn detailed_groups_report_median_speed_and_first_token_average() { + let failed = CallRecord { + error_category: Some("overloaded".to_string()), + ..timed("m-a", 1_000, Some(9_000), 10_000) + }; + let entries: Vec = [ + // 200, 100 and a lower bound of 100 tokens/s: the median is 100. + timed("m-a", 200, Some(100), 1_100), + timed("m-a", 100, Some(200), 1_200), + timed("m-a", 1_000, None, 10_000), + // Too short for a speed, but its first token still counts. + timed("m-a", 10, Some(300), 400), + // A failed call counts for neither. + failed, + // No timing at all. + CallRecord { + model: Some("m-b".to_string()), + ..record("c", 0) + }, + ] + .into_iter() + .map(entry) + .collect(); + + let plain = summarize(&entries, GroupBy::Model, None); + assert!(plain + .iter() + .all(|s| s.speed.is_none() && s.first_token.is_none())); + + let detailed = Summarizer::new(GroupBy::Model, None) + .detailed() + .tap(&entries); + let a = &detailed[0]; + assert_eq!(model_of(&a.key), Some("m-a")); + let speed = a.speed.clone().expect("a speed"); + assert_eq!( + ( + speed.calls, + speed.median_tokens_per_second, + speed.lower_bound + ), + (3, 100.0, true) + ); + let first = a.first_token.clone().expect("a first token"); + assert_eq!((first.calls, first.average_ms), (3, 200.0)); + let b = &detailed[1]; + assert_eq!((b.speed.clone(), b.first_token.clone()), (None, None)); +} + +#[test] +fn selector_keeps_calls_that_match_every_filter() { + let mut elsewhere = entry(served("m-b", Some("p2"), 0)); + elsewhere.cwd = Some("/Work/Other".to_string()); + let failed = entry(CallRecord { + error_category: Some("overloaded".to_string()), + ..served("m-a", Some("p1"), 0) + }); + let unnamed = entry(record("c", 0)); + let plain = entry(served("m-a", Some("p1"), 0)); + let keeps = |selector: &CallSelector| -> Vec { + [&plain, &failed, &elsewhere, &unnamed] + .into_iter() + .map(|entry| selector.keeps(entry)) + .collect() + }; + + assert!(CallSelector::default().is_open()); + assert_eq!(keeps(&CallSelector::default()), [true; 4]); + + let models = CallSelector { + models: vec!["m-a".to_string()], + ..CallSelector::default() + }; + assert_eq!(keeps(&models), [true, true, false, false]); + // The empty name selects calls that name no model. + let none = CallSelector { + models: vec![String::new()], + providers: vec![String::new()], + ..CallSelector::default() + }; + assert_eq!(keeps(&none), [false, false, false, true]); + + let providers = CallSelector { + providers: vec!["p2".to_string()], + ..CallSelector::default() + }; + assert_eq!(keeps(&providers), [false, false, true, false]); + + let failures = CallSelector { + failed: Some(true), + ..CallSelector::default() + }; + assert_eq!(keeps(&failures), [false, true, false, false]); + let successes = CallSelector { + failed: Some(false), + ..CallSelector::default() + }; + assert_eq!(keeps(&successes), [true, false, true, true]); + + // Words match in any field, ignoring case, and all must match. + let search = CallSelector::default().with_search(" WORK m-b "); + assert!(!search.is_open()); + assert_eq!(keeps(&search), [false, false, true, false]); + assert_eq!( + keeps(&CallSelector::default().with_search("p1 m-a")), + [true, true, false, false] + ); + + // Filters combine. + let both = CallSelector { + models: vec!["m-a".to_string()], + failed: Some(false), + ..CallSelector::default() + }; + assert_eq!(keeps(&both), [true, false, false, false]); +} + +trait Tap { + fn tap(self, entries: &[CallEntry]) -> Vec; +} + +impl Tap for Summarizer<'_> { + fn tap(mut self, entries: &[CallEntry]) -> Vec { + for entry in entries { + self.add(entry); + } + self.finish() + } +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 80df022e..2497edd4 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4185,14 +4185,46 @@ Lithe list, search and sum them without the CLI running: 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, hourAnchorMs?}` serve the host's own views; `agent` is + groupBy, splitBy?, utcOffsetSeconds, hourAnchorMs?, models?, providers?, + failed?, search?, detail?}` serve the host's own views; `agent` is `/`, and `stats` groups by `hour`, `day`, `agent`, `model`, - `session` or `cwd`. Hour keys and alignment follow the `agents/usage` rules above. + `provider`, `modelProvider`, `session`, `cwd` or `all` (every call as one + group, for totals that cannot be summed from other groups). Hour keys and + alignment follow the `agents/usage` rules above. The new group names are + the host's only: `agents/usage` still accepts the names listed above. + - `splitBy` (`agent`, `model`, `provider` or `modelProvider`) splits every + group once more, so `groupBy: "day"` with `splitBy: "model"` answers one + summary per day and model; a summary then carries the second key in + `split`, shaped like `key`. Without `splitBy` the summaries are as before. + Another name refuses with `agentSessions.invalidSplit`. + - `models` and `providers` keep only calls whose model that answered (or + asked for) or provider is listed; the empty string stands for calls that + name none. `failed` keeps only failed (`true`) or successful (`false`) + calls. `search` keeps calls whose model, requested model, provider, + agent, session ID or directory contains every whitespace-separated word, + ignoring case. All filters must hold, and they apply to the summaries and + to `speeds`. At most 64 models and 64 providers, each name and the search + text at most 256 bytes; more refuses with `agentSessions.invalidFilter`. + - A `provider` key is `{kind: "provider", provider?}` and a `modelProvider` + key `{kind: "modelProvider", model?, provider?}`, each field absent for + calls that do not name it; the `all` key is `{kind: "all"}`. + - `detail: true` adds to each summary `speed {calls, medianTokensPerSecond, + lowerBound}`, the median output speed over the group's calls with a + speed and at least 100 output tokens (the rule of `speeds`), and + `firstToken {calls, averageMs}`, the mean wait for the first token over + its successful calls that report one. Each is absent when no call of the + group qualifies. Without `detail` neither is present. + - All of this was added within `agents` 0. An older Core refuses `splitBy`, + the filters and `detail` as unknown fields and the new group names as + `agentSessions.invalidGroup`. - `agentSessions.calls {agents?, sessionID?, sinceMs?, untilMs?, model?, - failed?, offset?, limit}` serves the host's request table: the calls the + models?, providers?, failed?, search?, offset?, limit}` serves the host's + request table: the calls the filter keeps, most recent first, `limit` 1–500 at an `offset` of at most 50000, with `total`, how many the filter keeps. `model` matches the model that answered, or the one asked for when the answer did not name it; + `models`, `providers`, `search` follow the rules of `agentSessions.stats` + above (and refuse alike), and every filter given must hold; `failed` keeps only failed (`true`) or only successful (`false`) calls. Each row gives `agent`, `pluginID`, `agentID`, `path`, `cwd?` and `call`, the call as `scan` reported it, plus what Core derives: `cost {usd, From eef97b43eac7f45fa9eb951f83ce840be9f50c8e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 20:49:20 +0800 Subject: [PATCH 2/2] =?UTF-8?q?docs(plugins):=20=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=AE=B0=E5=BD=95=E7=99=BB=E8=AE=B0=20#245?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index d9ae18d4..8a04e8b7 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#245](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/245)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.stats` 新增可选 `splitBy`(`agent`/`model`/`provider`/`modelProvider`,在 `groupBy` 之后再拆一层,第二个键在 summary 的 `split`)、筛选 `models`、`providers`、`failed`、`search`(同时作用于 `summaries` 和 `speeds`)和 `detail`(每组增加 `speed` 速度中位数与 `firstToken` 平均首字耗时);`groupBy` 新增只给宿主的 `provider`、`modelProvider`、`all`。`agentSessions.calls` 新增 `models`、`providers`、`search`,与 stats 的筛选规则相同。新增错误码 `agentSessions.invalidSplit`、`agentSessions.invalidFilter`。`agents/usage`(插件)的分组和回答不变。旧 Core 把新字段当未知字段拒绝,把新分组名当 `agentSessions.invalidGroup` 拒绝。没有新增宿主方法、通知或能力版本。 | | [#241](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/241)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.search` 的命中新增 `generation` 和 `readBytes`,都是命中所在文件(可能是子代理文件)的值,宿主据此从命中处用 `agentSessions.page` 分页读取该文件。旧 Core 不回答这两个字段。没有新增宿主方法、通知、错误码或能力版本。 | | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。事件重放同时限制 8192 条 / 16 MiB,交互状态只保留每会话最新快照;`agents.waitEvents` 增加 `recoveries` 与可选 `acknowledge`,拒绝的补充在预留的 64 条 / 16 MiB 容量中保留,直到宿主恢复并显式确认。停止后的有效当前轮次问题被抑制,不阻塞同批结束事件。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision 为 [`1f843f8ee3aac802cda17ad8df43b51e30862b0d`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/1f843f8ee3aac802cda17ad8df43b51e30862b0d)(本 PR,尚未合入);桌面端尚未发布。 | | [#231](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/231)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 | `agents/usage` 支持按小时汇总。默认按指定 UTC 偏移对齐整点,也可用 `hourAnchorMs` 对齐滚动窗口。 |