@unieai/rabi-session-stats 0.2.1-rc.3 → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -167,7 +167,8 @@ const sessionStatsProjectionDefinition = {
167
167
  ttftSteps: state.ttftSteps,
168
168
  decodeMs: state.decodeMs,
169
169
  decodeTokens: state.decodeTokens
170
- })
170
+ }),
171
+ summary: false
171
172
  }
172
173
  };
173
174
  //#endregion
@@ -190,9 +191,10 @@ const inject = ["sessionProjections"];
190
191
  * Register the `sessionStats` unit; the registration is an effect on this
191
192
  * plugin's fiber, so unloading removes the key.
192
193
  * @param ctx - registrant context carrying the projection registry.
194
+ * @returns when the plugin is ready.
193
195
  */
194
- function apply(ctx) {
195
- ctx.sessionProjections.register(sessionStatsProjectionDefinition);
196
+ async function apply(ctx) {
197
+ await ctx.sessionProjections.register(sessionStatsProjectionDefinition);
196
198
  }
197
199
  //#endregion
198
200
  export { apply, inject, name };
@@ -18,6 +18,7 @@ export declare const inject: string[];
18
18
  * Register the `sessionStats` unit; the registration is an effect on this
19
19
  * plugin's fiber, so unloading removes the key.
20
20
  * @param ctx - registrant context carrying the projection registry.
21
+ * @returns when the plugin is ready.
21
22
  */
22
- export declare function apply(ctx: Context): void;
23
+ export declare function apply(ctx: Context): Promise<void>;
23
24
  //# sourceMappingURL=index.d.ts.map
@@ -17,7 +17,8 @@ export const inject = ['sessionProjections'];
17
17
  * Register the `sessionStats` unit; the registration is an effect on this
18
18
  * plugin's fiber, so unloading removes the key.
19
19
  * @param ctx - registrant context carrying the projection registry.
20
+ * @returns when the plugin is ready.
20
21
  */
21
- export function apply(ctx) {
22
- ctx.sessionProjections.register(sessionStatsProjectionDefinition);
22
+ export async function apply(ctx) {
23
+ await ctx.sessionProjections.register(sessionStatsProjectionDefinition);
23
24
  }
@@ -61,11 +61,6 @@ interface SessionStatsState extends SessionStatsTotals {
61
61
  /** Dispatch times of tool calls whose result has not landed, by callId. */
62
62
  pendingCalls: Record<string, number>;
63
63
  }
64
- declare module '@unieai/rabi-session-projection/types' {
65
- interface SessionProjectionStateMap {
66
- sessionStats: SessionStatsState;
67
- }
68
- }
69
64
  /** The `sessionStats` unit registered on `ctx.sessionProjections` (exported for the unit spec). */
70
65
  export declare const sessionStatsProjectionDefinition: {
71
66
  key: "sessionStats";
@@ -123,6 +118,7 @@ export declare const sessionStatsProjectionDefinition: {
123
118
  decodeMs: number;
124
119
  decodeTokens: number;
125
120
  };
121
+ summary: false;
126
122
  };
127
123
  };
128
124
  export {};
@@ -163,5 +163,6 @@ export const sessionStatsProjectionDefinition = {
163
163
  decodeMs: state.decodeMs,
164
164
  decodeTokens: state.decodeTokens,
165
165
  }),
166
+ summary: false,
166
167
  },
167
168
  };
@@ -35,8 +35,12 @@ export interface SessionStatsProjection {
35
35
  }
36
36
  declare module '@unieai/rabi-session-projection/types' {
37
37
  interface SessionProjectionMap {
38
- /** Whole-log turn/step counts and wall times; see {@link SessionStatsProjection}. */
39
- sessionStats: SessionStatsProjection;
38
+ /**
39
+ * Whole-log turn/step counts and wall times; see
40
+ * {@link SessionStatsProjection}. Excluded from Session summary payloads:
41
+ * no list row renders these figures.
42
+ */
43
+ sessionStats: SessionProjectionSummaryExcluded<SessionStatsProjection>;
40
44
  }
41
45
  }
