diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5c8b5545..b963376c 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -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 | diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 83bf3457..beed2700 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -888,16 +888,23 @@ impl Records { group_by: String, #[serde(default)] utc_offset_seconds: i32, + #[serde(default)] + hour_anchor_ms: Option, } 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) => { @@ -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 @@ -1041,19 +1048,30 @@ impl Records { group_by: String, #[serde(default)] utc_offset_seconds: i32, + #[serde(default)] + hour_anchor_ms: Option, } 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 = runtime @@ -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 { - if !(-14 * 3600..=14 * 3600).contains(&utc_offset_seconds) { +fn parse_group_by( + name: &str, + utc_offset_seconds: i32, + hour_anchor_ms: Option, + host: bool, +) -> Option { + 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), diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 496a078a..ea57d1e6 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -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, link: Arc, host: Host, @@ -468,6 +467,8 @@ struct Harness { /// The last event sequence [`Harness::next_event`] looked at. cursor: u64, trace: Option, + // Drop the runtime and its SQLite handles before removing the test directory on Windows. + dir: TempDir, } impl Harness { @@ -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; diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs index 615dcc6d..03c78524 100644 --- a/rust/crates/agent-sessions/src/stats.rs +++ b/rust/crates/agent-sessions/src/stats.rs @@ -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 @@ -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. @@ -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(), }, diff --git a/rust/crates/agent-sessions/src/tests/stats.rs b/rust/crates/agent-sessions/src/tests/stats.rs index 963e8e42..74c739f0 100644 --- a/rust/crates/agent-sessions/src/tests/stats.rs +++ b/rust/crates/agent-sessions/src/tests/stats.rs @@ -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. diff --git a/rust/fixtures/ai/agent-usage-hours-v1.json b/rust/fixtures/ai/agent-usage-hours-v1.json new file mode 100644 index 00000000..67a7fdb8 --- /dev/null +++ b/rust/fixtures/ai/agent-usage-hours-v1.json @@ -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 } + } + ] +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 7d7e232a..42cd5859 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -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 @@ -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 @@ -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 - `/`, and `stats` groups by `day`, `agent`, `model`, - `session` or `cwd`. + groupBy, utcOffsetSeconds, hourAnchorMs?}` serve the host's own views; `agent` is + `/`, and `stats` groups by `hour`, `day`, `agent`, `model`, + `session` or `cwd`. Hour keys and alignment follow the `agents/usage` rules above. - `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 diff --git a/shared/plugins/contract/v1/fixtures/agents/native-session.json b/shared/plugins/contract/v1/fixtures/agents/native-session.json index e3358ef7..0558b59c 100644 --- a/shared/plugins/contract/v1/fixtures/agents/native-session.json +++ b/shared/plugins/contract/v1/fixtures/agents/native-session.json @@ -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 } } } ] } diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 5cca1867..d59a012c 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -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)。 @@ -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). diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 970c84c2..048b7946 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -33,7 +33,7 @@ - 用户逐个 Agent 同意后,Core 才读取 `sessionSources` 声明的目录:只读匹配 `include` 的普通文件,不跟随符号链接;后端的 `scan` 函数把新增的行变成记录,`read` 函数把记录的范围变成标题或消息。 - Core 缓存记录,负责列表、全文搜索和统计;缓存不存正文,可以删除重建。 -- `lithe/host/agents/usage` 按天、Agent 或模型汇总用户已开启记录的 Agent 的用量,并带上最近的额度窗口。它只给数字和模型名,不含对话正文、标题、会话 ID 或工作目录,适合做跨 Agent 的统计和额度面板。 +- `lithe/host/agents/usage` 按小时、天、Agent 或模型汇总用户已开启记录的 Agent 的用量,并带上最近的额度窗口。它只给数字和模型名,不含对话正文、标题、会话 ID 或工作目录,适合做跨 Agent 的统计和额度面板。 - `agentSessions.calls` 按时间倒序分页列出 `scan` 报告的每一次调用,带所属 Agent 和调用本身(模型、令牌数等),以及 Core 算出的费用、缓存命中率和速度,供用量页的请求列表和详情使用;不含正文。 - 连续浏览正文用 `agentSessions.page`,按返回的字节边界向前或向后读取。恢复会话前先同步并固定 `readBytes`,历史与新的会话事件分别保存,避免把旧提示误当成新轮次。Core 向普通 `read` 函数传 `messageIDs: true` 时,插件可返回稳定的消息 `id` 来识别同一消息的镜像;省略或为 `false` 时不得返回 `id`,保证旧 Core 仍接受原来的结果。没有稳定标识的格式省略 `id`,不按文本去重。四语 SDK 的普通 JSON 函数处理器直接支持这个可选参数。参见 [读取样例](../../contract/v1/fixtures/agents/record-read.json)。 @@ -105,7 +105,7 @@ The tool always comes from the plugin's `requiresTools`: the host discovers it a - 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 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. +- `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. ### The library: instructions, skills, MCP servers and hooks diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 239ead8c..a5270620 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#231](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/231)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 | `agents/usage` 支持按小时汇总。默认按指定 UTC 偏移对齐整点,也可用 `hourAnchorMs` 对齐滚动窗口。 | | [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。同时增加可选请求参数 `toolCalls`:只有 `true` 时 `tool` 消息才可带实时 `toolCall` 的详情 `toolCallID`、`status`、`toolKind`、`title`、`locations`(同一调用和它的结果共用 `toolCallID`,宿主按实时方式合并,让历史轮次和实时显示一致)。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,两个参数都由它发送,旧 `agentSessions.read` 和标题读取不协商,回答里出现这些详情字段(包括显式 `null`)时以 `agentSessions.invalidRead` 拒绝。`agentSessions.list` 的会话新增 `generation`:文件只增长时不变,被替换或截断后重新读取时换新值;`agentSessions.page` 必须带上同一次列表的 `generation`,不一致时回答 `changed`。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `15c0717`;宿主发布版本尚未产生。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | diff --git a/shared/plugins/sdk/go/lithe/agents.go b/shared/plugins/sdk/go/lithe/agents.go index 279e7905..fc10713b 100644 --- a/shared/plugins/sdk/go/lithe/agents.go +++ b/shared/plugins/sdk/go/lithe/agents.go @@ -201,8 +201,11 @@ func (a *Agents) Report(session string, events any) error { return err } +// AgentUsageByHour groups usage in hourly buckets identified by key.startMs. +const AgentUsageByHour = "hour" + // Usage answers { sinceMs, untilMs, summaries, speeds, rateLimits } for -// { groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }. +// { groupBy, sinceMs?, untilMs?, utcOffsetSeconds?, hourAnchorMs? }. func (a *Agents) Usage(params any) (json.RawMessage, error) { value, err := toValue(params) if err != nil { diff --git a/shared/plugins/sdk/go/lithe/agents_test.go b/shared/plugins/sdk/go/lithe/agents_test.go index e15693f4..186c26f0 100644 --- a/shared/plugins/sdk/go/lithe/agents_test.go +++ b/shared/plugins/sdk/go/lithe/agents_test.go @@ -260,7 +260,7 @@ func TestAgentHostMethodsSendTheFixtureRequests(t *testing.T) { eq(t, request["params"], encode(t, at(test, "request", "params"))) answer := map[string]any{} if at(test, "call") == "usage" { - answer = map[string]any{"sinceMs": 1, "untilMs": 2, "summaries": []any{}, "rateLimits": []any{}} + answer = at(test, "result").(map[string]any) } host.reply(request, answer) must(t, within(t, done)) diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java index 86c80b1b..09ca5995 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -1026,6 +1026,9 @@ public Agents agents() { } public final class Agents { + /** Hourly usage grouping; each summary key carries its startMs. */ + public static final String USAGE_BY_HOUR = "hour"; + /** Writes 1-256 lines, without line breaks, to the standard input of {@code session}'s CLI. */ public CompletableFuture write(String session, List lines) { return sessionRequest(Protocol.HOST_AGENTS_WRITE, session, "lines", lines); @@ -1038,7 +1041,7 @@ public CompletableFuture report(String session, List events) { /** * {@code { sinceMs, untilMs, summaries, speeds, rateLimits }} for - * {@code { groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }}. + * {@code { groupBy, sinceMs?, untilMs?, utcOffsetSeconds?, hourAnchorMs? }}. */ public CompletableFuture> usage(Map params) { Object message = params == null ? new LinkedHashMap() : params; diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java index b84bf16e..e3aa0372 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java @@ -265,6 +265,7 @@ void agentHostMethodsSendTheFixtureRequests() { Backend backend = Backend.create("agents-test", null); TestHost host = session(backend); Host.Agents agents = backend.host().agents(); + Set answered = new HashSet<>(); for (Object raw : list(FIXTURE.get("methods"))) { Map entry = object(raw); String call = (String) entry.get("call"); @@ -282,11 +283,12 @@ void agentHostMethodsSendTheFixtureRequests() { pending = agents.usage(object(entry.get("params"))); } Map request = object(entry.get("request")); - Map sent = host.waitFor(message -> request.get("method").equals(message.get("method")), - (String) request.get("method")); + Map sent = host.waitFor(message -> request.get("method").equals(message.get("method")) + && !answered.contains(message.get("id")), (String) request.get("method")); + answered.add(sent.get("id")); assertEquals(request.get("params"), sent.get("params")); Map answer = call.equals("usage") - ? map("sinceMs", 1L, "untilMs", 2L, "summaries", new ArrayList<>(), "rateLimits", new ArrayList<>()) + ? object(entry.get("result")) : map(); host.send(map("id", sent.get("id"), "result", answer)); Object result = Fixtures.await(pending, call); diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index d8078f4b..78b2fb3e 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -1020,7 +1020,9 @@ export interface AgentSessionHandle { export type AgentSessionEvent = JsonObject & { kind: string }; export interface AgentUsageParams { - groupBy: 'day' | 'agent' | 'model'; + groupBy: 'hour' | 'day' | 'agent' | 'model'; + /** For hour grouping, aligns 60-minute buckets to this Unix millisecond instant. */ + hourAnchorMs?: number; sinceMs?: number; untilMs?: number; utcOffsetSeconds?: number; diff --git a/shared/plugins/sdk/node/test/agents.test.mjs b/shared/plugins/sdk/node/test/agents.test.mjs index 1cbb388a..08bbab47 100644 --- a/shared/plugins/sdk/node/test/agents.test.mjs +++ b/shared/plugins/sdk/node/test/agents.test.mjs @@ -147,7 +147,7 @@ test('agent host methods send the fixture requests', async () => { entry.request.method, ); assert.deepEqual(request.params, entry.request.params); - const answer = entry.call === 'usage' ? { sinceMs: 1, untilMs: 2, summaries: [], rateLimits: [] } : {}; + const answer = entry.result ?? {}; host.send({ id: request.id, result: answer }); assert.deepEqual(await withTimeout(call, entry.call), entry.call === 'usage' ? answer : undefined); } diff --git a/shared/plugins/sdk/node/test/types/agents.mts b/shared/plugins/sdk/node/test/types/agents.mts index 6fa6168f..f128adfe 100644 --- a/shared/plugins/sdk/node/test/types/agents.mts +++ b/shared/plugins/sdk/node/test/types/agents.mts @@ -50,7 +50,8 @@ backend.function('usage.today', async (_params, context) => { return { summaries: usage.summaries.length }; }); -// @ts-expect-error groupBy is day, agent or model. +void backend.host.agents.usage({ groupBy: 'hour', hourAnchorMs: 1 }); +// @ts-expect-error session is a host-only grouping. void backend.host.agents.usage({ groupBy: 'session' }); // @ts-expect-error a handler answers prompts. backend.onAgentSessions(() => ({ output() {}, decidePermission() {} })); diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs index 95d5bbac..5272c977 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs @@ -172,6 +172,9 @@ pub struct Agents { } impl Agents { + /// Hourly usage grouping; each summary key carries its startMs. + pub const USAGE_BY_HOUR: &str = "hour"; + /// Writes `lines` to the standard input of `session`'s CLI. pub fn write>(&self, session: &str, lines: &[S]) -> Result<(), SdkError> { let lines: Vec<&str> = lines.iter().map(AsRef::as_ref).collect(); @@ -194,7 +197,7 @@ impl Agents { } /// The usage totals `{ sinceMs, untilMs, summaries, speeds, rateLimits }` for - /// `{ groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }`. + /// `{ groupBy, sinceMs?, untilMs?, utcOffsetSeconds?, hourAnchorMs? }`. pub fn usage(&self, params: Value) -> Result { match self.host.request(methods::AGENTS_USAGE, params)? { result @ Value::Object(_) => Ok(result), diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs index e403a5d7..fd160552 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs @@ -315,7 +315,7 @@ fn agent_host_methods_send_the_fixture_requests() { assert_eq!(request["method"], case["request"]["method"]); assert_eq!(request["params"], case["request"]["params"]); let answer = if case["call"] == "usage" { - json!({ "sinceMs": 1, "untilMs": 2, "summaries": [], "rateLimits": [] }) + case["result"].clone() } else { json!({}) };