From d80d8eee7cdbd6e6bf5eb79c7b67b6b6b6fc81cc Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Fri, 4 Dec 2026 00:52:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(agents):=20=E7=94=A8=E9=87=8F=E8=A1=A5?= =?UTF-8?q?=E9=BD=90=E4=BC=9A=E8=AF=9D=E5=88=86=E4=BD=8D=E6=95=B0=E3=80=81?= =?UTF-8?q?=E6=AF=8F=E6=97=A5=E6=B6=88=E6=81=AF=E6=95=B0=E3=80=81=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87=E5=8D=A0=E7=94=A8=E3=80=81=E9=A2=9D=E5=BA=A6?= =?UTF-8?q?=E5=8E=86=E5=8F=B2=E5=92=8C=E6=8C=89=E7=9B=AE=E5=BD=95=E7=AD=9B?= =?UTF-8?q?=E9=80=89=EF=BC=8C=E6=8F=92=E4=BB=B6=E5=8F=AF=E4=B8=8A=E6=8A=A5?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E4=B8=8E=E7=94=A8=E9=80=94=EF=BC=8C=E5=88=B7?= =?UTF-8?q?=E6=96=B0=E9=A2=9D=E5=BA=A6=E3=80=81=E8=87=AA=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E4=BB=B7=E6=A0=BC=E3=80=81=E6=B1=87=E7=8E=87=E5=92=8C=E9=A2=9D?= =?UTF-8?q?=E5=BA=A6=E6=8F=90=E9=86=92=E7=94=B1=E6=8F=92=E4=BB=B6=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 72 +- rust/crates/agent-runtime/src/files.rs | 104 ++ rust/crates/agent-runtime/src/interaction.rs | 20 +- rust/crates/agent-runtime/src/lib.rs | 36 +- rust/crates/agent-runtime/src/library.rs | 123 +-- .../agent-runtime/src/library/backups.rs | 7 +- .../agent-runtime/src/library/instructions.rs | 6 +- .../agent-runtime/src/library/providers.rs | 6 +- .../src/library/providers/models.rs | 59 +- rust/crates/agent-runtime/src/live.rs | 35 +- .../agent-runtime/src/projection/command.rs | 2 +- .../agent-runtime/src/projection/wire.rs | 2 +- rust/crates/agent-runtime/src/records.rs | 519 ++++++--- .../agent-runtime/src/records/history.rs | 211 ++++ .../agent-runtime/src/records/subagents.rs | 15 +- .../crates/agent-runtime/src/records/usage.rs | 982 ++++++++++++++++++ rust/crates/agent-runtime/src/tests.rs | 2 + rust/crates/agent-runtime/src/tests/files.rs | 63 ++ rust/crates/agent-runtime/src/tests/usage.rs | 862 +++++++++++++++ .../agent-sessions/benches/daily_overview.rs | 2 + rust/crates/agent-sessions/src/lib.rs | 6 +- rust/crates/agent-sessions/src/model.rs | 22 + rust/crates/agent-sessions/src/pricing.rs | 33 +- rust/crates/agent-sessions/src/stats.rs | 182 +++- .../agent-sessions/src/stats/messages.rs | 80 ++ .../agent-sessions/src/stats/overview.rs | 120 ++- .../agent-sessions/src/stats/sessions.rs | 253 +++++ rust/crates/agent-sessions/src/store.rs | 101 +- rust/crates/agent-sessions/src/tests/mod.rs | 5 + rust/crates/agent-sessions/src/tests/stats.rs | 6 + rust/crates/agent-sessions/src/tests/store.rs | 15 +- rust/crates/agent-sessions/src/tests/usage.rs | 685 ++++++++++++ rust/crates/core/src/protocol/command.rs | 39 + .../core/src/runtime/dispatcher/agents.rs | 4 +- .../diagnostics/src/catalog_generated.rs | 84 ++ rust/crates/plugin-agents/src/lib.rs | 90 +- rust/crates/plugin-agents/src/tests.rs | 68 ++ rust/logging/events/agent.json | 150 +++ shared/plugins/contract/v1/README.md | 237 ++++- .../v1/fixtures/agents/agents.plugin.json | 6 + .../fixtures/manifest/invalid-manifests.json | 2 + .../contract/v1/plugin-manifest.schema.json | 33 + shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 60 +- .../plugins/reference/protocol-changelog.md | 3 +- 46 files changed, 4976 insertions(+), 444 deletions(-) create mode 100644 rust/crates/agent-runtime/src/files.rs create mode 100644 rust/crates/agent-runtime/src/records/history.rs create mode 100644 rust/crates/agent-runtime/src/records/usage.rs create mode 100644 rust/crates/agent-runtime/src/tests/files.rs create mode 100644 rust/crates/agent-runtime/src/tests/usage.rs create mode 100644 rust/crates/agent-sessions/src/stats/messages.rs create mode 100644 rust/crates/agent-sessions/src/stats/sessions.rs create mode 100644 rust/crates/agent-sessions/src/tests/usage.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index bfec6cc5..1c816791 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -491,18 +491,25 @@ or removing a command fails until the table changes in the same commit. | `agents.close` | End a live agent session | | `agents.waitEvents` | Wait, bounded, for agent session events after a sequence | | `agents.projection` | Read a bounded conversation view or apply a loaded history page | -| `agentSessions.configure` | Open the agent session record cache | +| `agentSessions.configure` | Open the agent session record cache, and with `dataDirectory` the user's usage settings and rate-limit history in the platform's application data | | `agentSessions.sync` | Read one agent's changed session files through its plugin | | `agentSessions.forget` | Drop one agent's cached session records | | `agentSessions.list` | List a page of recorded agent sessions by directory and order, with their activity, whether each can be resumed, and the whole list's counts with each directory group's `category` (`root`, `temporary`, `hidden`), or find one by its ID | | `agentSessions.search` | Search recorded agent session text; with `snippets: true` each hit carries a `snippet` and the UTF-8 byte ranges of its matched words | | `agentSessions.read` | Read one recorded range as messages and where the next page starts | | `agentSessions.page` | Read a bounded whole-line window before or after a recorded byte cursor, growing only for a long source line | -| `agentSessions.stats` | Sum recorded agent usage with the latest rate limits. Optional `overview` returns totals, breakdown and time series in one snapshot; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs` | -| `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | +| `agentSessions.stats` | Sum recorded agent usage with the latest rate limits. Optional `overview` returns totals, breakdown and time series in one snapshot, and with `overview.speeds: true` also the speed ranking; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs`; groups and splits by the plugin's `account` and `purpose` labels and filters by them, by `cancelled` and by whole working directories (`cwds`); `sessions: {top?}` adds figures per session (nearest-rank p50, p90, p99, mean and max of calls, tokens, cost and duration, and the costliest sessions), `messages: true` the messages per hour or day, and a chosen currency `currency {code, perUSD, atMs}` | +| `agentSessions.calls` | List a page of recorded agent calls, most recent first, filtered like `agentSessions.stats` (`cwds` included), with their cost, cache hit rate and speed, the `generation` and `size` that open the call with `agentSessions.page`, and `context {tokens, window?, share?}`, how full the call's context was against the model's listed window | | `agentSessions.resume` | Build the arguments, directory and copyable command line that continue a recorded session in the agent's terminal form, from the plugin's `terminal.resumeArguments`; needs `agents.run` | | `agentSessions.export` | Export a recorded session as Markdown of at most `maxBytes`: messages, replies, one line per tool call and their times, keeping the start or the end, in words the host passes in `labels` | | `agentSessions.subagents` | List a recorded session's subagents, as the plugin's scan reports them, with their calls and each one's usage; empty when the plugin reports none | +| `agentUsage.read` | Read the user's usage settings: the chosen currency, the kept exchange rates and each installed agent's prices and alerts | +| `agentUsage.setPrice` | Set or remove the price of one model of an agent whose plugin declares `usage.customPrices` (user requests only); its calls use it before the price table | +| `agentUsage.setAlert` | Set or remove alert thresholds on a rate-limit window of an agent whose plugin declares `usage.rateLimitAlerts` (user requests only) | +| `agentUsage.setCurrency` | Choose the currency costs are shown in, one with an exchange rate a plugin reported, or US dollars (user requests only) | +| `agentUsage.refreshRateLimits` | Ask the plugin's `usage.rateLimits` function for the agent's current rate limits and keep them as its latest snapshot (user requests only) | +| `agentUsage.refreshExchangeRates` | Ask the plugin's `usage.exchangeRates` function for rates of currencies per US dollar and keep them (user requests only) | +| `agentUsage.rateLimitHistory` | Read the kept readings of an agent's rate-limit windows in a range | | `agentLibrary.configure` | Open the agent library in the platform's application data | | `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold, with the agent's `backup: {savedAtMs, modifiedSince}` while Core keeps one; an agent's `instructions` is `{path, state, ownLines?}`, `state` comparing Lithe's block in the file with the library (`absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge`, `unreadable`) and `ownLines` counting the user's own lines outside it; a library saved with `active` reads as that set `on`; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | | `agentLibrary.save` | Replace the library the user edited if it is still at the revision read (instruction sets each with `on` and `agents`; `active` is refused), then write Lithe's block in the instruction file of every agent that follows the library, never over a block edited outside Lithe, and answer each agent's `written`, `unchanged`, `skipped` or `failed` with its reason in `instructions` | @@ -9477,5 +9484,60 @@ prefixes, adjacent pairs of CJK characters and single CJK characters. A hit over 256 KiB, hits past 4 MiB in one search and hits the backend cannot read carry neither field; the search does not fail. -The session cache's layout version is 4: a cache of another version is deleted -and rebuilt from the session files on the first sync. +#### Usage features + +A plugin declares the usage features it implements for an agent in +`agents[].usage {rateLimits?, exchangeRates?, customPrices?, +rateLimitAlerts?}`; the catalog gives `usage` with each as a boolean. An +`agentUsage.*` command for a feature the declaration leaves out refuses with +`agentUsage.notDeclared` (`not_supported`), which the host shows as +unsupported. Core makes no network request for any of them. + +- `refreshRateLimits {pluginID, agentID}` calls the plugin function with + `{agentID}` (15 seconds), checks the answer as a `rateLimits` session event + (`agentUsage.invalidAnswer`), keeps it timed now and answers `{rateLimits}`, + the agent's entry as `agentSessions.stats` gives it. +- `refreshExchangeRates {pluginID, agentID, currencies}` takes 1–32 ISO 4217 + codes other than `USD` (`agentUsage.invalidCurrency`), calls the function + with `{agentID, base: "USD", currencies}` and accepts exactly `{rates}`, units + per US dollar above 0 and at most 10000000 for asked currencies. It answers + every kept rate, `{currency, perUSD, atMs, pluginID, agentID}`. + `setCurrency {currency}` takes a code with a kept rate + (`agentUsage.noExchangeRate`), or `null` or `USD`. Costs stay in US dollars; + `agentSessions.stats` adds `currency {code, perUSD, atMs}`. +- `setPrice {pluginID, agentID, model, price}`: `price` is `{input, output, + cacheRead?, cacheWrite?, reasoning?}` in US dollars per million tokens, 0 to + 100000 each, or `null`; at most 256 models per agent + (`agentUsage.invalidPrice`). The agent's calls of `model` use it whatever + provider served them, before the price table and without one. +- `setAlert {pluginID, agentID, window, thresholds}`: up to four percentages + 1–100, duplicates dropped, `[]` removing them; at most eight windows per + agent (`agentUsage.invalidAlert`). Rate-limit windows then carry `alert + {thresholds, reached?}`, and Core logs `agent.usage.alert_hit` when a kept + snapshot reaches a higher threshold than the one before it. +- `rateLimitHistory {pluginID, agentID, window?, sinceMs?, untilMs?}` answers + `{windows: [{window, label?, windowMinutes?, points: [{atMs, usedPercent, + resetsAtMs?}]}]}`, points oldest first (`agentUsage.invalidRange` when the + range ends before it starts). Every kept snapshot adds a point per window, + at least five minutes apart within a cycle (a closer reading replaces the + last value), a new cycle always starting one; points older than 35 days + and beyond 4000 per window are dropped, and `agentSessions.forget` removes + the agent's history. +- `read {}` answers `{currency?, exchangeRates, agents: [{pluginID, agentID, + prices, alerts}]}`. + +The settings (`usage-settings.json`) and history (`rate-limit-history.json`) +live owner-only in the `dataDirectory` of `agentSessions.configure`, which is +absolute and not the cache directory (`agentSessions.invalidDirectory`); +without it every command but `refreshRateLimits` refuses with +`agentUsage.notConfigured`. A settings file Core cannot read is moved to +`usage-settings.unreadable.json`. Changes and plugin calls run only for user +requests (`agentUsage.userActionRequired`). Other refusals: +`agentUsage.unknownAgent`, `agentUsage.notGranted` (the user enabled neither +running nor reading the agent), `agentUsage.backendUnavailable`, +`agentUsage.pluginFailed` and `agentUsage.saveFailed`. + +The session cache's layout version is 5, which added the `account`, +`purpose`, `cancelled` and `toolUses` of calls and the daily rows that count +them: a cache of another version is deleted and rebuilt from the session +files on the first sync. diff --git a/rust/crates/agent-runtime/src/files.rs b/rust/crates/agent-runtime/src/files.rs new file mode 100644 index 00000000..548b6fe1 --- /dev/null +++ b/rust/crates/agent-runtime/src/files.rs @@ -0,0 +1,104 @@ +//! Files the runtime keeps for itself or edits for the user: reads bounded +//! in size, and writes that replace a file whole, so that a reader sees +//! either the old bytes or the new ones and never part of a write. + +use std::fs; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Why a bounded read failed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ReadFailure { + /// The file is larger than the bound. + TooLarge, + /// Something other than a file is there, or reading it failed. + Io(io::ErrorKind), +} + +impl ReadFailure { + /// The failure's category, as log events name it. + pub(crate) fn kind(self) -> io::ErrorKind { + match self { + ReadFailure::TooLarge => io::ErrorKind::FileTooLarge, + ReadFailure::Io(kind) => kind, + } + } +} + +/// The bytes of the file at `path`, following links; `None` when nothing is +/// there. A file larger than `max` is refused without reading more than +/// `max + 1` bytes of it. +pub(crate) fn read_bounded(path: &Path, max: u64) -> Result>, ReadFailure> { + let failed = |error: io::Error| ReadFailure::Io(error.kind()); + let mut file = match fs::File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(failed(error)), + }; + let metadata = file.metadata().map_err(failed)?; + if !metadata.is_file() { + return Err(ReadFailure::Io(io::ErrorKind::InvalidInput)); + } + if metadata.len() > max { + return Err(ReadFailure::TooLarge); + } + let mut bytes = Vec::new(); + Read::by_ref(&mut file) + .take(max + 1) + .read_to_end(&mut bytes) + .map_err(failed)?; + if bytes.len() as u64 > max { + return Err(ReadFailure::TooLarge); + } + Ok(Some(bytes)) +} + +/// A new name next to `target`, unique within the process, for a file +/// written for `purpose` and then renamed over `target` or removed. +pub(crate) fn sibling_temporary(target: &Path, purpose: &str) -> Option { + static NEXT: AtomicU64 = AtomicU64::new(0); + let parent = target.parent()?; + let name = target.file_name()?.to_string_lossy(); + Some(parent.join(format!( + ".{name}.lithe-{purpose}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + ))) +} + +/// Replaces the file at `target` with `bytes`: a new owner-only file next +/// to it, given the old file's permissions when there is one, written to +/// disk, then renamed over it. `target` is never a link; callers resolve +/// links first. When the write fails and the new file cannot be removed +/// either, `kept` hears why, since that file may hold a copy of `bytes`. +pub(crate) fn replace_file( + target: &Path, + bytes: &[u8], + kept: impl FnOnce(&io::Error), +) -> io::Result<()> { + let temporary = sibling_temporary(target, "write") + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + let existing = fs::metadata(target).ok(); + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + lithe_platform::fs::owner_only_file(&mut options); + let result = (|| { + let mut file = options.open(&temporary)?; + file.write_all(bytes)?; + if let Some(metadata) = &existing { + fs::set_permissions(&temporary, metadata.permissions())?; + } + file.sync_all()?; + drop(file); + fs::rename(&temporary, target) + })(); + if result.is_err() { + if let Err(error) = fs::remove_file(&temporary) { + if error.kind() != io::ErrorKind::NotFound { + kept(&error); + } + } + } + result +} diff --git a/rust/crates/agent-runtime/src/interaction.rs b/rust/crates/agent-runtime/src/interaction.rs index 9657c96c..03fb8b59 100644 --- a/rust/crates/agent-runtime/src/interaction.rs +++ b/rust/crates/agent-runtime/src/interaction.rs @@ -4,7 +4,7 @@ //! because the engine may call back while holding its own backend lock. use crate::live::{self, LiveSession}; -use crate::Runtime; +use crate::{refusal, require_user, Runtime}; use lithe_plugin_rpc::{codes, AGENTS_DID_ANSWER_QUESTION, AGENTS_DID_CANCEL, AGENTS_DID_PROMPT}; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; @@ -234,7 +234,7 @@ pub(crate) enum Delivery { pub(crate) fn send(session: &LiveSession, delivery: Delivery) -> Result<(), CoreError> { session.interaction_sender.try_send(delivery).map_err(|_| { - live::refusal( + refusal( ErrorCode::InvalidRequest, "agents.interactionBusy", "The agent input queue is busy; try again.", @@ -443,7 +443,7 @@ pub(crate) fn worker( pub(crate) fn delivered(receiver: mpsc::Receiver) -> Result<(), CoreError> { match receiver.recv_timeout(std::time::Duration::from_secs(5)) { Ok(true) | Err(mpsc::RecvTimeoutError::Timeout) => Ok(()), - _ => Err(live::refusal( + _ => Err(refusal( ErrorCode::ProcessFailed, "agents.backendUnavailable", "The agent backend did not acknowledge the input.", @@ -474,7 +474,7 @@ pub(crate) fn respond_question(runtime: &Arc, payload: Value) -> Result cancelled: bool, } let request: Request = crate::decode(payload)?; - live::require_user("answer a question of")?; + require_user(|| live::user_action_required("answer a question of"))?; let session = runtime.live.session(&request.session)?; let mut state = session.lock_turns(); let pending = state @@ -482,7 +482,7 @@ pub(crate) fn respond_question(runtime: &Arc, payload: Value) -> Result .questions .get(&request.request) .ok_or_else(|| { - live::refusal( + refusal( ErrorCode::InvalidRequest, "agents.questionNotPending", "This question is no longer waiting for an answer.", @@ -493,7 +493,7 @@ pub(crate) fn respond_question(runtime: &Arc, payload: Value) -> Result || state.interaction.stopping || state.active_turn != Some(pending.turn) { - return Err(live::refusal( + return Err(refusal( ErrorCode::InvalidRequest, "agents.questionNotPending", "The question's turn is stopping or ended.", @@ -524,7 +524,7 @@ pub(crate) fn respond_question(runtime: &Arc, payload: Value) -> Result }) }; if !valid { - return Err(live::refusal( + return Err(refusal( ErrorCode::InvalidRequest, "agents.invalidQuestionAnswer", "Answer each question using its options or allowed text.", @@ -558,11 +558,11 @@ pub(crate) fn update_queue(runtime: &Arc, payload: Value) -> Result, payload: Value) -> Result self.records.resume(self, payload), "agentSessions.export" => self.records.export(self, payload), "agentSessions.subagents" => self.records.subagents(self, payload), + "agentUsage.read" => self.records.usage_read(self, payload), + "agentUsage.setPrice" => self.records.usage_set_price(self, payload), + "agentUsage.setAlert" => self.records.usage_set_alert(self, payload), + "agentUsage.setCurrency" => self.records.usage_set_currency(payload), + "agentUsage.refreshRateLimits" => self.records.usage_refresh_rate_limits(self, payload), + "agentUsage.refreshExchangeRates" => { + self.records.usage_refresh_exchange_rates(self, payload) + } + "agentUsage.rateLimitHistory" => self.records.usage_rate_limit_history(self, payload), "agentLibrary.configure" => self.library.configure(payload), "agentLibrary.read" => self.library.read(self, payload), "agentLibrary.save" => self.library.save(self, payload), @@ -186,7 +198,8 @@ fn runtime() -> &'static Arc { }) } -/// Runs one `agents.*`, `agentSessions.*` or `agentLibrary.*` command. +/// Runs one `agents.*`, `agentSessions.*`, `agentUsage.*`, `agentLibrary.*` +/// or `agentProviders.*` command. pub fn execute(command: &str, payload: Value) -> Result { runtime().execute(command, payload) } @@ -202,6 +215,23 @@ pub(crate) fn decode(payload: Value) -> Result CoreError { + CoreError::new(code, message).with_details(details) +} + +/// Lets through only a request the user made; any other, from a plugin or +/// the background, gets the refusal `refused` makes. Commands that change +/// what the user owns, or act for the user, check this first. +pub(crate) fn require_user(refused: impl FnOnce() -> CoreError) -> Result<(), CoreError> { + if lithe_request_context::trace::current().source == lithe_request_context::Source::User { + Ok(()) + } else { + Err(refused()) + } +} + /// Milliseconds since the Unix epoch. pub(crate) fn now_ms() -> i64 { SystemTime::now() diff --git a/rust/crates/agent-runtime/src/library.rs b/rust/crates/agent-runtime/src/library.rs index 9f416ad3..274a48ab 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -55,16 +55,16 @@ pub(crate) use providers::is_endpoint_for_test; use crate::backend::BackendLink; use crate::catalog::CatalogAgent; -use crate::{log, Runtime}; +use crate::files::{read_bounded, replace_file, sibling_temporary, ReadFailure}; +use crate::{log, refusal, require_user, Runtime}; use lithe_plugin_agents::{resolve_root, ConfigurationDeclaration}; use lithe_protocol::{CoreError, ErrorCode}; -use lithe_request_context::Source; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::fs; -use std::io::{self, Read, Write}; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, PoisonError, RwLock}; @@ -768,39 +768,6 @@ impl Snapshot { // --------------------------------------------------------------------------- // Files. -/// Why a bounded read failed. -#[derive(Debug)] -enum ReadFailure { - TooLarge, - Io, -} - -/// The bytes of the file at `path`, following links; `None` when nothing is -/// there. -fn read_bounded(path: &Path, max: u64) -> Result>, ReadFailure> { - let mut file = match fs::File::open(path) { - Ok(file) => file, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), - Err(_) => return Err(ReadFailure::Io), - }; - let metadata = file.metadata().map_err(|_| ReadFailure::Io)?; - if !metadata.is_file() { - return Err(ReadFailure::Io); - } - if metadata.len() > max { - return Err(ReadFailure::TooLarge); - } - let mut bytes = Vec::new(); - Read::by_ref(&mut file) - .take(max + 1) - .read_to_end(&mut bytes) - .map_err(|_| ReadFailure::Io)?; - if bytes.len() as u64 > max { - return Err(ReadFailure::TooLarge); - } - Ok(Some(bytes)) -} - fn digest(bytes: &[u8]) -> String { Sha256::digest(bytes) .iter() @@ -808,51 +775,12 @@ fn digest(bytes: &[u8]) -> String { .collect() } -/// A new name next to `target` for a file that replaces it. -fn sibling_temporary(target: &Path, purpose: &str) -> Option { - static NEXT: AtomicU64 = AtomicU64::new(0); - let parent = target.parent()?; - let name = target.file_name()?.to_string_lossy(); - Some(parent.join(format!( - ".{name}.lithe-{purpose}-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - ))) -} - -/// Replaces the file at `target` with `bytes`: a new file next to it, with -/// the old file's permissions (owner-only for a new file), written to disk, -/// then renamed over it. `target` is never a link; callers resolve links -/// first. +/// [`replace_file`] for the library: a new file left behind by a failed +/// write is logged as a [`Leftover::Temporary`]. fn write_replacing(target: &Path, bytes: &[u8]) -> io::Result<()> { - let temporary = sibling_temporary(target, "write") - .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; - let existing = fs::metadata(target).ok(); - let mut options = fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; - let mode = existing - .as_ref() - .map_or(0o600, |metadata| metadata.permissions().mode() & 0o7777); - options.mode(mode); - } - let result = (|| { - let mut file = options.open(&temporary)?; - file.write_all(bytes)?; - if let Some(metadata) = &existing { - // The mode given to `open` is narrowed by the umask. - fs::set_permissions(&temporary, metadata.permissions())?; - } - file.sync_all()?; - drop(file); - fs::rename(&temporary, target) - })(); - if result.is_err() { - remove_leftover(&temporary, Leftover::Temporary); - } - result + replace_file(target, bytes, |error| { + leftover_kept(Leftover::Temporary, error) + }) } /// What the library leaves behind when it cannot clean up after itself, @@ -1044,7 +972,7 @@ fn unquote(value: &str) -> String { fn skill_description(directory: &Path) -> Option> { let bytes = match read_bounded(&directory.join(SKILL_FILE), MAX_SKILL_FILE_BYTES) { Ok(Some(bytes)) => bytes, - Ok(None) | Err(ReadFailure::Io) => return None, + Ok(None) | Err(ReadFailure::Io(_)) => return None, // A skill too large to read for its description is still a skill. Err(ReadFailure::TooLarge) => return Some(None), }; @@ -1104,7 +1032,7 @@ fn agent_skills(root: &Path, library: &Path) -> Result, ReadFail let entries = match fs::read_dir(root) { Ok(entries) => entries, Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(_) => return Err(ReadFailure::Io), + Err(error) => return Err(ReadFailure::Io(error.kind())), }; let library_skills = library.join(SKILLS_DIRECTORY); let mut skills = Vec::new(); @@ -1189,10 +1117,6 @@ fn copy_tree(from: &Path, to: &Path, depth: usize, copied: &mut Copied) -> Resul // --------------------------------------------------------------------------- // Refusals. -fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { - CoreError::new(code, message).with_details(details) -} - fn not_configured() -> CoreError { refusal( ErrorCode::InvalidRequest, @@ -1236,7 +1160,7 @@ fn too_large_skill() -> CoreError { fn read_failure(failure: ReadFailure) -> CoreError { match failure { ReadFailure::TooLarge => too_large_file(), - ReadFailure::Io => unreadable_file(), + ReadFailure::Io(_) => unreadable_file(), } } @@ -1256,16 +1180,13 @@ fn invalid_change(message: &str) -> CoreError { ) } -fn require_user() -> Result<(), CoreError> { - if lithe_request_context::trace::current().source == Source::User { - Ok(()) - } else { - Err(refusal( - ErrorCode::PermissionDenied, - "agentLibrary.userActionRequired", - "Only the user can change the agent library or an agent's configuration.", - )) - } +/// The refusal of a change the user did not make, for [`require_user`]. +fn user_action_required() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentLibrary.userActionRequired", + "Only the user can change the agent library or an agent's configuration.", + ) } // --------------------------------------------------------------------------- @@ -2026,7 +1947,7 @@ impl Library { revision: String, library: LibraryData, } - require_user()?; + require_user(user_action_required)?; let request: SaveRequest = crate::decode(payload)?; let config = self.config()?; if let Err(field) = request.library.check() { @@ -2062,7 +1983,7 @@ impl Library { /// `agentLibrary.apply`: one change to one agent's configuration. pub fn apply(&self, runtime: &Runtime, payload: Value) -> Result { - require_user()?; + require_user(user_action_required)?; let request: ApplyRequest = crate::decode(payload)?; let started = Instant::now(); let agent = configurable_agent(runtime, &request.agent)?; @@ -2495,7 +2416,7 @@ impl Library { #[serde(default)] directory: Option, } - require_user()?; + require_user(user_action_required)?; let request: ImportRequest = crate::decode(payload)?; let config = self.config()?; let source = match (&request.agent, &request.name, &request.directory) { @@ -2628,7 +2549,7 @@ impl Library { struct RemoveRequest { name: String, } - require_user()?; + require_user(user_action_required)?; let request: RemoveRequest = crate::decode(payload)?; let config = self.config()?; if !is_skill_name(&request.name) { diff --git a/rust/crates/agent-runtime/src/library/backups.rs b/rust/crates/agent-runtime/src/library/backups.rs index 766eaba0..7793b719 100644 --- a/rust/crates/agent-runtime/src/library/backups.rs +++ b/rust/crates/agent-runtime/src/library/backups.rs @@ -38,8 +38,9 @@ use super::{ agent_paths, configurable_agent, digest, ensure_private_directory, leftover_kept, read_bounded, - real_file, refusal, remove_leftover, require_user, write_replacing, Config, Leftover, Library, - INSTRUCTIONS_BACKUP_ID, MAX_CONFIGURATION_FILE_BYTES, MAX_LIBRARY_FILE_BYTES, + real_file, refusal, remove_leftover, require_user, user_action_required, write_replacing, + Config, Leftover, Library, INSTRUCTIONS_BACKUP_ID, MAX_CONFIGURATION_FILE_BYTES, + MAX_LIBRARY_FILE_BYTES, }; use crate::{log, Runtime}; use lithe_protocol::{CoreError, ErrorCode}; @@ -460,7 +461,7 @@ impl Library { /// `discardLaterChanges`. Putting the instruction file back stops the /// agent following the library, answered as `unfollowed`. pub fn restore_backup(&self, runtime: &Runtime, payload: Value) -> Result { - require_user()?; + require_user(user_action_required)?; let request: RestoreRequest = crate::decode(payload)?; let started = Instant::now(); let agent = configurable_agent(runtime, &request.agent)?; diff --git a/rust/crates/agent-runtime/src/library/instructions.rs b/rust/crates/agent-runtime/src/library/instructions.rs index c2e688d2..5251ee42 100644 --- a/rust/crates/agent-runtime/src/library/instructions.rs +++ b/rust/crates/agent-runtime/src/library/instructions.rs @@ -379,7 +379,9 @@ fn assess(file: Option<&str>, wanted: &str, written: Option<&str>) -> Assessment /// The instruction file's text; a file that is not UTF-8 cannot be read. fn read_text(path: &Path) -> Result, ReadFailure> { read_bounded(path, MAX_INSTRUCTIONS_FILE_BYTES)? - .map(|bytes| String::from_utf8(bytes).map_err(|_| ReadFailure::Io)) + .map(|bytes| { + String::from_utf8(bytes).map_err(|_| ReadFailure::Io(std::io::ErrorKind::InvalidData)) + }) .transpose() } @@ -394,7 +396,7 @@ pub(super) fn entry(path: &Path, wanted: &str, written: Option<&str>) -> Value { entry["ownLines"] = json!(assessed.own_lines); } Err(ReadFailure::TooLarge) => entry["state"] = json!(State::TooLarge.token()), - Err(ReadFailure::Io) => entry["state"] = json!(State::Unreadable.token()), + Err(ReadFailure::Io(_)) => entry["state"] = json!(State::Unreadable.token()), } entry } diff --git a/rust/crates/agent-runtime/src/library/providers.rs b/rust/crates/agent-runtime/src/library/providers.rs index dca8a641..0321c910 100644 --- a/rust/crates/agent-runtime/src/library/providers.rs +++ b/rust/crates/agent-runtime/src/library/providers.rs @@ -39,8 +39,8 @@ use super::backups; use super::saved::{self, SavedProvider}; use super::{ agent_paths, backend_unavailable, check_description, check_name, configurable_agent, - files_param, path_text, refusal, require_user, with_staged, AgentPaths, Check, Config, Library, - FUNCTION_TIMEOUT, + files_param, path_text, refusal, require_user, user_action_required, with_staged, AgentPaths, + Check, Config, Library, FUNCTION_TIMEOUT, }; use crate::backend::BackendLink; use crate::catalog::CatalogAgent; @@ -1760,7 +1760,7 @@ impl Library { /// `agentProviders.apply`: one declared change to one agent's model, /// providers or profile. pub fn apply_providers(&self, runtime: &Runtime, payload: Value) -> Result { - require_user()?; + require_user(user_action_required)?; let request: ApplyRequest = crate::decode(payload)?; let started = Instant::now(); let agent = configurable_agent(runtime, &request.agent)?; diff --git a/rust/crates/agent-runtime/src/library/providers/models.rs b/rust/crates/agent-runtime/src/library/providers/models.rs index 65229abc..67e43058 100644 --- a/rust/crates/agent-runtime/src/library/providers/models.rs +++ b/rust/crates/agent-runtime/src/library/providers/models.rs @@ -19,12 +19,14 @@ //! //! Core remembers the model IDs each agent's plugin last listed, in memory //! ([`Catalogs`]), so a switch the user flips is checked without asking the -//! plugin again; a plugin that writes the menu is always read again. +//! plugin again; a plugin that writes the menu is always read again. It +//! remembers their context windows too, which the session records use to +//! tell how full a call's context was. use super::super::{ agent_paths, check_name, configurable_agent, ensure_private_directory, read_bounded, - require_user, unreadable_file, write_failed, write_replacing, Config, Library, - MAX_LIBRARY_FILE_BYTES, + require_user, unreadable_file, user_action_required, write_failed, write_replacing, Config, + Library, MAX_LIBRARY_FILE_BYTES, }; use super::{ check_level_value, check_model_ids, declaration, invalid_change, log_change, not_declared, @@ -139,22 +141,40 @@ pub(super) fn shown_view(view: &mut Value, hidden: &[String]) { // --------------------------------------------------------------------------- // The models each plugin last listed. -/// The IDs of the models each agent's plugin last listed, by agent record -/// key, from the last snapshot Core read for the agent itself (never from a -/// staged copy). At most one list of at most `MAX_MODELS` IDs per agent the +/// The models each agent's plugin last listed, by agent record key, from +/// the last snapshot Core read for the agent itself (never from a staged +/// copy). At most one list of at most `MAX_MODELS` models per agent the /// catalog has. #[derive(Default)] -pub(in crate::library) struct Catalogs(Mutex>>); +pub(in crate::library) struct Catalogs(Mutex>); + +/// The IDs of the models one snapshot listed, and the context windows of +/// those that report one. +#[derive(Default)] +struct Listed { + ids: Vec, + context_windows: BTreeMap, +} impl Catalogs { - fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap>> { + fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap> { self.0.lock().unwrap_or_else(PoisonError::into_inner) } /// Remembers the models a snapshot of the agent lists. pub(super) fn remember(&self, agent_key: &str, snapshot: &ProvidersSnapshot) { - self.lock() - .insert(agent_key.to_string(), listed_ids(snapshot)); + let context_windows = snapshot + .models + .iter() + .filter_map(|model| Some((model.id.clone(), model.context_window?))) + .collect(); + self.lock().insert( + agent_key.to_string(), + Listed { + ids: listed_ids(snapshot), + context_windows, + }, + ); } /// Forgets the agents not in `keys`, such as those of a removed plugin. @@ -163,7 +183,20 @@ impl Catalogs { } fn get(&self, agent_key: &str) -> Option> { - self.lock().get(agent_key).cloned() + self.lock().get(agent_key).map(|listed| listed.ids.clone()) + } +} + +impl Library { + /// The context window in tokens of each model the agent's plugin last + /// listed with one, by model ID; empty when Core has not read the + /// agent's models in this run. + pub(crate) fn context_windows(&self, agent_key: &str) -> BTreeMap { + self.catalogs + .lock() + .get(agent_key) + .map(|listed| listed.context_windows.clone()) + .unwrap_or_default() } } @@ -269,7 +302,7 @@ impl Library { /// `agentProviders.showModels`: shows and hides listed models in Lithe's /// pickers, and in the CLI's own menu when the plugin writes it. pub fn show_models(&self, runtime: &Runtime, payload: Value) -> Result { - require_user()?; + require_user(user_action_required)?; let request: ShowRequest = crate::decode(payload)?; let started = Instant::now(); let agent = configurable_agent(runtime, &request.agent)?; @@ -414,7 +447,7 @@ impl Library { runtime: &Runtime, payload: Value, ) -> Result { - require_user()?; + require_user(user_action_required)?; let request: ApplySettingsRequest = crate::decode(payload)?; let started = Instant::now(); let agent = configurable_agent(runtime, &request.agent)?; diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index 19b80fb8..85785e14 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -14,7 +14,7 @@ //! session ID, the plugin and agent IDs and stable codes only. use crate::events::{EventQueue, ReportRefusal, SessionEvent, TurnState, MAX_EVENTS_PER_REPORT}; -use crate::{log, log_fields, Runtime}; +use crate::{log, log_fields, refusal, require_user, Runtime}; use lithe_lsp_engine::agent_host::{AgentBackend, AgentHostFailure}; use lithe_lsp_transport::process::{LspProcessHandle, LspProcessSpec}; use lithe_plugin_rpc::{ @@ -22,7 +22,6 @@ use lithe_plugin_rpc::{ AGENTS_DID_PROMPT, AGENTS_DID_SET_CONFIG_OPTION, AGENTS_DID_START, }; use lithe_protocol::{CoreError, ErrorCode}; -use lithe_request_context::Source; use serde::Deserialize; use serde_json::{json, Value}; use std::collections::{BTreeMap, VecDeque}; @@ -467,20 +466,14 @@ struct StartRequest { environment: BTreeMap, } -pub(crate) fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { - CoreError::new(code, message).with_details(details) -} - -pub(crate) fn require_user(action: &str) -> Result<(), CoreError> { - if lithe_request_context::trace::current().source == Source::User { - Ok(()) - } else { - Err(refusal( - ErrorCode::PermissionDenied, - "agents.userActionRequired", - &format!("Only the user can {action} an agent session."), - )) - } +/// The refusal of `action` on a session by anyone but the user, for +/// [`require_user`]. +pub(crate) fn user_action_required(action: &str) -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agents.userActionRequired", + &format!("Only the user can {action} an agent session."), + ) } /// `agents.start`: starts a native session of an agent. @@ -506,7 +499,7 @@ pub(crate) fn start(runtime: &Arc, payload: Value) -> Result, request: StartRequest) -> Result { - require_user("start")?; + require_user(|| user_action_required("start"))?; if lithe_workspace::is_remote() { return Err(refusal( ErrorCode::NotSupported, @@ -1125,7 +1118,7 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result MAX_PROMPT_BYTES || (request.text.trim().is_empty() && request.attachments.is_empty()) { @@ -1300,7 +1293,7 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result, payload: Value) -> Result { let request: SessionRequest = crate::decode(payload)?; - require_user("stop")?; + require_user(|| user_action_required("stop"))?; let session = runtime.live.session(&request.session)?; let mut state = session.lock_turns(); let Some(turn) = state.active_turn else { @@ -1347,7 +1340,7 @@ pub(crate) fn respond_permission( option: String, } let request: PermissionAnswer = crate::decode(payload)?; - require_user("answer a permission request of")?; + require_user(|| user_action_required("answer a permission request of"))?; let session = runtime.live.session(&request.session)?; let turn = session .lock_turns() @@ -1405,7 +1398,7 @@ pub(crate) fn set_config_option( value: String, } let request: ConfigAnswer = crate::decode(payload)?; - require_user("change a setting of")?; + require_user(|| user_action_required("change a setting of"))?; let session = runtime.live.session(&request.session)?; session .lock_turns() diff --git a/rust/crates/agent-runtime/src/projection/command.rs b/rust/crates/agent-runtime/src/projection/command.rs index 22acaf80..26709b1a 100644 --- a/rust/crates/agent-runtime/src/projection/command.rs +++ b/rust/crates/agent-runtime/src/projection/command.rs @@ -1,7 +1,7 @@ //! Application-only operations for an in-memory view. No operation reads files or starts a CLI. use super::{Projection, Value}; -use crate::live::refusal; +use crate::refusal; use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::json; diff --git a/rust/crates/agent-runtime/src/projection/wire.rs b/rust/crates/agent-runtime/src/projection/wire.rs index 9ef4f7b0..1e8d3c2f 100644 --- a/rust/crates/agent-runtime/src/projection/wire.rs +++ b/rust/crates/agent-runtime/src/projection/wire.rs @@ -1,7 +1,7 @@ //! Split unusually large rows, file lists or interaction headers at the application boundary. //! Normal deltas take the fast path without allocating another serialized copy. use super::{Value, PAGE_BYTES}; -use crate::live::refusal; +use crate::refusal; use lithe_protocol::{CoreError, ErrorCode}; use serde_json::json; use std::collections::VecDeque; diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index eab4d778..4408b9df 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -7,7 +7,9 @@ //! The cache lives in the directory the host names, which is in the platform's //! Caches directory and never in the application bundle; deleting it loses //! nothing the agents' own files do not hold, except the last rate-limit -//! snapshots in `rate-limits.json`. +//! snapshots in `rate-limits.json`. What the user sets and the rate-limit +//! history are user data and live in a data directory instead (`usage` and +//! `history`). //! //! Two connections to the cache keep a long sync from blocking the views: the //! writer syncs and forgets, the reader lists, searches, reads and sums. The @@ -21,9 +23,11 @@ use crate::backend::BackendLink; use crate::catalog::{record_key, split_record_key, CatalogAgent}; use crate::events::{check_rate_limits, RateLimits, RateWindow, MAX_RATE_WINDOWS}; -use crate::{log, now_ms, Runtime}; +use crate::{log, now_ms, refusal, Runtime}; use lithe_agent_sessions::folder_category; -use lithe_agent_sessions::pricing::{call_cost, PriceTable}; +use lithe_agent_sessions::pricing::{call_cost, Price, PriceTable}; +use lithe_agent_sessions::stats::messages::MessageCounter; +use lithe_agent_sessions::stats::sessions::SessionTally; use lithe_agent_sessions::stats::{ call_speed, model_name, CallSelector, GroupBy, Overview, OverviewQuery, SpeedRanker, Summarizer, }; @@ -38,7 +42,7 @@ use lithe_plugin_rpc::codes; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use std::collections::{BTreeMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, VecDeque}; use std::fs; use std::path::{Path, PathBuf}; use std::sync::{Mutex, MutexGuard, PoisonError, RwLock}; @@ -77,7 +81,8 @@ const MAX_CALLS_PAGE: usize = 500; /// keeps while it walks the cache. const MAX_CALLS_OFFSET: usize = 50_000; -/// Longest directory `agentSessions.list`'s `cwdUnder` takes, in bytes. +/// Longest directory `agentSessions.list`'s `cwdUnder` and the `cwds` of +/// `agentSessions.stats` and `agentSessions.calls` take, in bytes. const MAX_FILTER_DIRECTORY_BYTES: usize = 4096; /// Largest `rate-limits.json` Core loads. @@ -88,9 +93,11 @@ const RATE_FILE: &str = "rate-limits.json"; const MILLISECONDS_PER_DAY: i64 = 86_400_000; mod export; +pub(crate) mod history; mod resume; mod snippets; mod subagents; +mod usage; /// Where the cache is and what the session roots resolve against. #[derive(Debug, Clone)] @@ -104,7 +111,7 @@ struct Config { /// The latest rate-limit state of one agent. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -struct RateSnapshot { +pub(crate) struct RateSnapshot { /// When the agent reported it, in Unix milliseconds. at_ms: i64, windows: Vec, @@ -113,7 +120,7 @@ struct RateSnapshot { } impl RateSnapshot { - fn new(limits: RateLimits, at_ms: i64) -> Self { + pub(crate) fn new(limits: RateLimits, at_ms: i64) -> Self { Self { at_ms, windows: limits.windows, @@ -141,8 +148,12 @@ pub(crate) struct Records { writer: Mutex>, reader: Mutex>, config: RwLock>, + /// The table from the host's prices file. + table: RwLock>, + /// The table with the prices the user set; what every cost uses. prices: RwLock>, rate_limits: Mutex>, + usage: Mutex, } fn not_configured() -> CoreError { @@ -153,10 +164,6 @@ fn not_configured() -> CoreError { .with_details("agentSessions.notConfigured") } -fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { - CoreError::new(code, message).with_details(details) -} - impl Records { fn config(&self) -> Option { self.config @@ -194,14 +201,24 @@ impl Records { /// A models.dev `api.json` the host keeps, to price calls. #[serde(default)] prices_file: Option, + /// A directory of the platform's application data for the + /// user's usage settings and the rate-limit history. + #[serde(default)] + data_directory: Option, } let request: ConfigureRequest = crate::decode(payload)?; let cache_directory = PathBuf::from(&request.cache_directory); - if !cache_directory.is_absolute() || !Path::new(&request.user_home).is_absolute() { + let data_directory = request.data_directory.as_deref().map(PathBuf::from); + if !cache_directory.is_absolute() + || !Path::new(&request.user_home).is_absolute() + || data_directory + .as_deref() + .is_some_and(|directory| !directory.is_absolute() || directory == cache_directory) + { return Err(refusal( ErrorCode::InvalidRequest, "agentSessions.invalidDirectory", - "The cache directory and user home must be absolute paths.", + "The cache directory, data directory and user home must be absolute paths, and the data directory is not the cache directory.", )); } if request.environment.len() > 256 @@ -217,6 +234,14 @@ impl Records { )); } + // Everything that can fail is opened before anything is replaced, so + // a refused configure leaves the previous one in place. + let same_data = self.lock_usage().directory() == data_directory.as_deref(); + let usage = match (&data_directory, same_data) { + (_, true) => None, + (Some(directory), false) => Some(usage::UsageState::open(directory)?), + (None, false) => Some(usage::UsageState::default()), + }; let same_directory = self .config() .is_some_and(|config| config.cache_directory == cache_directory); @@ -227,6 +252,9 @@ impl Records { *self.lock_reader() = Some(reader); *self.lock_rates() = load_rate_file(&cache_directory); } + if let Some(usage) = usage { + *self.lock_usage() = usage; + } *self.config.write().unwrap_or_else(PoisonError::into_inner) = Some(Config { cache_directory, user_home: request.user_home, @@ -234,22 +262,42 @@ impl Records { }); let mut answer = json!({}); - match request.prices_file.as_deref().map(load_prices) { - None => { - *self.prices.write().unwrap_or_else(PoisonError::into_inner) = None; - } + let table = match request.prices_file.as_deref().map(load_prices) { + None => None, Some(Ok(table)) => { answer["pricedModels"] = json!(table.len()); - *self.prices.write().unwrap_or_else(PoisonError::into_inner) = Some(table); + Some(table) } Some(Err(error)) => { - *self.prices.write().unwrap_or_else(PoisonError::into_inner) = None; answer["pricesError"] = json!(error.code); + None } - } + }; + *self.table.write().unwrap_or_else(PoisonError::into_inner) = table; + let overrides = self.lock_usage().overrides(); + self.apply_overrides(overrides); Ok(answer) } + /// Makes the prices every cost uses: the host's table with the prices + /// the user set, which apply even without a table. + fn apply_overrides(&self, overrides: HashMap>) { + let table = self + .table + .read() + .unwrap_or_else(PoisonError::into_inner) + .clone(); + let prices = match table { + None if overrides.is_empty() => None, + table => { + let mut table = table.unwrap_or_default(); + table.set_overrides(overrides); + Some(table) + } + }; + *self.prices.write().unwrap_or_else(PoisonError::into_inner) = prices; + } + /// `agentSessions.sync`: brings the records of one agent up to date. pub fn sync(&self, runtime: &Runtime, payload: Value) -> Result { let request: AgentRequest = crate::decode(payload)?; @@ -360,6 +408,7 @@ impl Records { if removed_limits { self.save_rate_file(); } + self.forget_history(&key); log( "agent.records.removed", [ @@ -983,13 +1032,33 @@ impl Records { #[serde(default)] providers: Vec, #[serde(default)] + accounts: Vec, + #[serde(default)] + purposes: Vec, + #[serde(default)] + cwds: Vec, + #[serde(default)] failed: Option, #[serde(default)] + cancelled: Option, + #[serde(default)] search: Option, #[serde(default)] detail: bool, #[serde(default)] overview: Option, + /// Figures per session, with at most `top` costliest sessions. + #[serde(default)] + sessions: Option, + /// Messages per hour or day. + #[serde(default)] + messages: bool, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct SessionsQuery { + #[serde(default)] + top: usize, } let request: StatsRequest = crate::decode(payload)?; let group_by = parse_group_by( @@ -1002,7 +1071,7 @@ impl Records { refusal( ErrorCode::InvalidRequest, "agentSessions.invalidGroup", - "Group by hour, day, agent, model, provider, modelProvider, session, cwd or all. Only hour accepts hourAnchorMs.", + "Group by hour, day, agent, model, provider, modelProvider, account, purpose, session, cwd or all. Only hour accepts hourAnchorMs.", ) })?; let split_by = request @@ -1013,104 +1082,200 @@ impl Records { refusal( ErrorCode::InvalidRequest, "agentSessions.invalidSplit", - "Split by agent, model, provider or modelProvider.", + "Split by agent, model, provider, modelProvider, account or purpose.", ) }) }) .transpose()?; let selector = call_selector( - request.models, - request.providers, - request.failed, + CallSelector { + models: request.models, + providers: request.providers, + accounts: request.accounts, + purposes: request.purposes, + failed: request.failed, + cancelled: request.cancelled, + cwds: request.cwds, + words: Vec::new(), + }, request.search.as_deref(), )?; + let messages = request + .messages + .then(|| { + MessageCounter::new(group_by, request.overview.as_ref()).ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidMessagesGroup", + "Messages are counted by hour or day.", + ) + }) + }) + .transpose()?; let readable = allowed_agents(runtime, request.agents); - if let Some(calendar) = request.overview { - let split = split_by.ok_or_else(|| { - refusal( - ErrorCode::InvalidRequest, - "agentSessions.invalidSplit", - "An overview requires splitBy.", - ) - })?; - if !matches!(group_by, GroupBy::Day { .. } | GroupBy::Hour { .. }) { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentSessions.invalidOverviewGroup", - "An overview requires day or hour grouping.", - )); - } - if !request.detail { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentSessions.invalidOverviewDetail", - "An overview requires detail.", - )); - } - if !calendar.valid() { - return Err(refusal( - ErrorCode::InvalidRequest, - "agentSessions.invalidCalendar", - "Supply valid offsets and chronologically ordered changes for the overview.", - )); - } - let result = if let Some(agents) = readable { + let filter = readable.map(|agents| CallFilter { + agents, + session_id: request.session_id, + since_ms: request.since_ms, + until_ms: request.until_ms, + }); + let mut answer = match &request.overview { + Some(calendar) => self.overview( + filter.as_ref(), + &selector, + group_by, + split_by, + calendar, + request.detail, + )?, + None => match &filter { + None => json!({ "summaries": [], "speeds": [] }), + Some(filter) => { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + let (summaries, speeds) = self.summarize( + store, + filter, + group_by, + split_by, + &selector, + request.detail, + )?; + json!({ "summaries": summaries, "speeds": speeds }) + } + }, + }; + if matches!(group_by, GroupBy::Cwd) { + self.add_folder_categories(&mut answer["summaries"]); + } + if let Some(query) = request.sessions { + answer["sessions"] = self.session_figures(filter.as_ref(), &selector, query.top)?; + } + if let Some(mut counter) = messages { + if let Some(filter) = &filter { let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; - let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); - store.usage_overview( - &CallFilter { - agents, - session_id: request.session_id, - since_ms: request.since_ms, - until_ms: request.until_ms, - }, - &selector, - prices.as_ref(), - group_by, - split, - &calendar, - )? - } else { - Overview::default() - }; - if let Some(reason) = result.cache_warning { - log( - "agent.records.usage_cache_failed", - [("reason", json!(reason))], - ); + store.for_each_message_time(filter, |at_ms| counter.add(at_ms))?; } - return Ok( - json!({"summaries": result.summaries, "groups": result.groups, - "series": result.series, "rateLimits": self.rate_limit_entries(runtime)}), + answer["messages"] = + serde_json::to_value(counter.finish()).unwrap_or_else(|_| json!([])); + } + answer["rateLimits"] = json!(self.rate_limit_entries(runtime)); + if let Some(currency) = self.currency_entry() { + answer["currency"] = currency; + } + Ok(answer) + } + + /// The overview of a statistics request: its summaries, groups and + /// series from the daily cache. + fn overview( + &self, + filter: Option<&CallFilter>, + selector: &CallSelector, + group_by: GroupBy, + split_by: Option, + calendar: &OverviewQuery, + detail: bool, + ) -> Result { + let split = split_by.ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidSplit", + "An overview requires splitBy.", + ) + })?; + if !matches!(group_by, GroupBy::Day { .. } | GroupBy::Hour { .. }) { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidOverviewGroup", + "An overview requires day or hour grouping.", + )); + } + if !detail { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidOverviewDetail", + "An overview requires detail.", + )); + } + if !calendar.valid() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidCalendar", + "Supply valid offsets and chronologically ordered changes for the overview.", + )); + } + let result = if let Some(filter) = filter { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); + store.usage_overview(filter, selector, prices.as_ref(), group_by, split, calendar)? + } else { + Overview::default() + }; + if let Some(reason) = result.cache_warning { + log( + "agent.records.usage_cache_failed", + [("reason", json!(reason))], ); } - let (summaries, speeds) = match readable { - None => (json!([]), json!([])), - Some(agents) => { - let filter = CallFilter { - agents, - session_id: request.session_id, - since_ms: request.since_ms, - until_ms: request.until_ms, - }; + let mut answer = json!({ + "summaries": result.summaries, + "groups": result.groups, + "series": result.series, + }); + if calendar.speeds { + answer["speeds"] = json!(result.speeds); + } + Ok(answer) + } + + /// Adds the folder category of each working directory group, as the + /// session list gives it. + fn add_folder_categories(&self, summaries: &mut Value) { + let home = self.config().map(|config| config.user_home); + for summary in summaries.as_array_mut().into_iter().flatten() { + let category = summary["key"]["cwd"] + .as_str() + .and_then(|cwd| folder_category(cwd, home.as_deref())); + if let Some(category) = category { + summary["key"]["category"] = json!(category); + } + } + } + + /// The figures per session of the calls `filter` and `selector` keep. + fn session_figures( + &self, + filter: Option<&CallFilter>, + selector: &CallSelector, + top: usize, + ) -> Result { + let figures = match filter { + None => SessionTally::new(None).finish(top), + Some(filter) => { + // The reader before the prices, as everywhere both are held. let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; - self.summarize( - store, - &filter, - group_by, - split_by, - &selector, - request.detail, - )? + let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); + let mut tally = SessionTally::new(prices.as_ref()); + store.for_each_call(filter, |entry| { + if selector.keeps(&entry) { + tally.add(&entry); + } + Ok(()) + })?; + tally.finish(top) } }; - Ok(json!({ - "summaries": summaries, - "speeds": speeds, - "rateLimits": self.rate_limit_entries(runtime), - })) + let mut figures = serde_json::to_value(figures).unwrap_or_else(|_| json!({})); + for session in figures["costliest"].as_array_mut().into_iter().flatten() { + if let Some(agent) = session["agent"].as_str().map(str::to_string) { + add_agent_ids(session, &agent); + } + } + Ok(figures) } /// `agentSessions.calls`: one page of the readable agents' calls for the @@ -1136,8 +1301,16 @@ impl Records { #[serde(default)] providers: Vec, #[serde(default)] + accounts: Vec, + #[serde(default)] + purposes: Vec, + #[serde(default)] + cwds: Vec, + #[serde(default)] failed: Option, #[serde(default)] + cancelled: Option, + #[serde(default)] search: Option, #[serde(default)] offset: usize, @@ -1154,9 +1327,16 @@ impl Records { } // `model` is the one-model form of `models`; both must hold. let selector = call_selector( - request.models, - request.providers, - request.failed, + CallSelector { + models: request.models, + providers: request.providers, + accounts: request.accounts, + purposes: request.purposes, + failed: request.failed, + cancelled: request.cancelled, + cwds: request.cwds, + words: Vec::new(), + }, request.search.as_deref(), )?; let Some(agents) = allowed_agents(runtime, request.agents) else { @@ -1194,12 +1374,13 @@ impl Records { Ok(()) })?; } + let windows = ContextWindows::of(runtime, &filter.agents); let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); let calls: Vec = newest .into_iter() .rev() .skip(request.offset) - .map(|entry| call_row(entry, prices.as_ref())) + .map(|entry| call_row(entry, prices.as_ref(), &windows)) .collect(); Ok(json!({ "calls": calls, "total": total })) } @@ -1340,23 +1521,22 @@ impl Records { self.keep_rate_snapshot(key, RateSnapshot::new(limits, at_ms)); } + /// Keeps a snapshot unless a later one is kept, and adds it to the + /// history. fn keep_rate_snapshot(&self, key: &str, snapshot: RateSnapshot) { - let changed = { + let previous = { let mut rates = self.lock_rates(); match rates.get(key) { - Some(current) if current.at_ms > snapshot.at_ms || *current == snapshot => false, - _ => { - rates.insert(key.to_string(), snapshot); - true - } + Some(current) if current.at_ms > snapshot.at_ms || *current == snapshot => return, + _ => rates.insert(key.to_string(), snapshot.clone()), } }; - if changed { - self.save_rate_file(); - } + self.save_rate_file(); + self.note_history(key, previous.as_ref(), &snapshot); } - /// The latest rate limits of the agents the user enabled. + /// The latest rate limits of the agents the user enabled. A window with + /// alert thresholds carries them and the highest one it reaches. fn rate_limit_entries(&self, runtime: &Runtime) -> Vec { let rates = self.lock_rates().clone(); rates @@ -1366,7 +1546,20 @@ impl Records { if !agent.may_run && !agent.may_read_sessions { return None; } + let alerts = self.alerts_of(&key); let mut value = serde_json::to_value(&snapshot).ok()?; + if let Some(windows) = value["windows"].as_array_mut() { + for (window, reported) in windows.iter_mut().zip(&snapshot.windows) { + let Some(thresholds) = alerts.get(&reported.id) else { + continue; + }; + let mut alert = json!({ "thresholds": thresholds }); + if let Some(reached) = usage::reached(thresholds, reported.used_percent) { + alert["reached"] = json!(reached); + } + window["alert"] = alert; + } + } value["pluginID"] = json!(agent.plugin_id); value["agentID"] = json!(agent.agent.id); Some(value) @@ -1507,18 +1700,64 @@ fn allowed_agents(runtime: &Runtime, requested: Option>) -> Option>); + +impl ContextWindows { + /// The windows of `agents`. + pub(super) fn of(runtime: &Runtime, agents: &[String]) -> Self { + Self( + agents + .iter() + .map(|key| (key.clone(), runtime.library.context_windows(key))) + .collect(), + ) + } + + fn get(&self, agent: &str, model: &str) -> Option { + self.0.get(agent)?.get(model).copied() + } +} + +/// How full the call's context was: the prompt's tokens (input, cache reads +/// and cache writes), and with the model's context window from its plugin's +/// model list, the share of it they took. Absent without an input count. +fn call_context(entry: &CallEntry, windows: &ContextWindows) -> Option { + let call = &entry.call; + let tokens = &call.tokens; + let prompt = [ + tokens.input?, + tokens.cache_read.unwrap_or(0), + tokens.cache_write_5m.unwrap_or(0), + tokens.cache_write_1h.unwrap_or(0), + ] + .into_iter() + .fold(0u64, u64::saturating_add); + let mut context = json!({ "tokens": prompt }); + if let Some(window) = model_name(call).and_then(|model| windows.get(&entry.agent, model)) { + context["window"] = json!(window); + context["share"] = json!(prompt as f64 / window as f64); + } + Some(context) +} + /// One row of `agentSessions.calls`: the call as the cache holds it, the agent /// split into plugin and agent IDs, and what Core derives from it. `cost` is /// absent without a price for the model or without the input and output /// counts; `cacheHitRate` is absent when the call reports no cache count. -fn call_row(entry: CallEntry, prices: Option<&PriceTable>) -> Value { +/// `generation` and `size` are those `agentSessions.page` takes to open the +/// file round `call.range`. +fn call_row(entry: CallEntry, prices: Option<&PriceTable>, windows: &ContextWindows) -> Value { let call = &entry.call; let cost = prices .and_then(|prices| { - model_name(call).and_then(|model| prices.lookup(call.provider.as_deref(), model)) + model_name(call) + .and_then(|model| prices.lookup_for(&entry.agent, call.provider.as_deref(), model)) }) .and_then(|price| call_cost(price, &call.tokens)) .map(|cost| json!({ "usd": cost.usd, "approximate": cost.approximate })); + let context = call_context(&entry, windows); let tokens = &call.tokens; let cache_hit_rate = tokens.reports_cache().then(|| { let read = tokens.cache_read.unwrap_or(0); @@ -1538,7 +1777,12 @@ fn call_row(entry: CallEntry, prices: Option<&PriceTable>) -> Value { "agent": entry.agent, "path": entry.path, "call": call, + "generation": entry.generation, + "size": entry.read_bytes, }); + if let Some(context) = context { + row["context"] = context; + } add_agent_ids(&mut row, &entry.agent); if let Some(cwd) = &entry.cwd { row["cwd"] = json!(cwd); @@ -1584,6 +1828,8 @@ fn parse_group_by( "cwd" if host => Some(GroupBy::Cwd), "provider" if host => Some(GroupBy::Provider), "modelProvider" if host => Some(GroupBy::ModelProvider), + "account" if host => Some(GroupBy::Account), + "purpose" if host => Some(GroupBy::Purpose), "all" if host => Some(GroupBy::All), _ => None, } @@ -1596,43 +1842,42 @@ fn parse_split_by(name: &str) -> Option { "model" => Some(GroupBy::Model), "provider" => Some(GroupBy::Provider), "modelProvider" => Some(GroupBy::ModelProvider), + "account" => Some(GroupBy::Account), + "purpose" => Some(GroupBy::Purpose), _ => None, } } -/// Most models or providers a request may filter by, and the longest name or -/// search text. +/// Most models, providers, accounts, purposes or directories a request may +/// filter by, and the longest name or search text; a directory may be as long +/// as [`MAX_FILTER_DIRECTORY_BYTES`]. 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 { +/// The selector of a statistics or calls request with its search words, or +/// a refusal when a filter is too long. +fn call_selector(selector: CallSelector, 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) + if too_long(&selector.models) + || too_long(&selector.providers) + || too_long(&selector.accounts) + || too_long(&selector.purposes) + || selector.cwds.len() > MAX_FILTER_NAMES + || selector + .cwds + .iter() + .any(|cwd| cwd.len() > MAX_FILTER_DIRECTORY_BYTES) || 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.", + "Filter by at most 64 each of models, providers, accounts, purposes and directories; each name and the search text at most 256 bytes, each directory at most 4096.", )); } - let selector = CallSelector { - models, - providers, - failed, - words: Vec::new(), - }; Ok(match search { Some(text) => selector.with_search(text), None => selector, diff --git a/rust/crates/agent-runtime/src/records/history.rs b/rust/crates/agent-runtime/src/records/history.rs new file mode 100644 index 00000000..efaca593 --- /dev/null +++ b/rust/crates/agent-runtime/src/records/history.rs @@ -0,0 +1,211 @@ +//! The rate-limit history: how much of each rate-limit window an agent had +//! used over time, from the snapshots Core keeps +//! (`agentUsage.rateLimitHistory`). +//! +//! Every snapshot Core keeps, whether an agent reported it while it ran, its +//! session files held it or the plugin read it when the user asked, adds a +//! point per window. Points of one window are at least [`POINT_GAP_MS`] +//! apart within a cycle: a reading closer to the last point replaces that +//! point's value and keeps its time. A new cycle (the reset time moves or the +//! used share drops) always starts a point. A reading equal to the last point +//! adds nothing. +//! +//! The history is user data: it lives in `rate-limit-history.json` in the +//! directory the host names in the platform's application data, owner-only, +//! never in the application bundle or the Caches directory. Points older than +//! [`HISTORY_DAYS`] days, and the oldest beyond [`MAX_POINTS_PER_WINDOW`] of +//! a window, are dropped when a point is added. `agentSessions.forget` +//! removes an agent's history with its last snapshot. A reading that only +//! replaces the last point's value is saved with the next point the history +//! adds; the latest value is in the snapshot file meanwhile. + +use super::RateSnapshot; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; + +/// Days of points the history keeps. +pub(crate) const HISTORY_DAYS: i64 = 35; + +/// Most points the history keeps per window. +pub(crate) const MAX_POINTS_PER_WINDOW: usize = 4000; + +/// Shortest time between two points of one window in one cycle. +pub(crate) const POINT_GAP_MS: i64 = 5 * 60_000; + +/// How far a window's reset time may move within one cycle, for providers +/// that report it with some jitter. +const RESET_JITTER_MS: i64 = 60_000; + +const MILLISECONDS_PER_DAY: i64 = 86_400_000; + +/// One reading of a window. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct HistoryPoint { + pub at_ms: i64, + pub used_percent: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resets_at_ms: Option, +} + +impl HistoryPoint { + /// Whether `next` belongs to a later cycle than this point. + fn starts_cycle(&self, next: &HistoryPoint) -> bool { + let reset_moved = match (self.resets_at_ms, next.resets_at_ms) { + (Some(before), Some(after)) => (after - before).abs() > RESET_JITTER_MS, + (None, None) => false, + _ => true, + }; + reset_moved || next.used_percent < self.used_percent + } +} + +/// The points of one window, with its last label and length. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct WindowHistory { + #[serde(default, skip_serializing_if = "Option::is_none")] + label: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + window_minutes: Option, + points: Vec, +} + +/// What [`RateHistory::note`] changed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Noted { + /// The reading added nothing. + Unchanged, + /// It replaced the last point's value; saved with the next point. + Replaced, + /// It added a point. + Added, +} + +/// The history of every agent, by agent record key, then window ID. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RateHistory { + agents: BTreeMap>, +} + +impl RateHistory { + /// Adds the windows of a snapshot the agent `key` reported. + pub fn note(&mut self, key: &str, snapshot: &RateSnapshot) -> Noted { + let windows = self.agents.entry(key.to_string()).or_default(); + let mut noted = Noted::Unchanged; + for window in &snapshot.windows { + let history = windows.entry(window.id.clone()).or_default(); + history.label.clone_from(&window.label); + history.window_minutes = window.window_minutes; + let point = HistoryPoint { + at_ms: snapshot.at_ms, + used_percent: window.used_percent, + resets_at_ms: window.resets_at_ms, + }; + let outcome = match history.points.last_mut() { + Some(last) if point.at_ms < last.at_ms => Noted::Unchanged, + Some(last) + if last.used_percent == point.used_percent + && last.resets_at_ms == point.resets_at_ms => + { + Noted::Unchanged + } + Some(last) + if !last.starts_cycle(&point) && point.at_ms - last.at_ms < POINT_GAP_MS => + { + last.used_percent = point.used_percent; + last.resets_at_ms = point.resets_at_ms; + Noted::Replaced + } + _ => { + history.points.push(point); + Noted::Added + } + }; + noted = match (noted, outcome) { + (Noted::Added, _) | (_, Noted::Added) => Noted::Added, + (Noted::Replaced, _) | (_, Noted::Replaced) => Noted::Replaced, + _ => Noted::Unchanged, + }; + } + if noted == Noted::Added { + self.prune(snapshot.at_ms); + } + noted + } + + /// Drops points older than [`HISTORY_DAYS`] before `now_ms` and the + /// oldest beyond [`MAX_POINTS_PER_WINDOW`], then windows and agents left + /// without points. + pub fn prune(&mut self, now_ms: i64) { + let oldest = now_ms.saturating_sub(HISTORY_DAYS * MILLISECONDS_PER_DAY); + for windows in self.agents.values_mut() { + for history in windows.values_mut() { + history.points.retain(|point| point.at_ms >= oldest); + let excess = history.points.len().saturating_sub(MAX_POINTS_PER_WINDOW); + history.points.drain(..excess); + } + windows.retain(|_, history| !history.points.is_empty()); + } + self.agents.retain(|_, windows| !windows.is_empty()); + } + + /// Forgets the agent `key`. Whether it had a history. + pub fn forget(&mut self, key: &str) -> bool { + self.agents.remove(key).is_some() + } + + /// Keeps only agents and points that pass the checks a snapshot passes, + /// for a history read from disk. + pub fn retain_valid(&mut self, valid_key: impl Fn(&str) -> bool) { + self.agents.retain(|key, _| valid_key(key)); + for windows in self.agents.values_mut() { + windows.retain(|id, history| { + history + .points + .retain(|point| (0.0..=100.0).contains(&point.used_percent)); + history.points.sort_by_key(|point| point.at_ms); + !id.is_empty() && !history.points.is_empty() + }); + } + self.agents.retain(|_, windows| !windows.is_empty()); + } + + /// The windows of the agent `key`, or only `window`, with their points + /// from `since_ms` (inclusive) to `until_ms` (exclusive), oldest first. + pub fn query( + &self, + key: &str, + window: Option<&str>, + since_ms: Option, + until_ms: Option, + ) -> Vec { + let Some(windows) = self.agents.get(key) else { + return Vec::new(); + }; + windows + .iter() + .filter(|(id, _)| window.is_none_or(|window| window == id.as_str())) + .map(|(id, history)| { + let points: Vec<&HistoryPoint> = history + .points + .iter() + .filter(|point| { + since_ms.is_none_or(|since| point.at_ms >= since) + && until_ms.is_none_or(|until| point.at_ms < until) + }) + .collect(); + let mut value = json!({ "window": id, "points": points }); + if let Some(label) = &history.label { + value["label"] = json!(label); + } + if let Some(minutes) = history.window_minutes { + value["windowMinutes"] = json!(minutes); + } + value + }) + .collect() + } +} diff --git a/rust/crates/agent-runtime/src/records/subagents.rs b/rust/crates/agent-runtime/src/records/subagents.rs index aed67867..e744dca1 100644 --- a/rust/crates/agent-runtime/src/records/subagents.rs +++ b/rust/crates/agent-runtime/src/records/subagents.rs @@ -6,7 +6,7 @@ use super::{ call_read, call_row, decode_title, find_session, not_configured, readable_key, rooted_sources, - source_index, text_lines, Records, + source_index, text_lines, ContextWindows, Records, }; use crate::Runtime; use lithe_agent_sessions::stats::{GroupBy, Summarizer}; @@ -49,7 +49,9 @@ impl Records { } let request: SubagentsRequest = crate::decode(payload)?; let agent = readable_key(runtime, &request.agent)?; - let (threads, titles) = self.subagent_records(&request.agent, &request.session_id)?; + let windows = ContextWindows::of(runtime, std::slice::from_ref(&request.agent)); + let (threads, titles) = + self.subagent_records(&request.agent, &request.session_id, &windows)?; // The plugin reads the titles after the cache and prices are let go. let titles = read_titles(runtime, self, &agent, titles); @@ -97,10 +99,13 @@ impl Records { &self, agent: &str, session_id: &str, + windows: &ContextWindows, ) -> Result<(BTreeMap, Vec<(String, String, Vec)>), CoreError> { - let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); + // The reader before the prices, in the order every reader of both + // takes them. let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; + let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); let session = find_session(store, agent, session_id)?; let mut threads: BTreeMap = BTreeMap::new(); let mut titles = Vec::new(); @@ -140,7 +145,9 @@ impl Records { subagent.first_call_ms = subagent.first_call_ms.or(Some(entry.call.started_at_ms)); if rows < MAX_SUBAGENT_CALL_ROWS { rows += 1; - subagent.calls.push(call_row(entry, prices.as_ref())); + subagent + .calls + .push(call_row(entry, prices.as_ref(), windows)); } Ok(()) })?; diff --git a/rust/crates/agent-runtime/src/records/usage.rs b/rust/crates/agent-runtime/src/records/usage.rs new file mode 100644 index 00000000..a1884bfb --- /dev/null +++ b/rust/crates/agent-runtime/src/records/usage.rs @@ -0,0 +1,982 @@ +//! The usage features agent plugins implement and the user's usage settings +//! (`agentUsage.*`): rate limits read when the user asks, prices the user +//! sets for an agent's models, the currency costs are shown in and its +//! exchange rate, and alerts on rate-limit windows. +//! +//! Core defines the shapes, checks what the plugin answers and keeps what the +//! user sets; the plugin implements the feature. A feature the agent's +//! `usage` declaration leaves out is refused with `agentUsage.notDeclared`, +//! which the host shows as unsupported. Core makes no network request here: +//! how a plugin learns the rate limits or exchange rates is its own business. +//! +//! Costs stay in US dollars in every answer. A currency the user chose is +//! reported with its rate beside them, and the host converts what it shows. +//! +//! The settings are user data: `usage-settings.json` in the directory the +//! host names in the platform's application data, owner-only, never in the +//! application bundle or the Caches directory. A file that cannot be read is +//! set aside as `usage-settings.unreadable.json` rather than overwritten. +//! Prices and alerts stay when an agent's records are forgotten, so they are +//! back when its plugin is installed again. + +use super::history::{Noted, RateHistory}; +use super::{log, now_ms, refusal, split_record_key, RateSnapshot, Records}; +use crate::catalog::CatalogAgent; +use crate::events::{check_rate_limits, RateLimits, MAX_RATE_WINDOWS}; +use crate::files::{read_bounded, replace_file}; +use crate::{require_user, Runtime}; +use lithe_agent_sessions::pricing::{Price, Rates}; +use lithe_agent_sessions::MAX_LABEL_BYTES; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, HashMap}; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::{MutexGuard, PoisonError}; +use std::time::Duration; + +/// The settings file in the data directory. +pub(crate) const SETTINGS_FILE: &str = "usage-settings.json"; +/// Where an unreadable settings file is set aside. +const UNREADABLE_SETTINGS_FILE: &str = "usage-settings.unreadable.json"; +/// The rate-limit history file in the data directory. +pub(crate) const HISTORY_FILE: &str = "rate-limit-history.json"; + +const MAX_SETTINGS_FILE_BYTES: u64 = 1024 * 1024; +const MAX_HISTORY_FILE_BYTES: u64 = 32 * 1024 * 1024; + +/// Most models one agent may have a price for. +pub(crate) const MAX_PRICED_MODELS: usize = 256; +/// Highest price accepted, in US dollars per million tokens. +pub(crate) const MAX_PRICE_PER_MILLION: f64 = 100_000.0; +/// Most thresholds one window may have. +pub(crate) const MAX_ALERT_THRESHOLDS: usize = 4; +/// Most currencies one exchange-rate request may name. +pub(crate) const MAX_CURRENCIES: usize = 32; +/// Highest units of a currency per US dollar accepted. +const MAX_UNITS_PER_USD: f64 = 10_000_000.0; + +/// How long a plugin's usage function may take. +const FUNCTION_TIMEOUT: Duration = Duration::from_secs(15); + +/// A price the user set for a model, in US dollars per million tokens. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct UserPrice { + input: f64, + output: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + cache_read: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + cache_write: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + reasoning: Option, +} + +impl UserPrice { + fn valid(&self) -> bool { + let valid = + |value: f64| value.is_finite() && (0.0..=MAX_PRICE_PER_MILLION).contains(&value); + valid(self.input) + && valid(self.output) + && [self.cache_read, self.cache_write, self.reasoning] + .into_iter() + .flatten() + .all(valid) + } + + fn price(&self) -> Price { + Price { + base: Rates { + input: self.input, + output: self.output, + reasoning: self.reasoning, + cache_read: self.cache_read, + cache_write: self.cache_write, + }, + tiers: Vec::new(), + } + } +} + +/// An exchange rate a plugin reported. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ExchangeRate { + /// Units of the currency per US dollar. + #[serde(rename = "perUSD")] + per_usd: f64, + /// When Core received it, in Unix milliseconds. + at_ms: i64, + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, +} + +/// What the user set. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Settings { + /// Prices by agent record key, then model name as calls are counted + /// under it. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + prices: BTreeMap>, + /// The currency costs are shown in; US dollars when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + currency: Option, + /// The last rate of each currency, by ISO 4217 code. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + exchange_rates: BTreeMap, + /// Alert thresholds in percent, ascending, by agent record key, then + /// window ID. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + alerts: BTreeMap>>, +} + +impl Settings { + /// Drops what a valid request could not have set, for a file read from + /// disk. + fn retain_valid(&mut self) { + let key_valid = |key: &String| split_record_key(key).is_some(); + self.prices.retain(|key, models| { + models.retain(|model, price| model_valid(model) && price.valid()); + key_valid(key) && !models.is_empty() && models.len() <= MAX_PRICED_MODELS + }); + self.exchange_rates + .retain(|code, rate| currency_valid(code) && rate_valid(rate.per_usd)); + if self + .currency + .as_ref() + .is_some_and(|code| !self.exchange_rates.contains_key(code)) + { + self.currency = None; + } + self.alerts.retain(|key, windows| { + windows + .retain(|window, thresholds| window_valid(window) && thresholds_valid(thresholds)); + key_valid(key) && !windows.is_empty() && windows.len() <= MAX_RATE_WINDOWS + }); + } +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct SettingsFile { + version: u32, + settings: Settings, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct HistoryFile { + version: u32, + history: RateHistory, +} + +/// The settings and history in memory, with the data directory they were +/// read from. Without a directory nothing is kept. +#[derive(Default)] +pub(super) struct UsageState { + directory: Option, + settings: Settings, + history: RateHistory, +} + +fn model_valid(model: &str) -> bool { + !model.is_empty() && model.len() <= MAX_LABEL_BYTES +} + +fn window_valid(window: &str) -> bool { + !window.is_empty() && window.len() <= MAX_LABEL_BYTES +} + +/// An ISO 4217 code: three uppercase ASCII letters. +fn currency_valid(code: &str) -> bool { + code.len() == 3 && code.bytes().all(|byte| byte.is_ascii_uppercase()) +} + +fn rate_valid(per_usd: f64) -> bool { + per_usd.is_finite() && per_usd > 0.0 && per_usd <= MAX_UNITS_PER_USD +} + +/// One to [`MAX_ALERT_THRESHOLDS`] percentages from 1 to 100, ascending. +fn thresholds_valid(thresholds: &[u8]) -> bool { + !thresholds.is_empty() + && thresholds.len() <= MAX_ALERT_THRESHOLDS + && thresholds.iter().all(|value| (1..=100).contains(value)) + && thresholds.windows(2).all(|pair| pair[0] < pair[1]) +} + +fn not_configured() -> CoreError { + refusal( + ErrorCode::InvalidRequest, + "agentUsage.notConfigured", + "No data directory is configured for usage settings.", + ) +} + +fn unknown_agent() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentUsage.unknownAgent", + "No installed plugin declares this agent.", + ) +} + +fn not_declared() -> CoreError { + refusal( + ErrorCode::NotSupported, + "agentUsage.notDeclared", + "The agent plugin does not implement this usage feature.", + ) +} + +fn save_failed() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentUsage.saveFailed", + "The usage settings could not be saved.", + ) +} + +/// The refusal of a usage change or plugin read the user did not ask for, +/// for [`require_user`]. +fn user_action_required() -> CoreError { + refusal( + ErrorCode::PermissionDenied, + "agentUsage.userActionRequired", + "Only the user can change usage settings or ask a plugin for usage data.", + ) +} + +/// The agent, when the user enabled it to run or to read its sessions. +fn usage_agent( + runtime: &Runtime, + plugin_id: &str, + agent_id: &str, +) -> Result { + let agent = runtime + .catalog + .find(plugin_id, agent_id) + .ok_or_else(unknown_agent)?; + if !agent.may_run && !agent.may_read_sessions { + return Err(refusal( + ErrorCode::PermissionDenied, + "agentUsage.notGranted", + "The user has not enabled this agent.", + )); + } + Ok(agent) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct AgentTarget { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, +} + +/// Logs a failed read or write of the `settings` or `history` file. +fn log_io_failure(file: &str, stage: &str, kind: io::ErrorKind) { + log( + "agent.usage.file_failed", + [ + ("file", json!(file)), + ("stage", json!(stage)), + ("error", json!("A usage file could not be read or written")), + ("error_code", json!(format!("{kind:?}"))), + ("error_domain", json!("io")), + ], + ); +} + +impl UsageState { + /// The data directory the state was read from. + pub fn directory(&self) -> Option<&Path> { + self.directory.as_deref() + } + + /// The state kept in `directory`, created owner-only when missing. An + /// unreadable settings file is set aside; an unreadable history starts + /// over. + pub fn open(directory: &Path) -> Result { + if !directory.is_dir() { + fs::create_dir_all(directory).map_err(|_| save_failed())?; + lithe_platform::fs::restrict_directory_to_owner(directory) + .map_err(|_| save_failed())?; + } + let settings_path = directory.join(SETTINGS_FILE); + let settings = match read_bounded(&settings_path, MAX_SETTINGS_FILE_BYTES) { + Ok(None) => Settings::default(), + Ok(Some(bytes)) => match serde_json::from_slice::(&bytes) { + Ok(file) if file.version == 1 => { + let mut settings = file.settings; + settings.retain_valid(); + settings + } + _ => { + set_aside(directory, &settings_path); + Settings::default() + } + }, + Err(failure) => { + log_io_failure("settings", "read", failure.kind()); + set_aside(directory, &settings_path); + Settings::default() + } + }; + let history = read_bounded(&directory.join(HISTORY_FILE), MAX_HISTORY_FILE_BYTES) + .ok() + .flatten() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|file| file.version == 1) + .map(|file| { + let mut history = file.history; + history.retain_valid(|key| split_record_key(key).is_some()); + history.prune(now_ms()); + history + }) + .unwrap_or_default(); + Ok(Self { + directory: Some(directory.to_path_buf()), + settings, + history, + }) + } + + fn save_settings(&self) -> Result<(), CoreError> { + let directory = self.directory.as_ref().ok_or_else(not_configured)?; + let bytes = serde_json::to_vec_pretty(&SettingsFile { + version: 1, + settings: self.settings.clone(), + }) + .map_err(|_| save_failed())?; + replace_file(&directory.join(SETTINGS_FILE), &bytes, |error| { + log_io_failure("settings", "cleanup", error.kind()); + }) + .map_err(|error| { + log_io_failure("settings", "write", error.kind()); + save_failed() + }) + } + + /// Saves the history; a failure is logged, and the next point tries + /// again. + fn save_history(&self) { + let Some(directory) = &self.directory else { + return; + }; + let Ok(bytes) = serde_json::to_vec(&HistoryFile { + version: 1, + history: self.history.clone(), + }) else { + return; + }; + let written = replace_file(&directory.join(HISTORY_FILE), &bytes, |error| { + log_io_failure("history", "cleanup", error.kind()); + }); + if let Err(error) = written { + log_io_failure("history", "write", error.kind()); + } + } + + /// The prices the user set, as the price table takes them. + pub fn overrides(&self) -> HashMap> { + self.settings + .prices + .iter() + .map(|(key, models)| { + let models = models + .iter() + .map(|(model, price)| (model.clone(), price.price())) + .collect(); + (key.clone(), models) + }) + .collect() + } +} + +/// Moves an unreadable settings file aside so a later save does not lose it. +fn set_aside(directory: &Path, path: &Path) { + if let Err(error) = fs::rename(path, directory.join(UNREADABLE_SETTINGS_FILE)) { + log_io_failure("settings", "setAside", error.kind()); + } +} + +impl Records { + pub(super) fn lock_usage(&self) -> MutexGuard<'_, UsageState> { + self.usage.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Adds a kept snapshot to the history and logs each alert threshold its + /// windows reach that `previous` had not reached. + pub(super) fn note_history( + &self, + key: &str, + previous: Option<&RateSnapshot>, + snapshot: &RateSnapshot, + ) { + let mut usage = self.lock_usage(); + if usage.directory.is_none() { + return; + } + if usage.history.note(key, snapshot) == Noted::Added { + usage.save_history(); + } + let Some(alerts) = usage.settings.alerts.get(key) else { + return; + }; + for window in &snapshot.windows { + let Some(thresholds) = alerts.get(&window.id) else { + continue; + }; + let before = previous + .and_then(|previous| previous.windows.iter().find(|w| w.id == window.id)) + .and_then(|previous| reached(thresholds, previous.used_percent)); + let now = reached(thresholds, window.used_percent); + if now.is_some() && now > before { + let (plugin_id, agent_id) = split_record_key(key).unwrap_or((key, "")); + log( + "agent.usage.alert_hit", + [ + ("plugin", json!(plugin_id)), + ("agent", json!(agent_id)), + ("threshold", json!(now)), + ], + ); + } + } + } + + /// Forgets the agent's history. + pub(super) fn forget_history(&self, key: &str) { + let mut usage = self.lock_usage(); + if usage.history.forget(key) { + usage.save_history(); + } + } + + /// The alert thresholds of the agent `key`, by window ID. + pub(super) fn alerts_of(&self, key: &str) -> BTreeMap> { + self.lock_usage() + .settings + .alerts + .get(key) + .cloned() + .unwrap_or_default() + } + + /// The currency the user chose and its rate, when it is not US dollars. + pub(super) fn currency_entry(&self) -> Option { + let usage = self.lock_usage(); + let code = usage.settings.currency.as_ref()?; + let rate = usage.settings.exchange_rates.get(code)?; + Some(json!({ "code": code, "perUSD": rate.per_usd, "atMs": rate.at_ms })) + } + + /// `agentUsage.read`: what the user set, for the agents installed now. + pub fn usage_read(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct ReadRequest {} + let _: ReadRequest = crate::decode(payload)?; + let usage = self.lock_usage(); + if usage.directory.is_none() { + return Err(not_configured()); + } + let settings = &usage.settings; + let keys: std::collections::BTreeSet<&String> = settings + .prices + .keys() + .chain(settings.alerts.keys()) + .collect(); + let mut agents = Vec::new(); + for key in keys { + let Some(agent) = runtime.catalog.find_key(key) else { + continue; + }; + let prices: Vec = settings + .prices + .get(key) + .into_iter() + .flatten() + .map(|(model, price)| { + let mut value = json!(price); + value["model"] = json!(model); + value + }) + .collect(); + let alerts: Vec = settings + .alerts + .get(key) + .into_iter() + .flatten() + .map(|(window, thresholds)| json!({ "window": window, "thresholds": thresholds })) + .collect(); + agents.push(json!({ + "pluginID": agent.plugin_id, + "agentID": agent.agent.id, + "prices": prices, + "alerts": alerts, + })); + } + let mut answer = json!({ + "exchangeRates": exchange_rate_entries(settings), + "agents": agents, + }); + if let Some(currency) = &settings.currency { + answer["currency"] = json!(currency); + } + Ok(answer) + } + + /// `agentUsage.setPrice`: sets or, with `price` null, removes the price + /// of one model for the agent's calls. + pub fn usage_set_price(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct PriceRequest { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, + model: String, + price: Option, + } + require_user(user_action_required)?; + let request: PriceRequest = crate::decode(payload)?; + let agent = usage_agent(runtime, &request.plugin_id, &request.agent_id)?; + if !agent + .agent + .usage + .as_ref() + .is_some_and(|usage| usage.custom_prices) + { + return Err(not_declared()); + } + let invalid = || { + refusal( + ErrorCode::InvalidRequest, + "agentUsage.invalidPrice", + "Name a model and give prices from 0 to 100000 US dollars per million tokens, for at most 256 models per agent.", + ) + }; + if !model_valid(&request.model) || request.price.is_some_and(|price| !price.valid()) { + return Err(invalid()); + } + let key = agent.record_key(); + let overrides = { + let mut usage = self.lock_usage(); + if usage.directory.is_none() { + return Err(not_configured()); + } + let before = usage.settings.clone(); + let models = usage.settings.prices.entry(key.clone()).or_default(); + match request.price { + Some(price) => { + models.insert(request.model.clone(), price); + } + None => { + models.remove(&request.model); + } + } + if models.len() > MAX_PRICED_MODELS { + usage.settings = before; + return Err(invalid()); + } + if models.is_empty() { + usage.settings.prices.remove(&key); + } + if let Err(error) = usage.save_settings() { + usage.settings = before; + return Err(error); + } + usage.overrides() + }; + self.apply_overrides(overrides); + log( + "agent.usage.price_changed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("removed", json!(request.price.is_none())), + ], + ); + Ok(json!({})) + } + + /// `agentUsage.setAlert`: sets the thresholds of one rate-limit window of + /// the agent, or with none removes them. + pub fn usage_set_alert(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct AlertRequest { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, + window: String, + thresholds: Vec, + } + require_user(user_action_required)?; + let mut request: AlertRequest = crate::decode(payload)?; + let agent = usage_agent(runtime, &request.plugin_id, &request.agent_id)?; + if !agent + .agent + .usage + .as_ref() + .is_some_and(|usage| usage.rate_limit_alerts) + { + return Err(not_declared()); + } + request.thresholds.sort_unstable(); + request.thresholds.dedup(); + let invalid = || { + refusal( + ErrorCode::InvalidRequest, + "agentUsage.invalidAlert", + "Name a window and give at most four thresholds from 1 to 100 percent, for at most eight windows per agent.", + ) + }; + if !window_valid(&request.window) + || (!request.thresholds.is_empty() && !thresholds_valid(&request.thresholds)) + { + return Err(invalid()); + } + let key = agent.record_key(); + let mut usage = self.lock_usage(); + if usage.directory.is_none() { + return Err(not_configured()); + } + let before = usage.settings.clone(); + let windows = usage.settings.alerts.entry(key.clone()).or_default(); + if request.thresholds.is_empty() { + windows.remove(&request.window); + } else { + windows.insert(request.window.clone(), request.thresholds); + } + if windows.len() > MAX_RATE_WINDOWS { + usage.settings = before; + return Err(invalid()); + } + if windows.is_empty() { + usage.settings.alerts.remove(&key); + } + if let Err(error) = usage.save_settings() { + usage.settings = before; + return Err(error); + } + Ok(json!({})) + } + + /// `agentUsage.setCurrency`: the currency costs are shown in, which needs + /// a rate a plugin reported; null or `USD` shows US dollars. + pub fn usage_set_currency(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct CurrencyRequest { + currency: Option, + } + require_user(user_action_required)?; + let request: CurrencyRequest = crate::decode(payload)?; + let currency = request.currency.filter(|code| code != "USD"); + if currency + .as_deref() + .is_some_and(|code| !currency_valid(code)) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentUsage.invalidCurrency", + "A currency is an ISO 4217 code of three uppercase letters.", + )); + } + let mut usage = self.lock_usage(); + if usage.directory.is_none() { + return Err(not_configured()); + } + if currency + .as_ref() + .is_some_and(|code| !usage.settings.exchange_rates.contains_key(code)) + { + return Err(refusal( + ErrorCode::EntryNotFound, + "agentUsage.noExchangeRate", + "No agent plugin has reported an exchange rate for this currency.", + )); + } + let before = usage.settings.currency.clone(); + usage.settings.currency = currency; + if let Err(error) = usage.save_settings() { + usage.settings.currency = before; + return Err(error); + } + Ok(json!({})) + } + + /// `agentUsage.refreshRateLimits`: asks the agent's plugin for its + /// current rate limits and keeps them as the agent's latest snapshot. + pub fn usage_refresh_rate_limits( + &self, + runtime: &Runtime, + payload: Value, + ) -> Result { + require_user(user_action_required)?; + let target: AgentTarget = crate::decode(payload)?; + let agent = usage_agent(runtime, &target.plugin_id, &target.agent_id)?; + let function = agent + .agent + .usage + .as_ref() + .and_then(|usage| usage.rate_limits.clone()) + .ok_or_else(not_declared)?; + let answer = call_usage_function( + runtime, + &agent, + "rateLimits", + &function, + json!({ "agentID": agent.agent.id }), + )?; + let limits: RateLimits = serde_json::from_value(answer) + .ok() + .filter(|limits| check_rate_limits(limits).is_ok()) + .ok_or_else(invalid_answer)?; + let key = agent.record_key(); + self.keep_rate_snapshot(&key, RateSnapshot::new(limits, now_ms())); + log( + "agent.usage.rate_limits_updated", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ], + ); + let entry = self.rate_limit_entries(runtime).into_iter().find(|entry| { + entry["pluginID"] == agent.plugin_id && entry["agentID"] == agent.agent.id + }); + Ok(json!({ "rateLimits": entry })) + } + + /// `agentUsage.refreshExchangeRates`: asks the agent's plugin for the + /// rates of `currencies` per US dollar and keeps them. + pub fn usage_refresh_exchange_rates( + &self, + runtime: &Runtime, + payload: Value, + ) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct RatesRequest { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, + currencies: Vec, + } + require_user(user_action_required)?; + let mut request: RatesRequest = crate::decode(payload)?; + request.currencies.sort(); + request.currencies.dedup(); + if request.currencies.is_empty() + || request.currencies.len() > MAX_CURRENCIES + || request + .currencies + .iter() + .any(|code| !currency_valid(code) || code == "USD") + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentUsage.invalidCurrency", + "Name one to 32 ISO 4217 currencies other than USD.", + )); + } + let agent = usage_agent(runtime, &request.plugin_id, &request.agent_id)?; + let function = agent + .agent + .usage + .as_ref() + .and_then(|usage| usage.exchange_rates.clone()) + .ok_or_else(not_declared)?; + if self.lock_usage().directory.is_none() { + return Err(not_configured()); + } + let answer = call_usage_function( + runtime, + &agent, + "exchangeRates", + &function, + json!({ + "agentID": agent.agent.id, + "base": "USD", + "currencies": request.currencies, + }), + )?; + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct RatesAnswer { + rates: BTreeMap, + } + let rates = serde_json::from_value::(answer) + .ok() + .filter(|answer| { + answer.rates.iter().all(|(code, per_usd)| { + request.currencies.contains(code) && rate_valid(*per_usd) + }) + }) + .ok_or_else(invalid_answer)? + .rates; + let at_ms = now_ms(); + let mut usage = self.lock_usage(); + if usage.directory.is_none() { + return Err(not_configured()); + } + let before = usage.settings.clone(); + for (code, per_usd) in &rates { + usage.settings.exchange_rates.insert( + code.clone(), + ExchangeRate { + per_usd: *per_usd, + at_ms, + plugin_id: agent.plugin_id.clone(), + agent_id: agent.agent.id.clone(), + }, + ); + } + if let Err(error) = usage.save_settings() { + usage.settings = before; + return Err(error); + } + log( + "agent.usage.exchange_rates_updated", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("asked", json!(request.currencies.len())), + ("answered", json!(rates.len())), + ], + ); + Ok(json!({ "exchangeRates": exchange_rate_entries(&usage.settings) })) + } + + /// `agentUsage.rateLimitHistory`: the agent's kept readings of each + /// rate-limit window, or of one, in a range. + pub fn usage_rate_limit_history( + &self, + runtime: &Runtime, + payload: Value, + ) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct HistoryRequest { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, + #[serde(default)] + window: Option, + #[serde(default)] + since_ms: Option, + #[serde(default)] + until_ms: Option, + } + let request: HistoryRequest = crate::decode(payload)?; + if matches!((request.since_ms, request.until_ms), (Some(since), Some(until)) if since >= until) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentUsage.invalidRange", + "The range ends before it starts.", + )); + } + let agent = usage_agent(runtime, &request.plugin_id, &request.agent_id)?; + let usage = self.lock_usage(); + if usage.directory.is_none() { + return Err(not_configured()); + } + Ok(json!({ + "windows": usage.history.query( + &agent.record_key(), + request.window.as_deref(), + request.since_ms, + request.until_ms, + ), + })) + } +} + +/// The highest of `thresholds` that `used_percent` reaches. +pub(super) fn reached(thresholds: &[u8], used_percent: f64) -> Option { + thresholds + .iter() + .rev() + .copied() + .find(|threshold| used_percent >= f64::from(*threshold)) +} + +fn exchange_rate_entries(settings: &Settings) -> Vec { + settings + .exchange_rates + .iter() + .map(|(code, rate)| { + let mut value = json!(rate); + value["currency"] = json!(code); + value + }) + .collect() +} + +fn invalid_answer() -> CoreError { + refusal( + ErrorCode::ParseFailed, + "agentUsage.invalidAnswer", + "The agent plugin returned an invalid usage answer.", + ) +} + +/// Calls the function the agent's plugin declares for `feature` +/// (`rateLimits` or `exchangeRates`). No runtime lock is held. +fn call_usage_function( + runtime: &Runtime, + agent: &CatalogAgent, + feature: &str, + function: &str, + params: Value, +) -> Result { + let backend = runtime + .link + .session_for(&agent.plugin_id, function, None) + .ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentUsage.backendUnavailable", + "The agent plugin's backend is not running.", + ) + })?; + runtime + .link + .call( + &backend, + &agent.plugin_id, + function, + params, + FUNCTION_TIMEOUT, + ) + .map_err(|_| { + log( + "agent.usage.plugin_failed", + [ + ("plugin", json!(agent.plugin_id)), + ("agent", json!(agent.agent.id)), + ("feature", json!(feature)), + ], + ); + refusal( + ErrorCode::ProcessFailed, + "agentUsage.pluginFailed", + "The agent plugin could not answer the usage request.", + ) + }) +} diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 97a59f3a..39e7db31 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -2505,9 +2505,11 @@ fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { assert!(crate::records::text_lines_for_test(b"").is_empty()); } +mod files; mod library; mod providers; mod sessions; +mod usage; #[test] fn turn_interaction_follows_the_shared_application_fixture() { diff --git a/rust/crates/agent-runtime/src/tests/files.rs b/rust/crates/agent-runtime/src/tests/files.rs new file mode 100644 index 00000000..16ba26f6 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/files.rs @@ -0,0 +1,63 @@ +//! The file helpers every part of the runtime shares: bounded reads and +//! writes that replace a file whole. + +use super::*; +use crate::files::{read_bounded, replace_file, ReadFailure}; + +/// The names in `directory`, sorted. +fn names(directory: &Path) -> Vec { + let mut names: Vec = fs::read_dir(directory) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +#[test] +fn bounded_reads_refuse_large_files_and_what_is_not_a_file() { + let dir = TempDir::new("files read"); + let file = dir.path().join("file"); + assert_eq!(read_bounded(&file, 4), Ok(None)); + fs::write(&file, b"four").unwrap(); + assert_eq!(read_bounded(&file, 4), Ok(Some(b"four".to_vec()))); + assert_eq!(read_bounded(&file, 3), Err(ReadFailure::TooLarge)); + // Windows refuses to open a directory; elsewhere it is not a file. + assert!(matches!( + read_bounded(dir.path(), 4), + Err(ReadFailure::Io(_)) + )); + assert_eq!( + ReadFailure::TooLarge.kind(), + std::io::ErrorKind::FileTooLarge + ); +} + +#[test] +fn replacing_a_file_leaves_only_the_new_bytes() { + let dir = TempDir::new("files replace"); + let file = dir.path().join("settings.json"); + let mut leftovers = 0; + replace_file(&file, b"first", |_| leftovers += 1).unwrap(); + replace_file(&file, b"second", |_| leftovers += 1).unwrap(); + assert_eq!(fs::read(&file).unwrap(), b"second"); + assert_eq!(names(dir.path()), ["settings.json"]); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(&file).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } + + // A write that cannot be put in place removes its new file. + let blocked = dir.path().join("blocked"); + fs::create_dir(&blocked).unwrap(); + fs::write( + blocked.join("inside"), + b"keeps the directory from being replaced", + ) + .unwrap(); + assert!(replace_file(&blocked, b"bytes", |_| leftovers += 1).is_err()); + assert_eq!(names(dir.path()), ["blocked", "settings.json"]); + assert_eq!(leftovers, 0); +} diff --git a/rust/crates/agent-runtime/src/tests/usage.rs b/rust/crates/agent-runtime/src/tests/usage.rs new file mode 100644 index 00000000..2182ff1a --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/usage.rs @@ -0,0 +1,862 @@ +//! Usage: the labels and counts a plugin reports on calls, the figures per +//! session, messages per day, how full each call's context was, and the +//! usage features a plugin implements (`agentUsage.*`): rate limits and +//! exchange rates read when the user asks, prices and alerts the user sets, +//! and the rate-limit history. + +use super::*; +use crate::events::{RateLimits, RateWindow}; +use crate::records::history::{Noted, RateHistory, HISTORY_DAYS, MAX_POINTS_PER_WINDOW}; +use crate::records::RateSnapshot; + +/// 2026-01-01T00:00:00Z. +const BASE_MS: i64 = 1_767_225_600_000; +const MINUTE_MS: i64 = 60_000; +const DAY_MS: i64 = 86_400_000; + +/// The synthetic plugin with `usage` declared for its agent. +fn usage_manifest(usage: Value) -> Value { + let mut manifest = manifest(); + manifest["agents"][0]["usage"] = usage; + manifest +} + +/// Configures the plugin with every permission it declares granted. +fn configure(harness: &Harness, manifest: Value) { + let grants = manifest["permissions"].clone(); + let answer = harness.run( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest, "grantedPermissions": grants }] }), + ); + assert_eq!(answer["rejected"], json!([]), "{answer}"); +} + +fn data_directory(harness: &Harness) -> PathBuf { + harness.dir.path().join("data") +} + +/// Configures the records with a data directory, and with `prices` when +/// given. +fn configure_data(harness: &Harness, prices: Option<&Path>) -> Value { + let mut payload = json!({ + "cacheDirectory": path_text(&harness.dir.path().join("cache")), + "userHome": path_text(&harness.dir.path().join("home")), + "dataDirectory": path_text(&data_directory(harness)), + }); + if let Some(prices) = prices { + payload["pricesFile"] = json!(path_text(prices)); + } + harness.run("agentSessions.configure", payload) +} + +fn as_background(action: impl FnOnce() -> T) -> T { + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let result = action(); + trace::replace(previous); + result +} + +/// A scan of the synthetic format that also reports the labels and counts +/// of calls, cache reads and the times of user messages. +fn usage_backend(function: &str, params: &Value) -> Result { + match function { + "sessions.scan" => { + let mut answer = scan(params); + let lines = params["lines"].as_array().unwrap(); + let mut calls = Vec::new(); + for line in lines { + let record: Value = serde_json::from_str(line["text"].as_str().unwrap()).unwrap(); + if record["type"] != "call" { + continue; + } + let offset = line["offset"].as_u64().unwrap(); + let mut call = json!({ + "key": record["key"], + "sessionID": record["session"], + "startedAtMs": record["at"], + "model": record["model"], + "tokens": { + "input": record["input"], + "output": record["output"], + "cacheRead": record["cacheRead"], + }, + "durationMs": record["duration"], + "range": { "start": offset, "end": offset + line["length"].as_u64().unwrap() }, + }); + for field in ["account", "purpose", "cancelled", "toolUses"] { + if !record[field].is_null() { + call[field] = record[field].clone(); + } + } + calls.push(call); + } + answer["calls"] = json!(calls); + Ok(answer) + } + _ => sample_backend(function, params), + } +} + +/// Two sessions in one file on two days: `s1` with three calls, `s2` with +/// one, and three user messages. +fn write_usage_file(harness: &Harness) { + let directory = harness + .dir + .path() + .join("home") + .join(".sample") + .join("sessions"); + fs::create_dir_all(&directory).unwrap(); + let day2 = BASE_MS + DAY_MS; + let lines = [ + json!({ "type": "session", "id": "s1", "cwd": "/tmp/scratch", "at": BASE_MS }), + json!({ "type": "user", "session": "s1", "text": "first question", "at": BASE_MS }), + json!({ "type": "call", "session": "s1", "key": "c1", "model": "sample-model", "input": 100, "output": 300, "cacheRead": 600, "duration": 2000, "at": BASE_MS, "account": "work", "purpose": "main", "toolUses": 2 }), + json!({ "type": "call", "session": "s1", "key": "c2", "model": "sample-model", "input": 200, "output": 100, "duration": 1000, "at": BASE_MS + 10_000, "account": "work", "purpose": "title", "cancelled": true }), + json!({ "type": "user", "session": "s1", "text": "second question", "at": BASE_MS + 20_000 }), + json!({ "type": "call", "session": "s1", "key": "c3", "model": "other-model", "input": 50, "output": 50, "duration": 500, "at": BASE_MS + 30_000, "account": "home", "purpose": "main" }), + json!({ "type": "session", "id": "s2", "cwd": "/work/project", "at": day2 }), + json!({ "type": "user", "session": "s2", "text": "next day", "at": day2 }), + json!({ "type": "call", "session": "s2", "key": "c4", "model": "sample-model", "input": 1000, "output": 1000, "duration": 4000, "at": day2 }), + ]; + let text: String = lines.iter().map(|line| format!("{line}\n")).collect(); + fs::write(directory.join("usage.jsonl"), text).unwrap(); +} + +fn synced_harness(name: &str, manifest: Value) -> Harness { + let harness = Harness::new(name, ALL_GRANTS); + configure(&harness, manifest); + harness.link.set_answer(usage_backend); + write_usage_file(&harness); + configure_data(&harness, None); + let report = harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + assert_eq!(report["filesRead"], 1, "{report}"); + harness +} + +fn group_counts(summaries: &Value, field: &str) -> BTreeMap { + summaries + .as_array() + .unwrap() + .iter() + .map(|summary| { + ( + summary["key"][field].as_str().unwrap_or("").to_string(), + ( + summary["calls"].as_u64().unwrap(), + summary["cancelledCalls"].as_u64().unwrap(), + summary["toolUses"].as_u64().unwrap(), + ), + ) + }) + .collect() +} + +#[test] +fn calls_are_grouped_and_filtered_by_their_labels() { + let harness = synced_harness("usage labels", manifest()); + let by_account = harness.run("agentSessions.stats", json!({ "groupBy": "account" })); + assert_eq!( + group_counts(&by_account["summaries"], "account"), + BTreeMap::from([ + (String::new(), (1, 0, 0)), + ("home".to_string(), (1, 0, 0)), + ("work".to_string(), (2, 1, 2)), + ]) + ); + let by_purpose = harness.run( + "agentSessions.stats", + json!({ "groupBy": "purpose", "accounts": ["work"], "cancelled": false }), + ); + assert_eq!( + group_counts(&by_purpose["summaries"], "purpose"), + BTreeMap::from([("main".to_string(), (1, 0, 2))]) + ); + let split = harness.run( + "agentSessions.stats", + json!({ "groupBy": "all", "splitBy": "purpose", "purposes": ["title"] }), + ); + assert_eq!( + split["summaries"][0]["split"]["purpose"], "title", + "{split}" + ); + + let calls = harness.run( + "agentSessions.calls", + json!({ "limit": 10, "accounts": ["work"], "search": "title" }), + ); + assert_eq!(calls["total"], 1, "{calls}"); + let row = &calls["calls"][0]; + assert_eq!(row["call"]["key"], "c2"); + assert_eq!(row["call"]["cancelled"], true); + assert_eq!(row["call"]["purpose"], "title"); + + let by_cwd = harness.run("agentSessions.stats", json!({ "groupBy": "cwd" })); + let scratch = by_cwd["summaries"] + .as_array() + .unwrap() + .iter() + .find(|summary| summary["key"]["cwd"] == "/tmp/scratch") + .expect("the scratch folder is a group"); + assert_eq!(scratch["key"]["category"], "temporary", "{by_cwd}"); + + let too_many: Vec = (0..65).map(|index| format!("a{index}")).collect(); + assert_eq!( + harness.refused( + "agentSessions.stats", + json!({ "groupBy": "all", "accounts": too_many }) + ), + "agentSessions.invalidFilter" + ); +} + +#[test] +fn stats_and_calls_keep_whole_directories_and_the_overview_ranks_speeds() { + let harness = Harness::new("usage directories", ALL_GRANTS); + configure(&harness, manifest()); + harness.link.set_answer(usage_backend); + write_usage_file(&harness); + // A sibling directory that shares the project's path as a prefix. + let sibling = [ + json!({ "type": "session", "id": "s3", "cwd": "/work/project-2", "at": BASE_MS + DAY_MS }), + json!({ "type": "call", "session": "s3", "key": "c5", "model": "sample-model", "input": 10, "output": 2000, "duration": 2000, "at": BASE_MS + DAY_MS + 1_000 }), + ]; + let text: String = sibling.iter().map(|line| format!("{line}\n")).collect(); + let sessions = harness + .dir + .path() + .join("home") + .join(".sample") + .join("sessions"); + fs::write(sessions.join("sibling.jsonl"), text).unwrap(); + configure_data(&harness, None); + let report = harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + assert_eq!(report["filesRead"], 2, "{report}"); + + let project = json!(["/work/project"]); + let exact = harness.run( + "agentSessions.stats", + json!({ "groupBy": "all", "cwds": project }), + ); + assert_eq!(exact["summaries"][0]["calls"], 1, "{exact}"); + let searched = harness.run( + "agentSessions.stats", + json!({ "groupBy": "all", "search": "/work/project" }), + ); + assert_eq!(searched["summaries"][0]["calls"], 2, "{searched}"); + let calls = harness.run( + "agentSessions.calls", + json!({ "limit": 10, "cwds": ["/work/project", "/tmp/scratch"] }), + ); + assert_eq!(calls["total"], 4, "{calls}"); + assert!(calls["calls"] + .as_array() + .unwrap() + .iter() + .all(|row| row["call"]["key"] != "c5")); + + // The overview ranks the same calls the plain statistics rank, when asked. + let calendar = json!({ "todayMs": BASE_MS + 5 * DAY_MS, "initialOffset": 0 }); + let overview = |speeds: bool| { + let mut calendar = calendar.clone(); + if speeds { + calendar["speeds"] = json!(true); + } + harness.run( + "agentSessions.stats", + json!({ "groupBy": "day", "splitBy": "model", "detail": true, + "overview": calendar, "cwds": ["/work/project", "/work/project-2"] }), + ) + }; + assert!(overview(false).get("speeds").is_none()); + let ranked = overview(true); + let plain = harness.run( + "agentSessions.stats", + json!({ "groupBy": "all", "cwds": ["/work/project", "/work/project-2"] }), + ); + assert_eq!(ranked["speeds"], plain["speeds"], "{ranked}"); + assert_eq!(ranked["speeds"][0]["calls"], 2, "{ranked}"); + + let too_many: Vec = (0..65).map(|index| format!("/work/{index}")).collect(); + let too_long = format!("/{}", "a".repeat(4096)); + for (command, payload) in [ + ( + "agentSessions.stats", + json!({ "groupBy": "all", "cwds": too_many }), + ), + ( + "agentSessions.calls", + json!({ "limit": 10, "cwds": [too_long] }), + ), + ] { + assert_eq!( + harness.refused(command, payload), + "agentSessions.invalidFilter" + ); + } +} + +#[test] +fn stats_give_figures_per_session_and_messages_per_day() { + let harness = synced_harness("usage sessions", manifest()); + let stats = harness.run( + "agentSessions.stats", + json!({ "groupBy": "day", "sessions": { "top": 1 }, "messages": true }), + ); + let sessions = &stats["sessions"]; + assert_eq!(sessions["count"], 2, "{stats}"); + assert_eq!(sessions["calls"]["max"], 3.0); + assert_eq!(sessions["calls"]["p50"], 1.0); + // s1: 100 + 300 + 600 + 200 + 100 + 50 + 50 tokens; s2: 2000. + assert_eq!(sessions["tokens"]["max"], 2000.0); + assert_eq!(sessions["tokens"]["p50"], 1400.0); + assert_eq!(sessions["uncachedTokens"]["p50"], 800.0); + // s1 runs from its first start to its last call's end: 30 s + 0.5 s. + assert_eq!(sessions["durationMs"]["p50"], 4000.0); + assert_eq!(sessions["durationMs"]["max"], 30_500.0); + // Without prices nothing is ranked by cost. + assert!(sessions.get("costUSD").is_none()); + assert_eq!(sessions["costliest"], json!([])); + + let messages = stats["messages"].as_array().unwrap(); + assert_eq!(messages.len(), 2, "{stats}"); + assert_eq!(messages[0]["key"]["date"], "2026-01-01"); + assert_eq!(messages[0]["messages"], 2); + assert_eq!(messages[1]["key"]["date"], "2026-01-02"); + assert_eq!(messages[1]["messages"], 1); + + assert_eq!( + harness.refused( + "agentSessions.stats", + json!({ "groupBy": "agent", "messages": true }) + ), + "agentSessions.invalidMessagesGroup" + ); +} + +#[test] +fn call_rows_locate_the_call_and_tell_how_full_its_context_was() { + let mut manifest = usage_manifest(json!({ "customPrices": true })); + manifest["permissions"] + .as_array_mut() + .unwrap() + .push(json!("agents.configuration")); + manifest["agents"][0]["configuration"] = json!({ + "files": [{ "id": "main", "roots": ["${userHome}/.sample/config.json"] }], + "providers": { "read": "providers.read" } + }); + let harness = synced_harness("usage context", manifest); + let calls = harness.run( + "agentSessions.calls", + json!({ "limit": 1, "sessionID": "s1" }), + ); + let row = &calls["calls"][0]; + assert_eq!(row["call"]["key"], "c3"); + assert_eq!(row["context"], json!({ "tokens": 50 }), "{row}"); + assert!(row["generation"].is_i64()); + assert!(row["size"].as_u64().unwrap() > row["call"]["range"]["end"].as_u64().unwrap()); + + // Once the plugin's model list is read, the window of a listed model is + // known. + harness.link.set_answer(|function, params| match function { + "providers.read" => Ok(json!({ + "format": "litheAgentProviders", + "version": 0, + "models": [{ "id": "sample-model", "contextWindow": 4000 }] + })), + _ => usage_backend(function, params), + }); + harness.run( + "agentLibrary.configure", + json!({ + "directory": path_text(&harness.dir.path().join("library")), + "userHome": path_text(&harness.dir.path().join("home")), + }), + ); + harness.run("agentProviders.read", json!({})); + let calls = harness.run( + "agentSessions.calls", + json!({ "limit": 10, "sessionID": "s1", "models": ["sample-model"] }), + ); + let first = &calls["calls"][1]; + assert_eq!(first["call"]["key"], "c1"); + assert_eq!( + first["context"], + json!({ "tokens": 700, "window": 4000, "share": 0.175 }), + "{first}" + ); +} + +#[test] +fn usage_features_a_plugin_leaves_out_are_refused() { + let harness = Harness::new("usage undeclared", ALL_GRANTS); + let target = json!({ "pluginID": PLUGIN, "agentID": AGENT }); + assert_eq!( + harness.refused("agentUsage.read", json!({})), + "agentUsage.notConfigured" + ); + configure_data(&harness, None); + let mut price = target.clone(); + price["model"] = json!("sample-model"); + price["price"] = json!({ "input": 1.0, "output": 2.0 }); + let mut alert = target.clone(); + alert["window"] = json!("5h"); + alert["thresholds"] = json!([80]); + let mut rates = target.clone(); + rates["currencies"] = json!(["EUR"]); + for (command, payload) in [ + ("agentUsage.setPrice", price), + ("agentUsage.setAlert", alert), + ("agentUsage.refreshRateLimits", target.clone()), + ("agentUsage.refreshExchangeRates", rates), + ] { + assert_eq!( + harness.refused(command, payload), + "agentUsage.notDeclared", + "{command}" + ); + } + assert!(harness.link.calls_of("usage.rateLimits").is_empty()); + let unknown = json!({ "pluginID": PLUGIN, "agentID": "missing" }); + assert_eq!( + harness.refused("agentUsage.refreshRateLimits", unknown), + "agentUsage.unknownAgent" + ); + assert_eq!( + harness.run("agentUsage.read", json!({})), + json!({ "exchangeRates": [], "agents": [] }) + ); +} + +#[test] +fn prices_the_user_sets_cost_the_agent_calls_before_the_table() { + let harness = synced_harness( + "usage prices", + usage_manifest(json!({ "customPrices": true })), + ); + let set = |price: Value| { + harness.run( + "agentUsage.setPrice", + json!({ "pluginID": PLUGIN, "agentID": AGENT, "model": "sample-model", "price": price }), + ) + }; + let all = || { + harness.run( + "agentSessions.stats", + json!({ "groupBy": "all", "sessions": { "top": 5 } }), + ) + }; + assert!(all()["summaries"][0].get("cost").is_none()); + + // A table that prices the model differently is overruled. + let table = harness.dir.path().join("api.json"); + fs::write( + &table, + json!({ "sample": { "models": { "sample-model": { "cost": { "input": 50.0, "output": 50.0 } } } } }) + .to_string(), + ) + .unwrap(); + configure_data(&harness, Some(&table)); + set(json!({ "input": 1.0, "output": 2.0, "cacheRead": 0.5 })); + let stats = all(); + let cost = &stats["summaries"][0]["cost"]; + // c1: 100 + 600 + 300 × 2 → 0.00103; c2: 200 + 200 → 0.0004; c4: 1000 + 2000 → 0.003. + let expected = + (100.0 + 600.0 * 0.5 + 300.0 * 2.0 + 200.0 + 100.0 * 2.0 + 1000.0 + 2000.0) / 1e6; + assert!( + (cost["usd"].as_f64().unwrap() - expected).abs() < 1e-12, + "{stats}" + ); + assert_eq!(cost["pricedCalls"], 3); + assert_eq!(cost["unpricedCalls"], 1); + let costliest = &stats["sessions"]["costliest"]; + assert_eq!(costliest[0]["sessionID"], "s2", "{stats}"); + assert_eq!(costliest[0]["pluginID"], PLUGIN); + assert_eq!(costliest[1]["sessionID"], "s1"); + let calls = harness.run("agentSessions.calls", json!({ "limit": 1 })); + assert!((calls["calls"][0]["cost"]["usd"].as_f64().unwrap() - 0.003).abs() < 1e-12); + + let read = harness.run("agentUsage.read", json!({})); + assert_eq!( + read["agents"][0]["prices"][0]["model"], "sample-model", + "{read}" + ); + assert_eq!(read["agents"][0]["prices"][0]["cacheRead"], 0.5); + + // Removing it leaves the table's price. + set(Value::Null); + let cost = all()["summaries"][0]["cost"]["usd"].as_f64().unwrap(); + assert!( + (cost - (100.0 + 600.0 + 300.0 + 200.0 + 100.0 + 1000.0 + 1000.0) * 50.0 / 1e6).abs() + < 1e-9 + ); + + let refused = |price: Value| { + harness.refused( + "agentUsage.setPrice", + json!({ "pluginID": PLUGIN, "agentID": AGENT, "model": "sample-model", "price": price }), + ) + }; + assert_eq!( + refused(json!({ "input": -1.0, "output": 1.0 })), + "agentUsage.invalidPrice" + ); + assert_eq!( + refused(json!({ "input": 1.0, "output": 100_001.0 })), + "agentUsage.invalidPrice" + ); + assert_eq!( + as_background(|| refused(json!({ "input": 1.0, "output": 1.0 }))), + "agentUsage.userActionRequired" + ); +} + +#[test] +fn settings_survive_a_restart_and_an_unreadable_file_is_set_aside() { + let harness = Harness::new("usage restart", ALL_GRANTS); + configure(&harness, usage_manifest(json!({ "rateLimitAlerts": true }))); + configure_data(&harness, None); + harness.run( + "agentUsage.setAlert", + json!({ "pluginID": PLUGIN, "agentID": AGENT, "window": "5h", "thresholds": [90, 50, 90] }), + ); + let settings = data_directory(&harness).join("usage-settings.json"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(&settings).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } + + let restarted = Runtime::new(harness.link.clone()); + restarted + .execute( + "agents.configure", + json!({ "plugins": [{ "manifest": usage_manifest(json!({ "rateLimitAlerts": true })), "grantedPermissions": ALL_GRANTS }] }), + ) + .unwrap(); + let configure = json!({ + "cacheDirectory": path_text(&harness.dir.path().join("cache-2")), + "userHome": path_text(&harness.dir.path().join("home")), + "dataDirectory": path_text(&data_directory(&harness)), + }); + restarted + .execute("agentSessions.configure", configure.clone()) + .unwrap(); + let read = restarted.execute("agentUsage.read", json!({})).unwrap(); + assert_eq!( + read["agents"][0]["alerts"], + json!([{ "window": "5h", "thresholds": [50, 90] }]), + "{read}" + ); + drop(restarted); + + fs::write(&settings, b"{ not json").unwrap(); + let again = Runtime::new(harness.link.clone()); + again.execute("agentSessions.configure", configure).unwrap(); + let read = again.execute("agentUsage.read", json!({})).unwrap(); + assert_eq!(read["agents"], json!([])); + assert_eq!( + fs::read(data_directory(&harness).join("usage-settings.unreadable.json")).unwrap(), + b"{ not json" + ); + drop(again); + + assert_eq!( + harness.refused( + "agentSessions.configure", + json!({ + "cacheDirectory": path_text(&harness.dir.path().join("cache")), + "userHome": path_text(&harness.dir.path().join("home")), + "dataDirectory": path_text(&harness.dir.path().join("cache")), + }) + ), + "agentSessions.invalidDirectory" + ); +} + +#[test] +fn rate_limits_refresh_through_the_plugin_with_alerts_and_history() { + let harness = Harness::new("usage refresh", ALL_GRANTS); + configure( + &harness, + usage_manifest(json!({ "rateLimits": "usage.rateLimits", "rateLimitAlerts": true })), + ); + configure_data(&harness, None); + let used = Arc::new(Mutex::new(json!(40.0))); + let answer = used.clone(); + harness.link.set_answer(move |function, params| match function { + "usage.rateLimits" => Ok(json!({ + "windows": [{ "id": "5h", "label": "5 hours", "usedPercent": answer.lock().unwrap().clone(), "windowMinutes": 300 }], + "plan": "pro" + })), + _ => sample_backend(function, params), + }); + let target = json!({ "pluginID": PLUGIN, "agentID": AGENT }); + let mut alert = target.clone(); + alert["window"] = json!("5h"); + for thresholds in [json!([0]), json!([101]), json!([10, 20, 30, 40, 50])] { + alert["thresholds"] = thresholds; + assert_eq!( + harness.refused("agentUsage.setAlert", alert.clone()), + "agentUsage.invalidAlert" + ); + } + alert["thresholds"] = json!([50, 90]); + harness.run("agentUsage.setAlert", alert); + + let refreshed = harness.run("agentUsage.refreshRateLimits", target.clone()); + let window = &refreshed["rateLimits"]["windows"][0]; + assert_eq!(window["usedPercent"], 40.0, "{refreshed}"); + assert_eq!(window["alert"], json!({ "thresholds": [50, 90] })); + assert_eq!( + harness.link.calls_of("usage.rateLimits")[0], + json!({ "agentID": AGENT }) + ); + + *used.lock().unwrap() = json!(60.0); + let (refreshed, logs) = capture::run(false, || { + harness.run("agentUsage.refreshRateLimits", target.clone()) + }); + assert_eq!( + refreshed["rateLimits"]["windows"][0]["alert"], + json!({ "thresholds": [50, 90], "reached": 50 }) + ); + let reached = logs + .iter() + .find(|log| log.event == "agent.usage.alert_hit") + .expect("the reached threshold is logged"); + assert_eq!(reached.fields["threshold"], 50); + assert_eq!(reached.fields["plugin"], PLUGIN); + let stats = harness.run("agentSessions.stats", json!({ "groupBy": "agent" })); + assert_eq!(stats["rateLimits"][0]["windows"][0]["alert"]["reached"], 50); + + // Both readings are within five minutes, so the history holds one point + // with the later value. + let history = harness.run("agentUsage.rateLimitHistory", target.clone()); + let windows = history["windows"].as_array().unwrap(); + assert_eq!(windows.len(), 1, "{history}"); + assert_eq!(windows[0]["window"], "5h"); + assert_eq!(windows[0]["label"], "5 hours"); + assert_eq!(windows[0]["windowMinutes"], 300); + assert_eq!(windows[0]["points"].as_array().map(Vec::len), Some(1)); + assert_eq!(windows[0]["points"][0]["usedPercent"], 60.0); + + *used.lock().unwrap() = json!(120.0); + assert_eq!( + harness.refused("agentUsage.refreshRateLimits", target.clone()), + "agentUsage.invalidAnswer" + ); + harness + .link + .set_answer(|_, _| Err(failure("plugin.function.failed"))); + assert_eq!( + harness.refused("agentUsage.refreshRateLimits", target.clone()), + "agentUsage.pluginFailed" + ); + harness.link.set_backend(None); + assert_eq!( + harness.refused("agentUsage.refreshRateLimits", target.clone()), + "agentUsage.backendUnavailable" + ); + assert_eq!( + as_background(|| harness.refused("agentUsage.refreshRateLimits", target.clone())), + "agentUsage.userActionRequired" + ); + let mut range = target.clone(); + range["sinceMs"] = json!(10); + range["untilMs"] = json!(10); + assert_eq!( + harness.refused("agentUsage.rateLimitHistory", range), + "agentUsage.invalidRange" + ); + + harness.run("agentSessions.forget", target.clone()); + let history = harness.run("agentUsage.rateLimitHistory", target); + assert_eq!(history["windows"], json!([])); +} + +#[test] +fn exchange_rates_come_from_the_plugin_and_choose_the_currency() { + let harness = Harness::new("usage currency", ALL_GRANTS); + configure( + &harness, + usage_manifest(json!({ "exchangeRates": "usage.exchangeRates" })), + ); + configure_data(&harness, None); + let rates = Arc::new(Mutex::new(json!({ "rates": { "EUR": 0.9, "JPY": 150.0 } }))); + let answer = rates.clone(); + harness + .link + .set_answer(move |function, params| match function { + "usage.exchangeRates" => Ok(answer.lock().unwrap().clone()), + _ => sample_backend(function, params), + }); + let currency = + |code: Value| harness.refused("agentUsage.setCurrency", json!({ "currency": code })); + assert_eq!(currency(json!("EUR")), "agentUsage.noExchangeRate"); + assert_eq!(currency(json!("eur")), "agentUsage.invalidCurrency"); + + let ask = |currencies: Value| json!({ "pluginID": PLUGIN, "agentID": AGENT, "currencies": currencies }); + for currencies in [json!([]), json!(["USD"]), json!(["EURO"])] { + assert_eq!( + harness.refused("agentUsage.refreshExchangeRates", ask(currencies)), + "agentUsage.invalidCurrency" + ); + } + let refreshed = harness.run( + "agentUsage.refreshExchangeRates", + ask(json!(["JPY", "EUR"])), + ); + assert_eq!( + harness.link.calls_of("usage.exchangeRates")[0], + json!({ "agentID": AGENT, "base": "USD", "currencies": ["EUR", "JPY"] }) + ); + let entries = refreshed["exchangeRates"].as_array().unwrap(); + assert_eq!(entries.len(), 2, "{refreshed}"); + assert_eq!(entries[0]["currency"], "EUR"); + assert_eq!(entries[0]["perUSD"], 0.9); + assert_eq!(entries[0]["pluginID"], PLUGIN); + + harness.run("agentUsage.setCurrency", json!({ "currency": "EUR" })); + let stats = harness.run("agentSessions.stats", json!({ "groupBy": "agent" })); + assert_eq!(stats["currency"]["code"], "EUR", "{stats}"); + assert_eq!(stats["currency"]["perUSD"], 0.9); + assert_eq!(harness.run("agentUsage.read", json!({}))["currency"], "EUR"); + harness.run("agentUsage.setCurrency", json!({ "currency": "USD" })); + let stats = harness.run("agentSessions.stats", json!({ "groupBy": "agent" })); + assert!(stats.get("currency").is_none()); + + // A rate for a currency not asked for, or not positive, is refused. + for answer in [ + json!({ "rates": { "GBP": 0.8 } }), + json!({ "rates": { "EUR": 0.0 } }), + json!({ "rates": { "EUR": 1.0 }, "extra": true }), + ] { + *rates.lock().unwrap() = answer; + assert_eq!( + harness.refused("agentUsage.refreshExchangeRates", ask(json!(["EUR"]))), + "agentUsage.invalidAnswer" + ); + } +} + +fn snapshot(at_ms: i64, used_percent: f64, resets_at_ms: Option) -> RateSnapshot { + RateSnapshot::new( + RateLimits { + windows: vec![RateWindow { + id: "5h".to_string(), + label: None, + used_percent, + window_minutes: Some(300), + resets_at_ms, + }], + plan: None, + }, + at_ms, + ) +} + +fn points(history: &RateHistory) -> Vec<(i64, f64)> { + history.query(AGENT_KEY, Some("5h"), None, None)[0]["points"] + .as_array() + .unwrap() + .iter() + .map(|point| { + ( + point["atMs"].as_i64().unwrap(), + point["usedPercent"].as_f64().unwrap(), + ) + }) + .collect() +} + +#[test] +fn the_history_keeps_points_apart_and_starts_a_point_per_cycle() { + let mut history = RateHistory::default(); + let reset = Some(BASE_MS + 300 * MINUTE_MS); + assert_eq!( + history.note(AGENT_KEY, &snapshot(BASE_MS, 10.0, reset)), + Noted::Added + ); + // Same reading: nothing. + assert_eq!( + history.note(AGENT_KEY, &snapshot(BASE_MS + MINUTE_MS, 10.0, reset)), + Noted::Unchanged + ); + // Closer than five minutes: replaces the value, keeps the time. + assert_eq!( + history.note(AGENT_KEY, &snapshot(BASE_MS + 2 * MINUTE_MS, 12.0, reset)), + Noted::Replaced + ); + // The reset time moving by under a minute is the same cycle. + assert_eq!( + history.note( + AGENT_KEY, + &snapshot(BASE_MS + 5 * MINUTE_MS, 15.0, reset.map(|at| at + 30_000)) + ), + Noted::Added + ); + // A drop starts a cycle even within five minutes. + assert_eq!( + history.note(AGENT_KEY, &snapshot(BASE_MS + 6 * MINUTE_MS, 1.0, reset)), + Noted::Added + ); + // An older reading is ignored. + assert_eq!( + history.note(AGENT_KEY, &snapshot(BASE_MS, 50.0, reset)), + Noted::Unchanged + ); + assert_eq!( + points(&history), + vec![ + (BASE_MS, 12.0), + (BASE_MS + 5 * MINUTE_MS, 15.0), + (BASE_MS + 6 * MINUTE_MS, 1.0) + ] + ); + let since = history.query( + AGENT_KEY, + None, + Some(BASE_MS + 5 * MINUTE_MS), + Some(BASE_MS + 6 * MINUTE_MS), + ); + assert_eq!(since[0]["points"].as_array().map(Vec::len), Some(1)); + assert!(history + .query(AGENT_KEY, Some("weekly"), None, None) + .is_empty()); + assert!(history.forget(AGENT_KEY)); + assert!(history.query(AGENT_KEY, None, None, None).is_empty()); +} + +#[test] +fn the_history_drops_old_points_and_caps_each_window() { + let mut history = RateHistory::default(); + history.note(AGENT_KEY, &snapshot(BASE_MS, 1.0, None)); + let later = BASE_MS + (HISTORY_DAYS + 1) * DAY_MS; + history.note(AGENT_KEY, &snapshot(later, 2.0, None)); + assert_eq!(points(&history), vec![(later, 2.0)]); + + let mut history = RateHistory::default(); + let count = MAX_POINTS_PER_WINDOW + 10; + for index in 0..count { + // Each point starts a cycle, so none replaces another. + let at = BASE_MS + index as i64 * 5 * MINUTE_MS; + history.note( + AGENT_KEY, + &snapshot(at, (index % 2) as f64 * 50.0, Some(at)), + ); + } + let kept = points(&history); + assert_eq!(kept.len(), MAX_POINTS_PER_WINDOW); + assert_eq!(kept[0].0, BASE_MS + 10 * 5 * MINUTE_MS); +} diff --git a/rust/crates/agent-sessions/benches/daily_overview.rs b/rust/crates/agent-sessions/benches/daily_overview.rs index 94bb6c9f..86103ab7 100644 --- a/rust/crates/agent-sessions/benches/daily_overview.rs +++ b/rust/crates/agent-sessions/benches/daily_overview.rs @@ -41,6 +41,7 @@ fn run(days: i64) { today_ms: days * DAY, initial_offset: 0, offsets: vec![], + speeds: false, }; let day = GroupBy::Day { utc_offset_seconds: 0, @@ -91,6 +92,7 @@ fn run(days: i64) { today_ms: (days - 1) * DAY, initial_offset: 0, offsets: Vec::new(), + speeds: false, }; let live = measure("warm overview with 1000 calls today", || { store diff --git a/rust/crates/agent-sessions/src/lib.rs b/rust/crates/agent-sessions/src/lib.rs index f195a8b9..afcdd757 100644 --- a/rust/crates/agent-sessions/src/lib.rs +++ b/rust/crates/agent-sessions/src/lib.rs @@ -20,7 +20,9 @@ //! when a message is shown. //! //! The cost, cache hit rate and speed of calls are computed once, here, in -//! [`stats`], with prices from a models.dev table ([`pricing`]). +//! [`stats`], with prices from a models.dev table and the prices the user +//! set ([`pricing`]), and so are the figures per session and the messages +//! per hour or day. //! //! [`folder_category`] tells which working directories of sessions are not //! project folders (a disk's root, a temporary directory, a hidden folder in @@ -50,6 +52,6 @@ pub use store::{ SessionEntry, SessionFilter, SessionGroup, SessionOrder, SessionStore, SyncReport, ThreadEntry, 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, + MAX_TOOL_USES, SCHEMA_VERSION, }; pub use text::{snippet, Snippet, SNIPPET_AFTER_CHARS, SNIPPET_BEFORE_CHARS}; diff --git a/rust/crates/agent-sessions/src/model.rs b/rust/crates/agent-sessions/src/model.rs index 44bb89be..620c9a14 100644 --- a/rust/crates/agent-sessions/src/model.rs +++ b/rust/crates/agent-sessions/src/model.rs @@ -121,10 +121,32 @@ pub struct CallRecord { /// names it (for example `rateLimited`). Never the error message. #[serde(default, skip_serializing_if = "Option::is_none")] pub error_category: Option, + /// The account that made the request, as the agent names it, for example + /// a login or an organization ID. A label: Core groups and filters by it + /// and never interprets it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account: Option, + /// What the request was for, as the agent names it, for example the main + /// conversation, a subagent or a title. A label: Core groups and filters + /// by it and never interprets it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub purpose: Option, + /// Whether the request was cancelled before it finished, by the user or + /// the agent. A cancelled request is not a failed one: it carries no + /// `error_category`. + #[serde(default, skip_serializing_if = "is_false")] + pub cancelled: bool, + /// How many tool calls the response asked for, when the agent records it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_uses: Option, /// The bytes of the session file that record the request. pub range: ByteRange, } +fn is_false(value: &bool) -> bool { + !*value +} + /// What a session file says about a session. A parser reports it whenever /// it learns more; the store keeps the latest present value of each field. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/rust/crates/agent-sessions/src/pricing.rs b/rust/crates/agent-sessions/src/pricing.rs index 9cb0daa9..41e6f701 100644 --- a/rust/crates/agent-sessions/src/pricing.rs +++ b/rust/crates/agent-sessions/src/pricing.rs @@ -4,6 +4,9 @@ //! is what the same tokens would cost at the provider's API prices. The table //! is models.dev's `api.json`: providers by ID, each with models by ID, each //! with a `cost` in US dollars per million tokens. +//! +//! The user may also set a price for a model of one agent, which applies to +//! that agent's calls before the table's ([`PriceTable::set_overrides`]). use std::collections::HashMap; @@ -75,13 +78,17 @@ pub struct CallCost { pub approximate: bool, } -/// Prices by provider and model. +/// Prices by provider and model, and the prices the user set by agent and +/// model. #[derive(Debug, Clone, Default)] pub struct PriceTable { prices: HashMap>, /// For a model without a known provider: the provider whose price to use, /// or `None` when providers price it differently. by_model: HashMap>, + /// The prices the user set, by agent record key, then model name as calls + /// are counted under it. They apply whatever provider served the call. + overrides: HashMap>, } impl PriceTable { @@ -136,12 +143,32 @@ impl PriceTable { self.prices.get(provider)?.get(model) } - /// Models with a price, counted once per provider. + /// The price of `model` for a call of `agent`: the one the user set for + /// the agent's model, otherwise [`lookup`](Self::lookup). + pub fn lookup_for(&self, agent: &str, provider: Option<&str>, model: &str) -> Option<&Price> { + self.overrides + .get(agent) + .and_then(|models| models.get(model)) + .or_else(|| self.lookup(provider, model)) + } + + /// Replaces the prices the user set, by agent record key and model. + pub fn set_overrides(&mut self, overrides: HashMap>) { + self.overrides = overrides; + } + + /// Whether the user set any price. + pub fn has_overrides(&self) -> bool { + self.overrides.values().any(|models| !models.is_empty()) + } + + /// Models with a price in the table, counted once per provider; prices + /// the user set are not counted. pub fn len(&self) -> usize { self.prices.values().map(HashMap::len).sum() } - /// Whether the table has no prices. + /// Whether the table has no prices; prices the user set are not counted. pub fn is_empty(&self) -> bool { self.prices.is_empty() } diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs index 79fe36ec..5bac0e06 100644 --- a/rust/crates/agent-sessions/src/stats.rs +++ b/rust/crates/agent-sessions/src/stats.rs @@ -8,10 +8,14 @@ //! - 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; failed and +//! cancelled calls have none; //! - 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. +//! first-token time is the mean over its calls that neither failed nor were +//! cancelled and report one; +//! - a session's figures ([`sessions`]) add up its calls in the range, and +//! their quantiles are nearest-rank values over the sessions. use std::collections::BTreeMap; @@ -63,6 +67,10 @@ pub enum GroupBy { /// By model and provider together, so one model served by two providers /// counts as two groups. ModelProvider, + /// By the account that made the call, as the agent names it. + Account, + /// By what the call was for, as the agent names it. + Purpose, /// All calls as one group, for totals that are not sums of other groups /// (a median speed, a hit rate). All, @@ -123,6 +131,18 @@ pub enum GroupKey { #[serde(skip_serializing_if = "Option::is_none")] provider: Option, }, + /// An account; absent for calls that do not name one. + Account { + /// The account, as the agent names it. + #[serde(skip_serializing_if = "Option::is_none")] + account: Option, + }, + /// A purpose; absent for calls that do not name one. + Purpose { + /// The purpose, as the agent names it. + #[serde(skip_serializing_if = "Option::is_none")] + purpose: Option, + }, /// Every call. All, } @@ -212,6 +232,10 @@ pub struct Summary { pub failed_calls: u64, /// Calls the agent made to compact its context. pub compaction_calls: u64, + /// Calls cancelled before they finished; they are not failed calls. + pub cancelled_calls: u64, + /// Tool calls the responses asked for, over the calls that report it. + pub tool_uses: u64, /// Token totals. pub tokens: TokenTotals, /// Cache reads over all input of the calls that report cache counts, or @@ -287,14 +311,13 @@ impl<'a> Summarizer<'a> { /// 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(), split.clone())) .or_insert_with(|| Accumulator::new(key, split, self.prices)); - accumulator.add(call, self.prices, self.detailed); + accumulator.add(entry, self.prices, self.detailed); } /// The groups, in order of their keys, then of their second keys. @@ -312,6 +335,8 @@ impl Accumulator { calls: 0, failed_calls: 0, compaction_calls: 0, + cancelled_calls: 0, + tool_uses: 0, tokens: TokenTotals::default(), cache_hit_rate: None, cost: prices.map(|_| CostTotal { @@ -361,6 +386,8 @@ impl Accumulator { dst.calls += src.calls; dst.failed_calls += src.failed_calls; dst.compaction_calls += src.compaction_calls; + dst.cancelled_calls += src.cancelled_calls; + dst.tool_uses = dst.tool_uses.saturating_add(src.tool_uses); dst.first_started_at_ms = dst.first_started_at_ms.min(src.first_started_at_ms); dst.last_started_at_ms = dst.last_started_at_ms.max(src.last_started_at_ms); dst.tokens.input = dst.tokens.input.saturating_add(src.tokens.input); @@ -388,11 +415,16 @@ impl Accumulator { self.lower_bound |= other.lower_bound; } - fn add(&mut self, call: &CallRecord, prices: Option<&PriceTable>, detailed: bool) { + fn add(&mut self, entry: &CallEntry, prices: Option<&PriceTable>, detailed: bool) { + let call = &entry.call; let summary = &mut self.summary; summary.calls += 1; summary.failed_calls += u64::from(call.error_category.is_some()); summary.compaction_calls += u64::from(call.compaction); + summary.cancelled_calls += u64::from(call.cancelled); + summary.tool_uses = summary + .tool_uses + .saturating_add(call.tool_uses.unwrap_or(0)); summary.first_started_at_ms = summary.first_started_at_ms.min(call.started_at_ms); summary.last_started_at_ms = summary.last_started_at_ms.max(call.started_at_ms); @@ -423,9 +455,7 @@ impl Accumulator { } if let (Some(prices), Some(cost)) = (prices, summary.cost.as_mut()) { - let priced = model_name(call) - .and_then(|model| prices.lookup(call.provider.as_deref(), model)) - .and_then(|price| call_cost(price, tokens)); + let priced = price_call(prices, entry); match priced { Some(priced) => { cost.usd += priced.usd; @@ -441,7 +471,9 @@ impl Accumulator { self.speeds.push(speed.tokens_per_second()); self.lower_bound |= matches!(speed, Speed::AtLeast(_)); } - if let (None, Some(first)) = (&call.error_category, call.first_token_ms) { + if let (None, false, Some(first)) = + (&call.error_category, call.cancelled, call.first_token_ms) + { self.first_token_total_ms += u128::from(first); self.first_token_calls += 1; } @@ -449,6 +481,15 @@ impl Accumulator { } } +/// What the call of `entry` would cost at `prices`: the price the user set +/// for its agent's model, or the table's for its provider and model. +pub fn price_call(prices: &PriceTable, entry: &CallEntry) -> Option { + let call = &entry.call; + model_name(call) + .and_then(|model| prices.lookup_for(&entry.agent, call.provider.as_deref(), model)) + .and_then(|price| call_cost(price, &call.tokens)) +} + /// Groups `entries` by `group_by`; see [`Summarizer`]. pub fn summarize<'e>( entries: impl IntoIterator, @@ -482,10 +523,10 @@ impl Speed { } } -/// The speed of a call, or `None` when it failed, lacks the counts, or its -/// timing says nothing reliable. +/// The speed of a call, or `None` when it failed or was cancelled, lacks the +/// counts, or its timing says nothing reliable. pub fn call_speed(call: &CallRecord) -> Option { - if call.error_category.is_some() { + if call.error_category.is_some() || call.cancelled { return None; } let output = call.tokens.output.filter(|output| *output > 0)?; @@ -563,16 +604,21 @@ impl SpeedRanker { 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)) - }); + sort_ranks(&mut ranks); ranks } } +/// Puts a speed ranking in order: fastest first, models tying by name. +pub(crate) fn sort_ranks(ranks: &mut [SpeedRank]) { + ranks.sort_by(|left, right| { + right + .median_tokens_per_second + .total_cmp(&left.median_tokens_per_second) + .then_with(|| left.model.cmp(&right.model)) + }); +} + /// The model a call is counted under: the one that answered, or the one asked /// for when the answer did not name it. pub fn model_name(call: &CallRecord) -> Option<&str> { @@ -599,15 +645,9 @@ fn group_key(group_by: GroupBy, entry: &CallEntry) -> GroupKey { GroupBy::Day { utc_offset_seconds } => GroupKey::Day { date: civil_date(entry.call.started_at_ms, utc_offset_seconds), }, - GroupBy::Hour { anchor_ms } => { - const HOUR: i64 = 3_600_000; - let started = entry.call.started_at_ms; - // Reduce both operands before subtracting so distant anchors cannot overflow. - let elapsed = (started.rem_euclid(HOUR) - anchor_ms.rem_euclid(HOUR)).rem_euclid(HOUR); - GroupKey::Hour { - start_ms: started.saturating_sub(elapsed), - } - } + GroupBy::Hour { anchor_ms } => GroupKey::Hour { + start_ms: hour_start(entry.call.started_at_ms, anchor_ms), + }, GroupBy::Agent => GroupKey::Agent { agent: entry.agent.clone(), }, @@ -628,10 +668,25 @@ fn group_key(group_by: GroupBy, entry: &CallEntry) -> GroupKey { model: model_name(&entry.call).map(str::to_string), provider: entry.call.provider.clone(), }, + GroupBy::Account => GroupKey::Account { + account: entry.call.account.clone(), + }, + GroupBy::Purpose => GroupKey::Purpose { + purpose: entry.call.purpose.clone(), + }, GroupBy::All => GroupKey::All, } } +/// The start of the hour bucket that holds `at_ms`, for buckets aligned to +/// `anchor_ms`. +fn hour_start(at_ms: i64, anchor_ms: i64) -> i64 { + const HOUR: i64 = 3_600_000; + // Reduce both operands before subtracting so distant anchors cannot overflow. + let elapsed = (at_ms.rem_euclid(HOUR) - anchor_ms.rem_euclid(HOUR)).rem_euclid(HOUR); + at_ms.saturating_sub(elapsed) +} + /// 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)] @@ -644,8 +699,21 @@ pub struct CallSelector { pub providers: Vec, /// `true` keeps only failed calls, `false` only successful ones. pub failed: Option, + /// Accounts; the empty name stands for calls that name none. Empty keeps + /// every account. + pub accounts: Vec, + /// Purposes; the empty name stands for calls that name none. Empty keeps + /// every purpose. + pub purposes: Vec, + /// `true` keeps only cancelled calls, `false` only the others. + pub cancelled: Option, + /// Working directories of the calls' sessions, matched exactly, so + /// `/work/a` keeps neither `/work/a-2` nor `/work/a/b`; the empty name + /// stands for sessions that record none. Empty keeps every directory. + pub cwds: Vec, /// Words that must each appear, ignoring case, in the model, requested - /// model, provider, agent, session or directory of the call. + /// model, provider, account, purpose, agent, session or directory of the + /// call. pub words: Vec, } @@ -661,32 +729,50 @@ impl CallSelector { self.models.is_empty() && self.providers.is_empty() && self.failed.is_none() + && self.accounts.is_empty() + && self.purposes.is_empty() + && self.cancelled.is_none() + && self.cwds.is_empty() && self.words.is_empty() } + /// Whether a call with these labels passes the selector's name filters + /// (models, providers, accounts, purposes) and its outcome filters. + pub(crate) fn keeps_labels( + &self, + model: Option<&str>, + provider: Option<&str>, + account: Option<&str>, + purpose: Option<&str>, + failed: bool, + cancelled: bool, + ) -> bool { + let listed = |names: &[String], value: Option<&str>| { + names.is_empty() || names.iter().any(|name| name == value.unwrap_or("")) + }; + listed(&self.models, model) + && listed(&self.providers, provider) + && listed(&self.accounts, account) + && listed(&self.purposes, purpose) + && self.failed.is_none_or(|wanted| wanted == failed) + && self.cancelled.is_none_or(|wanted| wanted == cancelled) + } + /// 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("")) - { + if !self.keeps_labels( + model_name(call), + call.provider.as_deref(), + call.account.as_deref(), + call.purpose.as_deref(), + call.error_category.is_some(), + call.cancelled, + ) { return false; } - if self - .failed - .is_some_and(|failed| call.error_category.is_some() != failed) - { + let cwd = entry.cwd.as_deref().unwrap_or(""); + if !self.cwds.is_empty() && !self.cwds.iter().any(|wanted| wanted == cwd) { return false; } if self.words.is_empty() { @@ -696,6 +782,8 @@ impl CallSelector { call.model.as_deref(), call.requested_model.as_deref(), call.provider.as_deref(), + call.account.as_deref(), + call.purpose.as_deref(), Some(entry.agent.as_str()), Some(call.session_id.as_str()), entry.cwd.as_deref(), @@ -746,5 +834,7 @@ pub(crate) fn civil_date(at_ms: i64, utc_offset_seconds: i32) -> String { format!("{year:04}-{month:02}-{day:02}") } +pub mod messages; mod overview; +pub mod sessions; pub use overview::{CalendarOffset, Overview, OverviewQuery}; diff --git a/rust/crates/agent-sessions/src/stats/messages.rs b/rust/crates/agent-sessions/src/stats/messages.rs new file mode 100644 index 00000000..fba5fcb4 --- /dev/null +++ b/rust/crates/agent-sessions/src/stats/messages.rs @@ -0,0 +1,80 @@ +//! Messages per hour or local day. +//! +//! A message is a searchable span the agent's plugin reported, as +//! [`SessionStore::for_each_message_time`](crate::SessionStore::for_each_message_time) +//! visits them: the prompts and replies of each session's own file, at the +//! time the plugin gave them. + +use std::collections::BTreeMap; + +use serde::Serialize; + +use super::{civil_date, hour_start, GroupBy, GroupKey, OverviewQuery}; + +/// How many messages one time bucket holds. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MessageCount { + /// The bucket, shaped like a summary's `hour` or `day` key. + pub key: GroupKey, + /// Messages written in it. + pub messages: u64, +} + +/// How [`MessageCounter`] finds the bucket of a time. +#[derive(Debug, Clone, Copy)] +enum Bucket<'a> { + Hour { anchor_ms: i64 }, + Day { utc_offset_seconds: i32 }, + Calendar(&'a OverviewQuery), +} + +/// Counts message times into hour or day buckets one at a time; it keeps one +/// count per occupied bucket. +#[derive(Debug)] +pub struct MessageCounter<'a> { + bucket: Bucket<'a>, + counts: BTreeMap, +} + +impl<'a> MessageCounter<'a> { + /// A counter that buckets like `group_by`, which must be `hour` or `day`; + /// a day follows `calendar` when given, so it matches an overview's days + /// across offset changes. `None` for any other grouping. + pub fn new(group_by: GroupBy, calendar: Option<&'a OverviewQuery>) -> Option { + let bucket = match (group_by, calendar) { + (GroupBy::Hour { anchor_ms }, _) => Bucket::Hour { anchor_ms }, + (GroupBy::Day { .. }, Some(calendar)) => Bucket::Calendar(calendar), + (GroupBy::Day { utc_offset_seconds }, None) => Bucket::Day { utc_offset_seconds }, + _ => return None, + }; + Some(Self { + bucket, + counts: BTreeMap::new(), + }) + } + + /// Counts a message written at `at_ms`. + pub fn add(&mut self, at_ms: i64) { + let key = match self.bucket { + Bucket::Hour { anchor_ms } => GroupKey::Hour { + start_ms: hour_start(at_ms, anchor_ms), + }, + Bucket::Day { utc_offset_seconds } => GroupKey::Day { + date: civil_date(at_ms, utc_offset_seconds), + }, + Bucket::Calendar(calendar) => GroupKey::Day { + date: calendar.day(at_ms).2, + }, + }; + *self.counts.entry(key).or_default() += 1; + } + + /// The occupied buckets, oldest first. + pub fn finish(self) -> Vec { + self.counts + .into_iter() + .map(|(key, messages)| MessageCount { key, messages }) + .collect() + } +} diff --git a/rust/crates/agent-sessions/src/stats/overview.rs b/rust/crates/agent-sessions/src/stats/overview.rs index 44526c9f..98865d3d 100644 --- a/rust/crates/agent-sessions/src/stats/overview.rs +++ b/rust/crates/agent-sessions/src/stats/overview.rs @@ -1,5 +1,6 @@ //! Daily usage shared by the overview totals, breakdown and chart. -//! Each finished local day contains only observed model/provider/outcome combinations. +//! Each finished local day contains only observed combinations of model, +//! provider, account, purpose and outcome. //! Its counts and speed block bounds can be read without loading the speed samples. use super::*; @@ -18,7 +19,8 @@ pub struct CalendarOffset { pub seconds: i32, } -/// Local calendar supplied by the desktop for an overview read. +/// What the host asks of an overview read: its local calendar, and whether +/// the models are also ranked by speed. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct OverviewQuery { @@ -29,6 +31,9 @@ pub struct OverviewQuery { /// Subsequent changes in chronological order. #[serde(default)] pub offsets: Vec, + /// Whether [`Overview::speeds`] ranks the models by median output speed. + #[serde(default)] + pub speeds: bool, } impl OverviewQuery { @@ -41,7 +46,9 @@ impl OverviewQuery { && self.offsets.windows(2).all(|w| w[0].at_ms < w[1].at_ms) } - fn day(&self, at: i64) -> (i64, i64, String) { + /// The local day that holds `at`: its first instant, the first instant + /// of the next day and its date. + pub(crate) fn day(&self, at: i64) -> (i64, i64, String) { let index = self.offsets.partition_point(|o| o.at_ms <= at); let offset = |i: usize| { if i == 0 { @@ -94,17 +101,25 @@ pub struct Overview { pub groups: Vec, /// Sparse hour or local day buckets, split by that dimension. pub series: Vec, + /// The models ranked by median output speed over the same calls, as + /// [`rank_speed`] ranks them; empty unless [`OverviewQuery::speeds`]. + pub speeds: Vec, /// Cache fallback reason for the runtime log; never included in the command response. #[serde(skip)] pub cache_warning: Option, } +/// The labels a day's calls are summed apart by: every dimension a filter or +/// split of an overview can name, so a finished day serves them all. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] struct CellKey { agent: String, model: Option, provider: Option, failed: bool, + account: Option, + purpose: Option, + cancelled: bool, } impl CellKey { @@ -114,16 +129,21 @@ impl CellKey { model: model_name(&entry.call).map(str::to_owned), provider: entry.call.provider.clone(), failed: entry.call.error_category.is_some(), + account: entry.call.account.clone(), + purpose: entry.call.purpose.clone(), + cancelled: entry.call.cancelled, } } fn keeps(&self, selector: &CallSelector) -> bool { - let matches = |names: &[String], value: Option<&str>| { - names.is_empty() || names.iter().any(|s| s == value.unwrap_or("")) - }; - matches(&selector.models, self.model.as_deref()) - && matches(&selector.providers, self.provider.as_deref()) - && selector.failed.is_none_or(|f| f == self.failed) + selector.keeps_labels( + self.model.as_deref(), + self.provider.as_deref(), + self.account.as_deref(), + self.purpose.as_deref(), + self.failed, + self.cancelled, + ) } fn group(&self, by: GroupBy) -> GroupKey { @@ -141,6 +161,12 @@ impl CellKey { model: self.model.clone(), provider: self.provider.clone(), }, + GroupBy::Account => GroupKey::Account { + account: self.account.clone(), + }, + GroupBy::Purpose => GroupKey::Purpose { + purpose: self.purpose.clone(), + }, _ => unreachable!("validated overview split"), } } @@ -340,6 +366,28 @@ fn block_median( Ok((at(last / 2)? + at(n / 2)?) / 2.0) } +/// The speed ranking of per-model summaries: those with a median speed. +fn speed_ranks(models: Vec) -> Vec { + let mut ranks: Vec = models + .into_iter() + .filter_map(|summary| { + let (GroupKey::Model { model: Some(model) }, Some(speed)) = + (summary.key, summary.speed) + else { + return None; + }; + Some(SpeedRank { + model, + calls: speed.calls, + median_tokens_per_second: speed.median_tokens_per_second, + lower_bound: speed.lower_bound, + }) + }) + .collect(); + sort_ranks(&mut ranks); + ranks +} + fn db_error(e: rusqlite::Error) -> CoreError { sql_error("Could not read or update daily agent usage", e) } @@ -385,15 +433,29 @@ struct Period<'a> { impl Period<'_> { // Only the rates used by this day's models matter. Updating an unrelated - // model in the price catalog keeps every statistic of this day reusable. + // model in the price catalog, or a price the user set for another agent + // or model, keeps every statistic of this day reusable. fn day_prices(&self, cells: &[Cell]) -> Result, CoreError> { let used = self.prices.map(|table| { cells .iter() - .filter_map(|cell| Some((cell.key.model.as_deref()?, cell.key.provider.as_deref()))) + .filter_map(|cell| { + Some(( + cell.key.agent.as_str(), + cell.key.model.as_deref()?, + cell.key.provider.as_deref(), + )) + }) .collect::>() .into_iter() - .map(|(model, provider)| (model, provider, table.lookup(provider, model))) + .map(|(agent, model, provider)| { + ( + agent, + model, + provider, + table.lookup_for(agent, provider, model), + ) + }) .collect::>() }); serde_json::to_vec(&used).map_err(|_| cache_error()) @@ -403,13 +465,18 @@ impl Period<'_> { let Some(table) = self.prices else { return saved == b"null"; }; - type ModelPrice = (String, Option, Option); + type ModelPrice = ( + String, + String, + Option, + Option, + ); let Ok(Some(rows)) = serde_json::from_slice::>>(saved) else { return false; }; - rows.iter().all(|(model, provider, price)| { - table.lookup(provider.as_deref(), model) == price.as_ref() + rows.iter().all(|(agent, model, provider, price)| { + table.lookup_for(agent, provider.as_deref(), model) == price.as_ref() }) } @@ -511,7 +578,7 @@ impl Period<'_> { cells .entry(CellKey::of(&entry)) .or_insert_with(|| Accumulator::new(GroupKey::All, None, self.prices)) - .add(&entry.call, self.prices, true); + .add(&entry, self.prices, true); Ok(()) })?; // A sync can remove the last copy between discovering a day and opening @@ -569,7 +636,12 @@ impl SessionStore { || !matches!(series, GroupBy::Day { .. } | GroupBy::Hour { .. }) || !matches!( split, - GroupBy::Model | GroupBy::Agent | GroupBy::Provider | GroupBy::ModelProvider + GroupBy::Model + | GroupBy::Agent + | GroupBy::Provider + | GroupBy::ModelProvider + | GroupBy::Account + | GroupBy::Purpose ) { return Err(CoreError::new( @@ -582,8 +654,10 @@ impl SessionStore { calendar, prices, }; + // Cached days keep no directory, so a directory filter reads the calls. let reusable = matches!(series, GroupBy::Day { .. }) && selector.words.is_empty() + && selector.cwds.is_empty() && filter.session_id.is_none(); let mut warning = if reusable { period.warm(self)? } else { None }; let snapshot = self.connection.unchecked_transaction().map_err(db_error)?; @@ -681,11 +755,16 @@ impl Period<'_> { Projection::default(), Projection::default(), ); + // Cells keep the same speeds a ranking takes, so one per model ranks them. + let mut ranking = self.calendar.speeds.then(Projection::default); let mut consume = |cell: &Cell, time: &GroupKey, samples: &Samples| { let group = cell.key.group(split); totals.add(GroupKey::All, None, cell, samples); groups.add(group.clone(), None, cell, samples); chart.add(time.clone(), Some(group), cell, samples); + if let (Some(ranking), Some(_)) = (ranking.as_mut(), &cell.key.model) { + ranking.add(cell.key.group(GroupBy::Model), None, cell, samples); + } }; self.visit_days::(store, |agent, start, end, date, complete| { let day = GroupKey::Day { date }; @@ -716,7 +795,7 @@ impl Period<'_> { .or_default() .entry(CellKey::of(&entry)) .or_insert_with(|| Accumulator::new(GroupKey::All, None, prices)) - .add(&entry.call, prices, true); + .add(&entry, prices, true); } Ok(()) })?; @@ -729,10 +808,15 @@ impl Period<'_> { } Ok(()) })?; + let speeds = match ranking { + Some(ranking) => speed_ranks(ranking.finish(store)?), + None => Vec::new(), + }; Ok(Overview { summaries: totals.finish(store)?, groups: groups.finish(store)?, series: chart.finish(store)?, + speeds, cache_warning: None, }) } diff --git a/rust/crates/agent-sessions/src/stats/sessions.rs b/rust/crates/agent-sessions/src/stats/sessions.rs new file mode 100644 index 00000000..72299b35 --- /dev/null +++ b/rust/crates/agent-sessions/src/stats/sessions.rs @@ -0,0 +1,253 @@ +//! Figures per session: how many sessions the calls of a range belong to, +//! the quantiles of their calls, tokens, cost and duration, and the costliest +//! of them. +//! +//! A session's figures add up only its calls in the range and kept by the +//! selector, so a session that began before the range counts from its first +//! call inside it. Quantiles are nearest-rank values: the value at rank +//! `ceil(p × n)` of the `n` sessions sorted ascending, so each is a figure a +//! real session has. + +use std::collections::HashMap; + +use serde::Serialize; + +use super::{price_call, CostBasis, CostTotal, TokenTotals}; +use crate::pricing::PriceTable; +use crate::store::CallEntry; + +/// Most sessions [`SessionFigures`] lists as the costliest. +pub const MAX_COSTLIEST_SESSIONS: usize = 50; + +/// Nearest-rank quantiles of one figure over the sessions that have it. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Quantiles { + /// Sessions the quantiles cover. + pub sessions: u64, + /// The mean over those sessions. + pub mean: f64, + /// The median. + pub p50: f64, + /// The 90th percentile. + pub p90: f64, + /// The 99th percentile. + pub p99: f64, + /// The largest value. + pub max: f64, +} + +impl Quantiles { + /// The quantiles of `values`, or `None` when there are none. + fn of(values: &mut [f64]) -> Option { + if values.is_empty() { + return None; + } + values.sort_by(f64::total_cmp); + let count = values.len(); + // Nearest rank: the smallest value with at least `p` of the values at + // or below it. Computed in integers so 0.9 × 10 is rank 9, not 10. + let at = |percent: usize| values[(percent * count).div_ceil(100).max(1) - 1]; + Some(Self { + sessions: count as u64, + mean: values.iter().sum::() / count as f64, + p50: at(50), + p90: at(90), + p99: at(99), + max: values[count - 1], + }) + } +} + +/// One session's calls in the range, added up. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionTotals { + /// The agent that ran the session. + pub agent: String, + /// The session, in the agent's own ID format. + #[serde(rename = "sessionID")] + pub session_id: String, + /// The session's working directory, when known. + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// Calls of the session in the range. + pub calls: u64, + /// Their token totals. + pub tokens: TokenTotals, + /// What they would cost at API prices, when a price table was given. + #[serde(skip_serializing_if = "Option::is_none")] + pub cost: Option, + /// The start of the first call, in Unix milliseconds. + pub first_started_at_ms: i64, + /// The end of the last call: its start plus its duration, or its start + /// when it reports no duration. + pub last_ended_at_ms: i64, +} + +impl SessionTotals { + fn all_tokens(&self) -> u64 { + let tokens = &self.tokens; + [ + tokens.input, + tokens.output, + tokens.cache_read, + tokens.cache_write_5m, + tokens.cache_write_1h, + ] + .into_iter() + .fold(0, u64::saturating_add) + } +} + +/// The figures per session of a range. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionFigures { + /// Sessions with at least one call in the range. + pub count: u64, + /// Calls per session. + #[serde(skip_serializing_if = "Option::is_none")] + pub calls: Option, + /// Tokens per session: input, output, cache reads and cache writes. + #[serde(skip_serializing_if = "Option::is_none")] + pub tokens: Option, + /// Tokens per session without the prompt cache: input and output. + #[serde(skip_serializing_if = "Option::is_none")] + pub uncached_tokens: Option, + /// US dollars per session at API prices, over the sessions with at least + /// one priced call; their unpriced calls add nothing. + #[serde(rename = "costUSD", skip_serializing_if = "Option::is_none")] + pub cost_usd: Option, + /// Milliseconds from the first call's start to the last call's end. + #[serde(skip_serializing_if = "Option::is_none")] + pub duration_ms: Option, + /// The costliest sessions, most expensive first, at most the number + /// asked for; sessions without a priced call are not listed. + pub costliest: Vec, +} + +/// Adds calls into per-session totals one at a time. It keeps one total per +/// session of the range, never the calls. +#[derive(Debug)] +pub struct SessionTally<'a> { + prices: Option<&'a PriceTable>, + sessions: HashMap<(String, String), SessionTotals>, +} + +impl<'a> SessionTally<'a> { + /// A tally that prices calls with `prices` when given. + pub fn new(prices: Option<&'a PriceTable>) -> Self { + Self { + prices, + sessions: HashMap::new(), + } + } + + /// Adds a call to its session. + pub fn add(&mut self, entry: &CallEntry) { + let call = &entry.call; + let ended = call + .duration_ms + .and_then(|duration| i64::try_from(duration).ok()) + .map_or(call.started_at_ms, |duration| { + call.started_at_ms.saturating_add(duration) + }); + let prices = self.prices; + let totals = self + .sessions + .entry((entry.agent.clone(), call.session_id.clone())) + .or_insert_with(|| SessionTotals { + agent: entry.agent.clone(), + session_id: call.session_id.clone(), + cwd: entry.cwd.clone(), + calls: 0, + tokens: TokenTotals::default(), + cost: prices.map(|_| CostTotal { + usd: 0.0, + basis: CostBasis::ApiPriceEquivalent, + priced_calls: 0, + unpriced_calls: 0, + approximate_calls: 0, + }), + first_started_at_ms: call.started_at_ms, + last_ended_at_ms: ended, + }); + totals.calls += 1; + totals.first_started_at_ms = totals.first_started_at_ms.min(call.started_at_ms); + totals.last_ended_at_ms = totals.last_ended_at_ms.max(ended); + let tokens = &call.tokens; + for (total, count) in [ + (&mut totals.tokens.input, tokens.input), + (&mut totals.tokens.output, tokens.output), + (&mut totals.tokens.cache_read, tokens.cache_read), + (&mut totals.tokens.cache_write_5m, tokens.cache_write_5m), + (&mut totals.tokens.cache_write_1h, tokens.cache_write_1h), + (&mut totals.tokens.reasoning, tokens.reasoning), + ] { + *total = total.saturating_add(count.unwrap_or(0)); + } + if let (Some(prices), Some(cost)) = (prices, totals.cost.as_mut()) { + match price_call(prices, entry) { + Some(priced) => { + cost.usd += priced.usd; + cost.priced_calls += 1; + cost.approximate_calls += u64::from(priced.approximate); + } + None => cost.unpriced_calls += 1, + } + } + } + + /// The figures, with at most `costliest` (capped at + /// [`MAX_COSTLIEST_SESSIONS`]) of the costliest sessions. + pub fn finish(self, costliest: usize) -> SessionFigures { + let sessions: Vec = self.sessions.into_values().collect(); + let figure = |value: &dyn Fn(&SessionTotals) -> Option| { + let mut values: Vec = sessions.iter().filter_map(value).collect(); + Quantiles::of(&mut values) + }; + let priced = |totals: &SessionTotals| { + totals + .cost + .filter(|cost| cost.priced_calls > 0) + .map(|cost| cost.usd) + }; + let calls = figure(&|totals| Some(totals.calls as f64)); + let tokens = figure(&|totals| Some(totals.all_tokens() as f64)); + let uncached_tokens = + figure(&|totals| Some(totals.tokens.input.saturating_add(totals.tokens.output) as f64)); + let cost_usd = figure(&priced); + let duration_ms = figure(&|totals| { + Some( + totals + .last_ended_at_ms + .saturating_sub(totals.first_started_at_ms) as f64, + ) + }); + let mut ranked: Vec = sessions + .iter() + .filter(|totals| priced(totals).is_some()) + .cloned() + .collect(); + // Ties go by agent and session ID, so the list is the same on every + // read of the same records. + ranked.sort_by(|left, right| { + priced(right) + .unwrap_or(0.0) + .total_cmp(&priced(left).unwrap_or(0.0)) + .then_with(|| left.agent.cmp(&right.agent)) + .then_with(|| left.session_id.cmp(&right.session_id)) + }); + ranked.truncate(costliest.min(MAX_COSTLIEST_SESSIONS)); + SessionFigures { + count: sessions.len() as u64, + calls, + tokens, + uncached_tokens, + cost_usd, + duration_ms, + costliest: ranked, + } + } +} diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs index f58eade5..9a68b012 100644 --- a/rust/crates/agent-sessions/src/store.rs +++ b/rust/crates/agent-sessions/src/store.rs @@ -30,16 +30,21 @@ use crate::text; /// Version of the database layout. A cache of another version is deleted and /// rebuilt from the session files, so it is never migrated. Version 4 added /// the `threads` table; an older Core on the same machine keeps its own file, -/// so it never leaves thread rows behind for file IDs it reuses. -pub const SCHEMA_VERSION: u32 = 4; +/// so it never leaves thread rows behind for file IDs it reuses. Version 5 +/// added each call's account, purpose, cancellation and tool uses, and the +/// daily usage rows that count them. +pub const SCHEMA_VERSION: u32 = 5; /// Longest identifier, in bytes: agent, session, call, thread and request IDs. pub const MAX_ID_BYTES: usize = 256; /// Longest label, in bytes: model, provider, effort, context window, error -/// category, agent version and thread kind. +/// category, account, purpose, agent version and thread kind. pub const MAX_LABEL_BYTES: usize = 256; +/// Most tool uses one call may report. +pub const MAX_TOOL_USES: u64 = 1_000_000; + /// Longest working directory, in bytes. const MAX_CWD_BYTES: usize = 4096; @@ -141,6 +146,10 @@ CREATE TABLE calls ( compaction INTEGER NOT NULL, request_id TEXT, error_category TEXT, + account TEXT, + purpose TEXT, + cancelled INTEGER NOT NULL, + tool_uses INTEGER, range_start INTEGER NOT NULL, range_end INTEGER NOT NULL, PRIMARY KEY (file_id, call_key) @@ -322,6 +331,12 @@ pub struct CallEntry { pub cwd: Option, /// The call. pub call: CallRecord, + /// The cache's reading of `path` the call's range belongs to, as + /// [`SessionEntry::generation`] describes it. + pub generation: i64, + /// How many bytes of `path` the cache has read, as + /// [`SessionEntry::read_bytes`] describes it. + pub read_bytes: u64, } /// Which sessions [`SessionStore::sessions`] lists. @@ -702,7 +717,9 @@ impl SessionStore { r.input_tokens, r.output_tokens, r.cache_read_tokens, r.cache_write_5m_tokens, r.cache_write_1h_tokens, r.reasoning_tokens, r.first_token_ms, r.duration_ms, r.compaction, r.request_id, - r.error_category, r.range_start, r.range_end + r.error_category, r.range_start, r.range_end, + r.account, r.purpose, r.cancelled, r.tool_uses, + f.generation, f.cursor_offset FROM selected_calls w JOIN calls r ON r.file_id = w.file_id AND r.call_key = w.call_key JOIN files f ON f.id = w.file_id @@ -737,6 +754,55 @@ impl SessionStore { Ok(visited) } + /// Visits the time of each message `filter` selects by agent, session + /// and time, in no particular order, and returns how many it visited. A + /// message is an indexed span of a session's own file: the file + /// [`sessions`](Self::sessions) lists the session from, so a session + /// copied into another file, or a subagent's file, is not counted twice. + /// Spans without a time are not visited. + pub fn for_each_message_time( + &self, + filter: &CallFilter, + mut visit: impl FnMut(i64), + ) -> Result { + const SQL: &str = " + WITH chosen AS ( + SELECT s.file_id, s.session_id, + ROW_NUMBER() OVER ( + PARTITION BY f.agent, s.session_id + ORDER BY s.described DESC, f.path + ) AS copy_rank + 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 (?2 IS NULL OR s.session_id = ?2) + ) + SELECT sp.at_ms + FROM chosen c + JOIN spans sp ON sp.file_id = c.file_id AND sp.session_id = c.session_id + WHERE c.copy_rank = 1 + AND sp.at_ms IS NOT NULL + AND sp.at_ms >= COALESCE(?3, -9223372036854775808) + AND (?4 IS NULL OR sp.at_ms < ?4)"; + let failed = |error| sql_error("Could not count agent messages", error); + let mut statement = self.connection.prepare_cached(SQL).map_err(failed)?; + let mut rows = statement + .query(params![ + agents_json(&filter.agents)?, + filter.session_id, + filter.since_ms, + filter.until_ms + ]) + .map_err(failed)?; + let mut visited = 0; + while let Some(row) = rows.next().map_err(failed)? { + cancellation::check()?; + visit(row.get(0).map_err(failed)?); + visited += 1; + } + Ok(visited) + } + /// Lists a page of sessions in the filter's order. pub fn sessions(&self, filter: &SessionFilter) -> Result, CoreError> { const SQL: &str = concat!( @@ -1514,9 +1580,9 @@ fn write_chunk<'a>( input_tokens, output_tokens, cache_read_tokens, cache_write_5m_tokens, cache_write_1h_tokens, reasoning_tokens, first_token_ms, duration_ms, compaction, request_id, error_category, - range_start, range_end) + range_start, range_end, account, purpose, cancelled, tool_uses) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, - ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23)", + ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27)", ) .map_err(write)?; for record in &output.calls { @@ -1547,7 +1613,11 @@ fn write_chunk<'a>( record.request_id, record.error_category, record.range.start, - record.range.end + record.range.end, + record.account, + record.purpose, + record.cancelled, + record.tool_uses ]) .map_err(write)?; report.calls += 1; @@ -1682,9 +1752,19 @@ fn validate(output: ScanOutput, start: u64, end: u64) -> Result MAX_TOOL_USES) { + return Err(invalid_output("calls[].toolUses is out of range")); + } check_tokens(&call.tokens)?; if call.first_token_ms.is_some_and(too_large) || call.duration_ms.is_some_and(too_large) { return Err(invalid_output("calls[] has a time out of range")); @@ -1860,11 +1940,17 @@ fn call_entry(row: &Row<'_>) -> rusqlite::Result { compaction: row.get(20)?, request_id: row.get(21)?, error_category: row.get(22)?, + account: row.get(25)?, + purpose: row.get(26)?, + cancelled: row.get(27)?, + tool_uses: row.get(28)?, range: ByteRange { start: row.get(23)?, end: row.get(24)?, }, }, + generation: row.get(29)?, + read_bytes: row.get(30)?, }) } @@ -1938,6 +2024,7 @@ mod transaction_tests { today_ms: 86_400_000, initial_offset: 0, offsets: vec![], + speeds: false, }, ) .unwrap(); diff --git a/rust/crates/agent-sessions/src/tests/mod.rs b/rust/crates/agent-sessions/src/tests/mod.rs index c2e02fb7..13f9bef4 100644 --- a/rust/crates/agent-sessions/src/tests/mod.rs +++ b/rust/crates/agent-sessions/src/tests/mod.rs @@ -6,6 +6,7 @@ mod pricing; mod stats; mod store; mod text; +mod usage; use std::fs::{self, OpenOptions}; use std::io::Write; @@ -137,6 +138,10 @@ impl SessionParser for LinesParser { compaction: false, request_id: None, error_category: text("error"), + account: text("account"), + purpose: text("purpose"), + cancelled: value.get("cancelled").and_then(Value::as_bool) == Some(true), + tool_uses: number("toolUses"), range: match value.get("badRange") { Some(_) => ByteRange { start: range.end + 10, diff --git a/rust/crates/agent-sessions/src/tests/stats.rs b/rust/crates/agent-sessions/src/tests/stats.rs index 239cb635..cf31d330 100644 --- a/rust/crates/agent-sessions/src/tests/stats.rs +++ b/rust/crates/agent-sessions/src/tests/stats.rs @@ -29,6 +29,10 @@ fn record(key: &str, at: i64) -> CallRecord { compaction: false, request_id: None, error_category: None, + account: None, + purpose: None, + cancelled: false, + tool_uses: None, range: ByteRange { start: 0, end: 1 }, } } @@ -39,6 +43,8 @@ fn entry(call: CallRecord) -> CallEntry { path: "/sessions/a.jsonl".to_string(), cwd: Some("/w".to_string()), call, + generation: 1, + read_bytes: 1, } } diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs index a3a66ff8..c55f245d 100644 --- a/rust/crates/agent-sessions/src/tests/store.rs +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -675,15 +675,17 @@ fn a_rebuild_with_other_chunks_gives_the_same_records() { let mut whole = SessionStore::open(&dir.path().join("whole")).expect("open"); sync_as(&mut whole, AGENT, &files); - assert_eq!( - calls(&incremental, &CallFilter::default()), - calls(&whole, &CallFilter::default()) - ); + // Each cache reads a file under its own generation; the records are the same. + let same_reading = |store: &SessionStore| { + let mut entries = calls(store, &CallFilter::default()); + entries.iter_mut().for_each(|entry| entry.generation = 0); + entries + }; + assert_eq!(same_reading(&incremental), same_reading(&whole)); assert_eq!( keys(&calls(&whole, &CallFilter::default())), ["c1", "c2", "c3", "c4"] ); - // Each cache reads a file under its own generation; the records are the same. let records = |store: &SessionStore| { let mut entries = sessions(store, every_session()); entries.iter_mut().for_each(|entry| entry.generation = 0); @@ -1217,6 +1219,7 @@ fn daily_overview_tracks_replaced_and_forgotten_copies() { today_ms: 5 * DAY, initial_offset: 0, offsets: vec![], + speeds: false, }; let filter = CallFilter { agents: vec![AGENT.into()], @@ -1326,6 +1329,7 @@ fn warm_overview_answers_from_saved_days_and_busy_writer_keeps_precise_results() today_ms: 3 * DAY, initial_offset: 0, offsets: vec![], + speeds: false, }; let expected = |filter: &CallFilter| { let mut sums = Summarizer::new(GroupBy::All, None).detailed(); @@ -1475,6 +1479,7 @@ fn overview_reuses_only_days_with_identical_calendar_bounds() { today_ms: 4 * DAY - i64::from(offset) * 1000, initial_offset: offset, offsets: vec![], + speeds: false, }; let answer = f .store diff --git a/rust/crates/agent-sessions/src/tests/usage.rs b/rust/crates/agent-sessions/src/tests/usage.rs new file mode 100644 index 00000000..646bf501 --- /dev/null +++ b/rust/crates/agent-sessions/src/tests/usage.rs @@ -0,0 +1,685 @@ +//! What the cache keeps of each call's account, purpose, cancellation and +//! tool uses, the statistics over them, the prices the user sets, the +//! figures per session and the messages per day. + +use std::collections::HashMap; +use std::fs; + +use serde_json::{json, Value}; + +use super::{append, session_line, text_line, LinesParser, TempDir}; +use crate::pricing::{Price, PriceTable, Rates}; +use crate::stats::messages::MessageCounter; +use crate::stats::sessions::SessionTally; +use crate::stats::{rank_speed, CallSelector, GroupBy, GroupKey, OverviewQuery, Summarizer}; +use crate::store::{CallEntry, CallFilter, SessionStore}; + +const AGENT: &str = "test-agent"; +const DAY: i64 = 86_400_000; + +fn line(value: Value) -> String { + format!("{value}\n") +} + +/// A cache with one session file of the synthetic format, synced. +fn store_with(dir: &TempDir, lines: &str) -> SessionStore { + let sessions = dir.path().join("sessions"); + fs::create_dir_all(&sessions).expect("create the sessions directory"); + let file = sessions.join("a.jsonl"); + append(&file, lines); + let mut store = SessionStore::open(&dir.path().join("cache")).expect("open the cache"); + let report = store + .sync_agent(AGENT, &[file], &mut LinesParser::default()) + .expect("sync"); + assert_eq!(report.files_failed, 0, "{report:?}"); + store +} + +fn calls(store: &SessionStore) -> Vec { + let mut entries = Vec::new(); + store + .for_each_call(&CallFilter::default(), |entry| { + entries.push(entry); + Ok(()) + }) + .expect("query the calls"); + entries +} + +/// Two sessions with labelled calls: s1 has two `main` calls of account +/// `a@x`, one cancelled; s2 has a `title` call of account `b@x`. +fn labelled_lines() -> String { + session_line("s1", "/w", 0) + + &line( + json!({"type": "call", "key": "c1", "at": 1_000, "model": "m", + "input": 100, "output": 200, "durationMs": 4_000, "firstTokenMs": 1_000, + "account": "a@x", "purpose": "main", "toolUses": 3}), + ) + + &line( + json!({"type": "call", "key": "c2", "at": 10_000, "model": "m", + "input": 50, "output": 150, "durationMs": 2_000, "firstTokenMs": 500, + "account": "a@x", "purpose": "main", "cancelled": true}), + ) + + &session_line("s2", "/v", 20_000) + + &line( + json!({"type": "call", "key": "c3", "at": 21_000, "model": "n", + "input": 10, "output": 5, "account": "b@x", "purpose": "title", "toolUses": 0}), + ) +} + +#[test] +fn calls_keep_their_account_purpose_cancellation_and_tool_uses() { + let dir = TempDir::new("labels-kept"); + let store = store_with(&dir, &labelled_lines()); + let entries = calls(&store); + let fields: Vec<_> = entries + .iter() + .map(|entry| { + let call = &entry.call; + ( + call.key.as_str(), + call.account.as_deref(), + call.purpose.as_deref(), + call.cancelled, + call.tool_uses, + ) + }) + .collect(); + assert_eq!( + fields, + [ + ("c1", Some("a@x"), Some("main"), false, Some(3)), + ("c2", Some("a@x"), Some("main"), true, None), + ("c3", Some("b@x"), Some("title"), false, Some(0)), + ] + ); + // The location a viewer opens a call at comes with it. + assert!(entries.iter().all(|entry| entry.read_bytes > 0)); + // An absent cancellation is not serialized, so call rows keep their shape. + let serialized = serde_json::to_value(&entries[0].call).expect("serialize"); + assert!(serialized.get("cancelled").is_none()); + assert_eq!(serialized["toolUses"], 3); +} + +#[test] +fn a_call_that_breaks_the_label_rules_fails_its_file() { + for (case, call) in [ + ( + "cancelled and failed", + json!({"type": "call", "key": "c", "at": 1, "cancelled": true, "error": "overloaded"}), + ), + ( + "a sentence as an account", + json!({"type": "call", "key": "c", "at": 1, "account": "my work account"}), + ), + ( + "too many tool uses", + json!({"type": "call", "key": "c", "at": 1, "toolUses": 1_000_001}), + ), + ] { + let dir = TempDir::new("labels-refused"); + let sessions = dir.path().join("sessions"); + fs::create_dir_all(&sessions).expect("create the sessions directory"); + let file = sessions.join("a.jsonl"); + append(&file, &(session_line("s", "/w", 0) + &line(call))); + let mut store = SessionStore::open(&dir.path().join("cache")).expect("open the cache"); + let report = store + .sync_agent(AGENT, &[file], &mut LinesParser::default()) + .expect("sync"); + assert_eq!(report.files_failed, 1, "{case}"); + assert!(calls(&store).is_empty(), "{case}"); + } +} + +#[test] +fn summaries_count_cancellations_and_tool_uses_and_group_by_account_and_purpose() { + let dir = TempDir::new("labels-grouped"); + let store = store_with(&dir, &labelled_lines()); + let entries = calls(&store); + + let mut by_account = Summarizer::new(GroupBy::Account, None) + .split_by(GroupBy::Purpose) + .detailed(); + entries.iter().for_each(|entry| by_account.add(entry)); + let summaries = by_account.finish(); + let rows: Vec<_> = summaries + .iter() + .map(|summary| { + ( + summary.key.clone(), + summary.split.clone(), + summary.calls, + summary.cancelled_calls, + summary.failed_calls, + summary.tool_uses, + ) + }) + .collect(); + let account = |name: &str| GroupKey::Account { + account: Some(name.to_string()), + }; + let purpose = |name: &str| { + Some(GroupKey::Purpose { + purpose: Some(name.to_string()), + }) + }; + assert_eq!( + rows, + [ + (account("a@x"), purpose("main"), 2, 1, 0, 3), + (account("b@x"), purpose("title"), 1, 0, 0, 0), + ] + ); + // A cancelled call has no speed and no first-token time: only c1 counts. + let main = &summaries[0]; + assert_eq!(main.speed.as_ref().map(|speed| speed.calls), Some(1)); + assert_eq!( + main.first_token.as_ref().map(|first| first.average_ms), + Some(1_000.0) + ); + let serialized = serde_json::to_value(main).expect("serialize"); + assert_eq!( + serialized["key"], + json!({"kind": "account", "account": "a@x"}) + ); + assert_eq!(serialized["cancelledCalls"], 1); + assert_eq!(serialized["toolUses"], 3); +} + +#[test] +fn selectors_keep_accounts_purposes_and_cancellations_and_search_their_names() { + let dir = TempDir::new("labels-selected"); + let store = store_with(&dir, &labelled_lines()); + let entries = calls(&store); + let kept = |selector: CallSelector| -> Vec { + entries + .iter() + .filter(|entry| selector.keeps(entry)) + .map(|entry| entry.call.key.clone()) + .collect() + }; + assert_eq!( + kept(CallSelector { + accounts: vec!["b@x".into()], + ..CallSelector::default() + }), + ["c3"] + ); + assert_eq!( + kept(CallSelector { + purposes: vec!["main".into()], + cancelled: Some(false), + ..CallSelector::default() + }), + ["c1"] + ); + assert_eq!( + kept(CallSelector { + cancelled: Some(true), + ..CallSelector::default() + }), + ["c2"] + ); + // The empty name stands for calls that name none. + assert!(kept(CallSelector { + purposes: vec![String::new()], + ..CallSelector::default() + }) + .is_empty()); + assert_eq!(kept(CallSelector::default().with_search("TITLE")), ["c3"]); +} + +#[test] +fn the_overview_filters_and_splits_saved_days_by_the_new_labels_like_exact_reads() { + let dir = TempDir::new("labels-overview"); + let mut lines = session_line("s1", "/w", 0); + for (index, (account, purpose, cancelled)) in [ + ("a@x", "main", false), + ("a@x", "subagent", true), + ("b@x", "main", false), + ("b@x", "title", false), + ] + .into_iter() + .enumerate() + { + let at = (index as i64 % 2) * DAY + 1_000 + index as i64; + lines += &line(json!({"type": "call", "key": format!("c{index}"), "at": at, + "model": "m", "input": 100, "output": 300, "durationMs": 3_000, + "firstTokenMs": 500, "account": account, "purpose": purpose, + "cancelled": cancelled, "toolUses": index})); + } + let store = store_with(&dir, &lines); + let filter = CallFilter { + agents: vec![AGENT.into()], + ..CallFilter::default() + }; + let calendar = OverviewQuery { + today_ms: 5 * DAY, + initial_offset: 0, + offsets: vec![], + speeds: false, + }; + for (selector, split) in [ + (CallSelector::default(), GroupBy::Account), + ( + CallSelector { + accounts: vec!["a@x".into()], + ..CallSelector::default() + }, + GroupBy::Purpose, + ), + ( + CallSelector { + purposes: vec!["main".into()], + cancelled: Some(false), + ..CallSelector::default() + }, + GroupBy::Account, + ), + ] { + // The second read answers finished days from the saved rows. + for _ in 0..2 { + let overview = store + .usage_overview( + &filter, + &selector, + None, + GroupBy::Day { + utc_offset_seconds: 0, + }, + split, + &calendar, + ) + .expect("overview"); + let mut groups = Summarizer::new(split, None).detailed(); + let mut series = Summarizer::new( + GroupBy::Day { + utc_offset_seconds: 0, + }, + None, + ) + .split_by(split) + .detailed(); + for entry in calls(&store).iter().filter(|entry| selector.keeps(entry)) { + groups.add(entry); + series.add(entry); + } + assert_eq!(overview.groups, groups.finish()); + assert_eq!(overview.series, series.finish()); + } + } +} + +/// Sessions in `/work/atlas`, a sibling `/work/atlas-2`, a child +/// `/work/atlas/sub` and one that records no directory, each with a call on +/// day 0 and day 1 at its own speed. +fn directory_lines() -> String { + let mut lines = String::new(); + for (index, cwd) in [ + Some("/work/atlas"), + Some("/work/atlas-2"), + Some("/work/atlas/sub"), + None, + ] + .into_iter() + .enumerate() + { + let id = format!("s{index}"); + let start = index as i64 * 10_000; + lines += &match cwd { + Some(cwd) => session_line(&id, cwd, start), + None => line(json!({"type": "session", "id": id, "at": start})), + }; + for day in 0..2 { + let model = if index % 2 == 0 { "m" } else { "n" }; + lines += &line(json!({"type": "call", "key": format!("{id}-{day}"), + "at": day * DAY + start + 1_000, "model": model, "input": 100, + "output": 400 + index * 100 + day as usize * 50, "durationMs": 3_000 + day * 500, + "firstTokenMs": 500})); + } + } + lines +} + +#[test] +fn directory_filters_match_whole_directories_in_selectors_and_the_overview() { + let dir = TempDir::new("directory-filter"); + let store = store_with(&dir, &directory_lines()); + let entries = calls(&store); + let kept = |selector: &CallSelector| -> Vec { + entries + .iter() + .filter(|entry| selector.keeps(entry)) + .map(|entry| entry.call.key.clone()) + .collect() + }; + let only = |cwds: &[&str]| CallSelector { + cwds: cwds.iter().map(|cwd| cwd.to_string()).collect(), + ..CallSelector::default() + }; + // Neither the sibling that shares the prefix nor the child is kept. + assert_eq!(kept(&only(&["/work/atlas"])), ["s0-0", "s0-1"]); + assert_eq!( + kept(&only(&["/work/atlas", "/work/atlas-2"])), + ["s0-0", "s1-0", "s0-1", "s1-1"] + ); + // The empty name stands for sessions that record no directory. + assert_eq!(kept(&only(&[""])), ["s3-0", "s3-1"]); + assert!(!only(&["/work/atlas"]).is_open()); + // A search for the path finds the sibling too, which the filter leaves out. + assert_eq!( + kept(&CallSelector::default().with_search("/work/atlas")).len(), + 6 + ); + + let filter = CallFilter { + agents: vec![AGENT.into()], + ..CallFilter::default() + }; + let calendar = OverviewQuery { + today_ms: 5 * DAY, + initial_offset: 0, + offsets: vec![], + speeds: true, + }; + let day = GroupBy::Day { + utc_offset_seconds: 0, + }; + let selector = only(&["/work/atlas", ""]); + // Warm the saved days first, so the filtered reads cannot answer from them. + store + .usage_overview( + &filter, + &CallSelector::default(), + None, + day, + GroupBy::Model, + &calendar, + ) + .expect("warm the days"); + for _ in 0..2 { + let overview = store + .usage_overview(&filter, &selector, None, day, GroupBy::Model, &calendar) + .expect("overview"); + let mut groups = Summarizer::new(GroupBy::Model, None).detailed(); + for entry in entries.iter().filter(|entry| selector.keeps(entry)) { + groups.add(entry); + } + assert_eq!(overview.groups, groups.finish()); + assert_eq!(overview.summaries[0].calls, 4); + } +} + +#[test] +fn the_overview_ranks_speeds_like_a_full_read_when_asked() { + let dir = TempDir::new("overview-speeds"); + let store = store_with(&dir, &directory_lines()); + let entries = calls(&store); + let filter = CallFilter { + agents: vec![AGENT.into()], + ..CallFilter::default() + }; + let calendar = |speeds| OverviewQuery { + today_ms: 5 * DAY, + initial_offset: 0, + offsets: vec![], + speeds, + }; + let day = GroupBy::Day { + utc_offset_seconds: 0, + }; + let hour = GroupBy::Hour { anchor_ms: 0 }; + let unasked = store + .usage_overview( + &filter, + &CallSelector::default(), + None, + day, + GroupBy::Agent, + &calendar(false), + ) + .expect("overview"); + assert!(unasked.speeds.is_empty()); + for (selector, series) in [ + (CallSelector::default(), day), + (CallSelector::default(), hour), + (CallSelector::default().with_search("atlas-2"), day), + ( + CallSelector { + models: vec!["m".into()], + ..CallSelector::default() + }, + day, + ), + ] { + let expected = rank_speed( + entries + .iter() + .filter(|entry| selector.keeps(entry)) + .map(|entry| &entry.call), + ); + assert!(!expected.is_empty()); + // The second day read answers finished days from the saved rows. + for _ in 0..2 { + let overview = store + .usage_overview( + &filter, + &selector, + None, + series, + GroupBy::Agent, + &calendar(true), + ) + .expect("overview"); + assert_eq!(overview.speeds, expected); + } + } +} + +fn flat(input: f64, output: f64) -> Price { + Price { + base: Rates { + input, + output, + reasoning: None, + cache_read: None, + cache_write: None, + }, + tiers: Vec::new(), + } +} + +#[test] +fn a_price_the_user_sets_applies_to_its_agents_calls_before_the_table() { + let mut table = PriceTable::from_models_dev( + br#"{"vendor":{"models":{"m":{"cost":{"input":1,"output":2}}}}}"#, + ) + .expect("read the table"); + assert!(!table.has_overrides()); + table.set_overrides(HashMap::from([( + AGENT.to_string(), + HashMap::from([ + ("m".to_string(), flat(10.0, 20.0)), + ("n".to_string(), flat(1.0, 1.0)), + ]), + )])); + assert!(table.has_overrides()); + assert_eq!(table.lookup_for(AGENT, None, "m"), Some(&flat(10.0, 20.0))); + // Another agent's call of the same model keeps the table's price, and a + // model the table lacks is priced only for the agent the user set it for. + assert_eq!(table.lookup_for("other", None, "m"), Some(&flat(1.0, 2.0))); + assert_eq!(table.lookup_for("other", None, "n"), None); + // The user's prices are not counted as the table's. + assert_eq!(table.len(), 1); +} + +#[test] +fn saved_days_are_priced_again_when_the_user_changes_a_price() { + let dir = TempDir::new("labels-repriced"); + let store = store_with(&dir, &labelled_lines()); + let filter = CallFilter { + agents: vec![AGENT.into()], + ..CallFilter::default() + }; + let calendar = OverviewQuery { + today_ms: 5 * DAY, + initial_offset: 0, + offsets: vec![], + speeds: false, + }; + let mut table = PriceTable::default(); + let cost = |table: &PriceTable| { + store + .usage_overview( + &filter, + &CallSelector::default(), + Some(table), + GroupBy::Day { + utc_offset_seconds: 0, + }, + GroupBy::Model, + &calendar, + ) + .expect("overview") + .summaries[0] + .cost + .expect("a cost") + }; + assert_eq!(cost(&table).priced_calls, 0); + for rate in [1.0, 2.0] { + table.set_overrides(HashMap::from([( + AGENT.to_string(), + HashMap::from([("m".to_string(), flat(rate * 1e6, 0.0))]), + )])); + let total = cost(&table); + assert_eq!((total.priced_calls, total.unpriced_calls), (2, 1)); + // c1 and c2 read 150 input tokens. + assert!((total.usd - 150.0 * rate).abs() < 1e-9, "{total:?}"); + } +} + +#[test] +fn session_figures_give_nearest_rank_quantiles_and_the_costliest_sessions() { + let dir = TempDir::new("session-figures"); + let mut lines = String::new(); + // Ten sessions; session k has k calls of 100 input tokens each, the + // first at k seconds and lasting a second. + for session in 1..=10i64 { + lines += &session_line(&format!("s{session:02}"), "/w", session * 1_000); + for call in 0..session { + lines += &line(json!({"type": "call", "key": format!("s{session}c{call}"), + "at": session * 1_000 + call * 10, "model": if session == 10 { "free" } else { "m" }, + "input": 100, "output": 0, "cacheRead": 10, "durationMs": 1_000})); + } + } + let store = store_with(&dir, &lines); + let table = PriceTable::from_models_dev( + br#"{"vendor":{"models":{"m":{"cost":{"input":1000000,"output":0,"cache_read":0}}}}}"#, + ) + .expect("read the table"); + let mut tally = SessionTally::new(Some(&table)); + calls(&store).iter().for_each(|entry| tally.add(entry)); + let figures = tally.finish(3); + assert_eq!(figures.count, 10); + let calls_per_session = figures.calls.clone().expect("calls"); + // Ranks: p50 of 10 is the 5th, p90 the 9th, p99 the 10th. + assert_eq!( + ( + calls_per_session.p50, + calls_per_session.p90, + calls_per_session.p99, + calls_per_session.max, + calls_per_session.mean + ), + (5.0, 9.0, 10.0, 10.0, 5.5) + ); + // Tokens count cache reads; the uncached figure leaves them out. + assert_eq!(figures.tokens.clone().expect("tokens").p50, 550.0); + assert_eq!(figures.uncached_tokens.clone().expect("tokens").p50, 500.0); + // Session 10 calls an unpriced model, so nine sessions have a cost. + let cost = figures.cost_usd.clone().expect("cost"); + assert_eq!((cost.sessions, cost.max), (9, 900.0)); + // A session lasts from its first call's start to its last call's end. + assert_eq!(figures.duration_ms.clone().expect("duration").p50, 1_040.0); + let costliest: Vec<_> = figures + .costliest + .iter() + .map(|session| session.session_id.as_str()) + .collect(); + assert_eq!(costliest, ["s09", "s08", "s07"]); + let serialized = serde_json::to_value(&figures).expect("serialize"); + assert_eq!(serialized["costUSD"]["p90"], 900.0); + assert_eq!(serialized["costliest"][0]["sessionID"], "s09"); + + let empty = SessionTally::new(None).finish(10); + assert_eq!( + serde_json::to_value(&empty).expect("serialize"), + json!({"count": 0, "costliest": []}) + ); +} + +#[test] +fn messages_are_counted_per_day_of_each_sessions_own_file() { + let dir = TempDir::new("messages-by-day"); + let sessions = dir.path().join("sessions"); + fs::create_dir_all(&sessions).expect("create the sessions directory"); + let own = sessions.join("a.jsonl"); + let copy = sessions.join("b.jsonl"); + append( + &own, + &(session_line("s1", "/w", 0) + + &text_line(1_000, "first prompt") + + &text_line(DAY + 1_000, "next day") + + &text_line(DAY + 2_000, "and again")), + ); + // A file that only carries the session on, as a resumed copy does, is + // not the session's own file: its spans are not counted again. + append( + ©, + &(line(json!({"type": "use", "id": "s1"})) + &text_line(1_500, "copied prompt")), + ); + let mut store = SessionStore::open(&dir.path().join("cache")).expect("open the cache"); + store + .sync_agent(AGENT, &[own, copy], &mut LinesParser::default()) + .expect("sync"); + let calendar = OverviewQuery { + today_ms: 5 * DAY, + initial_offset: 0, + offsets: vec![], + speeds: false, + }; + let mut counter = MessageCounter::new( + GroupBy::Day { + utc_offset_seconds: 0, + }, + Some(&calendar), + ) + .expect("a day counter"); + let visited = store + .for_each_message_time(&CallFilter::default(), |at| counter.add(at)) + .expect("count"); + assert_eq!(visited, 3); + assert_eq!( + serde_json::to_value(counter.finish()).expect("serialize"), + json!([ + {"key": {"kind": "day", "date": "1970-01-01"}, "messages": 1}, + {"key": {"kind": "day", "date": "1970-01-02"}, "messages": 2}, + ]) + ); + // Hours, and a time range that ends before the second day. + let mut hours = MessageCounter::new(GroupBy::Hour { anchor_ms: 0 }, None).expect("hours"); + store + .for_each_message_time( + &CallFilter { + until_ms: Some(DAY), + ..CallFilter::default() + }, + |at| hours.add(at), + ) + .expect("count"); + assert_eq!( + serde_json::to_value(hours.finish()).expect("serialize"), + json!([{"key": {"kind": "hour", "startMs": 0}, "messages": 1}]) + ); + assert!(MessageCounter::new(GroupBy::Model, None).is_none()); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 45cc3444..4aaba03b 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -274,6 +274,25 @@ pub enum AgentsCommand { /// Lists a recorded session's subagents with their calls and usage /// (`agentSessions.subagents`). RecordsSubagents, + /// Reads the user's usage settings (`agentUsage.read`). + UsageRead, + /// Sets or removes the user's price of one model of an agent + /// (`agentUsage.setPrice`). + UsageSetPrice, + /// Sets or removes alert thresholds of an agent's rate-limit window + /// (`agentUsage.setAlert`). + UsageSetAlert, + /// Chooses the currency costs are shown in (`agentUsage.setCurrency`). + UsageSetCurrency, + /// Asks an agent's plugin for its current rate limits + /// (`agentUsage.refreshRateLimits`). + UsageRefreshRateLimits, + /// Asks an agent's plugin for exchange rates from US dollars + /// (`agentUsage.refreshExchangeRates`). + UsageRefreshExchangeRates, + /// Reads the kept readings of an agent's rate-limit windows + /// (`agentUsage.rateLimitHistory`). + UsageRateLimitHistory, /// Opens the agent library directory (`agentLibrary.configure`). LibraryConfigure, /// Reads the library and what each agent's configuration holds (`agentLibrary.read`). @@ -331,6 +350,13 @@ impl AgentsCommand { Self::RecordsResume => "agentSessions.resume", Self::RecordsExport => "agentSessions.export", Self::RecordsSubagents => "agentSessions.subagents", + Self::UsageRead => "agentUsage.read", + Self::UsageSetPrice => "agentUsage.setPrice", + Self::UsageSetAlert => "agentUsage.setAlert", + Self::UsageSetCurrency => "agentUsage.setCurrency", + Self::UsageRefreshRateLimits => "agentUsage.refreshRateLimits", + Self::UsageRefreshExchangeRates => "agentUsage.refreshExchangeRates", + Self::UsageRateLimitHistory => "agentUsage.rateLimitHistory", Self::LibraryConfigure => "agentLibrary.configure", Self::LibraryRead => "agentLibrary.read", Self::LibrarySave => "agentLibrary.save", @@ -1360,6 +1386,19 @@ impl CoreCommand { "agentSessions.resume" => Some(Self::Agents(AgentsCommand::RecordsResume)), "agentSessions.export" => Some(Self::Agents(AgentsCommand::RecordsExport)), "agentSessions.subagents" => Some(Self::Agents(AgentsCommand::RecordsSubagents)), + "agentUsage.read" => Some(Self::Agents(AgentsCommand::UsageRead)), + "agentUsage.setPrice" => Some(Self::Agents(AgentsCommand::UsageSetPrice)), + "agentUsage.setAlert" => Some(Self::Agents(AgentsCommand::UsageSetAlert)), + "agentUsage.setCurrency" => Some(Self::Agents(AgentsCommand::UsageSetCurrency)), + "agentUsage.refreshRateLimits" => { + Some(Self::Agents(AgentsCommand::UsageRefreshRateLimits)) + } + "agentUsage.refreshExchangeRates" => { + Some(Self::Agents(AgentsCommand::UsageRefreshExchangeRates)) + } + "agentUsage.rateLimitHistory" => { + Some(Self::Agents(AgentsCommand::UsageRateLimitHistory)) + } "agentLibrary.configure" => Some(Self::Agents(AgentsCommand::LibraryConfigure)), "agentLibrary.read" => Some(Self::Agents(AgentsCommand::LibraryRead)), "agentLibrary.save" => Some(Self::Agents(AgentsCommand::LibrarySave)), diff --git a/rust/crates/core/src/runtime/dispatcher/agents.rs b/rust/crates/core/src/runtime/dispatcher/agents.rs index d35ea35f..02c54e6a 100644 --- a/rust/crates/core/src/runtime/dispatcher/agents.rs +++ b/rust/crates/core/src/runtime/dispatcher/agents.rs @@ -1,5 +1,5 @@ -//! `agents.*`, `agentSessions.*`, `agentLibrary.*` and `agentProviders.*` commands, run by -//! `lithe-agent-runtime` (plan API-45). +//! `agents.*`, `agentSessions.*`, `agentUsage.*`, `agentLibrary.*` and +//! `agentProviders.*` commands, run by `lithe-agent-runtime` (plan API-45). use crate::protocol::{AgentsCommand, CoreResponse}; use serde_json::Value; diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 17195436..d1be28ea 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -380,6 +380,90 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.usage.alert_hit", + channel: "agent", + level: LogLevel::Info, + message: "A rate-limit window of an agent reached an alert threshold the user set", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "threshold", field_type: FieldType::Int, required: true, description: "Highest threshold reached, in percent of the window used, such as 80", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.usage.exchange_rates_updated", + channel: "agent", + level: LogLevel::Info, + message: "An agent plugin reported exchange rates on request", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "answered", field_type: FieldType::Int, required: true, description: "Currencies the plugin gave a rate for", reason: None }, + FieldMetadata { name: "asked", field_type: FieldType::Int, required: true, description: "Currencies the request named, after removing duplicates", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.usage.file_failed", + channel: "agent", + level: LogLevel::Warn, + message: "A usage file in the data directory could not be read or written", + fields: &[ + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Filesystem error category, such as PermissionDenied; never a path or file content", reason: None }, + FieldMetadata { name: "file", field_type: FieldType::Token, required: true, description: "Which file: settings (the user's prices, currency, rates and alerts) or history (the rate-limit history)", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Step that failed: read, write (the new file and putting it in place), cleanup (removing the new file after a failed write, which leaves it behind) or setAside (moving an unreadable settings file aside)", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.usage.plugin_failed", + channel: "agent", + level: LogLevel::Warn, + message: "An agent plugin could not answer a usage request", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "feature", field_type: FieldType::Token, required: true, description: "Usage feature asked for: rateLimits or exchangeRates", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.usage.price_changed", + channel: "agent", + level: LogLevel::Info, + message: "The user set or removed a model price for an agent", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "removed", field_type: FieldType::Bool, required: true, description: "True when the price was removed, false when it was set; the model and amounts are not logged", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.usage.rate_limits_updated", + channel: "agent", + level: LogLevel::Info, + message: "An agent plugin reported the agent's current rate limits on request", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "app.action.performed", channel: "app", diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index d97356ab..f9447ac1 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -26,6 +26,11 @@ //! applies a change, and only through a staged copy it checks first. //! `configuration.providers` names the backend functions that report and //! change the CLI's model, model providers and profiles in those files. +//! - `usage` says which usage features the plugin implements for the agent: +//! backend functions that read its current rate limits or exchange rates +//! when the user asks, and whether the user may set prices for its models +//! or alerts on its rate-limit windows. Core refuses a feature the plugin +//! leaves out. //! //! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-25-agent-native-cli-and-local-session-records.md @@ -144,6 +149,45 @@ pub struct AgentDeclaration { /// Where the CLI keeps the configuration Lithe's agent library manages. #[serde(default, skip_serializing_if = "Option::is_none")] pub configuration: Option, + /// The usage features the plugin implements for the agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub usage: Option, +} + +/// The usage features a plugin implements for one agent. A feature left out +/// is one the host shows as unsupported and Core refuses with +/// `agentUsage.notDeclared`. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UsageDeclaration { + /// Backend function that reads the agent's current rate-limit windows + /// when the user asks Lithe to refresh them. How it learns them is the + /// plugin's own business; Core makes no request for it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rate_limits: Option, + /// Backend function that answers exchange rates from US dollars, which + /// Lithe uses to show costs in another currency. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exchange_rates: Option, + /// Whether the user may set per-model prices for the agent's calls, + /// which Core keeps and uses before the price table. + #[serde(default, skip_serializing_if = "is_false")] + pub custom_prices: bool, + /// Whether the user may set alert thresholds on the agent's rate-limit + /// windows. + #[serde(default, skip_serializing_if = "is_false")] + pub rate_limit_alerts: bool, +} + +impl UsageDeclaration { + /// Whether the declaration names a backend function. + pub fn has_function(&self) -> bool { + self.rate_limits.is_some() || self.exchange_rates.is_some() + } +} + +fn is_false(value: &bool) -> bool { + !*value } /// The configuration of an agent that Lithe's agent library reads and @@ -375,14 +419,18 @@ pub struct DeclarationContext<'a> { impl AgentDeclaration { /// Whether Core starts the backend for this agent: a native session, a - /// session source or configuration files are served by backend functions. - /// A terminal or ACP agent alone runs only its tool. + /// session source, configuration files or a usage function are served by + /// backend functions. A terminal or ACP agent alone runs only its tool. pub fn needs_backend(&self) -> bool { self.native.is_some() || !self.session_sources.is_empty() || self.configuration.as_ref().is_some_and(|configuration| { configuration.read.is_some() || configuration.providers.is_some() }) + || self + .usage + .as_ref() + .is_some_and(UsageDeclaration::has_function) } } @@ -499,10 +547,13 @@ pub fn validate_declarations( if let Some(configuration) = &agent.configuration { check_configuration(configuration, &format!("{field}.configuration"))?; } + if let Some(usage) = &agent.usage { + check_usage(usage, &format!("{field}.usage"))?; + } if agent.needs_backend() && !context.has_backend { return Err(invalid( field, - "Native sessions, session sources and configuration files are served by the plugin backend.", + "Native sessions, session sources, configuration files and usage functions are served by the plugin backend.", )); } } @@ -732,6 +783,31 @@ fn check_configuration(configuration: &ConfigurationDeclaration, field: &str) -> Ok(()) } +/// Checks `usage`: at least one feature, and function IDs. +fn check_usage(usage: &UsageDeclaration, field: &str) -> Validation<()> { + if !usage.has_function() && !usage.custom_prices && !usage.rate_limit_alerts { + return Err(invalid( + field, + "A usage declaration declares at least one feature.", + )); + } + for (name, function) in [ + ("rateLimits", &usage.rate_limits), + ("exchangeRates", &usage.exchange_rates), + ] { + if function + .as_deref() + .is_some_and(|function| !is_function_id(function)) + { + return Err(invalid( + format!("{field}.{name}"), + "A usage function ID is dot-separated lowerCamelCase segments.", + )); + } + } + Ok(()) +} + fn check_providers( providers: &ProvidersDeclaration, configuration: &ConfigurationDeclaration, @@ -974,6 +1050,14 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { if let Some(icon) = &agent.icon { entry["icon"] = json!(icon); } + if let Some(usage) = &agent.usage { + entry["usage"] = json!({ + "rateLimits": usage.rate_limits.is_some(), + "exchangeRates": usage.exchange_rates.is_some(), + "customPrices": usage.custom_prices, + "rateLimitAlerts": usage.rate_limit_alerts, + }); + } if let Some(native) = agent.native.as_ref().filter(|n| !n.image_types.is_empty()) { entry["imageTypes"] = json!(native.image_types); } diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs index ad9e4b17..dd2177fa 100644 --- a/rust/crates/plugin-agents/src/tests.rs +++ b/rust/crates/plugin-agents/src/tests.rs @@ -588,3 +588,71 @@ fn resume_arguments_name_the_session_and_reach_the_review() { ); } } + +fn with_usage(usage: Value) -> Value { + let mut value = sample(); + value["usage"] = usage; + value +} + +#[test] +fn accepts_usage_and_reports_its_features() { + let mut agents = [agent(with_usage(json!({ + "rateLimits": "usage.rateLimits", + "customPrices": true + })))]; + check(&mut agents, true).expect("usage validates"); + let entry = catalog_entry("dev.lithe.test.agents", &agents[0]); + assert_eq!( + entry["usage"], + json!({ + "rateLimits": true, + "exchangeRates": false, + "customPrices": true, + "rateLimitAlerts": false + }) + ); + assert!(entry["usage"].get("function").is_none()); + assert!(catalog_entry("dev.lithe.test.agents", &agent(sample())) + .get("usage") + .is_none()); +} + +#[test] +fn usage_functions_need_a_backend_and_settings_do_not() { + let mut value = with_usage(json!({ "exchangeRates": "usage.exchangeRates" })); + value.as_object_mut().unwrap().remove("native"); + value.as_object_mut().unwrap().remove("sessionSources"); + assert!(agent(value.clone()).needs_backend()); + assert_eq!(rejected_field(value.clone(), false), "agents[0]"); + + value["usage"] = json!({ "customPrices": true, "rateLimitAlerts": true }); + assert!(!agent(value.clone()).needs_backend()); + check(&mut [agent(value)], false).expect("settings alone need no backend"); +} + +#[test] +fn usage_is_not_empty_and_names_functions_correctly() { + let cases: [(Value, &str); 4] = [ + (json!({}), "agents[0].usage"), + (json!({ "customPrices": false }), "agents[0].usage"), + ( + json!({ "rateLimits": "Usage.Rates" }), + "agents[0].usage.rateLimits", + ), + ( + json!({ "exchangeRates": "usage.exchange-rates" }), + "agents[0].usage.exchangeRates", + ), + ]; + for (usage, field) in cases { + assert_eq!( + rejected_field(with_usage(usage.clone()), true), + field, + "{usage}" + ); + } + assert!( + serde_json::from_value::(with_usage(json!({ "clear": true }))).is_err() + ); +} diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index ad5027f1..4e979110 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -296,6 +296,156 @@ "rate": 60, "owner": "Lithe" }, + { + "id": "agent.usage.file_failed", + "channel": "agent", + "level": "warn", + "message": "A usage file in the data directory could not be read or written", + "fields": { + "file": { + "type": "token", + "required": true, + "description": "Which file: settings (the user's prices, currency, rates and alerts) or history (the rate-limit history)" + }, + "stage": { + "type": "token", + "required": true, + "description": "Step that failed: read, write (the new file and putting it in place), cleanup (removing the new file after a failed write, which leaves it behind) or setAside (moving an unreadable settings file aside)" + }, + "error": { + "type": "error", + "required": true, + "description": "Filesystem error category, such as PermissionDenied; never a path or file content" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.usage.price_changed", + "channel": "agent", + "level": "info", + "message": "The user set or removed a model price for an agent", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "removed": { + "type": "bool", + "required": true, + "description": "True when the price was removed, false when it was set; the model and amounts are not logged" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.usage.rate_limits_updated", + "channel": "agent", + "level": "info", + "message": "An agent plugin reported the agent's current rate limits on request", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.usage.exchange_rates_updated", + "channel": "agent", + "level": "info", + "message": "An agent plugin reported exchange rates on request", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "asked": { + "type": "int", + "required": true, + "description": "Currencies the request named, after removing duplicates" + }, + "answered": { + "type": "int", + "required": true, + "description": "Currencies the plugin gave a rate for" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.usage.plugin_failed", + "channel": "agent", + "level": "warn", + "message": "An agent plugin could not answer a usage request", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "feature": { + "type": "token", + "required": true, + "description": "Usage feature asked for: rateLimits or exchangeRates" + } + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.usage.alert_hit", + "channel": "agent", + "level": "info", + "message": "A rate-limit window of an agent reached an alert threshold the user set", + "fields": { + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity that declares the agent" + }, + "agent": { + "type": "id", + "required": true, + "description": "Agent ID the plugin declares" + }, + "threshold": { + "type": "int", + "required": true, + "description": "Highest threshold reached, in percent of the window used, such as 80" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "agent.library.read_finished", "channel": "agent", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d429a6ec..5b6bcae5 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3741,6 +3741,7 @@ rejections. | `update` | `{arguments}`, nonempty: runs `tool` with these arguments to update the CLI, after the user confirms. A CLI without a self-update command declares none. | | `sessionSources` | Up to four [session sources](#session-records): where the CLI keeps its session files and the backend functions that parse them. | | `configuration` | Where the CLI keeps the instructions, skills, MCP servers and hooks the [agent library](#agent-configuration) manages, and the backend functions that read and edit its files. | +| `usage` | `{rateLimits?, exchangeRates?, customPrices?, rateLimitAlerts?}`: the [usage features](#usage-features) the plugin implements for the agent. `rateLimits` and `exchangeRates` are backend functions; `customPrices` and `rateLimitAlerts` are `true` when the user may set prices for the agent's models or alerts on its rate-limit windows. At least one is declared; a feature left out is one the host shows as unsupported. | - A plugin declares at most eight agents; the host shows them sorted by `id`. Each agent declares at least one of `native`, `acp` and `terminal`. @@ -3748,9 +3749,9 @@ rejections. each, without NUL. Arguments are fixed: they take no templates, except `${sessionID}` in `terminal.resumeArguments`. - A function ID is dot-separated lowerCamelCase segments, as in - [plugin functions](#plugin-functions). `native`, `sessionSources` and the - `read` and `edit` of `configuration` are served by the plugin backend, so - they need `backend`. + [plugin functions](#plugin-functions). `native`, `sessionSources`, the + `read` and `edit` of `configuration` and the functions of `usage` are + served by the plugin backend, so they need `backend`. - Every rejection is `plugin.manifest.invalid` with `field` naming the place, such as `agents[0].tool` or `agents[0].sessionSources[1].include[0]`. @@ -3780,15 +3781,16 @@ A missing permission is `plugin.permission.undeclared`; a permission no agent needs is `plugin.manifest.invalid` (`" is declared, but no agent needs it."`). `agents.usage.read` is the exception, since a plugin without agents of its own may read the totals. Every agent that declares -`native`, `sessionSources` or a `configuration` with `read` needs the -activation event `onAgent:`, and +`native`, `sessionSources`, a `configuration` with `read` or `providers`, or +a `usage` with `rateLimits` or `exchangeRates` needs the activation event +`onAgent:`, and the event is refused for an agent that needs no backend (`plugin.activation.invalid` either way): a terminal-only or ACP-only agent runs only its tool, and a plugin of such agents alone needs no `backend`. `onAgent:` is one of the ways a [backend](#backend-lifecycle-and-workspace-contexts) starts: the host starts the backend before it starts a native session of the agent, syncs its -records or reads its configuration files. +records, reads its configuration files or calls a usage function. ### Host commands @@ -3807,6 +3809,9 @@ environment variables the session and configuration roots read. An agent that declares `configuration` gives `configuration: {instructions, skills, files, editable}`, which of them it declares and whether it declares `edit`, and `mayConfigure`, whether its plugin is granted `agents.configuration`. +An agent that declares `usage` gives `usage: {rateLimits, exchangeRates, +customPrices, rateLimitAlerts}`, each `true` when the plugin implements the +feature, without the function IDs. | Command | Payload | Result | | --- | --- | --- | @@ -4190,9 +4195,13 @@ Lithe list, search and sum them without the CLI running: and syncs only the agents the user enabled. Core reads the files; the backend sees only the lines Core hands it. - The host opens the cache with `agentSessions.configure {cacheDirectory, - userHome, environment?, pricesFile?}`. `cacheDirectory` is a writable - platform cache directory, never in the package or the installation. The - answer reports `pricedModels` or `pricesError`. + userHome, environment?, pricesFile?, dataDirectory?}`. `cacheDirectory` is + a writable platform cache directory, never in the package or the + installation. `dataDirectory` is a directory of the platform's application + data, never the cache directory, for what the user sets and the rate-limit + history of the [usage features](#usage-features); without it Core keeps + neither, and one it cannot create refuses with `agentUsage.saveFailed`. + The answer reports `pricedModels` or `pricesError`. - `agentSessions.sync {pluginID, agentID}` reads the files that changed since the last sync and answers the counts, `truncatedSources` and `unreadableEntries`. Lines reach `scan` in chunks of at most 4 MiB; a line @@ -4203,13 +4212,15 @@ Lithe list, search and sum them without the CLI running: sessionID?, limit}` (at most 200), `agentSessions.read {agent, path, range}` and `agentSessions.stats {agents?, sessionID?, sinceMs?, untilMs?, groupBy, splitBy?, utcOffsetSeconds, hourAnchorMs?, models?, providers?, - failed?, search?, detail?}` serve the host's own views; `agent` is + accounts?, purposes?, cwds?, failed?, cancelled?, search?, detail?, + sessions?, messages?}` serve the host's own views; `agent` is `/`, and `stats` groups by `hour`, `day`, `agent`, `model`, - `provider`, `modelProvider`, `session`, `cwd` or `all` (every call as one + `provider`, `modelProvider`, `account`, `purpose`, `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 + - `splitBy` (`agent`, `model`, `provider`, `modelProvider`, `account` or + `purpose`) 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. @@ -4217,14 +4228,56 @@ Lithe list, search and sum them without the CLI running: - `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`. + calls. `accounts` and `purposes` keep only calls with a listed `account` + or `purpose`, the empty string standing for calls without one; + `cancelled` keeps only cancelled (`true`) or only other (`false`) calls. + `cwds` keeps only calls whose session's working directory is listed, + compared whole and byte for byte, so `/work/atlas` keeps neither + `/work/atlas-2` nor `/work/atlas/sub`; the empty string stands for + sessions that record no directory. A directory is matched as the `cwd` + key of a `cwd` group gives it. + `search` keeps calls whose model, requested model, provider, account, + purpose, agent, session ID or directory contains every + whitespace-separated word, ignoring case. All filters must hold, and they + apply to the summaries, to `speeds` and to `sessions`. At most 64 each of + models, providers, accounts, purposes and directories, each name and the + search text at most 256 bytes and each directory at most 4096; 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"}`. + key `{kind: "modelProvider", model?, provider?}`, an `account` key + `{kind: "account", account?}` and a `purpose` key `{kind: "purpose", + purpose?}`, each field absent for calls that do not name it; the `all` + key is `{kind: "all"}`. A `cwd` key also gives the folder `category` of + the session list's groups (below) when the directory is not a project + folder, so a host groups projects the same way in both views. + - `sessions: {top?}` adds `sessions`, figures per session over the calls + the filters keep: `count`, the sessions with at least one such call, and + for each of `calls`, `tokens` (input, output, cache reads and writes), + `uncachedTokens` (input and output), `costUSD` and `durationMs` the + quantiles `{sessions, mean, p50, p90, p99, max}` over the sessions that + have the figure. A quantile is the nearest rank: the value at rank + `ceil(p × n / 100)` of the `n` values sorted ascending, so each is a value + a real session has. A session's figures add up only its calls in the + range, so a session that began before `sinceMs` counts from its first + call inside it. `costUSD` covers the sessions with at least one priced + call, their unpriced calls adding nothing; `durationMs` runs from the + first call's start to the last call's end (its start plus `durationMs`, + or its start). `costliest` lists at most `top` (at most 50, default 0) + sessions by cost, most expensive first, ties by agent and session ID, + each `{agent, pluginID, agentID, sessionID, cwd?, calls, tokens, cost, + firstStartedAtMs, lastEndedAtMs}`. A quantile without a session is + absent. + - `messages: true` adds `messages`, `[{key, messages}]` per occupied hour + or day, oldest first, keyed like the summaries of that grouping and, with + `overview`, by its calendar. A message is a searchable span `scan` + reported with an `atMs`, in the file the session list gives the session + from, so a copied file or a subagent's file is not counted twice. The + agent, session and time filters apply; the call filters do not, since a + message is not a call. Another grouping refuses with + `agentSessions.invalidMessagesGroup`. + - With a currency the user chose, the answer also gives `currency: {code, + perUSD, atMs}`; every cost stays in US dollars, and the host converts + what it shows. See [Usage features](#usage-features). - `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 @@ -4233,7 +4286,8 @@ Lithe list, search and sum them without the CLI running: group qualifies. Without `detail` neither is present. - The desktop may request an overview in one read. With `groupBy: "day"` or `"hour"`, `splitBy` and `detail: true`, pass - `overview: {todayMs, initialOffset, offsets?: [{atMs, seconds}]}`. + `overview: {todayMs, initialOffset, offsets?: [{atMs, seconds}], + speeds?}`. `todayMs` is today's local midnight in Unix milliseconds. Offsets are seconds east of UTC (strictly between −86400 and 86400). Changes have strictly increasing UTC instants, at most 4096. Supply the offset in effect @@ -4242,7 +4296,11 @@ Lithe list, search and sum them without the CLI running: `series` (time buckets split by that same dimension), and `rateLimits`. All three arrays respect the same readable agents, filters and database snapshot. Empty arrays denote no matches. Hour alignment and exact - median rules are unchanged. This mode omits the separate speed ranking. + median rules are unchanged. The separate speed ranking is left out unless + `overview.speeds` is `true`; then the answer also has `speeds`, the models + ranked over the same calls by the rule of `speeds` without an overview, + so a host needs no second read for it. A directory filter or `search` + reads the calls of every day, since saved days keep no directory or text. Day buckets follow the overview calendar, including offset transitions. For hour buckets, `utcOffsetSeconds` supplies the alignment unless an explicit `hourAnchorMs` is given. Equivalent cost totals may differ in their last @@ -4258,20 +4316,32 @@ Lithe list, search and sum them without the CLI running: the filters and `detail` as unknown fields and the new group names as `agentSessions.invalidGroup`. - `agentSessions.calls {agents?, sessionID?, sinceMs?, untilMs?, model?, - models?, providers?, failed?, search?, offset?, limit}` serves the host's + models?, providers?, accounts?, purposes?, cwds?, failed?, cancelled?, + 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; + `models`, `providers`, `accounts`, `purposes`, `cwds`, `cancelled` and + `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, approximate}` at API prices when the model is priced, `cacheHitRate` when the call reports a cache count, and `speed {kind: measured|atLeast, tokensPerSecond}` when its timing allows. `path` and `call.range` are what - `agentSessions.read` takes to show the call's messages. Another page or + `agentSessions.read` takes to show the call's messages, and `generation` + and `size` (the bytes of `path` the cache has read) with `call.range.start` + as the cursor are what `agentSessions.page` takes to open the file round + the call. `context {tokens, window?, share?}`, present when the call + reports its input, tells how full the call's context was: `tokens` is the + prompt (input, cache reads and cache writes); `window`, the model's + `contextWindow` from the last [listed models](#listed-models) Core read + from the agent's plugin in this run, and `share`, `tokens / window`, are + absent when Core has no window for the model. A host draws a session's + context curve from its rows in call order. A price the user set for the + model applies before the table's. Another page or limit refuses with `agentSessions.invalidPage`. It was added within `agents` 0; an older Core refuses it as an unknown command. - A listed session gives `readBytes`, how many bytes of `path` the cache has @@ -4353,8 +4423,16 @@ state?, threads?}` and has 30 seconds. It answers: - `calls`: one per model call, `{key, sessionID, threadID?, startedAtMs, 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. A later scan of the file may + firstTokenMs?, durationMs?, compaction, requestID?, errorCategory?, + account?, purpose?, cancelled?, toolUses?, range: {start, end}}`, `key` + unique in the file. `account` (the login or organization that made the + call) and `purpose` (what it was for, such as the main conversation, a + subagent or a title) are labels as the agent names them, 1–256 visible + ASCII bytes without spaces, which Core groups and filters by and never + interprets. + `cancelled: true` marks a call stopped before it finished; it carries no + `errorCategory`. `toolUses`, at most 1000000, counts the tool calls the + response asked for. 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; @@ -4414,22 +4492,26 @@ Existing backends may ignore `messageIDs` and keep returning no IDs. This is a normal plugin function in all four official SDKs; no new handler or SDK version is required. Fixture: `fixtures/agents/record-read.json`. -A summary is `{key, calls, failedCalls, compactionCalls, tokens: {input, -output, cacheRead, cacheWrite5m, cacheWrite1h, reasoning}, cacheHitRate?, -cost?, firstStartedAtMs, lastStartedAtMs}`. `key` is `{kind: "day", date}`, +A summary is `{key, calls, failedCalls, compactionCalls, cancelledCalls, +toolUses, tokens: {input, output, cacheRead, cacheWrite5m, cacheWrite1h, +reasoning}, cacheHitRate?, cost?, firstStartedAtMs, lastStartedAtMs}`; +`toolUses` adds up the calls that report it. `key` is `{kind: "day", date}`, `{kind: "agent", agent}`, `{kind: "model", model?}`, `{kind: "session", 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. `stats` and `usage` also answer `speeds`, the models ranked fastest +the tokens would cost at the API prices of `pricesFile`, or at a price the +user set for the agent's model, not what the user 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 +and cancelled calls and speeds above 10000 tokens per second are left out, +and cancelled calls stay out of the first-token average. Rate limits are `{atMs, windows, plan?, pluginID, agentID}`; Core keeps the latest per agent -in `rate-limits.json` in the cache directory. +in `rate-limits.json` in the cache directory. A window with alert +thresholds the user set also gives `alert: {thresholds, reached?}`, +`reached` being the highest threshold its `usedPercent` reaches. #### Search snippets @@ -4609,6 +4691,90 @@ declares them only in a version that requires a host with them; it never asks `scan` for `threads`; and it refuses the commands as unknown. No operation here writes the agent's session files: Core only reads them. +#### Usage features + +The agent's `usage` declaration names what its plugin implements; Core +defines the shapes, checks what the plugin answers and keeps what the user +sets. A command for a feature the declaration leaves out refuses with +`agentUsage.notDeclared` (`not_supported`), which the host shows as "this +plugin does not support this feature". Core makes no network request for +any of them: how a plugin learns rate limits or exchange rates is its own +business. + +| Command | Payload | Result | +| --- | --- | --- | +| `agentUsage.read` | `{}` | `{currency?, exchangeRates, agents}` | +| `agentUsage.setPrice` | `{pluginID, agentID, model, price}` | `{}` | +| `agentUsage.setAlert` | `{pluginID, agentID, window, thresholds}` | `{}` | +| `agentUsage.setCurrency` | `{currency}` | `{}` | +| `agentUsage.refreshRateLimits` | `{pluginID, agentID}` | `{rateLimits}` | +| `agentUsage.refreshExchangeRates` | `{pluginID, agentID, currencies}` | `{exchangeRates}` | +| `agentUsage.rateLimitHistory` | `{pluginID, agentID, window?, sinceMs?, untilMs?}` | `{windows}` | + +- A command that names an agent names an installed one + (`agentUsage.unknownAgent`) the user enabled to run or to read its + sessions (`agentUsage.notGranted`). Every command needs the + `dataDirectory` of `agentSessions.configure` + (`agentUsage.notConfigured`), except `refreshRateLimits`, whose snapshot + goes where any other does. +- `setPrice`, `setAlert`, `setCurrency`, `refreshRateLimits` and + `refreshExchangeRates` run only for a request whose origin is the user + (`agentUsage.userActionRequired`). +- **Prices** (`customPrices`). `price` is `{input, output, cacheRead?, + cacheWrite?, reasoning?}` in US dollars per million tokens, each 0 to + 100000, or `null` to remove the model's price. `model` is the name calls + are counted under (the model that answered, or the one asked for), 1–256 + bytes; at most 256 models per agent (`agentUsage.invalidPrice`). A price + applies to the agent's calls of that model whatever provider served them, + before the table of `pricesFile`, and without a table too; costs, + summaries, the daily cache and call rows change at once. +- **Alerts** (`rateLimitAlerts`). `thresholds` is up to four percentages + from 1 to 100 for the window ID the agent reports, duplicates dropped; + `[]` removes them; at most eight windows per agent + (`agentUsage.invalidAlert`). The rate limits of `agentSessions.stats` and + `refreshRateLimits` mark each window with `alert`, and Core logs + `agent.usage.alert_hit` when a kept snapshot reaches a higher threshold + than the one before it. The host decides how to tell the user. +- **Rate limits** (`rateLimits`). Core calls the function with `{agentID}` + and waits 15 seconds. It answers `{windows, plan?}` as the `rateLimits` + session event does; anything else is `agentUsage.invalidAnswer`. Core + keeps it, timed now, as the agent's latest snapshot and answers the + agent's entry as `agentSessions.stats` gives it. +- **Exchange rates** (`exchangeRates`). `currencies` is 1–32 ISO 4217 codes + other than `USD` (`agentUsage.invalidCurrency`). Core calls the function + with `{agentID, base: "USD", currencies}` and waits 15 seconds; it answers + exactly `{rates}`, units of each currency per US dollar (above 0, at most + 10000000) for some of the asked currencies (`agentUsage.invalidAnswer` + otherwise). Core keeps the last rate of each currency with the time and + the agent that gave it, and answers every kept rate as `{currency, perUSD, + atMs, pluginID, agentID}`. `setCurrency {currency}` chooses the currency + costs are shown in: a code with a kept rate (`agentUsage.noExchangeRate` + without one), or `null` or `USD` for US dollars. +- **Rate-limit history.** Every snapshot Core keeps, from a session event, + a session file or `refreshRateLimits`, adds a point `{atMs, usedPercent, + resetsAtMs?}` per window. Within one cycle points are at least five + minutes apart: a closer reading replaces the last point's value and keeps + its time. A new cycle (the reset time moves by more than a minute, or the + used share drops) always starts a point, and a reading equal to the last + point adds none. Points older than 35 days and the oldest beyond 4000 per + window are dropped. `rateLimitHistory` answers `{windows: [{window, + label?, windowMinutes?, points}]}`, points oldest first from `sinceMs` + (inclusive) to `untilMs` (exclusive), only `window` when given + (`agentUsage.invalidRange` when the range ends before it starts). + `agentSessions.forget` removes the agent's history. +- `read` answers `currency?` (absent for US dollars), `exchangeRates` and + `agents: [{pluginID, agentID, prices: [{model, input, output, …}], + alerts: [{window, thresholds}]}]` for the installed agents with any. +- Files: `usage-settings.json` (prices, currency, rates, alerts) and + `rate-limit-history.json` in `dataDirectory`, owner-only, written whole + through a temporary file. A settings file Core cannot read is moved to + `usage-settings.unreadable.json` rather than overwritten. Prices and + alerts stay when an agent's records are forgotten. +- Refusals of calling the plugin: `agentUsage.backendUnavailable` (its + backend is not running) and `agentUsage.pluginFailed` (the function + failed or timed out); a settings file that cannot be written is + `agentUsage.saveFailed`, and nothing changes. + `agentSessions.*` refusals: `agentSessions.notConfigured`, `agentSessions.invalidDirectory`, `agentSessions.invalidEnvironment`, `agentSessions.unknownAgent` (always `entry_not_found`, for an `agent` key @@ -4619,7 +4785,8 @@ under the agent's roots), `agentSessions.discoveryFailed`, `agentSessions.invalidScan`, `agentSessions.readFailed`, `agentSessions.invalidRead`, `agentSessions.invalidGroup`, `agentSessions.invalidSplit`, `agentSessions.invalidOverviewGroup`, `agentSessions.invalidOverviewDetail`, -`agentSessions.invalidCalendar`, `agentSessions.unknownSession`, +`agentSessions.invalidCalendar`, `agentSessions.invalidMessagesGroup`, +`agentSessions.unknownSession`, `agentSessions.runNotGranted`, `agentSessions.toolNotFound`, `agentSessions.noResume`, `agentSessions.unsafeResume` and `agentSessions.invalidExport`. diff --git a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json index 7e98b547..cec3e1ef 100644 --- a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -100,6 +100,12 @@ "setProvider" ] } + }, + "usage": { + "rateLimits": "example.usage.rateLimits", + "exchangeRates": "example.usage.exchangeRates", + "customPrices": true, + "rateLimitAlerts": true } } ], diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index a163a05f..1888b080 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -1008,6 +1008,8 @@ {"name": "a configuration file is declared once", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": [{"id": "main", "roots": ["${userHome}/.example/a.json"]}, {"id": "main", "roots": ["${userHome}/.example/b.json"]}]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.files[1].id"}, {"name": "configuration files need a read function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/edit"}, {"op": "remove", "path": "/agents/0/configuration/read"}, {"op": "remove", "path": "/agents/0/configuration/providers"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.read"}, {"name": "providers are read from configuration files", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/edit"}, {"op": "remove", "path": "/agents/0/configuration/read"}, {"op": "set", "path": "/agents/0/configuration/files", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers"}, + {"name": "a usage declaration declares a feature", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/usage", "value": {"customPrices": false}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].usage"}, + {"name": "a usage function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/usage/rateLimits", "value": "Example Rates"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].usage.rateLimits"}, {"name": "a providers function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/read", "value": "Example Read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.read"}, {"name": "provider operations need an edit function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/providers/edit"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.edit"}, {"name": "a providers edit function declares its operations", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations"}, diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 327bed37..1a95ce81 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -13,6 +13,7 @@ {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"]}}}}, "then": {"properties": {"permissions": {"contains": {"const": "agents.configuration"}}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"], "properties": {"configuration": {"required": ["read"]}}}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["configuration"], "properties": {"configuration": {"required": ["providers"]}}}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, + {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["usage"], "properties": {"usage": {"anyOf": [{"required": ["rateLimits"]}, {"required": ["exchangeRates"]}]}}}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}}}}, {"if": {"required": ["permissions"], "properties": {"permissions": {"contains": {"const": "agents.usage.read"}}}}, "then": {"required": ["backend"]}}, {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, @@ -497,6 +498,38 @@ }, "configuration": { "$ref": "#/$defs/agentConfiguration" + }, + "usage": { + "$ref": "#/$defs/agentUsage" + } + } + }, + "agentUsage": { + "description": "The usage features the plugin implements for the agent. Core refuses a feature left out with agentUsage.notDeclared, and makes no network request for any of them.", + "type": "object", + "additionalProperties": false, + "anyOf": [ + {"required": ["rateLimits"]}, + {"required": ["exchangeRates"]}, + {"required": ["customPrices"], "properties": {"customPrices": {"const": true}}}, + {"required": ["rateLimitAlerts"], "properties": {"rateLimitAlerts": {"const": true}}} + ], + "properties": { + "rateLimits": { + "description": "Backend function that reads the agent's current rate limits when the user asks: {agentID} to {windows, plan?}.", + "$ref": "#/$defs/pluginFunctionID" + }, + "exchangeRates": { + "description": "Backend function that answers exchange rates from US dollars: {agentID, base: \"USD\", currencies} to {rates: {CODE: unitsPerUSD}}.", + "$ref": "#/$defs/pluginFunctionID" + }, + "customPrices": { + "description": "Whether the user may set per-model prices for the agent's calls, which Core keeps and uses before the price table.", + "type": "boolean" + }, + "rateLimitAlerts": { + "description": "Whether the user may set alert thresholds on the agent's rate-limit windows.", + "type": "boolean" } } }, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index fd00d60f..6ec67a81 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -61,7 +61,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-38 | 受管网络 | 部分完成 | `network/request`:可取消、有界 HTTP(S) | 下载文件、身份验证会话 | [工作流](../guides/plugin-workflows.md) | | API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | -| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充);插件可在 `providers` 快照里[列出模型](../contract/v1/README.md#listed-models)及其推理强度、速度档和上下文窗口,Core 检查选择在清单里、组合是插件允许的,用户在 Lithe 选择器里显示或隐藏模型的开关由 Core 记住(`agentProviders.showModels`),插件声明 `setModelMenu` 时 CLI 自己的模型菜单跟着变,开关和选择可整组读出、写回(`agentProviders.readModelSettings`、`agentProviders.applyModelSettings`)(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区、模型方案的保存与切换;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充);插件可在 `providers` 快照里[列出模型](../contract/v1/README.md#listed-models)及其推理强度、速度档和上下文窗口,Core 检查选择在清单里、组合是插件允许的,用户在 Lithe 选择器里显示或隐藏模型的开关由 Core 记住(`agentProviders.showModels`),插件声明 `setModelMenu` 时 CLI 自己的模型菜单跟着变,开关和选择可整组读出、写回(`agentProviders.readModelSettings`、`agentProviders.applyModelSettings`)(`agents` 0 内的补充);插件可在调用上报告账号 `account`、用途 `purpose`、是否取消 `cancelled` 和工具调用次数 `toolUses`,`agentSessions.stats` 可按账号和用途分组筛选,并给出按会话的分位数统计(p50、p90、p99)、最贵的会话和每小时或每天的消息数,`agentSessions.calls` 每行带上下文占用和定位用的 `generation`、`size`;Agent 声明 [`usage`](../contract/v1/README.md#usage-features) 说明插件实现了哪些用量功能:用户要求时读取额度(`agentUsage.refreshRateLimits`)、给出汇率(`agentUsage.refreshExchangeRates`、`agentUsage.setCurrency`)、用户自定义模型价格(`agentUsage.setPrice`)和额度提醒(`agentUsage.setAlert`),没声明的功能以 `agentUsage.notDeclared` 拒绝,Core 不为这些功能联网;Core 在平台数据目录里保存额度历史(`agentUsage.rateLimitHistory`)(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区、模型方案的保存与切换;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | ### 计划中的 API @@ -284,7 +284,7 @@ Status meanings: | API-38 | Managed network | Partial | `network/request`: bounded HTTP(S) with cancellation | File downloads and authentication sessions | [Workflows](../guides/plugin-workflows.md) | | API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | -| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0); the plugin may [list models](../contract/v1/README.md#listed-models) in the `providers` snapshot with their reasoning efforts, speeds, and context windows, Core checks that a pick is listed and a combination the plugin allows, Core keeps the switches with which the user shows or hides models in Lithe's pickers (`agentProviders.showModels`), the CLI's own model menu follows them when the plugin declares `setModelMenu`, and the switches and picks are read and written back as one group (`agentProviders.readModelSettings`, `agentProviders.applyModelSettings`) (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces, saving and switching model plans; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | +| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0); the plugin may [list models](../contract/v1/README.md#listed-models) in the `providers` snapshot with their reasoning efforts, speeds, and context windows, Core checks that a pick is listed and a combination the plugin allows, Core keeps the switches with which the user shows or hides models in Lithe's pickers (`agentProviders.showModels`), the CLI's own model menu follows them when the plugin declares `setModelMenu`, and the switches and picks are read and written back as one group (`agentProviders.readModelSettings`, `agentProviders.applyModelSettings`) (an addition within `agents` 0); a plugin may report on a call its `account`, `purpose`, whether it was `cancelled` and its `toolUses`, `agentSessions.stats` groups and filters by account and purpose and gives per-session quantiles (p50, p90, p99), the costliest sessions and messages per hour or day, and each `agentSessions.calls` row gives the call's context occupancy and the `generation` and `size` that locate it; an agent's [`usage`](../contract/v1/README.md#usage-features) declares the usage features its plugin implements: reading rate limits when the user asks (`agentUsage.refreshRateLimits`), exchange rates (`agentUsage.refreshExchangeRates`, `agentUsage.setCurrency`), user-set model prices (`agentUsage.setPrice`) and rate-limit alerts (`agentUsage.setAlert`); a feature left out is refused with `agentUsage.notDeclared`, and Core makes no network request for them; Core keeps the rate-limit history in the platform's data directory (`agentUsage.rateLimitHistory`) (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces, saving and switching model plans; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | ### Planned APIs diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 00e29abf..49839d71 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -67,7 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令;插件在 `providers` 快照里列出的模型(`models`、`efforts`、`speeds`、`effort`、`speed`、`modelMenu`、`targets.modelMenu`)、操作 `setEffort`、`setSpeed`、`setModelMenu` 和 `setModel` 的 `effort`、`speed`,以及命令 `agentProviders.showModels`、`agentProviders.readModelSettings`、`agentProviders.applyModelSettings` 是最后的补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令;插件在 `providers` 快照里列出的模型(`models`、`efforts`、`speeds`、`effort`、`speed`、`modelMenu`、`targets.modelMenu`)、操作 `setEffort`、`setSpeed`、`setModelMenu` 和 `setModel` 的 `effort`、`speed`,以及命令 `agentProviders.showModels`、`agentProviders.readModelSettings`、`agentProviders.applyModelSettings` 是其后的补充;Agent 的 `usage` 声明、`scan` 调用的 `account`、`purpose`、`cancelled`、`toolUses`、`agentSessions.configure` 的 `dataDirectory`、`agentSessions.stats` 的账号和用途分组筛选、`sessions` 与 `messages`、`agentSessions.calls` 的 `context`、`generation`、`size`,以及 `agentUsage.*` 命令是最后的补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -188,7 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands; the models a plugin lists in the `providers` snapshot (`models`, `efforts`, `speeds`, `effort`, `speed`, `modelMenu`, `targets.modelMenu`), the operations `setEffort`, `setSpeed` and `setModelMenu` with the `effort` and `speed` of `setModel`, and the commands `agentProviders.showModels`, `agentProviders.readModelSettings` and `agentProviders.applyModelSettings` were added last | ✅ | Pending host integration | [Agents](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands; the models a plugin lists in the `providers` snapshot (`models`, `efforts`, `speeds`, `effort`, `speed`, `modelMenu`, `targets.modelMenu`), the operations `setEffort`, `setSpeed` and `setModelMenu` with the `effort` and `speed` of `setModel`, and the commands `agentProviders.showModels`, `agentProviders.readModelSettings` and `agentProviders.applyModelSettings` were added after that; an agent's `usage` declaration, the `account`, `purpose`, `cancelled` and `toolUses` of `scan` calls, the `dataDirectory` of `agentSessions.configure`, account and purpose grouping and filters, `sessions` and `messages` in `agentSessions.stats`, `context`, `generation` and `size` in `agentSessions.calls`, and the `agentUsage.*` commands were added last | ✅ | Pending host integration | [Agents](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | | `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | ✅ | [Toolchains](domains/toolchains.md) | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 55dfd42d..fe56276d 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -8,13 +8,13 @@ | 项目 | 内容 | | --- | --- | -| 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`,每个插件最多 8 个 | -| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read`、`providers` 的 `configuration` 时还需要 `backend` 0。`configuration`、`agents.configuration`、`native.imageTypes`、提示附件、`configuration.providers` 和 `agentLibrary.read` 的筛选排序参数是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单、带 `attachments` 的 `agents.prompt` 和带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?, usage?}`,每个插件最多 8 个 | +| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources`、带 `read`、`providers` 的 `configuration` 或带函数的 `usage` 时还需要 `backend` 0。`usage` 声明、调用的 `account`、`purpose`、`cancelled`、`toolUses`、`agentUsage.*` 命令和用量统计的新参数也是 `agents` 0 内的补充。`configuration`、`agents.configuration`、`native.imageTypes`、提示附件、`configuration.providers` 和 `agentLibrary.read` 的筛选排序参数是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单、带 `attachments` 的 `agents.prompt` 和带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | API 编号 | API-45 | | 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.configuration`(有 `configuration`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | -| 激活事件 | 声明了 `native`、`sessionSources` 或带 `read`、`providers` 的 `configuration` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | +| 激活事件 | 声明了 `native`、`sessionSources`、带 `read`、`providers` 的 `configuration` 或带 `rateLimits`、`exchangeRates` 的 `usage` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | | 后端启动 | 只有终端形式的 Agent 不需要后端 | -| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有。`configuration` 的 `read`、`edit` 和 `providers` 的 `read`、`edit` 都是普通插件函数,任何 SDK 版本都能注册,见各 SDK 的 Agent configuration functions 一节 | +| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有。`configuration` 的 `read`、`edit` 和 `providers` 的 `read`、`edit` 都是普通插件函数,任何 SDK 版本都能注册,见各 SDK 的 Agent configuration functions 一节;`usage` 的 `rateLimits`、`exchangeRates` 同样是普通插件函数 | | 安装审查 | 每种运行形式列成一条 `agent` 程序,每个会话来源列成一条 `agentSessions` 程序,声明了 `configuration` 的 Agent 列成一条 `agentConfiguration` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录和文件会被读取或修改 | | Lithe 桌面端 | 接入中,尚未声明 `agents` | @@ -44,7 +44,9 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 - 用户逐个 Agent 同意后,Core 才读取 `sessionSources` 声明的目录:只读匹配 `include` 的普通文件,不跟随符号链接;后端的 `scan` 函数把新增的行变成记录,`read` 函数把记录的范围变成标题或消息。 - Core 缓存记录,负责列表、全文搜索和统计;缓存不存正文,可以删除重建。 - `lithe/host/agents/usage` 按小时、天、Agent 或模型汇总用户已开启记录的 Agent 的用量,并带上最近的额度窗口。它只给数字和模型名,不含对话正文、标题、会话 ID 或工作目录,适合做跨 Agent 的统计和额度面板。 -- `agentSessions.calls` 按时间倒序分页列出 `scan` 报告的每一次调用,带所属 Agent 和调用本身(模型、令牌数等),以及 Core 算出的费用、缓存命中率和速度,供用量页的请求列表和详情使用;不含正文。 +- `agentSessions.calls` 按时间倒序分页列出 `scan` 报告的每一次调用,带所属 Agent 和调用本身(模型、令牌数等),以及 Core 算出的费用、缓存命中率和速度,供用量页的请求列表和详情使用;不含正文。每行还带 `generation`、`size`,和 `call.range` 一起交给 `agentSessions.page` 就能定位到这次调用的消息;带 `context {tokens, window?, share?}` 说明这次调用的上下文占了多少:`tokens` 是提示的令牌数(输入、缓存读取和缓存写入),`window` 取自 Core 本次运行最近读到的插件模型列表里该模型的 `contextWindow`,没有就只给 `tokens`。按调用顺序画出来就是一个会话的上下文曲线。 +- 插件可以在调用上报告 `account`(发起调用的账号或组织)、`purpose`(调用的用途,比如主对话、子代理、生成标题)、`cancelled`(中途取消,取消不算失败)和 `toolUses`(响应要求的工具调用次数)。`account` 和 `purpose` 是插件自己的叫法,Core 原样分组、筛选,不解释取值。`agentSessions.stats` 和 `agentSessions.calls` 可以按 `accounts`、`purposes`、`cancelled` 筛选,也可以用 `cwds` 按工作目录整段精确筛选(`/work/atlas` 不会连带 `/work/atlas-2` 或子目录,空字符串代表没记录目录的会话),统计还可以按 `account`、`purpose` 分组或拆分;汇总多了 `cancelledCalls` 和 `toolUses`,取消的调用不计入速度和首字时间。按 `cwd` 分组时,每个目录带上和会话列表相同的 `category`,宿主可以用同一规则按项目归类。带 `overview` 的统计再加 `overview.speeds: true`,同一次读取就给出模型速度排名 `speeds`,规则和不带 `overview` 时相同。 +- `agentSessions.stats` 带 `sessions: {top?}` 时给出按会话的统计:会话数,以及每个会话的调用数、令牌数、费用和时长的平均值、p50、p90、p99 和最大值(最近秩法,每个分位数都是某个真实会话的值),和最贵的至多 50 个会话;带 `messages: true` 并按小时或天分组时给出每个时间段的消息数(插件报告的可搜索片段,复制的文件和子代理文件不重复计算)。按天分组、范围一年就能画 53 周的热力图。 - 在终端继续一条会话:插件在 `terminal.resumeArguments` 里声明恢复参数(如 `["--resume", "${sessionID}"]`),列表里的会话带 `resumable`。宿主调用 `agentSessions.resume` 拿到参数、工作目录和按 POSIX shell 或 PowerShell 转义好的可复制命令行,再用已有的终端形式运行;需要 `agents.run`。Core 只接受由字母、数字和 `.`、`_`、`:`、`-` 组成、不以 `-` 开头的会话 ID,会话文件里的 ID 不会变成 CLI 选项或 shell 语法。 - `agentSessions.export` 把一条会话导出为 Markdown:用户消息、回复、每次工具调用一行和时间,不含思考和工具输出;`maxBytes` 限制大小,`keep` 选择保留开头还是结尾。标题、表头和省略提示等文字全部由宿主在必填的 `labels` 里按界面语言传入,Core 不带默认文字。换一个 Agent 继续时,宿主导出(保留结尾),用 `agents.start` 启动另一个 Agent,再用第一条 `agents.prompt` 把内容发过去。 - 子代理明细:插件的 `scan` 在请求带 `threads: true` 时报告 `threads`(子代理的线程 ID、上级线程、类型、开始时间和任务所在的范围),调用用 `threadID` 指明所属线程。`agentSessions.subagents` 把两者合起来,给出每个子代理的调用和用量;插件什么都不报告时返回空列表。Core 不认识任何 Agent 的子代理格式。 @@ -53,6 +55,19 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 - 以上操作对 Agent 的会话文件都只读:Core 不删除、不移动、不改写它们。 - 连续浏览正文用 `agentSessions.page`,按返回的字节边界向前或向后读取。恢复会话前先同步并固定 `readBytes`,历史与新的会话事件分别保存,避免把旧提示误当成新轮次。Core 向普通 `read` 函数传 `messageIDs: true` 时,插件可返回稳定的消息 `id` 来识别同一消息的镜像;省略或为 `false` 时不得返回 `id`,保证旧 Core 仍接受原来的结果。没有稳定标识的格式省略 `id`,不按文本去重。四语 SDK 的普通 JSON 函数处理器直接支持这个可选参数。参见 [读取样例](../../contract/v1/fixtures/agents/record-read.json)。 +### 用量功能:额度刷新、自定义价格、货币汇率和额度提醒 + +Agent 的 `usage` 声明插件实现了哪些用量功能:`rateLimits`(用户要求时读取当前额度的后端函数)、`exchangeRates`(给出美元汇率的后端函数)、`customPrices`(用户可以给这个 Agent 的模型设价格)、`rateLimitAlerts`(用户可以给额度窗口设提醒)。没声明的功能,`agentUsage.*` 命令以 `agentUsage.notDeclared` 拒绝,宿主据此显示“该插件不支持这项功能”;目录里的 `usage` 只说每项是否支持,不给函数 ID。 + +- Core 定义形状、检查插件的回答、保存用户的设置;插件实现功能。Core 不为这些功能联网,插件怎么拿到额度和汇率是插件自己的事。 +- `agentUsage.refreshRateLimits` 调用插件的 `rateLimits` 函数,回答形状和会话事件里的 `rateLimits` 相同,Core 把它存为这个 Agent 最新的额度快照。 +- `agentUsage.setPrice` 保存用户给某个模型设的价格(美元/百万令牌),这个 Agent 的调用先用它,再用价格表;没有价格表时也生效。 +- `agentUsage.refreshExchangeRates` 向插件要若干货币对美元的汇率,`agentUsage.setCurrency` 选择显示的货币。费用始终以美元给出,选了货币时统计结果带 `currency {code, perUSD, atMs}`,由宿主换算显示。 +- `agentUsage.setAlert` 给一个额度窗口设至多 4 个百分比阈值。额度快照的窗口带 `alert {thresholds, reached?}`;新的快照达到更高阈值时 Core 记 `agent.usage.alert_hit` 日志,怎么提醒用户由宿主决定。 +- 额度历史:Core 保存的每个额度快照都按窗口记一个点,同一周期内至少间隔 5 分钟,新周期必定开新点,保留 35 天、每个窗口最多 4000 个点。`agentUsage.rateLimitHistory` 按窗口和时间范围查询。 +- 设置和历史是用户数据,存在宿主在 `agentSessions.configure` 里给的 `dataDirectory`(平台应用数据目录,不是缓存目录)里的 `usage-settings.json` 和 `rate-limit-history.json`,仅所有者可读写。读不出的设置文件改名为 `usage-settings.unreadable.json` 保留。`agentSessions.forget` 删除该 Agent 的额度历史,价格和提醒保留。 +- 改设置和向插件要数据只接受用户发起的请求(`agentUsage.userActionRequired`)。命令、字段和拒绝码见[契约的 Usage features](../../contract/v1/README.md#usage-features)。 + ### 资源库:指令、技能、MCP 服务器与 Hooks 宿主的 Agent 资源库把指令、技能、MCP 服务器和 Hooks 存一份,用户按 Agent 开关后,Core 写进每个 CLI 自己的配置。插件只声明 `configuration`: @@ -120,19 +135,20 @@ Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库 | [Host commands](../../contract/v1/README.md#host-commands) | 宿主调用的 `agents.*` 命令和事件队列 | | [Native sessions](../../contract/v1/README.md#native-sessions) | 启动流程、通知、宿主方法、会话事件 | | [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | +| [Usage features](../../contract/v1/README.md#usage-features) | `usage` 声明、`agentUsage.*` 命令、插件的额度和汇率函数、设置与额度历史的存放和拒绝码 | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储、命令和筛选、`read` 与 `edit` 函数、限制和拒绝码 | | [Instruction files](../../contract/v1/README.md#instruction-files) | 指令文件里 Lithe 的块、状态、保存后同步、并入资源库和已有数据的迁移 | | [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`、`agentProviders.*` 命令、快照与修改、隐私规则和拒绝码 | | [Backups and restore](../../contract/v1/README.md#backups-and-restore) | 资源库和供应商修改前的备份、`backup` 状态、`agentProviders.restore` 与拒绝码 | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | 日志只记 ID 和元数据,不读凭据文件 | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | 不运行 ACP 客户端,只在可信本地工作区运行 | -| [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*`、`agentSessions.*`、`agentLibrary.*` 与 `agentProviders.*` 命令(Rust Core API 文档) | +| [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*`、`agentSessions.*`、`agentUsage.*`、`agentLibrary.*` 与 `agentProviders.*` 命令(Rust Core API 文档) | ### 示例与用例 | 文件 | 内容 | | --- | --- | -| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | 一个带原生会话、终端形式、更新命令、一个会话来源和一份资源库配置声明的 Agent | +| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | 一个带原生会话、终端形式、更新命令、一个会话来源、一份资源库配置声明和全部用量功能的 Agent | | [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | 只有终端形式、不需要后端的 Agent | | [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | 以这两个清单为基础的拒绝用例 | | [`agents/native-session.json`](../../contract/v1/fixtures/agents/native-session.json) | 原生会话通知和每个会话的处理器依次收到的调用、启动或提示失败时报告的 `turnEnded`、`agents` 宿主方法的请求;四个 SDK 的测试都用它 | @@ -146,13 +162,13 @@ A plugin can connect an agent command-line tool that the user installed and sign | Item | Value | | --- | --- | -| Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`, at most 8 per plugin | -| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read` or `providers`. `configuration`, `agents.configuration`, `native.imageTypes`, prompt attachments, `configuration.providers` and the filter and sort parameters of `agentLibrary.read` were added within `agents` 0; a Core that does not know them refuses such a manifest, an `agents.prompt` with `attachments` and an `agentLibrary.read` with filters, and answers no `agentProviders.*` command. See [versions](../capabilities-and-versions.md#capability-versions-requires) | +| Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?, usage?}`, at most 8 per plugin | +| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources`, a `configuration` with `read` or `providers`, or a `usage` with a function. The `usage` declaration, the `account`, `purpose`, `cancelled` and `toolUses` of calls, the `agentUsage.*` commands and the new statistics parameters were also added within `agents` 0. `configuration`, `agents.configuration`, `native.imageTypes`, prompt attachments, `configuration.providers` and the filter and sort parameters of `agentLibrary.read` were added within `agents` 0; a Core that does not know them refuses such a manifest, an `agents.prompt` with `attachments` and an `agentLibrary.read` with filters, and answers no `agentProviders.*` command. See [versions](../capabilities-and-versions.md#capability-versions-requires) | | API IDs | API-45 | | Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.configuration` (with `configuration`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | -| Activation events | An agent that declares `native`, `sessionSources` or a `configuration` with `read` or `providers` needs `onAgent:`; other agents may not have one | +| Activation events | An agent that declares `native`, `sessionSources`, a `configuration` with `read` or `providers`, or a `usage` with `rateLimits` or `exchangeRates` needs `onAgent:`; other agents may not have one | | Backend launch | A terminal-only agent needs no backend | -| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not. The `read` and `edit` of `configuration` and of `providers` are ordinary plugin functions any SDK version registers; see each SDK's Agent configuration functions section | +| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not. The `read` and `edit` of `configuration` and of `providers` are ordinary plugin functions any SDK version registers; see each SDK's Agent configuration functions section. So are the `rateLimits` and `exchangeRates` of `usage` | | Install review | Each form is an `agent` program, each session source an `agentSessions` program, and each agent that declares `configuration` an `agentConfiguration` program, so the user sees how the CLI will run and which directories and files will be read or changed before installing | | Lithe desktop | Integration in progress; does not declare `agents` yet | @@ -201,7 +217,9 @@ and the [shared Core/desktop fixture](../../../../rust/fixtures/agents/turn-inte - Core reads the directories `sessionSources` declares only after the user consents for that agent. It reads only regular files that match `include` and does not follow symbolic links. The backend's `scan` function turns new lines into records, and its `read` function turns recorded ranges into titles or messages. - Core caches the records and answers lists, full-text search, and statistics. The cache stores no message text and can be deleted and rebuilt. - `lithe/host/agents/usage` sums the usage of the agents whose records the user enabled, by hour, day, agent, or model, with the latest quota windows. It carries only numbers and model names, never conversation text, titles, session IDs, or working directories, so it suits cross-agent statistics and quota panels. -- `agentSessions.calls` pages through every call `scan` reported, most recent first, with its agent and the call itself (model, tokens and so on), plus the cost, cache hit rate and speed Core derives, for the request list and details of a usage page. It carries no message text. +- `agentSessions.calls` pages through every call `scan` reported, most recent first, with its agent and the call itself (model, tokens and so on), plus the cost, cache hit rate and speed Core derives, for the request list and details of a usage page. It carries no message text. Each row also gives `generation` and `size`, which with `call.range` are what `agentSessions.page` takes to open the call's messages, and `context {tokens, window?, share?}`, how full the call's context was: `tokens` is the prompt (input, cache reads and cache writes), and `window` the model's `contextWindow` from the plugin's model list Core last read in this run; without one only `tokens` is given. In call order, the rows draw a session's context curve. +- A plugin may report on a call its `account` (the login or organization that made it), `purpose` (what it was for, such as the main conversation, a subagent or a title), `cancelled` (stopped before it finished, which is not a failure) and `toolUses` (the tool calls the response asked for). `account` and `purpose` are the plugin's own names; Core groups and filters by them as they are and never interprets them. `agentSessions.stats` and `agentSessions.calls` filter by `accounts`, `purposes` and `cancelled`, and by whole working directories with `cwds` (`/work/atlas` keeps neither `/work/atlas-2` nor a subdirectory; the empty string stands for sessions that record none), and statistics group or split by `account` and `purpose`; summaries add `cancelledCalls` and `toolUses`, and cancelled calls stay out of speeds and first-token times. Grouped by `cwd`, each directory carries the same `category` as the session list, so a host groups projects by one rule. An `overview` read with `overview.speeds: true` also answers `speeds`, the models ranked by the same rule as without `overview`, in the same read. +- `agentSessions.stats` with `sessions: {top?}` gives figures per session: the session count, the mean, p50, p90, p99 and maximum of each session's calls, tokens, cost and duration (nearest rank, so each quantile is a real session's value), and at most 50 of the costliest sessions; with `messages: true` and hour or day grouping it gives the messages per bucket (the searchable spans the plugin reported, a copied file or a subagent's file counted once). Grouped by day over a year, that draws a 53-week heatmap. - To continue a session in the terminal, a plugin declares `terminal.resumeArguments` (for example `["--resume", "${sessionID}"]`), and listed sessions carry `resumable`. The host calls `agentSessions.resume` for the arguments, the working directory and a command line to copy, quoted for a POSIX shell or PowerShell, then runs them through its existing terminal form; it needs `agents.run`. Core accepts only session IDs of letters, digits, `.`, `_`, `:` and `-` that do not start with `-`, so an ID from a session file never becomes a CLI option or shell syntax. - `agentSessions.export` exports a session as Markdown: the user's messages, the replies, one line per tool call and their times, without thoughts or tool output. `maxBytes` bounds it and `keep` keeps the start or the end. The host passes every word it shows, such as headings, header names and the omission line, in the required `labels`, in the interface language; Core has no default text. To continue with another agent, a host exports (keeping the end), starts the other agent with `agents.start` and sends the text in its first `agents.prompt`. - Subagents: when the request has `threads: true`, the plugin's `scan` reports `threads` (each subagent's thread ID, parent thread, kind, start and the range of its task), and calls name their thread in `threadID`. `agentSessions.subagents` joins the two and gives each subagent's calls and usage; a plugin that reports neither gives an empty list. Core knows no agent's subagent format. @@ -209,6 +227,19 @@ and the [shared Core/desktop fixture](../../../../rust/fixtures/agents/turn-inte - With `snippets: true`, each hit of `agentSessions.search` carries `snippet` (36 characters before the first match to 120 after it, with `…` where cut) and `snippetMatches` (UTF-8 byte ranges of the matched words in the snippet, every word, ignoring case, overlaps merged), matched by the search index's own rules; a hit beyond the read bound has no snippet and nothing fails. - All of these only read the agent's session files: Core never deletes, moves or rewrites them. +### Usage features: rate-limit refresh, custom prices, currency and rate-limit alerts + +An agent's `usage` declares the usage features its plugin implements: `rateLimits` (a backend function that reads the current rate limits when the user asks), `exchangeRates` (a backend function that gives exchange rates from US dollars), `customPrices` (the user may set prices for the agent's models) and `rateLimitAlerts` (the user may set alerts on its rate-limit windows). A feature left out is refused by the `agentUsage.*` commands with `agentUsage.notDeclared`, which the host shows as "this plugin does not support this feature"; the catalog's `usage` says only whether each is supported, without function IDs. + +- Core defines the shapes, checks the plugin's answers and keeps the user's settings; the plugin implements the feature. Core makes no network request for any of them: how a plugin learns rate limits and exchange rates is its own business. +- `agentUsage.refreshRateLimits` calls the plugin's `rateLimits` function, whose answer is shaped like the `rateLimits` session event, and Core keeps it as the agent's latest snapshot. +- `agentUsage.setPrice` keeps the price the user set for a model, in US dollars per million tokens; the agent's calls use it before the price table, and without a table too. +- `agentUsage.refreshExchangeRates` asks the plugin for the rates of some currencies per US dollar, and `agentUsage.setCurrency` chooses the currency shown. Costs are always given in US dollars; with a currency chosen, statistics also give `currency {code, perUSD, atMs}`, and the host converts what it shows. +- `agentUsage.setAlert` sets up to four percentage thresholds on a rate-limit window. Windows of the rate-limit snapshots carry `alert {thresholds, reached?}`; when a new snapshot reaches a higher threshold Core logs `agent.usage.alert_hit`, and the host decides how to tell the user. +- Rate-limit history: every snapshot Core keeps adds a point per window, at least five minutes apart within a cycle, a new cycle always starting one, kept for 35 days and at most 4000 points per window. `agentUsage.rateLimitHistory` reads them by window and range. +- The settings and history are user data: `usage-settings.json` and `rate-limit-history.json`, owner-only, in the `dataDirectory` the host gives `agentSessions.configure` (the platform's application data, not the cache directory). A settings file that cannot be read is kept as `usage-settings.unreadable.json`. `agentSessions.forget` removes the agent's rate-limit history and keeps its prices and alerts. +- Changing a setting and asking a plugin for data run only for a request the user started (`agentUsage.userActionRequired`). Commands, fields and refusal codes are in the contract's [Usage features](../../contract/v1/README.md#usage-features). + ### The library: instructions, skills, MCP servers and hooks The host's agent library keeps one copy of instructions, skills, MCP servers and hooks; once the user turns them on per agent, Core writes them into each CLI's own configuration. The plugin only declares `configuration`: @@ -276,19 +307,20 @@ Before Core replaces any of an agent's files, it backs the file up under `backup | [Host commands](../../contract/v1/README.md#host-commands) | The `agents.*` commands the host calls and the event queue | | [Native sessions](../../contract/v1/README.md#native-sessions) | Launch flow, notifications, host methods, session events | | [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | +| [Usage features](../../contract/v1/README.md#usage-features) | The `usage` declaration, the `agentUsage.*` commands, the plugin's rate-limit and exchange-rate functions, where settings and rate-limit history are kept, and refusal codes | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage, commands and filters, the `read` and `edit` functions, limits, and refusal codes | | [Instruction files](../../contract/v1/README.md#instruction-files) | Lithe's block in the instruction file, its states, the sync after a save, import, and how existing data is migrated | | [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`, the `agentProviders.*` commands, snapshots and changes, privacy rules, and refusal codes | | [Backups and restore](../../contract/v1/README.md#backups-and-restore) | Backups before library and providers changes, the `backup` status, `agentProviders.restore` and its refusal codes | | [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | Logs carry only IDs and metadata; no credential file is read | | [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | No ACP client; trusted local workspaces only | -| [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*`, `agentSessions.*`, `agentLibrary.*`, and `agentProviders.*` commands (Rust Core API document) | +| [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*`, `agentSessions.*`, `agentUsage.*`, `agentLibrary.*`, and `agentProviders.*` commands (Rust Core API document) | ### Examples and cases | File | Content | | --- | --- | -| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | An agent with a native session, a terminal form, an update command, one session source, and a library configuration declaration | +| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | An agent with a native session, a terminal form, an update command, one session source, a library configuration declaration, and every usage feature | | [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | A terminal-only agent without a backend | | [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | Rejection cases built on these two manifests | | [`agents/native-session.json`](../../contract/v1/fixtures/agents/native-session.json) | Native-session notifications with the calls each session's handler receives, the `turnEnded` reports of failed starts and prompts, and the `agents` host method requests; all four SDKs test against it | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1139c36a..9749d744 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#263](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/263)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 插件可在 `configuration.providers` 的 `read` 快照里列出 Agent 能用的模型 `models`(每项 `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`,最多 512 个),以及 CLI 提供的推理强度 `efforts`、速度档 `speeds`(各最多 16 个,每项 `{id, name?}`)、正在用的 `effort`、`speed`(`{id, source?}`)、CLI 自己的模型菜单 `modelMenu` 和写它的文件 `targets.modelMenu`;插件不列就没有,宿主和 Core 不内置任何模型名单。`configuration.providers.operations` 新增 `setEffort`、`setSpeed`、`setModelMenu`,`setModel` 可带 `effort`、`speed`(插件也声明了 `setEffort`、`setSpeed` 时);有清单时 Core 在调用插件前检查选择在清单里、组合是模型支持的,换模型时保留的强度和速度也要新模型支持(来源层是 `default` 的不查),新增错误码 `agentProviders.unknownModel`、`agentProviders.unknownEffort`、`agentProviders.unknownSpeed`、`agentProviders.unsupportedCombination`。`setModelMenu` 只由 Core 发给插件,宿主经 `agentProviders.apply` 发它以 `agentProviders.invalidChange` 拒绝。`agentProviders.read` 总是回答 `models`,每项带 `shown`。新增宿主命令 `agentProviders.showModels {agent, show?, hide?}`:用户隐藏的模型按隐藏顺序记在资源库目录的 `models.json`(仅所有者可读写),默认全部显示,插件新加的模型也显示,插件去掉的模型保留记录,每个 Agent 最多 1024 条,超出先丢最早的、已不在清单里的;插件声明 `setModelMenu` 时 Core 经暂存副本让插件把显示的模型写进 CLI 的菜单,写失败把开关放回,不声明时开关只影响 Lithe 的选择器。新增 `agentProviders.readModelSettings {agent}` 和 `agentProviders.applyModelSettings {agent, settings}`,把开关和模型、强度、速度作为一组读出和写回(写回先全部检查,一个被拒就都不改),供以后的模型方案使用。日志 `agent.providers.change_applied`、`agent.providers.change_failed` 的 `change` 新增取值 `showModels`、`applyModelSettings`。样例见 `contract/v1/fixtures/agents/model-catalog.json`。插件函数 `edit` 新增上述操作,`read` 回答新增上述字段;没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码,只更新说明。 | +| [#267](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/267)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 用量统计与用量功能。`scan` 的调用新增可选的 `account`、`purpose`(插件自己的标签,1–256 个可见 ASCII 字节、不含空格,Core 原样分组筛选、不解释)、`cancelled`(中途取消,不能同时带 `errorCategory`)和 `toolUses`(最多 1000000);会话缓存布局升到 5,首次同步时重建。`agentSessions.stats` 新增 `groupBy`/`splitBy` 取值 `account`、`purpose`,筛选 `accounts`、`purposes`、`cancelled` 和按工作目录整段精确匹配的 `cwds`(至多 64 个、每个至多 4096 字节,超出以 `agentSessions.invalidFilter` 拒绝;空字符串代表没记录目录的会话),`overview.speeds: true`(概览同一次读取也给出 `speeds` 速度排名),`sessions: {top?}`(按会话的调用数、令牌数、费用、时长的均值和 p50、p90、p99、最大值,最近秩法;最贵的至多 50 个会话)和 `messages: true`(按小时或天的消息数,其他分组以新错误码 `agentSessions.invalidMessagesGroup` 拒绝);汇总新增 `cancelledCalls`、`toolUses`,取消的调用不计入速度和首字时间;`cwd` 分组的键带 `category`;选了货币时回答带 `currency {code, perUSD, atMs}`。`agentSessions.calls` 新增同样的筛选,每行新增 `generation`、`size`(交给 `agentSessions.page` 定位到这次调用)和 `context {tokens, window?, share?}`(窗口取自插件模型列表的 `contextWindow`)。`agentSessions.configure` 新增 `dataDirectory`(平台应用数据目录,不能是缓存目录)。Agent 新增声明 `usage {rateLimits?, exchangeRates?, customPrices?, rateLimitAlerts?}`,前两项是插件函数(Agent 因此需要后端和 `onAgent:`),目录条目带 `usage` 布尔值。新增宿主命令 `agentUsage.read`、`agentUsage.setPrice`、`agentUsage.setAlert`、`agentUsage.setCurrency`、`agentUsage.refreshRateLimits`、`agentUsage.refreshExchangeRates`、`agentUsage.rateLimitHistory`,错误码 `agentUsage.notConfigured`、`agentUsage.unknownAgent`、`agentUsage.notGranted`、`agentUsage.notDeclared`(插件没声明这项功能,`not_supported`)、`agentUsage.userActionRequired`、`agentUsage.backendUnavailable`、`agentUsage.pluginFailed`、`agentUsage.invalidAnswer`、`agentUsage.invalidPrice`、`agentUsage.invalidAlert`、`agentUsage.invalidCurrency`、`agentUsage.noExchangeRate`、`agentUsage.invalidRange`、`agentUsage.saveFailed`。用户设的价格先于价格表;额度窗口带 `alert {thresholds, reached?}`;额度历史同一周期内至少隔 5 分钟一个点,保留 35 天、每窗口最多 4000 点。设置和历史存在 `dataDirectory` 的 `usage-settings.json`、`rate-limit-history.json`(仅所有者可读写)。Core 不为这些功能联网。新增日志 `agent.usage.file_failed`、`agent.usage.price_changed`、`agent.usage.rate_limits_updated`、`agent.usage.exchange_rates_updated`、`agent.usage.plugin_failed`、`agent.usage.alert_hit`。插件函数 `rateLimits` 收 `{agentID}` 回 `{windows, plan?}`,`exchangeRates` 收 `{agentID, base: "USD", currencies}` 回 `{rates}`;没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码。 | ## 按协议查首次出现 @@ -241,6 +241,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#263](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/263) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 插件可在 `configuration.providers` 的 `read` 快照里列出 Agent 能用的模型 `models`(每项 `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`,最多 512 个),以及 CLI 提供的推理强度 `efforts`、速度档 `speeds`(各最多 16 个,每项 `{id, name?}`)、正在用的 `effort`、`speed`(`{id, source?}`)、CLI 自己的模型菜单 `modelMenu` 和写它的文件 `targets.modelMenu`;插件不列就没有,宿主和 Core 不内置任何模型名单。`configuration.providers.operations` 新增 `setEffort`、`setSpeed`、`setModelMenu`,`setModel` 可带 `effort`、`speed`(插件也声明了 `setEffort`、`setSpeed` 时);有清单时 Core 在调用插件前检查选择在清单里、组合是模型支持的,换模型时保留的强度和速度也要新模型支持(来源层是 `default` 的不查),新增错误码 `agentProviders.unknownModel`、`agentProviders.unknownEffort`、`agentProviders.unknownSpeed`、`agentProviders.unsupportedCombination`。`setModelMenu` 只由 Core 发给插件,宿主经 `agentProviders.apply` 发它以 `agentProviders.invalidChange` 拒绝。`agentProviders.read` 总是回答 `models`,每项带 `shown`。新增宿主命令 `agentProviders.showModels {agent, show?, hide?}`:用户隐藏的模型按隐藏顺序记在资源库目录的 `models.json`(仅所有者可读写),默认全部显示,插件新加的模型也显示,插件去掉的模型保留记录,每个 Agent 最多 1024 条,超出先丢最早的、已不在清单里的;插件声明 `setModelMenu` 时 Core 经暂存副本让插件把显示的模型写进 CLI 的菜单,写失败把开关放回,不声明时开关只影响 Lithe 的选择器。新增 `agentProviders.readModelSettings {agent}` 和 `agentProviders.applyModelSettings {agent, settings}`,把开关和模型、强度、速度作为一组读出和写回(写回先全部检查,一个被拒就都不改),供以后的模型方案使用。日志 `agent.providers.change_applied`、`agent.providers.change_failed` 的 `change` 新增取值 `showModels`、`applyModelSettings`。样例见 `contract/v1/fixtures/agents/model-catalog.json`。插件函数 `edit` 新增上述操作,`read` 回答新增上述字段;没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码,只更新说明。 | | [#262](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/262) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 已记录会话的五项补充,对 Agent 的会话文件都只读。**恢复命令**:清单 `agents[].terminal` 新增可选 `resumeArguments`(1–64 个参数,至少含一次 `${sessionID}`,不得有其他 `${`),安装审查的终端程序随之列出模板;宿主命令 `agentSessions.resume {agent, sessionID, toolPath, shell?}` 回答 `{pluginID, agentID, sessionID, executable, arguments, shell, cwd?, commandLine?}`,`commandLine` 按 `posix` 或 `powershell`(默认随宿主平台)转义;Core 只接受由字母、数字、`.`、`_`、`:`、`-` 组成、不以 `-` 开头、最长 256 字节的会话 ID;需要 `agents.run`,宿主用已有终端形式运行,不新增执行通道。`agentSessions.list` 的会话新增 `resumable`。**导出**:宿主命令 `agentSessions.export {agent, sessionID, labels, maxBytes?, keep?, utcOffsetSeconds?}` 回答 `{changed, markdown, messages, truncated}`,含用户消息、回复、每次工具调用一行和时间,不含思考和工具输出;`maxBytes` 4 KiB–4 MiB(默认 1 MiB),`keep` 为 `start` 或 `end`,最多读源文件 64 MiB。导出里的文字全部来自必填的 `labels`(`untitled`、`agent`、`session`、`directory`、`started`、`lastActive`、`timeZone`、`user`、`assistant`、`tool`、`failed`、`earlierOmitted`、`laterOmitted`,各 1–256 字节、不含控制字符),宿主按界面语言传入,Core 不带默认文字;缺少、多出或不合法的标签以 `agentSessions.invalidExport` 拒绝。**子代理**:`scan` 请求新增可选 `threads: true`,只有这时后端才可回答 `threads`(`{sessionID, threadID, parentThreadID?, kind?, startedAtMs?, updatedAtMs?, titleRange?}`);宿主命令 `agentSessions.subagents {agent, sessionID}` 合并线程描述和带 `threadID` 的调用,回答每个子代理的调用行与用量汇总,插件不报告时为空列表。**其他文件夹**:`agentSessions.list` 的 `groups` 新增 `category`(`root`、`temporary`、`hidden`),按路径形式套用 macOS、Linux、Windows 规则,共享用例 `rust/fixtures/agents/folder-categories-v1.json`。**搜索片段**:`agentSessions.search` 新增可选 `snippets: true`,命中带 `snippet`(第一个命中词前 36 个字符到其后 120 个字符,截断处加 `…`)和 `snippetMatches`(片段内的 UTF-8 字节区间,多词、不分大小写、重叠或相接的合并),匹配规则与搜索索引相同;单个命中超过 256 KiB 或一次搜索累计超过 4 MiB 时不给片段、不报错。`agentSessions.read`、`agentSessions.page` 对拆不开的 `agent` 键也回答 `agentSessions.unknownAgent` 和 `entry_not_found`(此前 `read` 回答 `invalid_request`,`page` 回答 `agentSessions.invalidPage`),与新命令一致,一个错误码只对应一个数字码。新增错误码 `agentSessions.unknownSession`、`agentSessions.runNotGranted`、`agentSessions.toolNotFound`、`agentSessions.noResume`、`agentSessions.unsafeResume`、`agentSessions.invalidExport`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明 `resumeArguments` 的清单,不发送 `threads`、严格拒绝回答里的 `threads`,把三个新命令当未知命令、把 `snippets` 当未知字段拒绝。`scan`、`read` 仍是普通 JSON 函数,四语 SDK 无类型或版本变化;新增日志事件 `agent.session.cleanup_failed`(启动失败或会话结束后停不掉的 Agent CLI,带 Core 错误码,不带参数或输出)和 `agent.records.rate_limits_save_failed`(额度快照写入或换名失败,只带步骤和文件系统错误类别,不带路径);`agents/didExit` 通知发不出去时记 `agent.interaction.failed`。没有新增插件可调用的宿主方法、通知或能力版本。样例见 `fixtures/agents/agents.plugin.json` 与 `fixtures/manifest/invalid-manifests.json`。 | | [#261](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/261) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的指令改为只写指令文件里 Lithe 标记的一块(`` 到 ``):块外用户文字逐字节保留,新块追加在用户文字之后,资源库文字里的标记行写成失效形式,多余的块和落单的标记行被清掉,指令为空时去掉整块,重复写入不变大;`state.json` 改记块内文字的哈希,旧 Core 整份写过且哈希一致的文件下次写成只有块,其他没有块的文件当作用户文字直接追加,不需确认。指令集新增可选 `on`、`agents`(空为所有 Agent),按 `sets` 顺序拼接后加 Agent 的 `extra`;去掉 `active`:读取带 `active` 的旧 `library.json` 时换成“该套开、其余关”,拼接结果逐字节不变,`save` 带 `active` 以 `agentLibrary.invalidLibrary` 拒绝。宿主命令 `agentLibrary.read` 的 `instructions.state` 改为 `absent`、`noBlock`、`current`、`stale`、`edited`、`tooLarge`、`unreadable`,新增 `ownLines`(块外用户文字行数);`agentLibrary.save` 回答新增 `instructions`:保存后 Core 给每个跟随的 Agent 写块,逐个回答 `written`、`unchanged`、`skipped`(带 `reason`)或 `failed`(带 `reason`),不覆盖用户改过的块;`agentLibrary.apply` 新增 `{category: "instructions", op: "import", id, name?, revision, replace?}`,把块外用户文字并入新建或已有的一套,先备份,文件只剩块,回答 `{changed, revision, instructions}`;`agentLibrary.otherInstructions` 收窄为“块里有不是 Lithe 写的内容”。`agentProviders.restore` 放回指令文件时关掉该 Agent 的跟随,回答新增 `unfollowed`,日志 `agent.providers.restore_applied` 新增字段 `unfollowed`。新增错误码 `agentLibrary.setExists`(并入时新建的一套 `id` 已存在)。新增日志事件 `agent.library.cleanup_failed`:资源库删不掉不再需要的文件(写入失败留下的临时文件、暂存副本、导入一半的技能、备份基线或历史),或失败后放不回备份记录时记录,只带对象种类和文件系统错误类别,不带路径。样例见 `rust/fixtures/agents/library-instructions-v1.json`。没有新增插件可调用的宿主方法、通知、插件函数参数或能力版本,插件后端协议和四语 SDK 不变。 | | [#260](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/260) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的修改替换 Agent 的文件前也先备份,和 `agentProviders.apply` 共用同一份备份。`agentLibrary.apply` 为 MCP 服务器、Hooks 改声明文件,以及整份写入指令文件(包括 `replace: true` 覆盖不是 Lithe 写的内容)之前先备份,备份不成功就不写文件,复用已有错误码 `agentProviders.backupFailed`;技能的符号链接不覆盖内容,不备份。同一个文件无论资源库还是供应商先改,都只存一份“自上次恢复以来 Lithe 第一次修改前的原样”(按第一个解析到该路径的声明文件归并,指令文件不是声明文件时单独一项)。宿主命令 `agentLibrary.read` 的每个 Agent 新增可选 `backup {savedAtMs, modifiedSince}`,和 `agentProviders.read` 的 `backup` 相同;后者现在也覆盖指令文件和资源库的修改。`agentProviders.restore` 不再要求 Agent 声明 `providers`(原来以 `agentProviders.notDeclared` 拒绝),恢复该 Agent 所有备份过的文件;放回指令文件前先忘掉 Core 最后写入的指令哈希,恢复后 `instructions.state` 按文件实际内容显示、不会是 `written`,再写入要重新确认 `replace: true`。旧 Core 只备份 `agentProviders.apply` 的修改,`agentLibrary.read` 不带 `backup`,对不声明 `providers` 的 Agent 的恢复回答 `agentProviders.notDeclared`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 |