42
46
  //# sourceMappingURL=types.d.ts.map
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Sitzungsstatistiken",
4
+ "description": "Fassen Sie statistische Informationen wie die Anzahl der Interaktionen und die für die Sitzung aufgewendete Zeit zusammen."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "estadísticas de sesión",
4
+ "description": "Resuma información estadística como el número de interacciones y el tiempo dedicado a la sesión."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "statistiques de session",
4
+ "description": "Résumez les informations statistiques telles que le nombre d’interactions et le temps passé sur la session."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "セッション統計",
4
+ "description": "セッションの対話回数や所要時間などの統計をまとめます。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "estatísticas da sessão",
4
+ "description": "Resuma informações estatísticas, como o número de interações e o tempo gasto na sessão."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "статистика сеанса",
4
+ "description": "Суммируйте статистическую информацию, такую как количество взаимодействий и время, потраченное на сеанс."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-session-stats",
3
3
  "description": "Whole-log conversation counts and wall times projection (sessionStats) for the Rabi Harness",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -30,16 +30,19 @@
30
30
  "lib/index.js",
31
31
  "lib/types/**/*.js",
32
32
  "lib/types/**/*.d.ts",
33
+ "lib/types/**/*.d.ts.map",
34
+ "lib/**/*.js.map",
35
+ "src",
33
36
  "README.md"
34
37
  ],
35
38
  "license": "MIT",
36
39
  "peerDependencies": {
37
- "@unieai/rabi-llm": "0.2.1-rc.3",
38
- "@unieai/rabi-session": "0.2.1-rc.3",
39
- "@unieai/rabi-session-projection": "0.2.1-rc.3",
40
- "@unieai/cordis": "4.0.5"
40
+ "@unieai/rabi-llm": "0.2.2-rc.5",
41
+ "@unieai/rabi-session": "0.2.2-rc.5",
42
+ "@unieai/rabi-session-projection": "0.2.2-rc.5",
43
+ "@unieai/cordis": "4.1.0"
41
44
  },
42
45
  "dependencies": {
43
- "zod": "4.4.3"
46
+ "zod": "4.6.6"
44
47
  }
45
48
  }
