Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ or removing a command fails until the table changes in the same commit.
| `agentSessions.search` | Search recorded agent session text |
| `agentSessions.read` | Read one recorded range as messages and where the next page starts |
| `agentSessions.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 |
| `agentSessions.stats` | Sum recorded agent usage with the latest rate limits; `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 |
| `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 |
Expand Down
58 changes: 43 additions & 15 deletions rust/crates/agent-runtime/src/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -888,16 +888,23 @@ impl Records {
group_by: String,
#[serde(default)]
utc_offset_seconds: i32,
#[serde(default)]
hour_anchor_ms: Option<i64>,
}
let request: StatsRequest = crate::decode(payload)?;
let group_by = parse_group_by(&request.group_by, request.utc_offset_seconds, true)
.ok_or_else(|| {
refusal(
ErrorCode::InvalidRequest,
"agentSessions.invalidGroup",
"Group by day, agent, model, session or cwd.",
)
})?;
let group_by = parse_group_by(
&request.group_by,
request.utc_offset_seconds,
request.hour_anchor_ms,
true,
)
.ok_or_else(|| {
refusal(
ErrorCode::InvalidRequest,
"agentSessions.invalidGroup",
"Group by hour, day, agent, model, session or cwd. Only hour accepts hourAnchorMs.",
)
})?;
let (summaries, speeds) = match allowed_agents(runtime, request.agents) {
None => (json!([]), json!([])),
Some(agents) => {
Expand Down Expand Up @@ -1025,7 +1032,7 @@ impl Records {
}

/// Answers `lithe/host/agents/usage` for a plugin granted
/// `agents.usage.read`: totals of the readable agents, grouped by day,
/// `agents.usage.read`: totals of the readable agents, grouped by hour, day,
/// agent or model, the models' median output speeds, and the agents'
/// rate limits. It carries no conversation text,
/// titles, session IDs or directories. Runs with the asking backend's
Expand All @@ -1041,19 +1048,30 @@ impl Records {
group_by: String,
#[serde(default)]
utc_offset_seconds: i32,
#[serde(default)]
hour_anchor_ms: Option<i64>,
}
let invalid = |message: &str| AgentHostFailure::new(codes::HOST_INVALID_PARAMS, message);
let request: UsageRequest = serde_json::from_value(params.clone())
.map_err(|error| invalid(&format!("Invalid usage request: {error}")))?;
let group_by = parse_group_by(&request.group_by, request.utc_offset_seconds, false)
.ok_or_else(|| invalid("Group usage by day, agent or model."))?;
let group_by = parse_group_by(
&request.group_by,
request.utc_offset_seconds,
request.hour_anchor_ms,
false,
)
.ok_or_else(|| {
invalid("Group usage by hour, day, agent or model. Only hour accepts hourAnchorMs.")
})?;
let until_ms = request
.until_ms
.unwrap_or_else(|| now_ms() + MILLISECONDS_PER_DAY);
let since_ms = request
.since_ms
.unwrap_or(until_ms - 30 * MILLISECONDS_PER_DAY);
if since_ms >= until_ms || until_ms - since_ms > MAX_USAGE_DAYS * MILLISECONDS_PER_DAY {
.unwrap_or_else(|| until_ms.saturating_sub(30 * MILLISECONDS_PER_DAY));
if since_ms >= until_ms
|| until_ms.saturating_sub(since_ms) > MAX_USAGE_DAYS * MILLISECONDS_PER_DAY
{
return Err(invalid("The usage range is empty or longer than 366 days."));
}
let agents: Vec<String> = runtime
Expand Down Expand Up @@ -1300,11 +1318,21 @@ fn add_agent_ids(value: &mut Value, key: &str) {
}
}

fn parse_group_by(name: &str, utc_offset_seconds: i32, host: bool) -> Option<GroupBy> {
if !(-14 * 3600..=14 * 3600).contains(&utc_offset_seconds) {
fn parse_group_by(
name: &str,
utc_offset_seconds: i32,
hour_anchor_ms: Option<i64>,
host: bool,
) -> Option<GroupBy> {
if !(-14 * 3600..=14 * 3600).contains(&utc_offset_seconds)
|| (hour_anchor_ms.is_some() && name != "hour")
{
return None;
}
match name {
"hour" => Some(GroupBy::Hour {
anchor_ms: hour_anchor_ms.unwrap_or(-i64::from(utc_offset_seconds) * 1000),
}),
"day" => Some(GroupBy::Day { utc_offset_seconds }),
"agent" => Some(GroupBy::Agent),
"model" => Some(GroupBy::Model),
Expand Down
46 changes: 45 additions & 1 deletion rust/crates/agent-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,6 @@ impl BackendLink for FakeLink {
/// A runtime with the synthetic plugin configured, a tool file, a working
/// directory and a session cache, driven as a user request.
struct Harness {
dir: TempDir,
runtime: Arc<Runtime>,
link: Arc<FakeLink>,
host: Host,
Expand All @@ -468,6 +467,8 @@ struct Harness {
/// The last event sequence [`Harness::next_event`] looked at.
cursor: u64,
trace: Option<trace::Context>,
// Drop the runtime and its SQLite handles before removing the test directory on Windows.
dir: TempDir,
}

impl Harness {
Expand Down Expand Up @@ -1721,6 +1722,49 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() {
);
}

#[test]
fn hourly_stats_match_the_shared_desktop_fixture() {
let fixture: Value = serde_json::from_str(include_str!(
"../../../fixtures/ai/agent-usage-hours-v1.json"
))
.expect("hourly stats fixture");
let harness = Harness::new("hourly-stats", ALL_GRANTS);
let at = fixture["callStartMs"].as_i64().expect("fixture call start");
write_session_file(&harness, at);
harness.run(
"agentSessions.sync",
json!({ "pluginID": PLUGIN, "agentID": AGENT }),
);
for case in fixture["cases"].as_array().expect("hourly stats cases") {
let mut query = case["query"].clone();
let host = harness.run("agentSessions.stats", query.clone());
let plugin = harness
.answer(AGENTS_USAGE, query.clone())
.expect("hourly usage");
assert_eq!(host["summaries"], plugin["summaries"]);
assert_eq!(host["summaries"][0]["key"], case["key"]);
assert_eq!(host["summaries"][0]["tokens"]["input"], 100);
query["sinceMs"] = json!(at - 1);
query["untilMs"] = json!(at);
assert_eq!(
harness.run("agentSessions.stats", query)["summaries"],
json!([])
);
}
let bad = json!({"groupBy": "day", "hourAnchorMs": at});
assert_eq!(
harness.refused("agentSessions.stats", bad.clone()),
"agentSessions.invalidGroup"
);
assert_eq!(
harness
.answer(AGENTS_USAGE, bad)
.expect_err("anchor without hour")
.code,
codes::HOST_INVALID_PARAMS
);
}

#[test]
fn rate_limits_survive_a_restart() {
let dir;
Expand Down
20 changes: 20 additions & 0 deletions rust/crates/agent-sessions/src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ pub enum GroupBy {
/// The offset of the user's time zone.
utc_offset_seconds: i32,
},
/// By elapsed hours measured from an absolute instant.
Hour {
/// Start of any bucket in this hourly series, in Unix milliseconds.
anchor_ms: i64,
},
/// By agent.
Agent,
/// By the model that answered, or the requested one when the answer did
Expand All @@ -61,6 +66,12 @@ pub enum GroupKey {
/// The date.
date: String,
},
/// An hour identified by its absolute start, including across clock changes.
Hour {
/// Start of the bucket in Unix milliseconds.
#[serde(rename = "startMs")]
start_ms: i64,
},
/// An agent.
Agent {
/// The agent.
Expand Down Expand Up @@ -420,6 +431,15 @@ 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::Agent => GroupKey::Agent {
agent: entry.agent.clone(),
},
Expand Down
40 changes: 40 additions & 0 deletions rust/crates/agent-sessions/src/tests/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,46 @@ fn calls_group_by_session_and_directory() {
);
}

#[test]
fn hours_use_the_anchor_and_return_only_occupied_buckets() {
// UTC+05:45 midnight, a millisecond anchor, and the first New York 01:30
// on 2026-11-01. One elapsed hour later it is 01:30 again after the fall-back.
for anchor_ms in [-20_700_000, 37_800_123, 1_793_511_000_000] {
let mut sums = Summarizer::new(GroupBy::Hour { anchor_ms }, None);
for (id, delta) in [
("a", -1),
("b", 0),
("c", 3_599_999),
("d", 3_600_000),
("e", 10_800_000),
] {
sums.add(&entry(record(id, anchor_ms + delta)));
}
let actual: Vec<_> = sums
.finish()
.into_iter()
.map(|s| (s.key, s.calls))
.collect();
let bucket = |delta, calls| {
(
GroupKey::Hour {
start_ms: anchor_ms + delta,
},
calls,
)
};
assert_eq!(
actual,
[
bucket(-3_600_000, 1),
bucket(0, 2),
bucket(3_600_000, 1),
bucket(10_800_000, 1)
]
);
}
}

#[test]
fn days_follow_the_user_time_zone() {
// 2026-11-24T20:00:00Z and 2026-11-25T02:00:00Z.
Expand Down
13 changes: 13 additions & 0 deletions rust/fixtures/ai/agent-usage-hours-v1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"callStartMs": 1795948200246,
"cases": [
{
"query": { "groupBy": "hour", "utcOffsetSeconds": 20700, "sinceMs": 1795948200246, "untilMs": 1795948200247 },
"key": { "kind": "hour", "startMs": 1795947300000 }
},
{
"query": { "groupBy": "hour", "hourAnchorMs": 1795948200123, "sinceMs": 1795948200123, "untilMs": 1796034600123 },
"key": { "kind": "hour", "startMs": 1795948200123 }
}
]
}
20 changes: 14 additions & 6 deletions shared/plugins/contract/v1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3948,7 +3948,7 @@ host never sees them):
| --- | --- | --- | --- |
| `lithe/host/agents/write` | `agents.native` | `{session, lines}` | `{}` |
| `lithe/host/agents/report` | `agents.native` | `{session, events}` | `{}` |
| `lithe/host/agents/usage` | `agents.usage.read` | `{sinceMs?, untilMs?, groupBy, utcOffsetSeconds?}` | `{sinceMs, untilMs, summaries, speeds, rateLimits}` |
| `lithe/host/agents/usage` | `agents.usage.read` | `{sinceMs?, untilMs?, groupBy, utcOffsetSeconds?, hourAnchorMs?}` | `{sinceMs, untilMs, summaries, speeds, rateLimits}` |

- `write` takes 1–256 lines of at most 16 MiB together, none with a line
break; Core adds the newline. More than 64 writes waiting for the CLI is
Expand All @@ -3958,9 +3958,17 @@ host never sees them):
event of a turn that is not the active one is `-32019`; more than 16
pending permission requests is `-32014`.
- `usage` sums the [session records](#session-records) of the agents whose
records the user enabled, grouped by `day`, `agent` or `model`, between
records the user enabled, grouped by `hour`, `day`, `agent` or `model`, between
`sinceMs` and `untilMs` (default the 30 days before tomorrow, at most 366
days; `utcOffsetSeconds` within ±14 hours sets the day boundary).
days; `utcOffsetSeconds` within ±14 hours sets the local calendar boundary).
With `groupBy: "hour"`, each summary uses `key: {kind: "hour", startMs}`.
The start is an absolute Unix millisecond timestamp. By default the buckets
start on the hour at the given fixed offset (UTC if omitted). Optional
`hourAnchorMs` aligns hour boundaries to the given Unix millisecond instant.
For a rolling window, set it to `sinceMs`. Each bucket spans 3,600,000 ms;
the filter includes starts at `sinceMs` and excludes starts at `untilMs`.
Only occupied buckets are returned, oldest first. An anchor on another
grouping is invalid. Older hosts reject the new grouping or field.
`speeds` ranks the models of the same calls by median output speed.
`rateLimits` holds the latest quota windows of the agents the user may run
or read. While the records are being written the answer is `-32020`; before
Expand Down Expand Up @@ -4038,9 +4046,9 @@ Lithe list, search and sum them without the CLI running:
order?, offset, limit, titles, counts?}` (at most 500), `agentSessions.search {text, agents?,
sessionID?, limit}` (at most 200), `agentSessions.read {agent, path,
range}` and `agentSessions.stats {agents?, sessionID?, sinceMs?, untilMs?,
groupBy, utcOffsetSeconds}` serve the host's own views; `agent` is
`<pluginID>/<agentID>`, and `stats` groups by `day`, `agent`, `model`,
`session` or `cwd`.
groupBy, utcOffsetSeconds, hourAnchorMs?}` serve the host's own views; `agent` is
`<pluginID>/<agentID>`, and `stats` groups by `hour`, `day`, `agent`, `model`,
`session` or `cwd`. Hour keys and alignment follow the `agents/usage` rules above.
- `agentSessions.calls {agents?, sessionID?, sinceMs?, untilMs?, model?,
failed?, offset?, limit}` serves the host's request table: the calls the
filter keeps, most recent first, `limit` 1–500 at an `offset` of at most
Expand Down
11 changes: 11 additions & 0 deletions shared/plugins/contract/v1/fixtures/agents/native-session.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,19 @@
},
{
"call": "usage",
"result": { "sinceMs": 1764460800000, "untilMs": 1764547200000, "summaries": [], "rateLimits": [] },
"params": { "groupBy": "day", "sinceMs": 1764460800000, "utcOffsetSeconds": 28800 },
"request": { "method": "lithe/host/agents/usage", "params": { "groupBy": "day", "sinceMs": 1764460800000, "utcOffsetSeconds": 28800 } }
},
{
"call": "usage",
"result": {
"sinceMs": 1795948200123, "untilMs": 1796034600123,
"summaries": [{ "key": { "kind": "hour", "startMs": 1795948200123 }, "calls": 1, "failedCalls": 0, "compactionCalls": 0, "tokens": { "input": 42, "output": 3, "cacheRead": 0, "cacheWrite5m": 0, "cacheWrite1h": 0, "reasoning": 0 }, "firstStartedAtMs": 1795948200200, "lastStartedAtMs": 1795948200200 }],
"speeds": [], "rateLimits": []
},
"params": { "groupBy": "hour", "sinceMs": 1795948200123, "untilMs": 1796034600123, "hourAnchorMs": 1795948200123 },
"request": { "method": "lithe/host/agents/usage", "params": { "groupBy": "hour", "sinceMs": 1795948200123, "untilMs": 1796034600123, "hourAnchorMs": 1795948200123 } }
}
]
}
4 changes: 2 additions & 2 deletions shared/plugins/reference/api-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I
| API-40 | `workspace/getHostPaths` | 远程上下文的根目录在远端主机上的绝对路径 `hostPath`,可用 `rootIDs` 指定根目录和顺序;只用在远端运行的进程参数、工作目录和语言服务器、调试器配置里;本地上下文返回 `plugin.host.authorityUnsupported` | `workspace.metadata`,单独的方法授权(只有服务授权得到 `permissionDenied`) | 0 |
| API-45 | `agents/write` | 写本插件原生会话里 CLI 的标准输入:1–256 行,合计不超过 16 MiB,不含换行符,由 Core 补上;Core 直接回答 | `agents.native`,单独的方法授权 | 0 |
| API-45 | `agents/report` | 报告本插件原生会话的事件(会话、消息、工具调用、计划、权限请求、用量、额度、回合结束、提示、用户可改的会话设置):1–256 个,一起校验,一个被拒就全部不生效;Core 直接回答 | `agents.native`,单独的方法授权 | 0 |
| API-45 | `agents/usage` | 按天、Agent 或模型汇总用户已开启记录的 Agent 的用量,带最近的额度窗口;只有数字和模型名,不含对话正文、标题、会话 ID 和目录;Core 直接回答 | `agents.usage.read`,单独的方法授权 | 0 |
| API-45 | `agents/usage` | 按小时、天、Agent 或模型汇总用户已开启记录的 Agent 的用量,带最近的额度窗口;只有数字和模型名,不含对话正文、标题、会话 ID 和目录;Core 直接回答 | `agents.usage.read`,单独的方法授权 | 0 |

快捷键导入提供者另有 `lithe/host/keymapImport/listInputs`、`lithe/host/keymapImport/readChunk` 两个方法,属于 `litheKeymapImport` 协议,不在 API-01–45 内,见[快捷键导入](domains/keymap-import.md)。

Expand Down Expand Up @@ -388,7 +388,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi
| API-40 | `workspace/getHostPaths` | Gives the absolute paths `hostPath` of a remote context's root folders on the remote host, optionally for the roots `rootIDs` names, in that order; used only in the arguments, working directories, and language server or debugger configuration of what runs on that host; a local context gets `plugin.host.authorityUnsupported` | `workspace.metadata`, as a method grant of its own (the service grant alone gets `permissionDenied`) | 0 |
| API-45 | `agents/write` | Writes the standard input of the CLI in one of this plugin's native sessions: 1–256 lines of at most 16 MiB together, without line breaks, which Core adds; answered by Core | `agents.native`, as a method grant of its own | 0 |
| API-45 | `agents/report` | Reports the events of one of this plugin's native sessions (session, message, tool call, plan, permission request, usage, rate limits, turn end, notice, session settings the user may change): 1–256, checked together, so when one is refused none applies; answered by Core | `agents.native`, as a method grant of its own | 0 |
| API-45 | `agents/usage` | Sums the usage of the agents whose records the user enabled, by day, agent, or model, with the latest quota windows; only numbers and model names, never conversation text, titles, session IDs, or directories; answered by Core | `agents.usage.read`, as a method grant of its own | 0 |
| API-45 | `agents/usage` | Sums the usage of the agents whose records the user enabled, by hour, day, agent, or model, with the latest quota windows; only numbers and model names, never conversation text, titles, session IDs, or directories; answered by Core | `agents.usage.read`, as a method grant of its own | 0 |

Shortcut import providers also have two methods, `lithe/host/keymapImport/listInputs` and `lithe/host/keymapImport/readChunk`. They belong to the `litheKeymapImport` protocol, outside API-01–45; see [Shortcut import](domains/keymap-import.md).

Expand Down
Loading
Loading