@unieai/rabi-session-stats 0.0.0-stage → 0.2.1-rc.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @unieai/rabi-session-stats
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Whole-log conversation counts and wall times projection (sessionStats) for the Rabi Harness
4
+
5
+ Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
+ not meant to be used on its own.
7
+
8
+ See LICENSE for the license and copyright of this package.
package/lib/index.js ADDED
@@ -0,0 +1,198 @@
1
+ import { z } from "zod";
2
+ import { assistantStreamFirstTokenTime } from "@unieai/rabi-llm";
3
+ //#region lib/types/projection.js
4
+ /**
5
+ * The `sessionStats` projection unit: a pure fold of step boundaries, stream
6
+ * embedded streams, tool pairs, and assembled assistant messages into whole-log counts
7
+ * and wall times.
8
+ *
9
+ * `step/end` — not `assistant/message` — is the counted step event because it
10
+ * is the step lifecycle authority: the loop appends exactly one per entered
11
+ * step, in a `finally`, so completed, failed, cancelled, and max-tokens steps
12
+ * all land one. Counting assembled assistant messages instead would overcount
13
+ * max-tokens usage-host messages (empty content, excluded from the surface)
14
+ * and undercount cancelled steps (aborted before the message assembles).
15
+ *
16
+ * The wall-time folds mirror the client window fold field by field
17
+ * (`deriveStats` in rabi-client-ui-conversation, that fold's whole-window
18
+ * fallback role): model time is `step/start` → `assistant/message`, first
19
+ * token is the first non-empty delta chunk and survives an in-step
20
+ * `llm/retry`, decode spans first token → assembled message on steps that
21
+ * also report output tokens, and tool time pairs `tool/call` → `tool/result`
22
+ * by callId. A cancelled step assembles no message, so its partial stream
23
+ * time stays uncounted in every time figure — matching the window, which
24
+ * renders it as an untimed interrupted node.
25
+ *
26
+ * @module @unieai/rabi-session-stats/projection
27
+ */
28
+ const sessionStatsSchema = z.object({
29
+ turns: z.number().int().nonnegative(),
30
+ steps: z.number().int().nonnegative(),
31
+ llmMs: z.number().nonnegative(),
32
+ toolMs: z.number().nonnegative(),
33
+ ttftMs: z.number().nonnegative(),
34
+ ttftSteps: z.number().int().nonnegative(),
35
+ decodeMs: z.number().nonnegative(),
36
+ decodeTokens: z.number().nonnegative()
37
+ }).strict();
38
+ /**
39
+ * The fold state's shape (totals plus in-flight boundaries), validated on
40
+ * persisted-cache rows after their `ver` gate — the unit's input boundary.
41
+ * The view is a strict subset of the state, so this schema extends
42
+ * `sessionStatsSchema` (the wire output boundary) with the boundary fields.
43
+ */
44
+ const sessionStatsStateSchema = sessionStatsSchema.extend({
45
+ lastTurn: z.number().int().nonnegative().nullable(),
46
+ openStep: z.object({
47
+ turn: z.number().int().nonnegative(),
48
+ step: z.number().int().nonnegative(),
49
+ startTime: z.number().nonnegative(),
50
+ firstTokenTime: z.number().nonnegative().nullable()
51
+ }).nullable(),
52
+ pendingCalls: z.record(z.string(), z.number().nonnegative())
53
+ });
54
+ /**
55
+ * Provider-reported completion tokens, guarded the way the window fold guards
56
+ * node usage.
57
+ * @param usage - the assistant/message event's optional usage record.
58
+ * @returns the output-token count, or null when unreported or invalid.
59
+ */
60
+ function usageOutputTokens(usage) {
61
+ if (typeof usage !== "object" || usage === null) return null;
62
+ const value = usage.outputTokens;
63
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
64
+ }
65
+ /** The `sessionStats` unit registered on `ctx.sessionProjections` (exported for the unit spec). */
66
+ const sessionStatsProjectionDefinition = {
67
+ key: "sessionStats",
68
+ stateVersion: 1,
69
+ stateSchema: sessionStatsStateSchema,
70
+ init: () => ({
71
+ turns: 0,
72
+ steps: 0,
73
+ llmMs: 0,
74
+ toolMs: 0,
75
+ ttftMs: 0,
76
+ ttftSteps: 0,
77
+ decodeMs: 0,
78
+ decodeTokens: 0,
79
+ lastTurn: null,
80
+ openStep: null,
81
+ pendingCalls: {}
82
+ }),
83
+ apply: (state, event) => {
84
+ switch (event.type) {
85
+ case "step/start": return {
86
+ ...state,
87
+ openStep: {
88
+ turn: event.data.turn,
89
+ step: event.data.step,
90
+ startTime: event.time,
91
+ firstTokenTime: null
92
+ }
93
+ };
94
+ case "assistant/attempt": {
95
+ const open = state.openStep;
96
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step) return state;
97
+ const first = assistantStreamFirstTokenTime(event.data.stream) ?? null;
98
+ if (open.firstTokenTime !== null || first === null) return state;
99
+ return {
100
+ ...state,
101
+ openStep: {
102
+ ...open,
103
+ firstTokenTime: first
104
+ }
105
+ };
106
+ }
107
+ case "assistant/message": {
108
+ const open = state.openStep;
109
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step) return state;
110
+ const firstToken = open.firstTokenTime ?? assistantStreamFirstTokenTime(event.data.stream) ?? null;
111
+ const next = {
112
+ ...state,
113
+ llmMs: state.llmMs + Math.max(0, event.time - open.startTime),
114
+ openStep: null
115
+ };
116
+ if (firstToken !== null) {
117
+ next.ttftMs += Math.max(0, firstToken - open.startTime);
118
+ next.ttftSteps += 1;
119
+ const outputTokens = usageOutputTokens(event.data.usage);
120
+ if (outputTokens !== null) {
121
+ next.decodeMs += Math.max(0, event.time - firstToken);
122
+ next.decodeTokens += outputTokens;
123
+ }
124
+ }
125
+ return next;
126
+ }
127
+ case "tool/call": return {
128
+ ...state,
129
+ pendingCalls: {
130
+ ...state.pendingCalls,
131
+ [event.data.callId]: event.time
132
+ }
133
+ };
134
+ case "tool/result": {
135
+ const callId = event.data.message.source.callId;
136
+ const dispatched = Object.hasOwn(state.pendingCalls, callId) ? state.pendingCalls[callId] : void 0;
137
+ if (dispatched === void 0) return state;
138
+ const pendingCalls = Object.fromEntries(Object.entries(state.pendingCalls).filter(([id]) => id !== callId));
139
+ return {
140
+ ...state,
141
+ toolMs: state.toolMs + Math.max(0, event.time - dispatched),
142
+ pendingCalls
143
+ };
144
+ }
145
+ case "step/end": return {
146
+ ...state,
147
+ turns: state.lastTurn === event.data.turn ? state.turns : state.turns + 1,
148
+ steps: state.steps + 1,
149
+ lastTurn: event.data.turn,
150
+ openStep: null
151
+ };
152
+ case "turn/end": return Object.keys(state.pendingCalls).length === 0 ? state : {
153
+ ...state,
154
+ pendingCalls: {}
155
+ };
156
+ default: return state;
157
+ }
158
+ },
159
+ wire: {
160
+ viewSchema: sessionStatsSchema,
161
+ view: (state) => ({
162
+ turns: state.turns,
163
+ steps: state.steps,
164
+ llmMs: state.llmMs,
165
+ toolMs: state.toolMs,
166
+ ttftMs: state.ttftMs,
167
+ ttftSteps: state.ttftSteps,
168
+ decodeMs: state.decodeMs,
169
+ decodeTokens: state.decodeTokens
170
+ })
171
+ }
172
+ };
173
+ //#endregion
174
+ //#region lib/types/index.js
175
+ /**
176
+ * Function plugin registering the `sessionStats` projection unit: whole-log
177
+ * turn/step counts and LLM/tool/first-token/decode wall times served through
178
+ * the session-projection seam (registry snapshot, change feed, and every
179
+ * projection carrier), so clients render full-session figures that paging and
180
+ * compaction cannot change. The plugin owns only the fold; delivery is the
181
+ * seam's.
182
+ *
183
+ * @module @unieai/rabi-session-stats
184
+ */
185
+ /** Cordis plugin name. */
186
+ const name = "session-stats";
187
+ /** The projection registry is the plugin's whole purpose; without it the fiber stays pending. */
188
+ const inject = ["sessionProjections"];
189
+ /**
190
+ * Register the `sessionStats` unit; the registration is an effect on this
191
+ * plugin's fiber, so unloading removes the key.
192
+ * @param ctx - registrant context carrying the projection registry.
193
+ */
194
+ function apply(ctx) {
195
+ ctx.sessionProjections.register(sessionStatsProjectionDefinition);
196
+ }
197
+ //#endregion
198
+ export { apply, inject, name };
@@ -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
+ export type * from './types.ts';
10
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,9 @@
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
+ export {};
@@ -0,0 +1,23 @@
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
+ import type { Context } from '@unieai/cordis';
12
+ export type * from './types.ts';
13
+ /** Cordis plugin name. */
14
+ export declare const name = "session-stats";
15
+ /** The projection registry is the plugin's whole purpose; without it the fiber stays pending. */
16
+ export declare const inject: string[];
17
+ /**
18
+ * Register the `sessionStats` unit; the registration is an effect on this
19
+ * plugin's fiber, so unloading removes the key.
20
+ * @param ctx - registrant context carrying the projection registry.
21
+ */
22
+ export declare function apply(ctx: Context): void;
23
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,23 @@
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
+ import { sessionStatsProjectionDefinition } from "./projection.js";
12
+ /** Cordis plugin name. */
13
+ export const name = 'session-stats';
14
+ /** The projection registry is the plugin's whole purpose; without it the fiber stays pending. */
15
+ export const inject = ['sessionProjections'];
16
+ /**
17
+ * Register the `sessionStats` unit; the registration is an effect on this
18
+ * plugin's fiber, so unloading removes the key.
19
+ * @param ctx - registrant context carrying the projection registry.
20
+ */
21
+ export function apply(ctx) {
22
+ ctx.sessionProjections.register(sessionStatsProjectionDefinition);
23
+ }
@@ -0,0 +1,129 @@
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
+ import { z } from 'zod';
26
+ /** Accumulated whole-log figures (the view is exactly these totals). */
27
+ interface SessionStatsTotals {
28
+ /** Distinct turns with at least one closed step so far. */
29
+ turns: number;
30
+ /** Closed steps so far. */
31
+ steps: number;
32
+ /** Summed model wall time over message-assembling steps, ms. */
33
+ llmMs: number;
34
+ /** Summed matched tool call→result wall time, ms. */
35
+ toolMs: number;
36
+ /** Summed first-token latency over `ttftSteps`, ms. */
37
+ ttftMs: number;
38
+ /** Steps carrying a recorded first token. */
39
+ ttftSteps: number;
40
+ /** Summed decode wall time over usage-reporting steps, ms. */
41
+ decodeMs: number;
42
+ /** Summed provider output tokens over the same steps. */
43
+ decodeTokens: number;
44
+ }
45
+ /**
46
+ * Fold state: the totals plus the in-flight boundaries they accrue from.
47
+ * Turn numbers are host-assigned and monotonic per session, so a single
48
+ * `lastTurn` slot decides "first closed step of a new turn"; the state is
49
+ * plain JSON per the unit contract (persisted-cache precondition).
50
+ */
51
+ interface SessionStatsState extends SessionStatsTotals {
52
+ /** Turn of the last counted `step/end`; null before the first. */
53
+ lastTurn: number | null;
54
+ /** The open step's boundary facts; null outside a step or after its message assembled. */
55
+ openStep: {
56
+ turn: number;
57
+ step: number;
58
+ startTime: number;
59
+ firstTokenTime: number | null;
60
+ } | null;
61
+ /** Dispatch times of tool calls whose result has not landed, by callId. */
62
+ pendingCalls: Record<string, number>;
63
+ }
64
+ declare module '@unieai/rabi-session-projection/types' {
65
+ interface SessionProjectionStateMap {
66
+ sessionStats: SessionStatsState;
67
+ }
68
+ }
69
+ /** The `sessionStats` unit registered on `ctx.sessionProjections` (exported for the unit spec). */
70
+ export declare const sessionStatsProjectionDefinition: {
71
+ key: "sessionStats";
72
+ stateVersion: number;
73
+ stateSchema: z.ZodObject<{
74
+ turns: z.ZodNumber;
75
+ steps: z.ZodNumber;
76
+ llmMs: z.ZodNumber;
77
+ toolMs: z.ZodNumber;
78
+ ttftMs: z.ZodNumber;
79
+ ttftSteps: z.ZodNumber;
80
+ decodeMs: z.ZodNumber;
81
+ decodeTokens: z.ZodNumber;
82
+ lastTurn: z.ZodNullable<z.ZodNumber>;
83
+ openStep: z.ZodNullable<z.ZodObject<{
84
+ turn: z.ZodNumber;
85
+ step: z.ZodNumber;
86
+ startTime: z.ZodNumber;
87
+ firstTokenTime: z.ZodNullable<z.ZodNumber>;
88
+ }, z.core.$strip>>;
89
+ pendingCalls: z.ZodRecord<z.ZodString, z.ZodNumber>;
90
+ }, z.core.$strict>;
91
+ init: () => {
92
+ turns: number;
93
+ steps: number;
94
+ llmMs: number;
95
+ toolMs: number;
96
+ ttftMs: number;
97
+ ttftSteps: number;
98
+ decodeMs: number;
99
+ decodeTokens: number;
100
+ lastTurn: null;
101
+ openStep: null;
102
+ pendingCalls: {};
103
+ };
104
+ apply: (state: NoInfer<SessionStatsState>, event: import("@unieai/rabi-session").SessionEvent) => SessionStatsState;
105
+ wire: {
106
+ viewSchema: z.ZodObject<{
107
+ turns: z.ZodNumber;
108
+ steps: z.ZodNumber;
109
+ llmMs: z.ZodNumber;
110
+ toolMs: z.ZodNumber;
111
+ ttftMs: z.ZodNumber;
112
+ ttftSteps: z.ZodNumber;
113
+ decodeMs: z.ZodNumber;
114
+ decodeTokens: z.ZodNumber;
115
+ }, z.core.$strict>;
116
+ view: (state: NoInfer<SessionStatsState>) => {
117
+ turns: number;
118
+ steps: number;
119
+ llmMs: number;
120
+ toolMs: number;
121
+ ttftMs: number;
122
+ ttftSteps: number;
123
+ decodeMs: number;
124
+ decodeTokens: number;
125
+ };
126
+ };
127
+ };
128
+ export {};
129
+ //# sourceMappingURL=projection.d.ts.map
@@ -0,0 +1,167 @@
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
+ import { z } from 'zod';
26
+ import { assistantStreamFirstTokenTime } from '@unieai/rabi-llm';
27
+ const sessionStatsSchema = z.object({
28
+ turns: z.number().int().nonnegative(),
29
+ steps: z.number().int().nonnegative(),
30
+ llmMs: z.number().nonnegative(),
31
+ toolMs: z.number().nonnegative(),
32
+ ttftMs: z.number().nonnegative(),
33
+ ttftSteps: z.number().int().nonnegative(),
34
+ decodeMs: z.number().nonnegative(),
35
+ decodeTokens: z.number().nonnegative(),
36
+ }).strict();
37
+ /**
38
+ * The fold state's shape (totals plus in-flight boundaries), validated on
39
+ * persisted-cache rows after their `ver` gate — the unit's input boundary.
40
+ * The view is a strict subset of the state, so this schema extends
41
+ * `sessionStatsSchema` (the wire output boundary) with the boundary fields.
42
+ */
43
+ const sessionStatsStateSchema = sessionStatsSchema.extend({
44
+ lastTurn: z.number().int().nonnegative().nullable(),
45
+ openStep: z.object({
46
+ turn: z.number().int().nonnegative(),
47
+ step: z.number().int().nonnegative(),
48
+ startTime: z.number().nonnegative(),
49
+ firstTokenTime: z.number().nonnegative().nullable(),
50
+ }).nullable(),
51
+ pendingCalls: z.record(z.string(), z.number().nonnegative()),
52
+ });
53
+ /**
54
+ * Provider-reported completion tokens, guarded the way the window fold guards
55
+ * node usage.
56
+ * @param usage - the assistant/message event's optional usage record.
57
+ * @returns the output-token count, or null when unreported or invalid.
58
+ */
59
+ function usageOutputTokens(usage) {
60
+ if (typeof usage !== 'object' || usage === null)
61
+ return null;
62
+ const value = usage.outputTokens;
63
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
64
+ }
65
+ /** The `sessionStats` unit registered on `ctx.sessionProjections` (exported for the unit spec). */
66
+ export const sessionStatsProjectionDefinition = {
67
+ key: 'sessionStats',
68
+ stateVersion: 1,
69
+ stateSchema: sessionStatsStateSchema,
70
+ init: () => ({
71
+ turns: 0,
72
+ steps: 0,
73
+ llmMs: 0,
74
+ toolMs: 0,
75
+ ttftMs: 0,
76
+ ttftSteps: 0,
77
+ decodeMs: 0,
78
+ decodeTokens: 0,
79
+ lastTurn: null,
80
+ openStep: null,
81
+ pendingCalls: {},
82
+ }),
83
+ apply: (state, event) => {
84
+ // Every uninteresting event returns the same reference (Object.is gates the change feed).
85
+ switch (event.type) {
86
+ case 'step/start':
87
+ return {
88
+ ...state,
89
+ openStep: { turn: event.data.turn, step: event.data.step, startTime: event.time, firstTokenTime: null },
90
+ };
91
+ case 'assistant/attempt': {
92
+ const open = state.openStep;
93
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step)
94
+ return state;
95
+ const first = assistantStreamFirstTokenTime(event.data.stream) ?? null;
96
+ if (open.firstTokenTime !== null || first === null)
97
+ return state;
98
+ return { ...state, openStep: { ...open, firstTokenTime: first } };
99
+ }
100
+ case 'assistant/message': {
101
+ const open = state.openStep;
102
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step)
103
+ return state;
104
+ const firstToken = open.firstTokenTime ?? assistantStreamFirstTokenTime(event.data.stream) ?? null;
105
+ // One assembled message per step: closing the boundary means a
106
+ // defensive duplicate cannot accrue twice.
107
+ const next = {
108
+ ...state,
109
+ llmMs: state.llmMs + Math.max(0, event.time - open.startTime),
110
+ openStep: null,
111
+ };
112
+ if (firstToken !== null) {
113
+ next.ttftMs += Math.max(0, firstToken - open.startTime);
114
+ next.ttftSteps += 1;
115
+ const outputTokens = usageOutputTokens(event.data.usage);
116
+ if (outputTokens !== null) {
117
+ next.decodeMs += Math.max(0, event.time - firstToken);
118
+ next.decodeTokens += outputTokens;
119
+ }
120
+ }
121
+ return next;
122
+ }
123
+ case 'tool/call':
124
+ return { ...state, pendingCalls: { ...state.pendingCalls, [event.data.callId]: event.time } };
125
+ case 'tool/result': {
126
+ // Own-key check: callId is provider-minted (model/tool JSON boundary),
127
+ // so a prototype property name ('constructor', 'toString') on a result
128
+ // with no recorded call must read as unmatched, not as an inherited
129
+ // function that would poison toolMs with NaN.
130
+ const callId = event.data.message.source.callId;
131
+ const dispatched = Object.hasOwn(state.pendingCalls, callId) ? state.pendingCalls[callId] : undefined;
132
+ if (dispatched === undefined)
133
+ return state;
134
+ const pendingCalls = Object.fromEntries(Object.entries(state.pendingCalls).filter(([id]) => id !== callId));
135
+ return { ...state, toolMs: state.toolMs + Math.max(0, event.time - dispatched), pendingCalls };
136
+ }
137
+ case 'step/end':
138
+ return {
139
+ ...state,
140
+ turns: state.lastTurn === event.data.turn ? state.turns : state.turns + 1,
141
+ steps: state.steps + 1,
142
+ lastTurn: event.data.turn,
143
+ openStep: null,
144
+ };
145
+ case 'turn/end':
146
+ // A call whose result never landed belongs to a cancelled or failed
147
+ // turn; results always land within their turn, so drop the leftovers
148
+ // instead of growing persisted state forever.
149
+ return Object.keys(state.pendingCalls).length === 0 ? state : { ...state, pendingCalls: {} };
150
+ default:
151
+ return state;
152
+ }
153
+ },
154
+ wire: {
155
+ viewSchema: sessionStatsSchema,
156
+ view: state => ({
157
+ turns: state.turns,
158
+ steps: state.steps,
159
+ llmMs: state.llmMs,
160
+ toolMs: state.toolMs,
161
+ ttftMs: state.ttftMs,
162
+ ttftSteps: state.ttftSteps,
163
+ decodeMs: state.decodeMs,
164
+ decodeTokens: state.decodeTokens,
165
+ }),
166
+ },
167
+ };
@@ -0,0 +1,42 @@
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
+ export {};
11
+ /**
12
+ * Whole-log conversation figures, independent of how much history a client
13
+ * has paged in. Counts and wall times all fold from the complete durable log;
14
+ * every field is 0 until its first contributing event lands. Field names
15
+ * mirror the client window fold so an assembly without this unit can fall
16
+ * back to it wholesale.
17
+ */
18
+ export interface SessionStatsProjection {
19
+ /** Distinct turns carrying at least one closed step (`step/end`); rejected or empty turns are uncounted. */
20
+ turns: number;
21
+ /** Closed steps (`step/end` events) — completed, failed, and cancelled steps alike. */
22
+ steps: number;
23
+ /** Summed model wall time (`step/start` → `assistant/message`) over steps that assembled a message. */
24
+ llmMs: number;
25
+ /** Summed tool wall time over `tool/call` → `tool/result` pairs matched by callId. */
26
+ toolMs: number;
27
+ /** Summed first-token latency (`step/start` → first non-empty delta chunk) over `ttftSteps`. */
28
+ ttftMs: number;
29
+ /** Steps carrying a recorded first token. */
30
+ ttftSteps: number;
31
+ /** Summed decode wall time (first token → `assistant/message`) over steps that also report output tokens. */
32
+ decodeMs: number;
33
+ /** Summed provider output tokens over the same decode-timed steps. */
34
+ decodeTokens: number;
35
+ }
36
+ declare module '@unieai/rabi-session-projection/types' {
37
+ interface SessionProjectionMap {
38
+ /** Whole-log turn/step counts and wall times; see {@link SessionStatsProjection}. */
39
+ sessionStats: SessionStatsProjection;
40
+ }
41
+ }
42
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,10 @@
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
+ export {};
package/locale/en.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "meta": {
3
+ "title": "session-stats"
4
+ }
5
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "会话统计",
4
+ "description": "汇总会话的交互次数和耗时等统计信息。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@unieai/rabi-session-stats",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Whole-log conversation counts and wall times projection (sessionStats) for the Rabi Harness",
4
+ "version": "0.2.1-rc.3",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "lib/index.js",
10
+ "types": "lib/types/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/types/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./types": {
17
+ "types": "./lib/types/types.d.ts",
18
+ "default": "./lib/types/types.js"
19
+ },
20
+ "./client": {
21
+ "types": "./lib/types/client.d.ts",
22
+ "default": "./lib/types/client.js"
23
+ },
24
+ "./src/*": "./src/*",
25
+ "./package.json": "./package.json",
26
+ "./locale/*.json": "./locale/*.json"
27
+ },
28
+ "files": [
29
+ "locale/*.json",
30
+ "lib/index.js",
31
+ "lib/types/**/*.js",
32
+ "lib/types/**/*.d.ts",
33
+ "README.md"
34
+ ],
35
+ "license": "MIT",
36
+ "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"
41
+ },
42
+ "dependencies": {
43
+ "zod": "4.4.3"
44
+ }
45
+ }