package/src/client.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Client-namespace projection of the session-stats domain: a pure re-export
3
+ * of the package's types outlet. Client code imports ONLY the client
4
+ * namespace (repo discipline), so `./client` projects the same single-source
5
+ * content `./types` serves to host consumers — zero duplication.
6
+ *
7
+ * @module @unieai/rabi-session-stats/client
8
+ */
9
+
10
+ export type * from './types.ts'
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Function plugin registering the `sessionStats` projection unit: whole-log
3
+ * turn/step counts and LLM/tool/first-token/decode wall times served through
4
+ * the session-projection seam (registry snapshot, change feed, and every
5
+ * projection carrier), so clients render full-session figures that paging and
6
+ * compaction cannot change. The plugin owns only the fold; delivery is the
7
+ * seam's.
8
+ *
9
+ * @module @unieai/rabi-session-stats
10
+ */
11
+
12
+ import type { Context } from '@unieai/cordis'
13
+ import { sessionStatsProjectionDefinition } from './projection.ts'
14
+
15
+ export type * from './types.ts'
16
+
17
+ /** Cordis plugin name. */
18
+ export const name = 'session-stats'
19
+ /** The projection registry is the plugin's whole purpose; without it the fiber stays pending. */
20
+ export const inject = ['sessionProjections']
21
+
22
+ /**
23
+ * Register the `sessionStats` unit; the registration is an effect on this
24
+ * plugin's fiber, so unloading removes the key.
25
+ * @param ctx - registrant context carrying the projection registry.
26
+ * @returns when the plugin is ready.
27
+ */
28
+ export async function apply(ctx: Context): Promise<void> {
29
+ await ctx.sessionProjections.register(sessionStatsProjectionDefinition)
30
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * The `sessionStats` projection unit: a pure fold of step boundaries, stream
3
+ * embedded streams, tool pairs, and assembled assistant messages into whole-log counts
4
+ * and wall times.
5
+ *
6
+ * `step/end` — not `assistant/message` — is the counted step event because it
7
+ * is the step lifecycle authority: the loop appends exactly one per entered
8
+ * step, in a `finally`, so completed, failed, cancelled, and max-tokens steps
9
+ * all land one. Counting assembled assistant messages instead would overcount
10
+ * max-tokens usage-host messages (empty content, excluded from the surface)
11
+ * and undercount cancelled steps (aborted before the message assembles).
12
+ *
13
+ * The wall-time folds mirror the client window fold field by field
14
+ * (`deriveStats` in rabi-client-ui-conversation, that fold's whole-window
15
+ * fallback role): model time is `step/start` → `assistant/message`, first
16
+ * token is the first non-empty delta chunk and survives an in-step
17
+ * `llm/retry`, decode spans first token → assembled message on steps that
18
+ * also report output tokens, and tool time pairs `tool/call` → `tool/result`
19
+ * by callId. A cancelled step assembles no message, so its partial stream
20
+ * time stays uncounted in every time figure — matching the window, which
21
+ * renders it as an untimed interrupted node.
22
+ *
23
+ * @module @unieai/rabi-session-stats/projection
24
+ */
25
+
26
+ import { z } from 'zod'
27
+ import { assistantStreamFirstTokenTime } from '@unieai/rabi-llm'
28
+ import type { ProjectionDefinition } from '@unieai/rabi-session-projection'
29
+
30
+
31
+ /** Accumulated whole-log figures (the view is exactly these totals). */
32
+ interface SessionStatsTotals {
33
+ /** Distinct turns with at least one closed step so far. */
34
+ turns: number
35
+ /** Closed steps so far. */
36
+ steps: number
37
+ /** Summed model wall time over message-assembling steps, ms. */
38
+ llmMs: number
39
+ /** Summed matched tool call→result wall time, ms. */
40
+ toolMs: number
41
+ /** Summed first-token latency over `ttftSteps`, ms. */
42
+ ttftMs: number
43
+ /** Steps carrying a recorded first token. */
44
+ ttftSteps: number
45
+ /** Summed decode wall time over usage-reporting steps, ms. */
46
+ decodeMs: number
47
+ /** Summed provider output tokens over the same steps. */
48
+ decodeTokens: number
49
+ }
50
+
51
+ /**
52
+ * Fold state: the totals plus the in-flight boundaries they accrue from.
53
+ * Turn numbers are host-assigned and monotonic per session, so a single
54
+ * `lastTurn` slot decides "first closed step of a new turn"; the state is
55
+ * plain JSON per the unit contract (persisted-cache precondition).
56
+ */
57
+ interface SessionStatsState extends SessionStatsTotals {
58
+ /** Turn of the last counted `step/end`; null before the first. */
59
+ lastTurn: number | null
60
+ /** The open step's boundary facts; null outside a step or after its message assembled. */
61
+ openStep: { turn: number; step: number; startTime: number; firstTokenTime: number | null } | null
62
+ /** Dispatch times of tool calls whose result has not landed, by callId. */
63
+ pendingCalls: Record<string, number>
64
+ }
65
+
66
+ const sessionStatsSchema = z.object({
67
+ turns: z.number().int().nonnegative(),
68
+ steps: z.number().int().nonnegative(),
69
+ llmMs: z.number().nonnegative(),
70
+ toolMs: z.number().nonnegative(),
71
+ ttftMs: z.number().nonnegative(),
72
+ ttftSteps: z.number().int().nonnegative(),
73
+ decodeMs: z.number().nonnegative(),
74
+ decodeTokens: z.number().nonnegative(),
75
+ }).strict()
76
+
77
+ /**
78
+ * The fold state's shape (totals plus in-flight boundaries), validated on
79
+ * persisted-cache rows after their `ver` gate — the unit's input boundary.
80
+ * The view is a strict subset of the state, so this schema extends
81
+ * `sessionStatsSchema` (the wire output boundary) with the boundary fields.
82
+ */
83
+ const sessionStatsStateSchema = sessionStatsSchema.extend({
84
+ lastTurn: z.number().int().nonnegative().nullable(),
85
+ openStep: z.object({
86
+ turn: z.number().int().nonnegative(),
87
+ step: z.number().int().nonnegative(),
88
+ startTime: z.number().nonnegative(),
89
+ firstTokenTime: z.number().nonnegative().nullable(),
90
+ }).nullable(),
91
+ pendingCalls: z.record(z.string(), z.number().nonnegative()),
92
+ })
93
+
94
+ /**
95
+ * Provider-reported completion tokens, guarded the way the window fold guards
96
+ * node usage.
97
+ * @param usage - the assistant/message event's optional usage record.
98
+ * @returns the output-token count, or null when unreported or invalid.
99
+ */
100
+ function usageOutputTokens(usage: unknown): number | null {
101
+ if (typeof usage !== 'object' || usage === null) return null
102
+ const value = (usage as { outputTokens?: unknown }).outputTokens
103
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null
104
+ }
105
+
106
+ /** The `sessionStats` unit registered on `ctx.sessionProjections` (exported for the unit spec). */
107
+ export const sessionStatsProjectionDefinition = {
108
+ key: 'sessionStats',
109
+ stateVersion: 1,
110
+ stateSchema: sessionStatsStateSchema,
111
+ init: () => ({
112
+ turns: 0,
113
+ steps: 0,
114
+ llmMs: 0,
115
+ toolMs: 0,
116
+ ttftMs: 0,
117
+ ttftSteps: 0,
118
+ decodeMs: 0,
119
+ decodeTokens: 0,
120
+ lastTurn: null,
121
+ openStep: null,
122
+ pendingCalls: {},
123
+ }),
124
+ apply: (state, event) => {
125
+ // Every uninteresting event returns the same reference (Object.is gates the change feed).
126
+ switch (event.type) {
127
+ case 'step/start':
128
+ return {
129
+ ...state,
130
+ openStep: { turn: event.data.turn, step: event.data.step, startTime: event.time, firstTokenTime: null },
131
+ }
132
+ case 'assistant/attempt': {
133
+ const open = state.openStep
134
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step) return state
135
+ const first = assistantStreamFirstTokenTime(event.data.stream) ?? null
136
+ if (open.firstTokenTime !== null || first === null) return state
137
+ return { ...state, openStep: { ...open, firstTokenTime: first } }
138
+ }
139
+ case 'assistant/message': {
140
+ const open = state.openStep
141
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step) return state
142
+ const firstToken = open.firstTokenTime ?? assistantStreamFirstTokenTime(event.data.stream) ?? null
143
+ // One assembled message per step: closing the boundary means a
144
+ // defensive duplicate cannot accrue twice.
145
+ const next: SessionStatsState = {
146
+ ...state,
147
+ llmMs: state.llmMs + Math.max(0, event.time - open.startTime),
148
+ openStep: null,
149
+ }
150
+ if (firstToken !== null) {
151
+ next.ttftMs += Math.max(0, firstToken - open.startTime)
152
+ next.ttftSteps += 1
153
+ const outputTokens = usageOutputTokens(event.data.usage)
154
+ if (outputTokens !== null) {
155
+ next.decodeMs += Math.max(0, event.time - firstToken)
156
+ next.decodeTokens += outputTokens
157
+ }
158
+ }
159
+ return next
160
+ }
161
+ case 'tool/call':
162
+ return { ...state, pendingCalls: { ...state.pendingCalls, [event.data.callId]: event.time } }
163
+ case 'tool/result': {
164
+ // Own-key check: callId is provider-minted (model/tool JSON boundary),
165
+ // so a prototype property name ('constructor', 'toString') on a result
166
+ // with no recorded call must read as unmatched, not as an inherited
167
+ // function that would poison toolMs with NaN.
168
+ const callId = event.data.message.source.callId
169
+ const dispatched = Object.hasOwn(state.pendingCalls, callId) ? state.pendingCalls[callId] : undefined
170
+ if (dispatched === undefined) return state
171
+ const pendingCalls = Object.fromEntries(
172
+ Object.entries(state.pendingCalls).filter(([id]) => id !== callId),
173
+ )
174
+ return { ...state, toolMs: state.toolMs + Math.max(0, event.time - dispatched), pendingCalls }
175
+ }
176
+ case 'step/end':
177
+ return {
178
+ ...state,
179
+ turns: state.lastTurn === event.data.turn ? state.turns : state.turns + 1,
180
+ steps: state.steps + 1,
181
+ lastTurn: event.data.turn,
182
+ openStep: null,
183
+ }
184
+ case 'turn/end':
185
+ // A call whose result never landed belongs to a cancelled or failed
186
+ // turn; results always land within their turn, so drop the leftovers
187
+ // instead of growing persisted state forever.
188
+ return Object.keys(state.pendingCalls).length === 0 ? state : { ...state, pendingCalls: {} }
189
+ default:
190
+ return state
191
+ }
192
+ },
193
+ wire: {
194
+ viewSchema: sessionStatsSchema,
195
+ view: state => ({
196
+ turns: state.turns,
197
+ steps: state.steps,
198
+ llmMs: state.llmMs,
199
+ toolMs: state.toolMs,
200
+ ttftMs: state.ttftMs,
201
+ ttftSteps: state.ttftSteps,
202
+ decodeMs: state.decodeMs,
203
+ decodeTokens: state.decodeTokens,
204
+ }),
205
+ summary: false,
206
+ },
207
+ } satisfies ProjectionDefinition<'sessionStats', SessionStatsState>
package/src/types.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Pure types of the session-stats domain: the ONE home of the `sessionStats`
3
+ * projection-key declaration, free of this package's host-side value imports
4
+ * (cordis context, zod, the llm chunk predicate). Two namespace projections
5
+ * serve it — `./types` for host consumers, `./client` for client aggregates —
6
+ * with zero content duplication.
7
+ *
8
+ * @module @unieai/rabi-session-stats/types
9
+ */
10
+
11
+ import type { SessionProjectionSummaryExcluded } from '@unieai/rabi-session-projection/types'
12
+
13
+ // Marks this file a module so the declaration below AUGMENTS the projection
14
+ // table instead of declaring an ambient module.
15
+ export {}
16
+
17
+ /**
18
+ * Whole-log conversation figures, independent of how much history a client
19
+ * has paged in. Counts and wall times all fold from the complete durable log;
20
+ * every field is 0 until its first contributing event lands. Field names
21
+ * mirror the client window fold so an assembly without this unit can fall
22
+ * back to it wholesale.
23
+ */
24
+ export interface SessionStatsProjection {
25
+ /** Distinct turns carrying at least one closed step (`step/end`); rejected or empty turns are uncounted. */
26
+ turns: number
27
+ /** Closed steps (`step/end` events) — completed, failed, and cancelled steps alike. */
28
+ steps: number
29
+ /** Summed model wall time (`step/start` → `assistant/message`) over steps that assembled a message. */
30
+ llmMs: number
31
+ /** Summed tool wall time over `tool/call` → `tool/result` pairs matched by callId. */
32
+ toolMs: number
33
+ /** Summed first-token latency (`step/start` → first non-empty delta chunk) over `ttftSteps`. */
34
+ ttftMs: number
35
+ /** Steps carrying a recorded first token. */
36
+ ttftSteps: number
37
+ /** Summed decode wall time (first token → `assistant/message`) over steps that also report output tokens. */
38
+ decodeMs: number
39
+ /** Summed provider output tokens over the same decode-timed steps. */
40
+ decodeTokens: number
41
+ }
42
+
43
+ declare module '@unieai/rabi-session-projection/types' {
44
+ interface SessionProjectionMap {
45
+ /**
46
+ * Whole-log turn/step counts and wall times; see
47
+ * {@link SessionStatsProjection}. Excluded from Session summary payloads:
48
+ * no list row renders these figures.
49
+ */
50
+ sessionStats: SessionProjectionSummaryExcluded<SessionStatsProjection>
51
+ }
52
+ }