refactor: dedupe shared helpers across ui/gateway/extensions

This commit is contained in:
Peter Steinberger
2026-02-15 03:33:33 +00:00
parent fe90e14239
commit fef86e475b
23 changed files with 898 additions and 1298 deletions

View File

@@ -25,6 +25,7 @@ import {
type DiscoveredSession,
} from "../../infra/session-cost-usage.js";
import { parseAgentSessionKey } from "../../routing/session-key.js";
import { buildUsageAggregateTail } from "../../shared/usage-aggregates.js";
import {
ErrorCodes,
errorShape,
@@ -692,6 +693,14 @@ export const usageHandlers: GatewayRequestHandlers = {
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;
};
const tail = buildUsageAggregateTail({
byChannelMap: byChannelMap,
latencyTotals,
dailyLatencyMap,
modelDailyMap,
dailyMap: dailyAggregateMap,
});
const aggregates: SessionsUsageAggregates = {
messages: aggregateMessages,
tools: {
@@ -718,35 +727,7 @@ export const usageHandlers: GatewayRequestHandlers = {
byAgent: Array.from(byAgentMap.entries())
.map(([id, totals]) => ({ agentId: id, totals }))
.toSorted((a, b) => b.totals.totalCost - a.totals.totalCost),
byChannel: Array.from(byChannelMap.entries())
.map(([name, totals]) => ({ channel: name, totals }))
.toSorted((a, b) => b.totals.totalCost - a.totals.totalCost),
latency:
latencyTotals.count > 0
? {
count: latencyTotals.count,
avgMs: latencyTotals.sum / latencyTotals.count,
minMs: latencyTotals.min === Number.POSITIVE_INFINITY ? 0 : latencyTotals.min,
maxMs: latencyTotals.max,
p95Ms: latencyTotals.p95Max,
}
: undefined,
dailyLatency: Array.from(dailyLatencyMap.values())
.map((entry) => ({
date: entry.date,
count: entry.count,
avgMs: entry.count ? entry.sum / entry.count : 0,
minMs: entry.min === Number.POSITIVE_INFINITY ? 0 : entry.min,
maxMs: entry.max,
p95Ms: entry.p95Max,
}))
.toSorted((a, b) => a.date.localeCompare(b.date)),
modelDaily: Array.from(modelDailyMap.values()).toSorted(
(a, b) => a.date.localeCompare(b.date) || b.cost - a.cost,
),
daily: Array.from(dailyAggregateMap.values()).toSorted((a, b) =>
a.date.localeCompare(b.date),
),
...tail,
};
const result: SessionsUsageResult = {