@@ -4,6 +4,7 @@ import type { SessionRecord } from '../models/SessionRecord';
44import type { TurnRecord , TurnSnapshot } from '../models/TurnRecord' ;
55import type { PersistedTurnEvent , SessionEventItem } from '../schemas/events' ;
66import type { TokenPagination } from '../schemas/pagination' ;
7+ import type { SessionMetricsChartsDataResponse , SessionMetricsMetersResponse } from '../schemas/session' ;
78import type { TerminalTurnState } from '../schemas/turn' ;
89import { assertCreateTurnThreadDelta } from './assertCreateTurnThreadDelta' ;
910import type {
@@ -15,6 +16,8 @@ import type {
1516 DeleteSessionInput ,
1617 FreezeAndGetTurnInput ,
1718 GetSessionInput ,
19+ GetSessionMetricsChartDataInput ,
20+ GetSessionMetricsInput ,
1821 GetTurnInput ,
1922 ISessionStore ,
2023 ListSessionEventsInput ,
@@ -39,6 +42,13 @@ import {
3942 type SessionEventPageCursor ,
4043} from './SessionEventPageToken' ;
4144import { decodeSessionListPageToken , paginateSessionListRows } from './SessionListPageToken' ;
45+ import {
46+ buildSessionMetricsChartData ,
47+ buildSessionMetricsMeters ,
48+ type SessionMetricsAggregate ,
49+ type SessionMetricsBucket ,
50+ sessionMetricsStepSeconds ,
51+ } from './sessionMetrics' ;
4252import {
4353 PreviousTurnRunningError ,
4454 SessionAlreadyExistsError ,
@@ -156,6 +166,18 @@ function paginate<T>(items: T[], limit: number, pageToken?: string): { data: T[]
156166 } ;
157167}
158168
169+ function continuousPercentile ( sortedValues : number [ ] , fraction : number ) : number {
170+ if ( sortedValues . length === 0 ) {
171+ return 0 ;
172+ }
173+ const position = fraction * ( sortedValues . length - 1 ) ;
174+ const lowerIndex = Math . floor ( position ) ;
175+ const upperIndex = Math . ceil ( position ) ;
176+ const lower = sortedValues [ lowerIndex ] ?? 0 ;
177+ const upper = sortedValues [ upperIndex ] ?? lower ;
178+ return lower + ( upper - lower ) * ( position - lowerIndex ) ;
179+ }
180+
159181/**
160182 * Reference ISessionStore implementation. Proves the contract without SSE/subscription
161183 * hooks. Deep-copies on read/write boundaries so callers cannot mutate stored state.
@@ -291,6 +313,91 @@ export class InMemorySessionStore<
291313 return { data : deepCopy ( page . data ) , pagination : page . pagination } ;
292314 }
293315
316+ private collectSessionMetricsData ( input : GetSessionMetricsInput ) : {
317+ aggregate : SessionMetricsAggregate ;
318+ buckets : SessionMetricsBucket [ ] ;
319+ step_seconds : number ;
320+ } {
321+ const step_seconds = sessionMetricsStepSeconds ( input ) ;
322+ const aggregate : SessionMetricsAggregate = {
323+ total_sessions : 0 ,
324+ total_turns : 0 ,
325+ total_cost_in_usd : 0 ,
326+ active_sessions : 0 ,
327+ min_turns_per_session : 0 ,
328+ max_turns_per_session : 0 ,
329+ median_turns_per_session : 0 ,
330+ min_session_duration_ms : 0 ,
331+ max_session_duration_ms : 0 ,
332+ median_session_duration_ms : 0 ,
333+ p95_session_duration_ms : 0 ,
334+ } ;
335+ const buckets = new Map < number , SessionMetricsBucket > ( ) ;
336+ const turnsPerSession : number [ ] = [ ] ;
337+ const sessionDurations : number [ ] = [ ] ;
338+
339+ for ( const stored of this . sessions . values ( ) ) {
340+ const record = stored . record ;
341+ const createdAtMs = record . created_at . getTime ( ) ;
342+ if (
343+ record . tenant_id !== input . tenant_id ||
344+ record . created_by !== input . created_by ||
345+ record . agent . type !== 'reference' ||
346+ record . agent . id !== input . agent_id ||
347+ createdAtMs < input . start_timestamp . getTime ( ) ||
348+ createdAtMs > input . end_timestamp . getTime ( )
349+ ) {
350+ continue ;
351+ }
352+
353+ aggregate . total_sessions += 1 ;
354+ aggregate . total_turns += record . metrics . total_turns ;
355+ aggregate . total_cost_in_usd += record . metrics . total_cost_in_usd ;
356+ // Turn/duration distributions only over sessions with ≥1 turn.
357+ if ( record . metrics . total_turns > 0 ) {
358+ aggregate . active_sessions += 1 ;
359+ turnsPerSession . push ( record . metrics . total_turns ) ;
360+ sessionDurations . push ( record . metrics . total_duration_ms ) ;
361+ }
362+
363+ const timestamp_seconds = Math . floor ( createdAtMs / 1000 / step_seconds ) * step_seconds ;
364+ const bucket = buckets . get ( timestamp_seconds ) ?? {
365+ timestamp_seconds,
366+ sessions : 0 ,
367+ turns : 0 ,
368+ cost : 0 ,
369+ } ;
370+ bucket . sessions += 1 ;
371+ bucket . turns += record . metrics . total_turns ;
372+ bucket . cost += record . metrics . total_cost_in_usd ;
373+ buckets . set ( timestamp_seconds , bucket ) ;
374+ }
375+
376+ turnsPerSession . sort ( ( a , b ) => a - b ) ;
377+ sessionDurations . sort ( ( a , b ) => a - b ) ;
378+ if ( aggregate . active_sessions > 0 ) {
379+ aggregate . min_turns_per_session = turnsPerSession [ 0 ] ?? 0 ;
380+ aggregate . max_turns_per_session = turnsPerSession . at ( - 1 ) ?? 0 ;
381+ aggregate . median_turns_per_session = continuousPercentile ( turnsPerSession , 0.5 ) ;
382+ aggregate . min_session_duration_ms = sessionDurations [ 0 ] ?? 0 ;
383+ aggregate . max_session_duration_ms = sessionDurations . at ( - 1 ) ?? 0 ;
384+ aggregate . median_session_duration_ms = continuousPercentile ( sessionDurations , 0.5 ) ;
385+ aggregate . p95_session_duration_ms = continuousPercentile ( sessionDurations , 0.95 ) ;
386+ }
387+
388+ return { aggregate, buckets : [ ...buckets . values ( ) ] , step_seconds } ;
389+ }
390+
391+ async getSessionMetricsMeters ( input : GetSessionMetricsInput ) : Promise < SessionMetricsMetersResponse > {
392+ const { aggregate } = this . collectSessionMetricsData ( input ) ;
393+ return buildSessionMetricsMeters ( aggregate ) ;
394+ }
395+
396+ async getSessionMetricsChartData ( input : GetSessionMetricsChartDataInput ) : Promise < SessionMetricsChartsDataResponse > {
397+ const { buckets, step_seconds } = this . collectSessionMetricsData ( input ) ;
398+ return buildSessionMetricsChartData ( { query : input , buckets, step_seconds } ) ;
399+ }
400+
294401 async createTurn ( input : CreateTurnInput < TTurnCustom > ) : Promise < void > {
295402 // Atomicity is free here: this body is fully synchronous, so Node's
296403 // run-to-completion guarantees it. Real backends must still use their own
0 commit comments