+ <>
+
+ {/* pt-3 给 y 轴最上方的 max 刻度留出上溢空间(-translate-y-1/2 会探出容器半行),避免与汇总行重叠。 */}
+
{[0, 1, 2, 3].map((step) => (
-
+
+ {axisFmt((max * step) / 3)}
+
))}
-
- {points.map((point) => (
+
+
+
setHover(null)}
+ >
+ {[0, 1, 2, 3].map((step) => (
+ key={step}
+ className={step === 0 ? styles.gridLine : `${styles.gridLine} ${styles.gridLineDashed}`}
+ style={{ bottom: `${(step * 100) / 3}%` }}
+ />
+ ))}
+
+ {buckets.map((bucket, index) => (
+ key={bucket.key}
+ className={hover?.index === index ? `${styles.barSlot} ${styles.slotHover}` : styles.barSlot}
+ >
+ {bucket.bars.map((bar) => (
+
+ ))}
+
+ ))}
+
+ {hover && hoveredBucket ? (
+
+
{hoveredBucket.label}
+ {hoveredBucket.bars.map((bar) => (
+
+
+ {bar.meta.label}
+
+ {bar.unknown ? "未知" : `${fmtFor(bar.meta)(bar.value)}${bar.meta.unit}`}
+
+
+ ))}
+ ) : null}
+
+
+ {primary.points.map((point) => (
+
+ {granularity === "hour" && Number(point.key.slice(11, 13)) % 4 !== 0
+ ? ""
+ : bucketLabel(granularity, point.key)}
+
))}
-
- {points.map((point) => (
-
- {shortDay(point.day)}
+
+ {series.length > 1 ? (
+
+ {series.map((s) => (
+
+
+ {s.meta.label}
+ {s.meta.legendHint ? `(${s.meta.legendHint})` : ""}
))}
-
-
+ ) : null}
+ >
+ );
+}
+
+/** 图表区:Token 消耗视图为总 Token + 缓存 Token 同桶双柱,其余指标单柱。 */
+function TrendChartArea({ metric, trend, currentKey }: { metric: TrendMetric; trend: UsageTrend; currentKey: string }) {
+ if (metric !== "tokens") {
+ return (
+
+ );
+ }
+ return (
+
);
}
-/** 模版用量逐日趋势卡:柱状图展示每日 Token 消耗与运行时长;数据来自限额账本条目逐日账(启用后开始记录)。
- * templateId 缺省为「全部」视角(全部模版条目求和),由服务端零值补全到今天(UTC 日键)。 */
-export function TemplateUsageTrendCard({ templateId }: { templateId?: string }) {
+/** 区间合计:未知指标(null)不按 0 计入,单独标 unknown 供「含未知」标记(P2-7)。 */
+function sumTotals(
+ points: UsageTrendPoint[],
+ read: (total: UsageTrendPoint["usage"]["total"]) => number | null,
+): { value: number; unknown: boolean } {
+ let value = 0;
+ let unknown = false;
+ for (const point of points) {
+ const metric = read(point.usage.total);
+ if (metric === null) unknown = true;
+ else value += metric;
+ }
+ return { value, unknown };
+}
+
+/** 区间五项合计:未知来源不按 0 计入并单独标记(P2-7);read 语义与图表 pick 共用,避免图表与合计口径漂移。 */
+function trendTotals(trend: UsageTrend) {
+ return {
+ tokens: sumTotals(trend.points, TREND_METRICS.tokens.pick),
+ cache: sumTotals(trend.points, CACHE_TOKEN_META.pick),
+ calls: sumTotals(trend.points, TREND_METRICS.calls.pick),
+ failures: sumTotals(trend.points, TREND_METRICS.failures.pick),
+ runtime: sumTotals(trend.points, TREND_METRICS.runtime.pick),
+ };
+}
+
+/** 「全部」口径部分成功提示:coverage 仅在部分模版绑定智能体查询失败时出现。 */
+function TrendCoverageNote({ trend }: { trend: UsageTrend }) {
+ if (!trend.coverage || trend.coverage.complete) return null;
+ return (
+
+ 部分智能体数据缺失({trend.coverage.missing_agent_ids.join("、")}),以下合计不含其用量。
+
+ );
+}
+
+/** 趋势卡内容:coverage 提示 + 五项合计(未知来源标「含未知」)+ 图表 + 统计周期脚注。 */
+function TrendContent({ trend, metric, currentKey }: { trend: UsageTrend; metric: TrendMetric; currentKey: string }) {
+ const totals = trendTotals(trend);
+ const hasUsage =
+ totals.tokens.value || totals.cache.value || totals.calls.value || totals.failures.value || totals.runtime.value;
+ return (
+ <>
+
+
+
+
+
+
+
+
+ {hasUsage ? (
+
+ ) : (
+
统计区间内暂无用量记录
+ )}
+
+ 统计周期:
+ {bucketLabel(trend.granularity, bucketKey(trend.granularity, Date.parse(trend.query_range.start_time)))}
+ {" – "}
+ {bucketLabel(trend.granularity, bucketKey(trend.granularity, Date.parse(trend.query_range.end_time) - 1))}
+ {trend.data_updated_at
+ ? ` · 数据更新于 ${new Date(trend.data_updated_at).toLocaleString("zh-CN", { hour12: false })}`
+ : " · 暂无用量数据"}
+
+ >
+ );
+}
+
+/** 模版用量趋势卡:数据来自 Provider 用量趋势(usage.trend,服务端聚合全部分页,UTC+8 对齐分桶)。
+ * 统计时间来自面板顶部选择器(range 毫秒);粒度按区间跨度隐含(≤24h 小时桶、≤120 天天桶、更长月桶)。
+ * agentId 缺省为「全部」视角:服务端逐模版绑定智能体(含已删模版)以 agent 维度查询并求和,非模版智能体不计入。 */
+export function TemplateUsageTrendCard({
+ agentId,
+ range,
+}: {
+ agentId?: string;
+ range: { start: number; end: number };
+}) {
const client = useMemo(getAdminClient, []);
- const [days, setDays] = useState<7 | 14 | 28>(7);
const [metric, setMetric] = useState
("tokens");
- const query = useAdminQuery(`usage:template-trend:${templateId ?? "all"}:${days}`, (signal) =>
- client.usage.templateTrend({ ...(templateId ? { templateId } : {}), days }, signal),
+ const granularity = granularityOf(range.end - range.start);
+ const query = useAdminQuery(`usage:trend:${agentId ?? "templates"}:${range.start}:${range.end}`, (signal) =>
+ client.usage.trend(
+ { ...(agentId ? { agentId } : {}), startTime: range.start, endTime: range.end, granularity },
+ signal,
+ ),
);
const loading = query.loading || (!query.data && !query.error);
const trend = query.data;
- const points = trend?.data ?? [];
return (
@@ -119,17 +488,6 @@ export function TemplateUsageTrendCard({ templateId }: { templateId?: string })
-
{loading ? (
@@ -139,28 +497,7 @@ export function TemplateUsageTrendCard({ templateId }: { templateId?: string })
) : null}
{query.error ? void query.refresh()} /> : null}
{!loading && !query.error && trend ? (
- <>
-
- sum + point.tokens, 0)}
- />
- sum + point.active_seconds, 0)}
- unit="秒"
- />
-
- {points.some((point) => point[metric] > 0) ? (
-
- ) : (
- 统计区间内暂无逐日用量记录
- )}
-
- 统计周期:{shortDay(trend.from_day)} – {shortDay(trend.to_day)} · 逐日数值按限额账本增量统计
- {trend.since_day ? `,自 ${trend.since_day} 起记录,不含更早历史` : ",暂无记录"}
-
- >
+
) : null}
);
diff --git a/apps/console/src/features/usage/usage-limit-panels.tsx b/apps/console/src/features/usage/usage-limit-panels.tsx
index 5c26c6b..cfb5a27 100644
--- a/apps/console/src/features/usage/usage-limit-panels.tsx
+++ b/apps/console/src/features/usage/usage-limit-panels.tsx
@@ -1,5 +1,6 @@
+import { ReloadOutlined } from "@ant-design/icons";
import type { UsageLimitDayState, UsageLimitMetricState } from "@openagentkit/sdk/protocol";
-import { Button, Result } from "antd";
+import { Button, Popover, Progress, Result, Tag, Tooltip } from "antd";
import { useMemo, useState } from "react";
import { type AdminClient, createAdminClient } from "../../lib/admin/index.ts";
import { useAdminQuery } from "../../lib/admin/use-admin-query.ts";
@@ -217,7 +218,168 @@ function PeriodUsageStatus({
);
}
-/** 月度/日度限额统计与累计 Session 快照分别展示,不受 Agent 明细筛选影响。 */
+/** 限额进度行:名称 + 进度条(未设置上限时留空)+ 已用/上限数字;90% 起警示、100% 标红。 */
+function LimitMetricRow({
+ label,
+ sub,
+ unit,
+ metric,
+ limitText,
+}: {
+ label: string;
+ sub: string;
+ unit: string;
+ metric: UsageLimitMetricState;
+ /** 日维度跟随月度时的覆盖文案;缺省按 metric 自身展示。 */
+ limitText?: string;
+}) {
+ const usedText = metric.used === null ? "待确认" : metric.used.toLocaleString("zh-CN");
+ const capText = limitText ?? (metric.limit === null ? "不限量" : metric.limit.toLocaleString("zh-CN"));
+ const ratio = metric.used !== null && metric.limit !== null && metric.limit > 0 ? metric.used / metric.limit : null;
+ const percent = ratio === null ? null : Math.min(100, Math.round(ratio * 1000) / 10);
+ const strokeColor =
+ ratio !== null && ratio >= 1
+ ? "var(--ant-color-error)"
+ : ratio !== null && ratio >= 0.9
+ ? "var(--ant-color-warning)"
+ : undefined;
+ return (
+
+
+ {label}
+ {sub}
+
+ {percent !== null ? (
+
+ ) : (
+
+ )}
+
+ 已用 {usedText}
+ {unit === "秒" ? " 秒" : ""} / {capText}
+
+
+ );
+}
+
+type MemberUsageLimitView = Awaited>;
+
+/** 紧凑卡头部:标题 + 作用域 tag + 口径说明 + 周期切换/设置/刷新操作。 */
+function LimitCardHead({
+ current,
+ period,
+ onPeriodChange,
+ canWrite,
+ editing,
+ onEdit,
+ refreshDisabled,
+ refreshing,
+ onRefresh,
+}: {
+ current: MemberUsageLimitView | null;
+ period: LimitPeriod;
+ onPeriodChange: (period: LimitPeriod) => void;
+ canWrite: boolean;
+ editing: boolean;
+ onEdit: () => void;
+ refreshDisabled: boolean;
+ refreshing: boolean;
+ onRefresh: () => void;
+}) {
+ return (
+
+
限额设置
+ {current &&
{current.override ? "个人限额" : "跟随默认限额"}}
+
全部 Agent 合计,不随上方 Agent 筛选变化
+
+ {current && }
+ {canWrite && current && !editing && (
+
+ )}
+
+ }
+ loading={refreshing}
+ disabled={refreshDisabled}
+ onClick={onRefresh}
+ />
+
+
+
+ );
+}
+
+/** 当前周期的限额进度区:两行进度 + 元信息(周期/重置/计量/更新 + 规则说明弹层)+ 超限警示。 */
+function LimitOverview({ current, period }: { current: MemberUsageLimitView; period: LimitPeriod }) {
+ const active =
+ period === "month"
+ ? { key: current.month, resetAt: current.reset_at, tokens: current.tokens, seconds: current.active_seconds }
+ : {
+ key: current.day_state.day,
+ resetAt: current.day_state.reset_at,
+ tokens: current.day_state.tokens,
+ seconds: current.day_state.active_seconds,
+ };
+ const fallbackFor = (dayLimit: number | null, monthLimit: number | null, unit: string) =>
+ period === "day" ? dayFallbackText(dayLimit, monthLimit, unit) : undefined;
+ return (
+ <>
+
+
+
+
+
+ {active.key}(UTC {period === "month" ? "月" : "日"}) · 下次重置 {timeText(active.resetAt)} UTC · 计量启用{" "}
+ {timeText(current.accounting_started_at)} · 最近更新 {timeText(current.refreshed_at)} UTC
+ {usageLimitNotice}} title="限额规则" trigger="click">
+
+
+
+ {(active.tokens.status !== "ok" || active.seconds.status !== "ok") && (
+
+ {active.tokens.status !== "ok" && (
+
+ Token {statusLabels[active.tokens.status]}
+
+ )}
+ {active.seconds.status !== "ok" && (
+
+ 运行时长 {statusLabels[active.seconds.status]}
+
+ )}
+
+ )}
+ >
+ );
+}
+
+/** 月度/日度限额紧凑卡:头部 + 进度条行 + 元信息,编辑器就地展开。 */
export function MemberUsageLimits({
memberId,
initiallyEditing = false,
@@ -241,63 +403,42 @@ export function MemberUsageLimits({
});
const current = view.data;
return (
-
-
- {usageLimitNotice}
+
+ setEditing(true)}
+ refreshDisabled={!canRead || editing}
+ refreshing={view.loading && !current}
+ onRefresh={() => void view.refresh()}
+ />
{(identity.loading || view.loading) && !current && 正在加载限额…
}
{identity.error && void identity.refresh()} />}
{view.error && void view.refresh()} />}
- {current && (
+ {current && }
+ {editing && canWrite && current && (
<>
-
-
- 计量启用(UTC):{timeText(current.accounting_started_at)};最近更新(UTC):
- {timeText(current.refreshed_at)}。 此处汇总该成员所有 Agent,不随下方 Agent 筛选变化。
-
- {editing && canWrite && (
- <>
- {policy.error && (
- void policy.refresh()} />
- )}
- {
- await client.members.setUsageLimit(memberId, limits);
- await view.refresh();
- }}
- onReset={async () => {
- await client.members.resetUsageLimit(memberId);
- await view.refresh();
- }}
- onClose={() => setEditing(false)}
- />
- >
+ {policy.error && (
+ void policy.refresh()} />
)}
+ {
+ await client.members.setUsageLimit(memberId, limits);
+ await view.refresh();
+ }}
+ onReset={async () => {
+ await client.members.resetUsageLimit(memberId);
+ await view.refresh();
+ }}
+ onClose={() => setEditing(false)}
+ />
>
)}
{identity.data?.role === "auditor" && 当前身份只读。
}
diff --git a/apps/console/src/features/usage/usage.module.less b/apps/console/src/features/usage/usage.module.less
index a7bcea8..0842a69 100644
--- a/apps/console/src/features/usage/usage.module.less
+++ b/apps/console/src/features/usage/usage.module.less
@@ -11,11 +11,6 @@
min-width: 0;
}
-/* flex column 容器默认 stretch 会把 Segmented 轨道拉满整行,恢复内容自适应宽度 */
-.viewToggle {
- align-self: flex-start;
-}
-
.pageTitle {
font-size: 18px;
font-weight: 600;
@@ -37,7 +32,6 @@
display: flex;
flex-wrap: wrap;
align-items: center;
- justify-content: space-between;
gap: 12px;
}
@@ -60,9 +54,29 @@ input.searchInput {
flex-shrink: 0;
}
-.pickerWrap {
- min-width: 0;
- flex: 1 1 0%;
+.pickerInline {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ color: var(--ant-color-text-secondary);
+}
+
+.inlineLabel {
+ flex: none;
+}
+
+.pickerControl {
+ width: 240px;
+
+ :global(.ant-form-item) {
+ margin-bottom: 0;
+ }
+}
+
+/* 刷新按钮右锚定:space-between 会把行内多个控件散开,改用 auto 边距 */
+.controlsRefresh {
+ margin-inline-start: auto;
}
/* 表格单元格 */
@@ -128,6 +142,15 @@ input.searchInput {
gap: 16px;
}
+/* 口径说明(弹层入口)靠左,统计时间区间靠右 */
+.rangeRow {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
.telemetrySection {
display: flex;
flex-direction: column;
@@ -289,10 +312,6 @@ input.searchInput {
gap: 8px;
}
-.datePicker {
- width: 208px;
-}
-
.selectName {
width: 176px;
}
@@ -333,10 +352,6 @@ input.searchInput {
gap: 8px;
}
-.daysSelect {
- width: 112px;
-}
-
.loadingText {
font-size: 13px;
color: var(--kit-fg-muted);
@@ -362,6 +377,14 @@ input.searchInput {
color: var(--kit-fg-muted);
}
+/* 合计含未知来源的小标记:弱化展示,悬停出说明 */
+.unknownMark {
+ margin-left: 4px;
+ font-weight: 400;
+ color: var(--kit-fg-muted);
+ cursor: help;
+}
+
.totalValue {
margin-top: 4px;
font-weight: 600;
@@ -432,6 +455,7 @@ input.searchInput {
.barSlot {
display: flex;
+ gap: 2px;
height: 100%;
min-width: 0;
flex: 1 1 0%;
@@ -447,16 +471,32 @@ input.searchInput {
transition: height var(--kit-duration-base) var(--kit-ease-out);
}
-.barToday {
+.barAccentToday {
background: var(--kit-accent);
}
/* 历史日期柱:同色半透明弱调 */
-.barPast {
+.barAccentPast {
background: var(--kit-accent);
opacity: 0.3;
}
+.barSecondaryToday {
+ background: var(--kit-success);
+}
+
+.barSecondaryPast {
+ background: var(--kit-success);
+ opacity: 0.3;
+}
+
+/* 未知桶(协议 null 表示来源未知):不按 0 绘制,基线处出短横标记 */
+.barUnknown {
+ height: 2px;
+ background: var(--kit-fg-muted);
+ opacity: 0.5;
+}
+
.chartXAxis {
display: flex;
justify-content: space-around;
@@ -476,6 +516,38 @@ input.searchInput {
text-align: center;
}
+/* 双系列图例(Token 消耗 = 总 Token + 缓存 Token),居中显示在图表下方 */
+.chartLegend {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 4px 16px;
+ margin-top: 8px;
+ font-size: 13px;
+ color: var(--kit-fg-muted);
+}
+
+.legendItem {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.legendAccent,
+.legendSecondary {
+ width: 10px;
+ height: 10px;
+ border-radius: 2px;
+}
+
+.legendAccent {
+ background: var(--kit-accent);
+}
+
+.legendSecondary {
+ background: var(--kit-success);
+}
+
.emptyChart {
padding-block: 32px;
font-size: 13px;
@@ -488,6 +560,66 @@ input.searchInput {
color: var(--kit-fg-muted);
}
+/* 悬停列高亮带:跟随鼠标 tooltip 定位的当前列背景,覆盖整个绘图区高度 */
+.slotHover {
+ border-radius: 4px;
+ background: var(--ant-color-fill-tertiary);
+}
+
+/* 跟随鼠标的列级 tooltip:白卡贴边浮层,data-flip 翻转避免溢出绘图区;入场消费冻结 overlay token */
+.chartTip {
+ position: absolute;
+ z-index: 10;
+ pointer-events: none;
+ min-width: 136px;
+ border: 1px solid var(--ant-color-border);
+ border-radius: 8px;
+ background: #fff;
+ box-shadow: var(--ant-box-shadow-secondary);
+ padding: 8px 10px;
+ animation: var(--kit-animate-overlay-in);
+}
+
+.chartTip[data-flip="right"] {
+ transform: translate(12px, -50%);
+}
+
+.chartTip[data-flip="left"] {
+ transform: translate(calc(-100% - 12px), -50%);
+}
+
+.chartTipTitle {
+ margin: 0 0 4px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--ant-color-text);
+}
+
+.chartTipRow {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 2px 0 0;
+ font-size: 12px;
+ color: var(--ant-color-text-secondary);
+}
+
+.chartTipDot {
+ flex-shrink: 0;
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+}
+
+.chartTipLabel {
+ flex: 1 1 0%;
+}
+
+.chartTipValue {
+ font-variant-numeric: tabular-nums;
+ color: var(--ant-color-text);
+}
+
/* ============ 用量限额编辑器(usage-limit-editor) ============ */
.editorRoot {
@@ -645,13 +777,108 @@ input.searchInput {
grid-template-columns: 1fr;
}
-/* ============ 响应式(sm 640 / md 768 / xl 1280) ============ */
+/* ============ 成员限额紧凑卡(member-usage-page) ============ */
-@media (min-width: 640px) {
- .pickerWrap {
- max-width: 384px;
+/* 灰底圆角卡:头部(标题 + 作用域 + 周期 + 操作)+ 进度条行 + 元信息,规则说明收进弹层 */
+.limitCard {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ border: 1px solid var(--ant-color-border);
+ border-radius: var(--kit-radius);
+ background: var(--kit-bg-subtle);
+ padding: 16px;
+}
+
+.limitCardHead {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 12px;
+}
+
+.limitCardActions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ margin-inline-start: auto;
+}
+
+.limitRows {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+/* 移动端纵排(名称 / 进度条 / 数字各占一行),md 768 起三列一行 */
+.limitRow {
+ display: grid;
+ gap: 8px;
+}
+
+.limitName {
+ font-size: 14px;
+ font-weight: 500;
+}
+
+.limitNameSub {
+ display: block;
+ font-weight: 400;
+ font-size: 12px;
+ color: var(--ant-color-text-secondary);
+}
+
+.limitBar {
+ margin: 0;
+}
+
+.limitFig {
+ font-size: 14px;
+ font-variant-numeric: tabular-nums;
+}
+
+.limitMeta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 8px;
+ font-size: 12px;
+ color: var(--ant-color-text-secondary);
+ font-variant-numeric: tabular-nums;
+}
+
+/* 弹层文字入口(口径说明 / 规则说明):行内小链接按钮 */
+.popLink {
+ padding: 0;
+ border: none;
+ background: none;
+ font-size: 12px;
+ color: var(--ant-color-primary);
+ cursor: pointer;
+}
+
+.limitStatuses {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+@media (min-width: 768px) {
+ .limitRow {
+ grid-template-columns: 200px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 16px;
+ }
+
+ .limitFig {
+ text-align: right;
}
+}
+/* ============ 响应式(sm 640 / md 768 / xl 1280) ============ */
+
+@media (min-width: 640px) {
.statGrid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
diff --git a/apps/console/src/lib/admin/client.ts b/apps/console/src/lib/admin/client.ts
index 85fa785..65b4875 100644
--- a/apps/console/src/lib/admin/client.ts
+++ b/apps/console/src/lib/admin/client.ts
@@ -28,7 +28,6 @@ import {
type MemberUsageLimitView,
type MemberUsageSummary,
type MemberView,
- type ModelUsagePage,
type OperationView,
OperationViewSchema,
type PlanResponse,
@@ -82,16 +81,17 @@ import {
type TemplateUpdateInput,
type TemplateUsageLimitView,
type TemplateUsageRow,
- type TemplateUsageTrend,
type TemplateVersionsPage,
type TemplateVersionsQuery,
type TemplateVersionView,
type TemplateView,
type ToolApprovalDecision,
type ToolApprovalsResponse,
- type ToolUsagePage,
+ type UsageGranularity,
type UsageLimitConfig,
type UsageLimitPolicy,
+ type UsageSummary,
+ type UsageTrend,
} from "@openagentkit/sdk/protocol";
import type { StreamSessionOptions, ThreadQueryOptions } from "@openagentkit/sdk/providers";
import { streamProtocolFrames } from "@openagentkit/sdk/providers/kit";
@@ -99,27 +99,15 @@ import { createRequest, type RequestClient, type RequestOptions } from "@openage
export type AdminClientOptions = RequestOptions | { request: RequestClient };
-/** Provider 侧用量明细的公共筛选;workspace 由服务端注入,前端不传。 */
+/** Provider 侧用量汇总的筛选;维度由服务端按 session_id / agent_id 推导,前端只传窗口。 */
export interface UsageTelemetryQuery {
- /** 传 session_id 时按会话口径查询(scope=session,忽略时间区间与 agent_id)。 */
+ /** 传 session_id 时按会话维度查询(dimension=session,忽略时间区间与 agent_id)。 */
session_id?: string;
- /** 毫秒时间戳;缺省为最近 7 天(session 口径下不传)。 */
+ /** 毫秒时间戳;缺省为最近 7 天(session 维度下不传)。 */
start_time?: number;
end_time?: number;
agent_id?: string;
- page_no?: number;
- page_size?: number;
- sort_order?: "asc" | "desc";
}
-export type ModelUsageQuery = UsageTelemetryQuery & {
- model_name?: string;
- sort_by?: "call_count" | "failed_count" | "input_tokens" | "output_tokens";
-};
-export type ToolUsageQuery = UsageTelemetryQuery & {
- source?: "builtin" | "mcp" | "custom";
- tool_name?: string;
- sort_by?: "call_count" | "failed_count";
-};
export interface DeclarationWrite {
base_revision: string;
@@ -159,10 +147,8 @@ export function createAdminClient(options: AdminClientOptions) {
}
const groupPath = (id: string) => `/api/admin/groups/${encodeURIComponent(id)}`;
const memberGroupsPath = (id: string) => `/api/admin/members/${encodeURIComponent(id)}/groups`;
- /** 用量明细 query 全量字段非空即拼;布尔外的值统一 String 化。 */
- function usageTelemetryQuery(
- query: UsageTelemetryQuery & { model_name?: string; source?: string; tool_name?: string; sort_by?: string },
- ) {
+ /** 用量汇总 query 全量字段非空即拼;布尔外的值统一 String 化。 */
+ function usageTelemetryQuery(query: UsageTelemetryQuery) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query)) {
if (value !== undefined && value !== "") params.set(key, String(value));
@@ -358,12 +344,9 @@ export function createAdminClient(options: AdminClientOptions) {
setPolicy: (limits: UsageLimitConfig) => write("/api/admin/usage-limits/policy", "PUT", limits),
},
usage: {
- /** Provider 侧模型用量明细(workspace scope 由服务端注入);默认统计最近 7 天。 */
- modelUsage: (query: ModelUsageQuery = {}, signal?: AbortSignal) =>
- get(`/api/admin/usage/model-usage${usageTelemetryQuery(query)}`, signal),
- /** Provider 侧工具调用明细(workspace scope 由服务端注入);默认统计最近 7 天。 */
- toolUsage: (query: ToolUsageQuery = {}, signal?: AbortSignal) =>
- get(`/api/admin/usage/tool-usage${usageTelemetryQuery(query)}`, signal),
+ /** Provider 侧用量汇总(模型与工具明细同一次响应);默认统计最近 7 天。 */
+ summary: (query: UsageTelemetryQuery = {}, signal?: AbortSignal) =>
+ get(`/api/admin/usage/summary${usageTelemetryQuery(query)}`, signal),
/** 以模版为主键聚合的体验会话用量(管理端「模版用量」视角);search 按模版名/智能体名/模版 ID 过滤。 */
templates: (query: { search?: string } = {}, signal?: AbortSignal) => {
const params = new URLSearchParams();
@@ -379,15 +362,22 @@ export function createAdminClient(options: AdminClientOptions) {
{ signal },
);
},
- /** 模版用量逐日趋势(限额账本条目逐日账);templateId 缺省为全部模版求和,days 支持 7/14/28。 */
- templateTrend: (query: { templateId?: string; days?: 7 | 14 | 28 } = {}, signal?: AbortSignal) => {
+ /** 用量分桶趋势:agentId 缺省为全部模版口径(服务端逐模版绑定智能体求和);granularity 缺省 day;时间毫秒,服务端按该粒度(UTC+8)分桶并聚合全部分页。 */
+ trend: (
+ query: {
+ agentId?: string;
+ startTime?: number;
+ endTime?: number;
+ granularity?: UsageGranularity;
+ } = {},
+ signal?: AbortSignal,
+ ) => {
const params = new URLSearchParams();
- if (query.templateId) params.set("template_id", query.templateId);
- if (query.days) params.set("days", String(query.days));
- return get(
- `/api/admin/usage/templates/daily-trend${params.size ? `?${params}` : ""}`,
- signal,
- );
+ if (query.agentId) params.set("agent_id", query.agentId);
+ if (query.granularity) params.set("granularity", query.granularity);
+ if (query.startTime !== undefined) params.set("start_time", String(query.startTime));
+ if (query.endTime !== undefined) params.set("end_time", String(query.endTime));
+ return get(`/api/admin/usage/trend${params.size ? `?${params}` : ""}`, signal);
},
templateLimit: (templateId: string, signal?: AbortSignal) =>
get(`/api/admin/usage/templates/${encodeURIComponent(templateId)}/usage-limit`, signal),
diff --git a/apps/console/src/lib/admin/index.ts b/apps/console/src/lib/admin/index.ts
index cb0fa97..ea9c09a 100644
--- a/apps/console/src/lib/admin/index.ts
+++ b/apps/console/src/lib/admin/index.ts
@@ -3,8 +3,6 @@ export {
type AdminClientOptions,
createAdminClient,
type DeclarationWrite,
- type ModelUsageQuery,
- type ToolUsageQuery,
} from "./client.ts";
export { createMemberUsageController, type MemberUsageSnapshot } from "./member-usage.ts";
export { type AdminOperationSnapshot, createAdminOperation } from "./operation.ts";
diff --git a/apps/console/src/lib/admin/member-usage.test.ts b/apps/console/src/lib/admin/member-usage.test.ts
index ac33761..1c5dc3a 100644
--- a/apps/console/src/lib/admin/member-usage.test.ts
+++ b/apps/console/src/lib/admin/member-usage.test.ts
@@ -10,7 +10,10 @@ function summary(value: number, count = 21, status: MemberUsageSummary["refresh_
metrics: Object.fromEntries(
SESSION_USAGE_METRICS.map((key) => [key, { value, covered_sessions: count }]),
) as MemberUsageSummary["metrics"],
- agents: ["agent/a", "agent-b"],
+ agents: [
+ { slug: "agent/a", display_name: "Agent A" },
+ { slug: "agent-b", display_name: null },
+ ],
refresh_status: status,
completed_sessions: count,
};
@@ -60,7 +63,14 @@ describe("成员用量查询编排", () => {
expect(controller.getSnapshot().page).toBe(2);
controller.setAgent("agent/a");
await vi.waitFor(() => expect(controller.getSnapshot().summary?.metrics.input_tokens.value).toBe(500));
- expect(controller.getSnapshot()).toMatchObject({ page: 1, agentSlug: "agent/a", agents: ["agent/a", "agent-b"] });
+ expect(controller.getSnapshot()).toMatchObject({
+ page: 1,
+ agentSlug: "agent/a",
+ agents: [
+ { slug: "agent/a", display_name: "Agent A" },
+ { slug: "agent-b", display_name: null },
+ ],
+ });
for (const url of urls.slice(-2)) {
expect(url.pathname).toContain("/kit/api/admin/members/member%20one/");
expect(url.searchParams.get("agent_slug")).toBe("agent/a");
diff --git a/apps/console/src/lib/admin/member-usage.ts b/apps/console/src/lib/admin/member-usage.ts
index e9a0a46..cd94038 100644
--- a/apps/console/src/lib/admin/member-usage.ts
+++ b/apps/console/src/lib/admin/member-usage.ts
@@ -6,7 +6,7 @@ export interface MemberUsageSnapshot {
summary: MemberUsageSummary | undefined;
sessions: MemberSessionUsage[];
agentSlug: string;
- agents: string[];
+ agents: MemberUsageSummary["agents"];
page: number;
hasNext: boolean;
loading: boolean;
diff --git a/apps/console/src/lib/stat-card.tsx b/apps/console/src/lib/stat-card.tsx
index 7c5505f..23f1682 100644
--- a/apps/console/src/lib/stat-card.tsx
+++ b/apps/console/src/lib/stat-card.tsx
@@ -10,10 +10,12 @@ export function StatCell({
hint,
missingText = "待获取",
}: {
- label: string;
+ /** 标签可携带行内节点(如口径说明的 info 图标)。 */
+ label: ReactNode;
value: number | null;
unit?: string;
- hint?: string;
+ /** 说明文案可为节点(如部分覆盖的警示色提示)。 */
+ hint?: ReactNode;
/** 缺失占位文案;已采集但 Provider 未返回的指标可用「未返回」与「待获取」区分。 */
missingText?: string;
}) {
diff --git a/apps/server/openapi.json b/apps/server/openapi.json
index eb2730c..122a970 100644
--- a/apps/server/openapi.json
+++ b/apps/server/openapi.json
@@ -9015,7 +9015,23 @@
"agents": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "deleted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "display_name"
+ ]
}
},
"refreshed_at": {
@@ -9383,7 +9399,23 @@
"agents": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "deleted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "display_name"
+ ]
}
},
"refreshed_at": {
@@ -12550,7 +12582,7 @@
},
"responses": {
"200": {
- "description": "条目已删除(确认令牌已消费)",
+ "description": "条目已标记删除(软删,确认令牌已消费)",
"content": {
"application/json": {
"schema": {
@@ -13557,6 +13589,9 @@
"unlisted"
]
},
+ "deleted": {
+ "type": "boolean"
+ },
"session_count": {
"type": "integer",
"minimum": 0
@@ -14555,7 +14590,7 @@
}
}
},
- "/api/admin/usage/model-usage": {
+ "/api/admin/usage/summary": {
"get": {
"tags": [
"admin"
@@ -14600,66 +14635,11 @@
"required": false,
"name": "agent_id",
"in": "query"
- },
- {
- "schema": {
- "type": "integer",
- "minimum": 1
- },
- "required": false,
- "name": "page_no",
- "in": "query"
- },
- {
- "schema": {
- "type": "integer",
- "minimum": 1,
- "maximum": 100
- },
- "required": false,
- "name": "page_size",
- "in": "query"
- },
- {
- "schema": {
- "type": "string",
- "enum": [
- "asc",
- "desc"
- ]
- },
- "required": false,
- "name": "sort_order",
- "in": "query"
- },
- {
- "schema": {
- "type": "string",
- "minLength": 1,
- "maxLength": 128
- },
- "required": false,
- "name": "model_name",
- "in": "query"
- },
- {
- "schema": {
- "type": "string",
- "enum": [
- "call_count",
- "failed_count",
- "input_tokens",
- "output_tokens"
- ]
- },
- "required": false,
- "name": "sort_by",
- "in": "query"
}
],
"responses": {
"200": {
- "description": "Provider 侧模型用量明细(workspace scope,workspace_ids 来自服务端配置);默认统计最近 7 天",
+ "description": "Provider 侧用量汇总(app-control usage.summary):维度由参数决定——传 session_id 为 dimension:session(按会话自身窗口,不传 time_range/granularity;本地账本已标记删除的会话直接返回零值空汇总,不查询 Provider),传 agent_id 为 dimension:agent,都不传为模版口径(服务端逐模版绑定智能体——含已删模版、去重——以 agent 维度查询并合并为各模版求和,非模版智能体不计入;单个智能体查询失败不打挂整个请求,返回已成功部分的合并并在 data.coverage 标注 {complete:false, missing_agent_ids},缺省即完整);?start_time=&end_time=(毫秒,缺省最近 7 天)在服务端转成 UTC+8 偏移的 RFC 3339 字符串;返回 {data:{query_range,data_updated_at,usage:{total,models,tools}}},指标统一为 {value,unit}(未知为 null、已知零值为 0,跨智能体合并时任一来源未知即未知,cache_hit_ratio 按合并后的 cache_read/input 重算);模型/工具明细同一次响应返回,无分页、无服务端名称筛选,单次明细合计上限 10 万条;无模版绑定时返回零值汇总;管理员与 auditor 可读",
"content": {
"application/json": {
"schema": {
@@ -14668,93 +14648,574 @@
"data": {
"type": "object",
"properties": {
- "items": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "workspace_id": {
- "type": "string"
- },
- "model_name": {
- "type": "string"
- },
- "call_count": {
- "type": "integer",
- "minimum": 0
- },
- "failed_count": {
- "type": "integer",
- "minimum": 0
- },
- "tokens": {
- "type": "object",
- "properties": {
- "input_tokens": {
- "type": "number"
+ "query_range": {
+ "type": "object",
+ "properties": {
+ "start_time": {
+ "type": "string"
+ },
+ "end_time": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "start_time",
+ "end_time"
+ ]
+ },
+ "data_updated_at": {
+ "type": "string",
+ "nullable": true
+ },
+ "usage": {
+ "type": "object",
+ "properties": {
+ "total": {
+ "type": "object",
+ "properties": {
+ "input_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
},
- "output_tokens": {
- "type": "number"
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "output_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "total_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_read_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_creation_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
},
- "cache_read_tokens": {
- "type": "number"
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_hit_ratio": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
},
- "cache_creation_tokens": {
- "type": "number"
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "model_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
},
- "total_tokens": {
- "type": "number"
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
},
- "cache_hit_ratio": {
- "type": "number"
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "builtin_tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "mcp_tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "custom_tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "turns": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "steps": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "interrupt_error_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "model_failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "tool_failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "runtime_ms": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ }
+ },
+ "required": [
+ "input_tokens",
+ "output_tokens",
+ "total_tokens",
+ "cache_read_tokens",
+ "cache_creation_tokens",
+ "cache_hit_ratio",
+ "model_call_count",
+ "tool_call_count",
+ "builtin_tool_call_count",
+ "mcp_tool_call_count",
+ "custom_tool_call_count",
+ "turns",
+ "steps",
+ "interrupt_error_count",
+ "model_failed_count",
+ "tool_failed_count",
+ "runtime_ms"
+ ]
+ },
+ "models": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "model_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "usage": {
+ "type": "object",
+ "properties": {
+ "input_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "output_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "total_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_read_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_creation_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_hit_ratio": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ }
+ },
+ "required": [
+ "input_tokens",
+ "output_tokens",
+ "total_tokens",
+ "cache_read_tokens",
+ "cache_creation_tokens",
+ "cache_hit_ratio",
+ "call_count",
+ "failed_count"
+ ]
}
},
"required": [
- "input_tokens",
- "output_tokens",
- "cache_read_tokens",
- "cache_creation_tokens",
- "total_tokens",
- "cache_hit_ratio"
+ "model_name",
+ "usage"
]
}
},
- "required": [
- "workspace_id",
- "model_name",
- "call_count",
- "failed_count",
- "tokens"
- ]
- }
- },
- "total": {
- "type": "integer",
- "minimum": 0
- },
- "total_call_count": {
- "type": "integer",
- "minimum": 0
- },
- "page_no": {
- "type": "integer",
- "minimum": 1
- },
- "page_size": {
- "type": "integer",
- "minimum": 1
+ "tools": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "source": {
+ "type": "string",
+ "nullable": true
+ },
+ "tool_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "usage": {
+ "type": "object",
+ "properties": {
+ "call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ }
+ },
+ "required": [
+ "call_count",
+ "failed_count"
+ ]
+ }
+ },
+ "required": [
+ "source",
+ "tool_name",
+ "usage"
+ ]
+ }
+ }
+ },
+ "required": [
+ "total",
+ "models",
+ "tools"
+ ]
},
- "data_updated_at": {
- "type": "number"
+ "coverage": {
+ "type": "object",
+ "properties": {
+ "complete": {
+ "type": "boolean"
+ },
+ "missing_agent_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "complete",
+ "missing_agent_ids"
+ ]
}
},
"required": [
- "items",
- "total",
- "total_call_count",
- "page_no",
- "page_size",
- "data_updated_at"
+ "data_updated_at",
+ "usage"
]
}
},
@@ -14966,7 +15427,7 @@
}
}
},
- "/api/admin/usage/tool-usage": {
+ "/api/admin/usage/trend": {
"get": {
"tags": [
"admin"
@@ -14992,16 +15453,6 @@
"name": "end_time",
"in": "query"
},
- {
- "schema": {
- "type": "string",
- "minLength": 1,
- "maxLength": 128
- },
- "required": false,
- "name": "session_id",
- "in": "query"
- },
{
"schema": {
"type": "string",
@@ -15012,76 +15463,23 @@
"name": "agent_id",
"in": "query"
},
- {
- "schema": {
- "type": "integer",
- "minimum": 1
- },
- "required": false,
- "name": "page_no",
- "in": "query"
- },
- {
- "schema": {
- "type": "integer",
- "minimum": 1,
- "maximum": 100
- },
- "required": false,
- "name": "page_size",
- "in": "query"
- },
- {
- "schema": {
- "type": "string",
- "enum": [
- "asc",
- "desc"
- ]
- },
- "required": false,
- "name": "sort_order",
- "in": "query"
- },
- {
- "schema": {
- "type": "string",
- "enum": [
- "builtin",
- "mcp",
- "custom"
- ]
- },
- "required": false,
- "name": "source",
- "in": "query"
- },
- {
- "schema": {
- "type": "string",
- "minLength": 1,
- "maxLength": 128
- },
- "required": false,
- "name": "tool_name",
- "in": "query"
- },
{
"schema": {
"type": "string",
"enum": [
- "call_count",
- "failed_count"
+ "hour",
+ "day",
+ "month"
]
},
"required": false,
- "name": "sort_by",
+ "name": "granularity",
"in": "query"
}
],
"responses": {
"200": {
- "description": "Provider 侧工具调用明细(workspace scope,workspace_ids 来自服务端配置);默认统计最近 7 天",
+ "description": "用量分桶趋势:传 agent_id 为 agent 维度;都不传为模版口径(服务端逐模版绑定智能体——含已删模版、去重——以 agent 维度查询并按时间桶合并为各模版求和,非模版智能体不计入,无模版绑定时返回空点;单个智能体查询失败不打挂整个请求,返回已成功部分的合并并在 data.coverage 标注 {complete:false, missing_agent_ids},缺省即完整;服务端分页游标缺失仍整体拒绝)(Provider 侧,UTC+8 对齐,无数据的时间桶省略);粒度由 granularity 参数决定(hour/day/month,缺省 day);服务端聚合全部分页返回,has_more 恒为 false",
"content": {
"application/json": {
"schema": {
@@ -15090,65 +15488,612 @@
"data": {
"type": "object",
"properties": {
- "items": {
+ "query_range": {
+ "type": "object",
+ "properties": {
+ "start_time": {
+ "type": "string"
+ },
+ "end_time": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "start_time",
+ "end_time"
+ ]
+ },
+ "data_updated_at": {
+ "type": "string",
+ "nullable": true
+ },
+ "granularity": {
+ "type": "string",
+ "enum": [
+ "hour",
+ "day",
+ "month"
+ ]
+ },
+ "points": {
"type": "array",
"items": {
"type": "object",
"properties": {
- "workspace_id": {
+ "start_time": {
"type": "string"
},
- "tool_name": {
+ "end_time": {
"type": "string"
},
- "source": {
- "type": "string"
- },
- "call_count": {
- "type": "integer",
- "minimum": 0
- },
- "failed_count": {
- "type": "integer",
- "minimum": 0
+ "usage": {
+ "type": "object",
+ "properties": {
+ "total": {
+ "type": "object",
+ "properties": {
+ "input_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "output_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "total_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_read_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_creation_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_hit_ratio": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "model_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "builtin_tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "mcp_tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "custom_tool_call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "turns": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "steps": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "interrupt_error_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "model_failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "tool_failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "runtime_ms": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ }
+ },
+ "required": [
+ "input_tokens",
+ "output_tokens",
+ "total_tokens",
+ "cache_read_tokens",
+ "cache_creation_tokens",
+ "cache_hit_ratio",
+ "model_call_count",
+ "tool_call_count",
+ "builtin_tool_call_count",
+ "mcp_tool_call_count",
+ "custom_tool_call_count",
+ "turns",
+ "steps",
+ "interrupt_error_count",
+ "model_failed_count",
+ "tool_failed_count",
+ "runtime_ms"
+ ]
+ },
+ "models": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "model_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "usage": {
+ "type": "object",
+ "properties": {
+ "input_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "output_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "total_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_read_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_creation_tokens": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "cache_hit_ratio": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ }
+ },
+ "required": [
+ "input_tokens",
+ "output_tokens",
+ "total_tokens",
+ "cache_read_tokens",
+ "cache_creation_tokens",
+ "cache_hit_ratio",
+ "call_count",
+ "failed_count"
+ ]
+ }
+ },
+ "required": [
+ "model_name",
+ "usage"
+ ]
+ }
+ },
+ "tools": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "source": {
+ "type": "string",
+ "nullable": true
+ },
+ "tool_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "usage": {
+ "type": "object",
+ "properties": {
+ "call_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ },
+ "failed_count": {
+ "type": "object",
+ "properties": {
+ "value": {
+ "type": "number",
+ "nullable": true
+ },
+ "unit": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "value",
+ "unit"
+ ]
+ }
+ },
+ "required": [
+ "call_count",
+ "failed_count"
+ ]
+ }
+ },
+ "required": [
+ "source",
+ "tool_name",
+ "usage"
+ ]
+ }
+ }
+ },
+ "required": [
+ "total",
+ "models",
+ "tools"
+ ]
}
},
"required": [
- "workspace_id",
- "tool_name",
- "source",
- "call_count",
- "failed_count"
+ "start_time",
+ "end_time",
+ "usage"
]
}
},
- "total": {
- "type": "integer",
- "minimum": 0
- },
- "total_call_count": {
- "type": "integer",
- "minimum": 0
- },
- "page_no": {
- "type": "integer",
- "minimum": 1
+ "has_more": {
+ "type": "boolean"
},
- "page_size": {
- "type": "integer",
- "minimum": 1
+ "next_page_token": {
+ "type": "string",
+ "nullable": true
},
- "data_updated_at": {
- "type": "number"
+ "coverage": {
+ "type": "object",
+ "properties": {
+ "complete": {
+ "type": "boolean"
+ },
+ "missing_agent_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "complete",
+ "missing_agent_ids"
+ ]
}
},
"required": [
- "items",
- "total",
- "total_call_count",
- "page_no",
- "page_size",
- "data_updated_at"
+ "query_range",
+ "data_updated_at",
+ "granularity",
+ "points",
+ "has_more",
+ "next_page_token"
]
}
},
@@ -20970,7 +21915,23 @@
"agents": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "deleted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "display_name"
+ ]
}
},
"refreshed_at": {
@@ -21497,7 +22458,23 @@
"agents": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "deleted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "display_name"
+ ]
}
},
"refreshed_at": {
@@ -21918,7 +22895,23 @@
"agents": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "deleted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "display_name"
+ ]
}
},
"refreshed_at": {
@@ -22349,7 +23342,23 @@
"agents": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "deleted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "display_name"
+ ]
}
},
"refreshed_at": {
@@ -24836,7 +25845,23 @@
"agents": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "deleted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "display_name"
+ ]
}
},
"refreshed_at": {
@@ -27029,7 +28054,7 @@
},
"responses": {
"200": {
- "description": "已删除模版全部版本及关联条目,既有会话和远端资源保留",
+ "description": "模版已标记删除(软删,确认令牌已消费);配置、版本与用量保留",
"content": {
"application/json": {
"schema": {
@@ -28781,6 +29806,9 @@
"listed"
]
},
+ "deleted": {
+ "type": "boolean"
+ },
"created_at": {
"type": "string"
},
diff --git a/apps/server/package.json b/apps/server/package.json
index 0b7ff62..ee5ded9 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -44,7 +44,7 @@
"dependencies": {
"@hono/node-server": "^2.1.4",
"@hono/zod-openapi": "^1.6.3",
- "@openagentpack/sdk": "0.10.0",
+ "@openagentpack/sdk": "0.11.0",
"hono": "^4.13.13",
"jszip": "3.10.2",
"mysql2": "^3.24.6",
diff --git a/apps/server/src/gateway/mock.ts b/apps/server/src/gateway/mock.ts
index f3e134d..4e20e39 100644
--- a/apps/server/src/gateway/mock.ts
+++ b/apps/server/src/gateway/mock.ts
@@ -9,12 +9,14 @@ import {
threadIdOf,
} from "@openagentkit/sdk/protocol";
import type {
- ModelUsageItem,
- ModelUsagePage,
- ModelUsageRequest,
- ToolUsageItem,
- ToolUsagePage,
- ToolUsageRequest,
+ UsageMetric,
+ UsageModelRow,
+ UsageSummary,
+ UsageSummaryRequest,
+ UsageSummaryResponse,
+ UsageToolRow,
+ UsageTrendRequest,
+ UsageTrendResponse,
} from "@openagentpack/sdk";
import { isRemoteCoordinator, projectMultiagentConfiguration } from "./agent-multiagent.ts";
import { memoryStoreConfiguration } from "./memory-store-configuration.ts";
@@ -43,12 +45,18 @@ interface MockSession extends MockInspectableSession {
stopReason?: string;
/** 创建时绑定的远端智能体;用量遥测按它归组。 */
agent_id: string;
+ /** 创建时间(毫秒);mock trend 按它分桶。 */
+ createdAt: number;
}
const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
const initialRemoteAgents = [
{ agent_id: "agent_mock_assistant", name: "assistant", version: 1 },
{ agent_id: "agent_mock_designer", name: "designer", version: 3 },
+ { agent_id: "agent_mock_writer", name: "writer", version: 1 },
+ { agent_id: "agent_mock_analyst", name: "analyst", version: 2 },
+ { agent_id: "agent_mock_reviewer", name: "reviewer", version: 1 },
+ { agent_id: "agent_mock_coder", name: "coder", version: 2 },
];
/** 回放 [start, end) 区间事件,返回新的游标。 */
@@ -88,9 +96,6 @@ function latestEvents(events: SessionEvent[]) {
return snapshots;
}
-/** mock 演示工作空间标识,与 admin 路由 telemetryWorkspaceId 的无凭据占位一致。 */
-const MOCK_WORKSPACE_ID = "ws-mock";
-
/** mock 遥测使用的演示模型名。 */
const MOCK_MODEL_NAME = "qwen3.8-max";
@@ -103,6 +108,17 @@ export interface MockTelemetryUsage {
cache_creation_tokens: number;
}
+/** 账本小时行:UTC 小时键(created_at 前 13 位),供 mock trend 重分桶到 UTC+8 时间桶。 */
+export interface MockTelemetryHourRow {
+ agent_key: string;
+ hour: string;
+ sessions: number;
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens: number;
+ cache_creation_tokens: number;
+}
+
/**
* 账本遥测源:由 services 组装时注入(mock 网关自身不读本地库,保持 Provider 抽象分层)。
* mock 明细据此伪造 Provider 侧调用——有会话才有行、Token 与汇总卡片同源、重启不丢。
@@ -110,6 +126,7 @@ export interface MockTelemetryUsage {
export interface MockTelemetrySource {
byAgent(): Promise