You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/23 09:34:12 UTC
(maka) 09/09: feat(usage): publish fixed-fence summaries with accounting coverage
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 7d4a24363945308b9e8a2fafd2c31c7540502826
Author: Wang <m4...@gmail.com>
AuthorDate: Wed Sep 23 17:33:53 2026 +0800
feat(usage): publish fixed-fence summaries with accounting coverage
Generated-by: Codex
---
crates/event-log/src/usage.rs | 28 +++
crates/event-log/src/usage/reads.rs | 20 +-
crates/event-log/src/usage/summary.rs | 250 +++++++++++++++++++++
crates/event-log/tests/tool_usage.rs | 16 ++
crates/event-log/tests/usage_paging.rs | 8 +-
crates/event-log/tests/usage_summary.rs | 194 ++++++++++++++++
crates/js-runtime/src/plugin/sdk.js | 5 +-
crates/plugins/src/usage.rs | 4 +-
crates/runtime-host/src/execution/plugins/usage.rs | 50 ++++-
.../runtime-host/src/plugins/javascript/bridge.rs | 4 +
.../src/plugins/javascript/bridge/wire.rs | 2 +
crates/runtime-host/src/plugins/usage.rs | 10 +-
.../tests/fixtures/background-plugin.mjs | 8 +-
crates/runtime-host/tests/fixtures/host-plugin.mjs | 7 +
.../integration/plugin_authorization/usage.rs | 4 +
crates/runtime/src/accounting.rs | 5 +
crates/runtime/src/accounting/summary.rs | 107 +++++++++
docs/rust-parity.md | 4 +-
docs/rust-parity.zh-CN.md | 4 +-
docs/rust-runtime.md | 4 +-
docs/rust-runtime.zh-CN.md | 4 +-
packages/plugin-sdk/README.md | 2 +
packages/plugin-sdk/README.zh-CN.md | 2 +
packages/plugin-sdk/src/usage.ts | 39 ++++
24 files changed, 741 insertions(+), 40 deletions(-)
diff --git a/crates/event-log/src/usage.rs b/crates/event-log/src/usage.rs
index 133edca9c7..83f7fdef06 100644
--- a/crates/event-log/src/usage.rs
+++ b/crates/event-log/src/usage.rs
@@ -28,6 +28,8 @@ use sqlx::{Row, sqlite::SqliteRow};
mod auxiliary;
mod reads;
+mod summary;
+pub use summary::Report;
pub(crate) mod valuation;
#[derive(Clone, Debug)]
@@ -41,6 +43,32 @@ pub struct Query {
}
impl Query {
+ /// Capture inside the same read transaction as every section of the result.
+ async fn fence(&self, connection: &mut sqlx::SqliteConnection) -> Result<u64, StoreError> {
+ let current = crate::sequence_number(
+ sqlx::query_scalar("SELECT COALESCE(MAX(sequence), 0) FROM event_log")
+ .fetch_one(connection)
+ .await?,
+ )?;
+ let through = self.through.unwrap_or(current);
+ if through > current {
+ return Err(invalid("Usage fence is in the future"));
+ }
+ Ok(through)
+ }
+
+ fn restrict(&self, sql: &mut sqlx::QueryBuilder<sqlx::Sqlite>, through: u64) {
+ sql.push(" WHERE completed_at >= ")
+ .push_bind(self.from)
+ .push(" AND completed_at <= ")
+ .push_bind(self.to)
+ .push(" AND completed_sequence <= ")
+ .push_bind(through as i64);
+ if let Some(session) = &self.session_id {
+ sql.push(" AND session_id = ").push_bind(session.clone());
+ }
+ }
+
fn validate(&self) -> Result<(), StoreError> {
if !self.from.is_finite() || !self.to.is_finite() || self.from < 0.0 || self.to < self.from
{
diff --git a/crates/event-log/src/usage/reads.rs b/crates/event-log/src/usage/reads.rs
index b0a4c44a14..300ee827d0 100644
--- a/crates/event-log/src/usage/reads.rs
+++ b/crates/event-log/src/usage/reads.rs
@@ -48,15 +48,7 @@ impl View {
}
fn restrict(&self, sql: &mut QueryBuilder<sqlx::Sqlite>, query: &Query, through: u64) {
- sql.push(" WHERE completed_at >= ")
- .push_bind(query.from)
- .push(" AND completed_at <= ")
- .push_bind(query.to)
- .push(" AND completed_sequence <= ")
- .push_bind(through as i64);
- if let Some(session) = &query.session_id {
- sql.push(" AND session_id = ").push_bind(session.clone());
- }
+ query.restrict(sql, through);
if let Self::Activity(selection) = self {
if let Some(kind) = selection.kind {
sql.push(" AND kind = ").push_bind(match kind {
@@ -99,15 +91,7 @@ pub(super) async fn page<T: Serialize + Send + 'static>(
.run(move |connection| {
Box::pin(async move {
let mut tx = connection.begin().await?;
- let current = crate::sequence_number(
- sqlx::query_scalar("SELECT COALESCE(MAX(sequence), 0) FROM event_log")
- .fetch_one(&mut *tx)
- .await?,
- )?;
- let through = query.through.unwrap_or(current);
- if through > current {
- return Err(invalid("Usage fence is in the future"));
- }
+ let through = query.fence(&mut tx).await?;
// Only closed internal view/column identifiers are interpolated.
let mut count = QueryBuilder::new("SELECT COUNT(*) FROM ");
count.push(view.table());
diff --git a/crates/event-log/src/usage/summary.rs b/crates/event-log/src/usage/summary.rs
new file mode 100644
index 0000000000..93e2c63444
--- /dev/null
+++ b/crates/event-log/src/usage/summary.rs
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::{EventLog, Query, StoreError, invalid};
+use maka_runtime::accounting::{
+ Cost, ModelSummary, ModelTotals, Pending, ProviderSummary, Summary, Tokens, ToolSummary,
+ ToolTotals,
+};
+use sqlx::{Connection, QueryBuilder, Row, Sqlite, sqlite::SqliteRow};
+
+/// Same canonical fence as activity paging, without activity-only filters.
+pub struct Report {
+ pub through: u64,
+ pub summary: Summary,
+}
+
+impl EventLog {
+ pub async fn usage_summary(&self, query: Query) -> Result<Report, StoreError> {
+ self.validate_root()?;
+ query.validate()?;
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin().await?;
+ let through = query.fence(&mut tx).await?;
+ let mut models = QueryBuilder::<Sqlite>::new("SELECT ");
+ models.push(MODELS);
+ query.restrict(&mut models, through);
+ let model_row = models.build().fetch_one(&mut *tx).await?;
+ let mut tools = QueryBuilder::<Sqlite>::new("SELECT ");
+ tools.push(TOOLS);
+ query.restrict(&mut tools, through);
+ let tool_row = tools.build().fetch_one(&mut *tx).await?;
+ let summary = Summary {
+ pending: Pending {
+ models: pending(&mut tx, &query, through, "model_usage", "started_at")
+ .await?,
+ tools: pending(
+ &mut tx,
+ &query,
+ through,
+ "tool_usage",
+ "json_extract(result, '$.startedAt')",
+ )
+ .await?,
+ },
+ models: read_models(&model_row)?,
+ tools: read_tools(&tool_row)?,
+ by_provider: groups(
+ &mut tx,
+ &query,
+ through,
+ MODELS,
+ "json_extract(quote_json, '$.providerId')",
+ )
+ .await?
+ .iter()
+ .map(|row| {
+ Ok(ProviderSummary {
+ provider_id: row.try_get("key")?,
+ totals: read_models(row)?,
+ })
+ })
+ .collect::<Result<_, StoreError>>()?,
+ by_model: groups(&mut tx, &query, through, MODELS, "model_id")
+ .await?
+ .iter()
+ .map(|row| {
+ Ok(ModelSummary {
+ model_id: row.try_get("key")?,
+ totals: read_models(row)?,
+ })
+ })
+ .collect::<Result<_, StoreError>>()?,
+ by_tool: groups(&mut tx, &query, through, TOOLS, "name")
+ .await?
+ .iter()
+ .map(|row| {
+ Ok(ToolSummary {
+ name: row.try_get("key")?,
+ totals: read_tools(row)?,
+ })
+ })
+ .collect::<Result<_, StoreError>>()?,
+ };
+ if serde_json::to_vec(&summary)?.len() > 48 * 1024 {
+ return Err(invalid(
+ "Usage summary exceeds response capacity; narrow the time range",
+ ));
+ }
+ tx.commit().await?;
+ Ok(Report { through, summary })
+ })
+ })
+ .await
+ }
+}
+
+async fn groups(
+ connection: &mut sqlx::SqliteConnection,
+ query: &Query,
+ through: u64,
+ columns: &'static str,
+ key: &'static str,
+) -> Result<Vec<SqliteRow>, StoreError> {
+ let mut sql = QueryBuilder::<Sqlite>::new("SELECT ");
+ sql.push(key).push(" AS key, ").push(columns);
+ query.restrict(&mut sql, through);
+ sql.push(" GROUP BY key ORDER BY calls DESC, key LIMIT 129");
+ let rows = sql.build().fetch_all(connection).await?;
+ if rows.len() > 128 {
+ return Err(invalid(
+ "Usage breakdown exceeds 128 groups; narrow the time range",
+ ));
+ }
+ Ok(rows)
+}
+
+async fn pending(
+ connection: &mut sqlx::SqliteConnection,
+ query: &Query,
+ through: u64,
+ table: &'static str,
+ started: &'static str,
+) -> Result<u64, StoreError> {
+ let mut sql = QueryBuilder::<Sqlite>::new("SELECT COUNT(*) AS calls FROM ");
+ sql.push(table)
+ .push(" WHERE ")
+ .push(started)
+ .push(" >= ")
+ .push_bind(query.from)
+ .push(" AND ")
+ .push(started)
+ .push(" <= ")
+ .push_bind(query.to)
+ .push(" AND sequence <= ")
+ .push_bind(through as i64)
+ .push(" AND (completed_sequence IS NULL OR completed_sequence > ")
+ .push_bind(through as i64)
+ .push(")");
+ if let Some(session) = &query.session_id {
+ sql.push(" AND session_id = ").push_bind(session.clone());
+ }
+ count(&sql.build().fetch_one(connection).await?, "calls")
+}
+
+const MODELS: &str = "COUNT(*) AS calls,
+ COALESCE(SUM(outcome = 'success'), 0) AS success,
+ COALESCE(SUM(outcome = 'error'), 0) AS error,
+ COALESCE(SUM(outcome = 'aborted'), 0) AS aborted,
+ COALESCE(SUM(outcome = 'unknown'), 0) AS unknown,
+ TOTAL(json_extract(usage, '$.input_tokens')) AS input,
+ COUNT(*) - COUNT(json_extract(usage, '$.input_tokens')) AS input_missing,
+ TOTAL(json_extract(usage, '$.output_tokens')) AS output,
+ COUNT(*) - COUNT(json_extract(usage, '$.output_tokens')) AS output_missing,
+ TOTAL(json_extract(usage, '$.cache_read_tokens')) AS cache_read,
+ COUNT(*) - COUNT(json_extract(usage, '$.cache_read_tokens')) AS cache_read_missing,
+ TOTAL(json_extract(usage, '$.cache_write_tokens')) AS cache_write,
+ COUNT(*) - COUNT(json_extract(usage, '$.cache_write_tokens')) AS cache_write_missing,
+ TOTAL(json_extract(usage, '$.reasoning_tokens')) AS reasoning,
+ COUNT(*) - COUNT(json_extract(usage, '$.reasoning_tokens')) AS reasoning_missing,
+ TOTAL(usd) AS usd,
+ COUNT(*) - COUNT(usd) AS unvalued,
+ COUNT(*) - COUNT(json_extract(quote_json, '$.pricing')) AS unpriced
+ FROM model_usage";
+
+const TOOLS: &str = "COUNT(*) AS calls,
+ COALESCE(SUM(json_extract(result, '$.outcome') = 'success'), 0) AS success,
+ COALESCE(SUM(json_extract(result, '$.outcome') = 'error'), 0) AS error,
+ COALESCE(SUM(json_extract(result, '$.outcome') = 'unknown'), 0) AS unknown,
+ COALESCE(SUM(json_extract(result, '$.kind') = 'rejected'), 0) AS rejected,
+ AVG(CASE WHEN json_extract(result, '$.outcome') IN ('success', 'error')
+ THEN MAX(completed_at - json_extract(result, '$.startedAt'), 0.0) END) AS latency
+ FROM tool_usage";
+
+fn read_models(row: &SqliteRow) -> Result<ModelTotals, StoreError> {
+ Ok(ModelTotals {
+ calls: count(row, "calls")?,
+ success: count(row, "success")?,
+ error: count(row, "error")?,
+ aborted: count(row, "aborted")?,
+ unknown: count(row, "unknown")?,
+ input: tokens(row, "input", "input_missing")?,
+ output: tokens(row, "output", "output_missing")?,
+ cache_read: tokens(row, "cache_read", "cache_read_missing")?,
+ cache_write: tokens(row, "cache_write", "cache_write_missing")?,
+ reasoning: tokens(row, "reasoning", "reasoning_missing")?,
+ cost: Cost {
+ known_usd: finite(row.try_get("usd")?)?,
+ unvalued: count(row, "unvalued")?,
+ unpriced: count(row, "unpriced")?,
+ },
+ })
+}
+fn read_tools(row: &SqliteRow) -> Result<ToolTotals, StoreError> {
+ Ok(ToolTotals {
+ calls: count(row, "calls")?,
+ success: count(row, "success")?,
+ error: count(row, "error")?,
+ unknown: count(row, "unknown")?,
+ rejected: count(row, "rejected")?,
+ mean_latency_ms: row
+ .try_get::<Option<f64>, _>("latency")?
+ .map(finite)
+ .transpose()?,
+ })
+}
+const MAX_NUMBER: u64 = (1 << 53) - 1;
+
+fn count(row: &SqliteRow, column: &str) -> Result<u64, StoreError> {
+ let value = crate::sequence_number(row.try_get(column)?)?;
+ if value > MAX_NUMBER {
+ return Err(invalid("Usage aggregate exceeds exact integer capacity"));
+ }
+ Ok(value)
+}
+fn tokens(row: &SqliteRow, value: &str, missing: &str) -> Result<Tokens, StoreError> {
+ // SQLite's TOTAL avoids signed-integer overflow on provider u64 counters.
+ // Only exact interoperable integer totals are exposed; overflow is not zero.
+ let known = finite(row.try_get(value)?)?;
+ if known > MAX_NUMBER as f64 || known.fract() != 0.0 {
+ return Err(invalid("Usage aggregate exceeds exact integer capacity"));
+ }
+ Ok(Tokens {
+ known: known as u64,
+ missing: count(row, missing)?,
+ })
+}
+fn finite(value: f64) -> Result<f64, StoreError> {
+ if !value.is_finite() || value < 0.0 {
+ return Err(invalid("Usage aggregate exceeds finite numeric capacity"));
+ }
+ Ok(value)
+}
diff --git a/crates/event-log/tests/tool_usage.rs b/crates/event-log/tests/tool_usage.rs
index 9ee7f32270..b7591eacf0 100644
--- a/crates/event-log/tests/tool_usage.rs
+++ b/crates/event-log/tests/tool_usage.rs
@@ -163,6 +163,22 @@ async fn tool_accounting_preserves_dispatch_truth_and_snapshot_without_private_b
);
let page = log.tool_attempts(query(), 0, 100).await.unwrap();
assert_eq!(page.total, 6);
+ let totals = log.usage_summary(query()).await.unwrap().summary.tools;
+ assert_eq!(
+ (
+ totals.calls,
+ totals.success,
+ totals.error,
+ totals.unknown,
+ totals.rejected
+ ),
+ (6, 1, 1, 2, 2)
+ );
+ assert_eq!(
+ totals.mean_latency_ms,
+ Some(3.875),
+ "refusals and unknown effects do not invent execution latency"
+ );
let find = |id: &str| {
page.attempts
.iter()
diff --git a/crates/event-log/tests/usage_paging.rs b/crates/event-log/tests/usage_paging.rs
index 4674bb5f0d..c3f8d0be9b 100644
--- a/crates/event-log/tests/usage_paging.rs
+++ b/crates/event-log/tests/usage_paging.rs
@@ -52,7 +52,7 @@ async fn accounting_pages_bound_bytes_without_dropping_records_or_reading_respon
log.append_batch(&[
event(Fact::ModelRequested {
step_id: format!("step-{i}"),
- model_id: "model".repeat(400),
+ model_id: format!("{i}-{}", "model".repeat(400)),
purpose: ModelPurpose::Main,
source_scope: LogScope::Session { id: "usage".into() },
source_high_water: 0,
@@ -124,6 +124,12 @@ async fn accounting_pages_bound_bytes_without_dropping_records_or_reading_respon
}
}
assert_eq!(seen.len(), 80);
+ assert!(
+ matches!(log.usage_summary(query).await,
+ Err(maka_event_log::StoreError::InvalidTransition(message))
+ if message.contains("response capacity")),
+ "oversized complete breakdowns fail rather than silently dropping groups"
+ );
log.close().await.unwrap();
}
diff --git a/crates/event-log/tests/usage_summary.rs b/crates/event-log/tests/usage_summary.rs
new file mode 100644
index 0000000000..16896eba33
--- /dev/null
+++ b/crates/event-log/tests/usage_summary.rs
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use maka_event_log::EventLog;
+use maka_runtime::{
+ accounting::Tokens,
+ event::{Fact, InvocationInput},
+ model::{ModelFinishReason, ModelStep, ModelUsage},
+ pricing::Quote,
+};
+use serde_json::json;
+#[path = "usage/fixture.rs"]
+mod fixture;
+use fixture::{event, query, request};
+
+#[tokio::test]
+async fn summary_keeps_missing_and_free_distinct_and_reuses_the_activity_fence() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("summary.sqlite");
+ let log = EventLog::open(&path).await.unwrap();
+ let empty = log.usage_summary(query()).await.unwrap().summary;
+ assert_eq!(empty.models.calls, 0);
+ assert_eq!(
+ empty.models.input,
+ Tokens {
+ known: 0,
+ missing: 0
+ }
+ );
+ assert_eq!(empty.tools.mean_latency_ms, None);
+ log.append(&event(
+ Fact::InvocationOpened {
+ configuration: None,
+ input: InvocationInput::Message {
+ content: "fixture".into(),
+ source_messages: vec![],
+ request_fingerprint: None,
+ },
+ },
+ 0,
+ ))
+ .await
+ .unwrap();
+ let priced: Quote = serde_json::from_value(json!({
+ "providerId":"fixture", "revision":1,
+ "pricing":{"modelKey":"fixture:model","inputUsdPer1M":1,"outputUsdPer1M":2}
+ }))
+ .unwrap();
+ let free: Quote = serde_json::from_value(json!({
+ "providerId":"fixture", "revision":2,
+ "pricing":{"modelKey":"fixture:model","inputUsdPer1M":0,"outputUsdPer1M":0}
+ }))
+ .unwrap();
+ for (id, quote, input, output) in [
+ ("free", Some(free), 1, Some(0)),
+ ("unpriced", None, 2, None),
+ ("partial", Some(priced.clone()), 3, None),
+ ] {
+ let mut admitted = request(id, 1000);
+ if let Some(quote) = quote {
+ admitted = admitted.with_quote(quote).unwrap();
+ }
+ log.append_batch(&[admitted, completed(id, input, output, 1250)])
+ .await
+ .unwrap();
+ }
+ log.append(&request("paid", 2000).with_quote(priced).unwrap())
+ .await
+ .unwrap();
+ let first = log.model_attempts(query(), 0, 100).await.unwrap();
+ let mut fixed = query();
+ fixed.through = Some(first.through);
+ log.append(&completed("paid", 1_000_000, Some(2_000_000), 2250))
+ .await
+ .unwrap();
+ let captured = log.usage_summary(fixed.clone()).await.unwrap();
+ assert_eq!(captured.through, first.through);
+ assert_eq!(captured.summary.models.calls, 3);
+ assert_eq!(captured.summary.pending.models, 1);
+ let current = log.usage_summary(query()).await.unwrap();
+ let models = ¤t.summary.models;
+ assert_eq!(current.summary.pending.models, 0);
+ assert_eq!(models.calls, 4);
+ assert_eq!(models.success, 4);
+ assert_eq!(
+ models.input,
+ Tokens {
+ known: 1_000_006,
+ missing: 0
+ }
+ );
+ assert_eq!(
+ models.output,
+ Tokens {
+ known: 2_000_000,
+ missing: 2
+ }
+ );
+ assert_eq!(
+ models.cache_read,
+ Tokens {
+ known: 0,
+ missing: 4
+ }
+ );
+ assert_eq!(models.cost.known_usd, 5.0);
+ assert_eq!(
+ models.cost.unvalued, 2,
+ "free is valued; incomplete usage is not"
+ );
+ assert_eq!(
+ models.cost.unpriced, 1,
+ "missing usage does not imply missing rates"
+ );
+ assert_eq!(current.summary.by_model.len(), 1);
+ assert_eq!(current.summary.by_model[0].totals, *models);
+ assert_eq!(current.summary.by_provider.len(), 2);
+ assert_eq!(
+ current.summary.by_provider[0].provider_id.as_deref(),
+ Some("fixture")
+ );
+ assert_eq!(current.summary.by_provider[0].totals.calls, 3);
+ assert_eq!(current.summary.by_provider[1].provider_id, None);
+ assert_eq!(current.summary.by_provider[1].totals.cost.unpriced, 1);
+ log.close().await.unwrap();
+ let log = EventLog::open(&path).await.unwrap();
+ assert_eq!(
+ log.usage_summary(query()).await.unwrap().summary,
+ current.summary
+ );
+ assert_eq!(
+ log.usage_summary(fixed.clone()).await.unwrap().summary,
+ captured.summary
+ );
+
+ log.append_batch(&[
+ request("overflow", 20000),
+ completed("overflow", u64::MAX, Some(0), 21000),
+ ])
+ .await
+ .unwrap();
+ assert!(matches!(log.usage_summary(query()).await,
+ Err(maka_event_log::StoreError::InvalidTransition(message))
+ if message.contains("exact integer capacity")));
+ assert_eq!(
+ log.usage_summary(fixed).await.unwrap().summary,
+ captured.summary,
+ "out-of-snapshot records cannot overflow this snapshot"
+ );
+ log.close().await.unwrap();
+}
+
+fn completed(
+ id: &str,
+ input: u64,
+ output: Option<u64>,
+ micros: u64,
+) -> maka_runtime::event::EventWrite {
+ event(
+ Fact::ModelCompleted {
+ step_id: id.into(),
+ output: ModelStep {
+ parts: vec![],
+ finish_reason: ModelFinishReason::Stop,
+ usage: ModelUsage {
+ input_tokens: Some(input),
+ output_tokens: output,
+ ..Default::default()
+ },
+ provider_options: None,
+ response_id: None,
+ model: None,
+ timestamp: None,
+ },
+ },
+ micros,
+ )
+}
diff --git a/crates/js-runtime/src/plugin/sdk.js b/crates/js-runtime/src/plugin/sdk.js
index a2eb622d44..a6e6c31ec4 100644
--- a/crates/js-runtime/src/plugin/sdk.js
+++ b/crates/js-runtime/src/plugin/sdk.js
@@ -302,7 +302,10 @@
...pricing,
update: (input) => host('pricing.update', { authority, input }),
}),
- usage: Object.freeze({ activity: (input) => host('usage.activity', { authority, input }) }),
+ usage: Object.freeze({
+ activity: (input) => host('usage.activity', { authority, input }),
+ summary: (input) => host('usage.summary', { authority, input }),
+ }),
sessions: Object.freeze({ list: (input = {}) => host('sessions.list', { authority, input }) }),
history: Object.freeze({
list: (input = {}) => host('history.list', { authority, input }),
diff --git a/crates/plugins/src/usage.rs b/crates/plugins/src/usage.rs
index 10bc27c982..f0820c2c77 100644
--- a/crates/plugins/src/usage.rs
+++ b/crates/plugins/src/usage.rs
@@ -23,7 +23,7 @@ use serde::{Deserialize, Serialize};
pub use maka_runtime::accounting::{
Activity, ActivityKind, ActivityStatus, AuxiliarySource, ModelAttempt, Origin, Outcome,
- Selection, ToolAttempt, ToolResult, ToolStatus,
+ Selection, Summary, ToolAttempt, ToolResult, ToolStatus,
};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -79,4 +79,6 @@ pub struct Page {
pub trait Usage: Send + Sync {
/// At most 100 rows / 48 KiB. Every continuation rechecks current authority.
fn activity(&self, call: Scope, input: Read) -> BoxFuture<'_, Result<Page, CommandError>>;
+ /// Headline totals for an activity cursor's range/scope/fence, not its list filters.
+ fn summary(&self, call: Scope, cursor: String) -> BoxFuture<'_, Result<Summary, CommandError>>;
}
diff --git a/crates/runtime-host/src/execution/plugins/usage.rs b/crates/runtime-host/src/execution/plugins/usage.rs
index 5030ab0ce1..b6b3c48d8f 100644
--- a/crates/runtime-host/src/execution/plugins/usage.rs
+++ b/crates/runtime-host/src/execution/plugins/usage.rs
@@ -22,7 +22,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use maka_plugins::{
authorization::{Boundary, Capability},
call::Scope,
- usage::{Filter, Page, Read},
+ usage::{Filter, Page, Read, Summary},
};
use serde::{Deserialize, Serialize};
@@ -72,6 +72,36 @@ fn invalid_cursor() -> Error {
}
impl Executions {
+ pub(crate) async fn plugin_usage_summary(
+ &self,
+ call: Scope,
+ cursor: String,
+ ) -> Result<Summary, Error> {
+ let cursor = Cursor::decode(&cursor, self.interactions.epoch())?;
+ self.check_usage_filter(&call, &cursor.filter).await?;
+ let report = self
+ .log
+ .usage_summary(maka_event_log::usage::Query {
+ from: cursor.filter.from,
+ to: cursor.filter.to,
+ session_id: cursor.filter.session_id.clone(),
+ through: Some(cursor.through),
+ })
+ .await
+ .map_err(usage_error)?;
+ self.check_usage_filter(&call, &cursor.filter).await?;
+ Ok(report.summary)
+ }
+
+ async fn check_usage_filter(&self, call: &Scope, filter: &Filter) -> Result<(), Error> {
+ let mut checked = filter.clone();
+ restrict(self.usage_boundary(call).await?, &mut checked)?;
+ if &checked != filter {
+ return Err(Error::Revoked);
+ }
+ Ok(())
+ }
+
async fn usage_boundary(&self, call: &Scope) -> Result<Boundary, Error> {
if call.identity.agent().is_some() {
self.plugin_execution_boundary(call).await
@@ -113,16 +143,9 @@ impl Executions {
100,
)
.await
- .map_err(|error| match error {
- maka_event_log::StoreError::InvalidTransition(message) => Error::Invalid(message),
- other => storage(other),
- })?;
+ .map_err(usage_error)?;
// Reading can yield to consent revocation or a Session boundary change.
- let mut checked = filter.clone();
- restrict(self.usage_boundary(&call).await?, &mut checked)?;
- if checked != filter {
- return Err(Error::Revoked);
- }
+ self.check_usage_filter(&call, &filter).await?;
if result.through > MAX_NUMBER || result.total > MAX_NUMBER || offset > result.total {
return Err(invalid_cursor());
}
@@ -174,3 +197,10 @@ fn restrict(boundary: Boundary, filter: &mut Filter) -> Result<(), Error> {
Boundary::Workspace { .. } | Boundary::Directory { .. } => Err(Error::Denied),
}
}
+
+fn usage_error(error: maka_event_log::StoreError) -> Error {
+ match error {
+ maka_event_log::StoreError::InvalidTransition(message) => Error::Invalid(message),
+ other => storage(other),
+ }
+}
diff --git a/crates/runtime-host/src/plugins/javascript/bridge.rs b/crates/runtime-host/src/plugins/javascript/bridge.rs
index a950dfbb06..38c65106be 100644
--- a/crates/runtime-host/src/plugins/javascript/bridge.rs
+++ b/crates/runtime-host/src/plugins/javascript/bridge.rs
@@ -309,6 +309,10 @@ impl State {
let call = self.calls.get(&input.authority)?;
encode(self.usage.activity(call, input.input).await?)
}
+ Request::UsageSummary(input) => {
+ let call = self.calls.get(&input.authority)?;
+ encode(self.usage.summary(call, input.input).await?)
+ }
Request::PricingQuery(input) => encode(self.pricing.query(input).await?),
Request::PricingUpdate(input) => {
let call = self.calls.get(&input.authority)?;
diff --git a/crates/runtime-host/src/plugins/javascript/bridge/wire.rs b/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
index 1e407a5b99..ae36786760 100644
--- a/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
+++ b/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
@@ -79,6 +79,8 @@ pub(super) enum Request {
HistoryRead(HistoryRead),
#[serde(rename = "usage.activity")]
UsageActivity(Authorized<maka_plugins::usage::Read>),
+ #[serde(rename = "usage.summary")]
+ UsageSummary(Authorized<String>),
#[serde(rename = "pricing.query")]
PricingQuery(maka_runtime::pricing::Query),
#[serde(rename = "pricing.update")]
diff --git a/crates/runtime-host/src/plugins/usage.rs b/crates/runtime-host/src/plugins/usage.rs
index 9b3505c5af..fe7c866730 100644
--- a/crates/runtime-host/src/plugins/usage.rs
+++ b/crates/runtime-host/src/plugins/usage.rs
@@ -22,10 +22,18 @@ use futures_util::future::BoxFuture;
use maka_plugins::{
call::Scope,
execution::CommandError,
- usage::{Page, Read, Usage},
+ usage::{Page, Read, Summary, Usage},
};
impl Usage for Effects {
+ fn summary(&self, call: Scope, cursor: String) -> BoxFuture<'_, Result<Summary, CommandError>> {
+ Box::pin(async move {
+ let _lease = self.owner.admit().map_err(|_| CommandError::Revoked)?;
+ let host = self.host.upgrade().ok_or(CommandError::Draining)?;
+ host.plugin_usage_summary(call, cursor).await
+ })
+ }
+
fn activity(&self, call: Scope, input: Read) -> BoxFuture<'_, Result<Page, CommandError>> {
Box::pin(async move {
let _lease = self.owner.admit().map_err(|_| CommandError::Revoked)?;
diff --git a/crates/runtime-host/tests/fixtures/background-plugin.mjs b/crates/runtime-host/tests/fixtures/background-plugin.mjs
index 8d4e40fe8a..cb655cfea9 100644
--- a/crates/runtime-host/tests/fixtures/background-plugin.mjs
+++ b/crates/runtime-host/tests/fixtures/background-plugin.mjs
@@ -49,8 +49,12 @@ export default async function (ctx) {
input.read
);
try {
- const page = await ctx.withAuthorization(input.grant, (call) => call.usage.activity(read));
- return JSON.parse(JSON.stringify({ page }));
+ const result = await ctx.withAuthorization(input.grant, async (call) => {
+ const page = await call.usage.activity(read);
+ const summary = await call.usage.summary(page.cursor);
+ return { page, summary };
+ });
+ return JSON.parse(JSON.stringify(result));
} catch (error) {
return { error: error.code };
}
diff --git a/crates/runtime-host/tests/fixtures/host-plugin.mjs b/crates/runtime-host/tests/fixtures/host-plugin.mjs
index cabf92a53e..f9525fd5b0 100644
--- a/crates/runtime-host/tests/fixtures/host-plugin.mjs
+++ b/crates/runtime-host/tests/fixtures/host-plugin.mjs
@@ -457,6 +457,13 @@ export default async function (ctx) {
)
)
throw new Error('Agent accounting lost usage or escaped its Session');
+ const summary = await call.usage.summary(usage.cursor);
+ if (
+ summary.models.calls === 0 ||
+ summary.models.input.known < 3 ||
+ summary.models.output.known < 5
+ )
+ throw new Error('Agent summary lost auxiliary model counters');
try {
await call.pricing.update({
expectedRevision: rates.revision,
diff --git a/crates/runtime-host/tests/integration/plugin_authorization/usage.rs b/crates/runtime-host/tests/integration/plugin_authorization/usage.rs
index 29a432f0cb..0c87686970 100644
--- a/crates/runtime-host/tests/integration/plugin_authorization/usage.rs
+++ b/crates/runtime-host/tests/integration/plugin_authorization/usage.rs
@@ -92,6 +92,10 @@ impl Probe {
)
.await;
assert_eq!(empty["page"]["total"], 0, "{empty}");
+ assert!(
+ empty["summary"]["models"]["calls"].as_u64().unwrap() > 0,
+ "activity filters must not erase headline usage: {empty}"
+ );
let repeated = read(
peer,
client,
diff --git a/crates/runtime/src/accounting.rs b/crates/runtime/src/accounting.rs
index d71cb6dcbd..db77489848 100644
--- a/crates/runtime/src/accounting.rs
+++ b/crates/runtime/src/accounting.rs
@@ -23,8 +23,13 @@ use crate::{context::ModelPurpose, event::Invocation, execution::ModelBinding, m
use serde::{Deserialize, Serialize};
use uuid::Uuid;
mod activity;
+mod summary;
mod tool;
pub use activity::{Activity, ActivityKind, ActivityStatus, Selection};
+pub use summary::{
+ Cost, ModelSummary, ModelTotals, Pending, ProviderSummary, Summary, Tokens, ToolSummary,
+ ToolTotals,
+};
pub use tool::{ToolAttempt, ToolResult, ToolStatus};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
diff --git a/crates/runtime/src/accounting/summary.rs b/crates/runtime/src/accounting/summary.rs
new file mode 100644
index 0000000000..aff2540258
--- /dev/null
+++ b/crates/runtime/src/accounting/summary.rs
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use serde::{Deserialize, Serialize};
+
+/// Sum of reported counters, qualified by calls that omitted this counter.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Tokens {
+ pub known: u64,
+ pub missing: u64,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Cost {
+ pub known_usd: f64,
+ /// Calls without a persisted valuation; includes unpriced calls.
+ pub unvalued: u64,
+ pub unpriced: u64,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ModelTotals {
+ pub calls: u64,
+ pub success: u64,
+ pub error: u64,
+ pub aborted: u64,
+ pub unknown: u64,
+ pub input: Tokens,
+ pub output: Tokens,
+ pub cache_read: Tokens,
+ pub cache_write: Tokens,
+ pub reasoning: Tokens,
+ pub cost: Cost,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ToolTotals {
+ /// Includes pre-dispatch refusals, which are counted separately below.
+ pub calls: u64,
+ pub success: u64,
+ pub error: u64,
+ pub unknown: u64,
+ pub rejected: u64,
+ /// Only known success/error settlements contribute to observed execution latency.
+ pub mean_latency_ms: Option<f64>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Summary {
+ pub models: ModelTotals,
+ pub tools: ToolTotals,
+ pub by_provider: Vec<ProviderSummary>,
+ pub by_model: Vec<ModelSummary>,
+ pub by_tool: Vec<ToolSummary>,
+ /// Unsettled admissions within the time range at this fence, not completed calls.
+ pub pending: Pending,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Pending {
+ pub models: u64,
+ pub tools: u64,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ProviderSummary {
+ /// Unknown identity is not inferred from a transport protocol or current settings.
+ pub provider_id: Option<String>,
+ pub totals: ModelTotals,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ModelSummary {
+ pub model_id: String,
+ pub totals: ModelTotals,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ToolSummary {
+ pub name: String,
+ pub totals: ToolTotals,
+}
diff --git a/docs/rust-parity.md b/docs/rust-parity.md
index b76447c01e..35bd045cba 100644
--- a/docs/rust-parity.md
+++ b/docs/rust-parity.md
@@ -89,7 +89,7 @@ implementations; wire adapters may retain existing client vocabulary.
| Goal | Query/arm/control, continuation, termination, budget and recovery semantics. | **Plugin + Host.** Goal policy owns subsequent submissions; Host enforces admitted hard limits and records usage. Retiring the plugin must close future submission admission. |
| Daily review / recap | Daily-review query/mutate, scheduled review and `session.recap.generate`. | **Plugin + Host.** Summarization/selection/output in plugins; reuse Scheduler and authorized history/model services. Host retains any canonical Session metadata commit. |
| External agents | Setup start/query/cancel; execution adapters, configuration, auth, conversation identity, adapter-specific attachments/interactions/resume/fork. | **Plugin + Host.** Implement concrete CLI/ACP adapters as Executor plugins over owned processes/HTTP. Generic Executor support is not a shipped adapter. Host owns authorization, cancellation and canonical external-event recording. |
-| Usage / Pricing | Physical Agent and auxiliary SDK accounting, frozen valuation, public Rust/JS scoped mixed model/tool activity paging, and shared native/plugin pricing query/CAS edits are implemented. Aggregates and Usage screens remain. | **Plugin + Host.** Reports and rebuildable projections may be an Insights domain; Host records usage independently of plugin availability and provides consistent reads. Missing usage must not become zero. |
+| Usage / Pricing | Physical Agent and auxiliary SDK accounting, frozen valuation, public Rust/JS scoped mixed model/tool activity paging, and shared native/plugin pricing query/CAS edits are implemented. Consistent summaries include complete bounded breakdowns and missing-data coverage; Usage screens remain. | **Plugin + Host.** Reports and rebuildable projections may be an Insights domain; Host records usage independently of plugin availability and provides consistent reads. Missing us [...]
| Background health | BackgroundTaskHealth process and endpoint checks. | **Plugin + Host.** Health interpretation and Tool in a plugin; Host exposes authorized resource observations and bounded probes. A stored PID is not resource ownership. |
| Session lineage | Public Rust/JS history copying and source reads, native branch/revision create/abandon, independent inherited pruning, Desktop canonical-input editing and complete durable drafts are implemented. Regeneration is removed; edits use revision and resend. | **Host.** One transactional lineage and workspace authority; plugins request changes through commands, not private lineage storage. |
| Session lifecycle | Native and public plugin removal/preview/receipt APIs, atomic family retirement and queued cancellation, restart cleanup and shared-worktree ownership are implemented. Unreferenced canonical-material reclamation and shared Session queries remain. | **Host.** Preserve referenced history and accepted receipts; unknown process cleanup must not delete its workspace. Shared queries require real collaboration authorization. |
@@ -112,7 +112,7 @@ Original TS plugins are not source-compatible with the new SDK.
| Skills: tool publication | Skill/SkillSearch are ordinary Contributions, without a package-name privilege. Per-step bindings capture handlers and supporting context together, after tool ceilings; physical retries retain the same snapshot. |
| WorkHub: precise execution commands | Typed commands carry stable operation IDs, exact targets and expected revisions. Correction freezes plugin intent before exact Host control/submission and atomically commits its business receipt; accepted work settles independently of plugin availability. Queue editing preserves the original submission proof. Plugins receive neither SQL transaction callbacks nor unrestricted execution handles. |
| WorkHub / Graph / Plan: selectable behavior | Open `BehaviorId` selects a typed Contribution; Graph/Swarm register independently. Host acceptance covers a non-builtin business. Preserve Session defaults and durable per-Turn choices; a requested unavailable behavior fails explicitly. Behavior preparation and input preparation are separate contracts, not one hook bus. |
-| Skills / Web / Recall / Insights: authorized services | Public history provides fixed-fence text paging and archived Session metadata to Rust and JS. Admitted Agent calls may read the trusted profile; Remote/background callers retain scoped history authorization. Public Usage reads expose scoped model/tool attempts and refusals without conversation bodies. Aggregates and reporting remain. Domain catalog/mutation APIs can be typed plugin Services rather than new kernel methods. |
+| Skills / Web / Recall / Insights: authorized services | Public history provides fixed-fence text paging and archived Session metadata to Rust and JS. Admitted Agent calls may read the trusted profile; Remote/background callers retain scoped history authorization. Public Usage reads expose scoped model/tool attempts and refusals without conversation bodies. Fixed-fence summaries and bounded breakdowns are available; reporting UI remains. Domain catalog/mutation APIs can be typed plugin [...]
| Skills / WorkHub / default behavior: business UI and prompt context | Published Clients own the actual Skills picker/management and WorkHub surface through Slots and Remote. Native adapters validate the originating Host and document; connection replacement revokes old Remote leases without replay. Prompt Contributions own business instructions. Inactive features remain visibly unavailable without blocking ordinary chat. |
| Other TS extension services | New SDK lacks equivalent public registrations/services for LSP routing, commands, Skills/Goals queries, shell environment contributions, Settings definitions, authorization flows and LLM adapter registration; questions/forms and source-input/attachment-copy contracts are public; permission approvals remain Host-owned. Implement domain registries as plugin services where possible, retaining Host authority for sensitive actions. `llm.generate` is not adapter [...]
diff --git a/docs/rust-parity.zh-CN.md b/docs/rust-parity.zh-CN.md
index 36995a15f6..6c696dadba 100644
--- a/docs/rust-parity.zh-CN.md
+++ b/docs/rust-parity.zh-CN.md
@@ -79,7 +79,7 @@ runtime 契约不能反向依赖插件实现,协议适配层可以保留现有
| Goal | 查询、arm、控制、续跑、终止、预算与恢复语义。 | **插件 + Host。** Goal 决定后续提交;Host 执行已准入的硬限制并记录用量。插件退休后不能继续提交。 |
| Daily review/recap | daily-review 查询/修改、定时复盘、`session.recap.generate`。 | **插件 + Host。** 选择、总结及输出由插件负责,复用 Scheduler 和授权历史/模型服务;规范 Session 元数据的提交仍归 Host。 |
| 外部 agent | setup start/query/cancel;具体执行适配、配置、鉴权、对话身份,以及附件/交互/resume/fork。 | **插件 + Host。** CLI/ACP 适配作为 Executor 插件,使用受管理进程/HTTP。已有 Executor 框架不等于已有具体 adapter。Host 负责授权、取消和外部事件落盘。 |
-| Usage/Pricing | 已实现 Agent 与辅助 SDK 的物理计量、冻结估价、公共 Rust/JS 作用域模型/工具混合活动分页,以及原生/插件共享的报价查询与 CAS 修改。聚合统计与 Usage 视图仍待接入。 | **插件 + Host。** 报表和可重建投影可归 Insights 领域;Host 不依赖插件存活来记录用量,并提供一致快照。缺失用量不能视为零。 |
+| Usage/Pricing | 已实现 Agent 与辅助 SDK 的物理计量、冻结估价、公共 Rust/JS 作用域模型/工具混合活动分页,以及原生/插件共享的报价查询与 CAS 修改。一致快照汇总包含有界完整分组与缺失数据覆盖率;Usage 视图仍待接入。 | **插件 + Host。** 报表和可重建投影可归 Insights 领域;Host 不依赖插件存活来记录用量,并提供一致快照。缺失用量不能视为零。 |
| 后台健康 | BackgroundTaskHealth 的进程和端点检查。 | **插件 + Host。** 插件解释健康状态并提供工具;Host 提供授权资源观察和有界探测。保存 PID 不等于拥有进程。 |
| Session 谱系 | 已实现公共 Rust/JS 历史复制和原始输入读取、原生分支/修订创建与放弃、继承历史独立裁剪、Desktop 规范输入编辑及完整持久草稿。已移除 regenerate,修改请求使用编辑重发。 | **Host。** 谱系及工作区只有一个事务权威;插件请求命令,不在私有存储中重做谱系。 |
| Session 生命周期 | 已实现原生与公共插件删除/预览/回执接口、原子家族退休及队列取消、重启清理和共享 worktree 所有权。无引用规范材料回收及 shared 查询仍待完成。 | **Host。** 保留被引用历史及已接受回执;进程清理不确定时不得删除工作目录。shared 查询需要真实协作授权。 |
@@ -101,7 +101,7 @@ runtime 契约不能反向依赖插件实现,协议适配层可以保留现有
| Skills:工具发布 | Skill/SkillSearch 是普通 Contribution,不享有包名特权。每步绑定在工具上限内共同捕获 handler 和支持上下文,物理重试保持原快照。 |
| WorkHub:精确执行命令 | 类型化命令携带稳定操作 ID、精确目标及预期 revision。纠正先冻结插件意图,再精确控制/提交 Host 工作,最后原子记录业务回执;已接受工作不依赖插件可用性继续结算。队列编辑保留原提交凭证。插件不获得 SQL 事务回调或无限制执行句柄。 |
| WorkHub/Graph/Plan:可选择的 behavior | 已用开放的 `BehaviorId` 选择类型化 Contribution,Graph/Swarm 独立注册;非内置业务已通过 Host 验收。保留 Session 默认值和持久单 Turn 选择;请求的 behavior 不可用时明确失败。behavior 准备与输入准备是独立契约,不合并为 hook 总线。 |
-| Skills/Web/Recall/Insights:授权服务 | Rust/JS 公共历史 API 提供固定水位文本分页及归档 Session 元数据。已准入 Agent 可读受信任 profile,Remote/后台调用保留相应范围的历史授权。公共 Usage 读取提供作用域内的模型/工具物理调用和派发前拒绝,不暴露对话正文;聚合与报表仍待完成。领域目录/修改接口可作为类型化插件 Service,不必成为内核方法。 |
+| Skills/Web/Recall/Insights:授权服务 | Rust/JS 公共历史 API 提供固定水位文本分页及归档 Session 元数据。已准入 Agent 可读受信任 profile,Remote/后台调用保留相应范围的历史授权。公共 Usage 读取提供作用域内的模型/工具物理调用和派发前拒绝,不暴露对话正文;固定快照汇总与有界分组已提供;报表界面仍待完成。领域目录/修改接口可作为类型化插件 Service,不必成为内核方法。 |
| Skills/WorkHub/默认行为:业务 UI 与 Prompt 上下文 | 发布的 Client 通过 Slot 和 Remote 拥有真实 Skills 选择器/管理页及 WorkHub 界面。原生适配验证原 Host 与 document;连接换代撤销旧 Remote 租约,不重放调用。Prompt Contribution 拥有业务指令。功能停用明确显示不可用,不阻塞普通聊天。 |
| 其余 TS 扩展服务 | 新 SDK 尚缺等价的公开 LSP 路由、Commands、Skills/Goals 查询、shell 环境变量 Contribution、Settings 定义、授权流程及 LLM adapter 注册;问题/表单、源输入与附件复制已有公共契约;权限审批仍归 Host。能由插件服务实现的领域注册放在插件侧,敏感行为权威仍归 Host。`llm.generate` 不等于 adapter 注册。 |
diff --git a/docs/rust-runtime.md b/docs/rust-runtime.md
index 55d1c62d60..fded74bb80 100644
--- a/docs/rust-runtime.md
+++ b/docs/rust-runtime.md
@@ -223,7 +223,9 @@ user/project content paths stay separate from private journals.
with reported usage and survive rejection, edits and recovery. Public Rust/JS Usage reads
recheck scoped authorization and return at most 100 rows / 48 KiB under a fixed settlement
fence, with one filtered activity page across model calls, tool effects and refusals.
- Continuation cursors expire on Host restart. Aggregates and Usage screens are not yet connected.
+ Continuation cursors expire on Host restart. Summaries share the activity fence, preserve missing-counter/
+ price coverage, and bound complete provider/model/tool breakdowns. Pending admissions remain separate.
+ Usage screens are not yet connected.
- Subscriptions deliver frames only after `subscription.ready`. Reconnection replays
active text from the committed log under backpressure; no copied transcript overlay.
- Model messages, content and tool outcomes are typed through provider projection.
diff --git a/docs/rust-runtime.zh-CN.md b/docs/rust-runtime.zh-CN.md
index 96fed7bc38..028be30a77 100644
--- a/docs/rust-runtime.zh-CN.md
+++ b/docs/rust-runtime.zh-CN.md
@@ -172,7 +172,9 @@ Host 不可连接不代表进程已停止。`host logs --root-id <rootId>` 返
Rust/JS 插件复用同一报价与修改路径;改价需要 profile 范围的明确授权,Agent 调用本身不授予该权限。
每次准入冻结公共提供商身份和报价,用量与估价一起提交;回复被拒绝、改价或恢复都不改写历史金额。
公共 Rust/JS Usage 读取逐次校验作用域授权,在固定结算快照下每页最多返回 100 条/48 KiB;
- 模型调用、工具执行和派发前拒绝共用筛选与活动分页。Host 重启使游标失效;聚合与 Usage 页面尚未接入。
+ 模型调用、工具执行和派发前拒绝共用筛选与活动分页。Host 重启使游标失效。
+ 汇总复用活动快照,保留缺失计数/报价覆盖率,并返回有界的完整提供商/模型/工具分组;待结算准入另列。
+ Usage 页面尚未接入。
- 模型消息、内容块与工具结果在 provider 投影中保持类型化;路由与发现共享类型化契约。
工具 JSON、schema 和厂商扩展保留开放结构。
- 订阅收到 `subscription.ready` 后才交付帧。重连按背压从已提交日志补发活动文本,
diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md
index e0c701ef13..718dc1f434 100644
--- a/packages/plugin-sdk/README.md
+++ b/packages/plugin-sdk/README.md
@@ -149,6 +149,8 @@ Activity entries are tagged `model` or `tool`. Optional `activity` filters selec
Each page contains at most 100 attempts / 48 KiB. `{ kind: 'continue', cursor }` re-reads that page; `nextCursor` advances under the same filter and settlement fence. Host restart invalidates cursors; every read checks current authorization.
+`call.usage.summary(cursor)` uses the same range, Session and fence, ignoring activity-only filters. Token and cost subtotals include missing-call coverage; unpriced calls differ from priced calls with incomplete usage. Provider/model/tool breakdowns are complete or fail explicitly (128 groups each, 48 KiB overall). Pending counts use admission time within the range and are excluded from completed totals. Nonfinite or inexact integer aggregates fail rather than becoming zero.
+
## Pricing
`ctx.pricing.query({ kind: 'start' })` reads the public rate catalog during activation. Continue with the returned revision and `nextOffset`; `revision_changed` requires a new scan. `call.pricing.update({ expectedRevision, mutation })` requires explicit profile `manage_pricing` consent. Edits share the native CAS and configuration notices, affect future admissions only, and finish after admission even if the caller stops waiting. A lost reply can yield `revision_conflict` on retry; query [...]
diff --git a/packages/plugin-sdk/README.zh-CN.md b/packages/plugin-sdk/README.zh-CN.md
index c5f0639f5b..a91c5c9832 100644
--- a/packages/plugin-sdk/README.zh-CN.md
+++ b/packages/plugin-sdk/README.zh-CN.md
@@ -153,6 +153,8 @@ Remote 回调可以抛出携带 `RemoteFailure.code` 的 `Error`。`outcome_unkn
每页最多 100 条/48 KiB。`{ kind: 'continue', cursor }` 重读该页,`nextCursor` 在相同筛选条件与结算快照下翻页。Host 重启使游标失效;每次读取都重新检查当前授权。
+`call.usage.summary(cursor)` 复用相同的范围、Session 和快照,忽略活动列表筛选。Token 和费用小计保留缺失调用数;未报价与已报价但用量不完整分别统计。提供商/模型/工具分组必须完整,否则明确报错(各最多 128 组,整体 48 KiB)。待结算数按范围内的准入时间统计,不计入已完成总额。非有限值或无法精确表示的整数会报错,不变成零。
+
## 报价
`ctx.pricing.query({ kind: 'start' })` 在激活期间即可读取公共报价。使用返回的 revision 与 `nextOffset` 继续分页,遇到 `revision_changed` 则重新读取。`call.pricing.update({ expectedRevision, mutation })` 需要 profile 范围的 `manage_pricing` 明确授权。修改复用原生 CAS 与配置通知,只影响后续准入;已接受的修改不会因调用者停止等待而中断。丢回复后重试可能返回 `revision_conflict`,应先查询再决定下一次修改。
diff --git a/packages/plugin-sdk/src/usage.ts b/packages/plugin-sdk/src/usage.ts
index 25f6c4915f..a97cd273a9 100644
--- a/packages/plugin-sdk/src/usage.ts
+++ b/packages/plugin-sdk/src/usage.ts
@@ -112,4 +112,43 @@ export interface Usage {
* with a profile or Session target. No conversation bodies are exposed.
*/
activity(input: UsageRead): Promise<UsagePage>;
+ /** Uses the activity cursor's scope, time range and fence, ignoring list filters.
+ * Known subtotals retain missing-call coverage; a zero estimate is not missing.
+ */
+ summary(cursor: string): Promise<UsageSummary>;
+}
+
+export interface UsageTokens {
+ known: number;
+ missing: number;
+}
+export interface UsageSummary {
+ /** Unsettled admissions within the time range at this fence, excluded from completed totals. */
+ pending: { models: number; tools: number };
+ /** Complete breakdowns, at most 128 groups each / 48 KiB overall; overflow fails explicitly. */
+ byProvider: readonly { providerId: string | null; totals: UsageSummary['models'] }[];
+ byModel: readonly { modelId: string; totals: UsageSummary['models'] }[];
+ byTool: readonly { name: string; totals: UsageSummary['tools'] }[];
+ models: {
+ calls: number;
+ success: number;
+ error: number;
+ aborted: number;
+ unknown: number;
+ input: UsageTokens;
+ output: UsageTokens;
+ cacheRead: UsageTokens;
+ cacheWrite: UsageTokens;
+ reasoning: UsageTokens;
+ cost: { knownUsd: number; unvalued: number; unpriced: number };
+ };
+ tools: {
+ calls: number;
+ success: number;
+ error: number;
+ unknown: number;
+ rejected: number;
+ /** Only known success/error settlements contribute to latency. */
+ meanLatencyMs: number | null;
+ };
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org