@unieai/rabi-session-stats 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/index.js +200 -0
- package/lib/types/client.d.ts +10 -0
- package/lib/types/client.js +9 -0
- package/lib/types/index.d.ts +24 -0
- package/lib/types/index.js +24 -0
- package/lib/types/projection.d.ts +125 -0
- package/lib/types/projection.js +168 -0
- package/lib/types/types.d.ts +46 -0
- package/lib/types/types.js +10 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +46 -4
- package/src/client.ts +10 -0
- package/src/index.ts +30 -0
- package/src/projection.ts +207 -0
- package/src/types.ts +52 -0
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
|
-
#
|
|
1
|
+
# @unieai/rabi-session-stats
|
|
2
2
|
|
|
3
|
-
|
|
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,200 @@
|
|
|
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
|
+
summary: false
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
//#endregion
|
|
175
|
+
//#region lib/types/index.js
|
|
176
|
+
/**
|
|
177
|
+
* Function plugin registering the `sessionStats` projection unit: whole-log
|
|
178
|
+
* turn/step counts and LLM/tool/first-token/decode wall times served through
|
|
179
|
+
* the session-projection seam (registry snapshot, change feed, and every
|
|
180
|
+
* projection carrier), so clients render full-session figures that paging and
|
|
181
|
+
* compaction cannot change. The plugin owns only the fold; delivery is the
|
|
182
|
+
* seam's.
|
|
183
|
+
*
|
|
184
|
+
* @module @unieai/rabi-session-stats
|
|
185
|
+
*/
|
|
186
|
+
/** Cordis plugin name. */
|
|
187
|
+
const name = "session-stats";
|
|
188
|
+
/** The projection registry is the plugin's whole purpose; without it the fiber stays pending. */
|
|
189
|
+
const inject = ["sessionProjections"];
|
|
190
|
+
/**
|
|
191
|
+
* Register the `sessionStats` unit; the registration is an effect on this
|
|
192
|
+
* plugin's fiber, so unloading removes the key.
|
|
193
|
+
* @param ctx - registrant context carrying the projection registry.
|
|
194
|
+
* @returns when the plugin is ready.
|
|
195
|
+
*/
|
|
196
|
+
async function apply(ctx) {
|
|
197
|
+
await ctx.sessionProjections.register(sessionStatsProjectionDefinition);
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
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,24 @@
|
|
|
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
|
+
* @returns when the plugin is ready.
|
|
22
|
+
*/
|
|
23
|
+
export declare function apply(ctx: Context): Promise<void>;
|
|
24
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
* @returns when the plugin is ready.
|
|
21
|
+
*/
|
|
22
|
+
export async function apply(ctx) {
|
|
23
|
+
await ctx.sessionProjections.register(sessionStatsProjectionDefinition);
|
|
24
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
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
|
+
/** The `sessionStats` unit registered on `ctx.sessionProjections` (exported for the unit spec). */
|
|
65
|
+
export declare const sessionStatsProjectionDefinition: {
|
|
66
|
+
key: "sessionStats";
|
|
67
|
+
stateVersion: number;
|
|
68
|
+
stateSchema: z.ZodObject<{
|
|
69
|
+
turns: z.ZodNumber;
|
|
70
|
+
steps: z.ZodNumber;
|
|
71
|
+
llmMs: z.ZodNumber;
|
|
72
|
+
toolMs: z.ZodNumber;
|
|
73
|
+
ttftMs: z.ZodNumber;
|
|
74
|
+
ttftSteps: z.ZodNumber;
|
|
75
|
+
decodeMs: z.ZodNumber;
|
|
76
|
+
decodeTokens: z.ZodNumber;
|
|
77
|
+
lastTurn: z.ZodNullable<z.ZodNumber>;
|
|
78
|
+
openStep: z.ZodNullable<z.ZodObject<{
|
|
79
|
+
turn: z.ZodNumber;
|
|
80
|
+
step: z.ZodNumber;
|
|
81
|
+
startTime: z.ZodNumber;
|
|
82
|
+
firstTokenTime: z.ZodNullable<z.ZodNumber>;
|
|
83
|
+
}, z.core.$strip>>;
|
|
84
|
+
pendingCalls: z.ZodRecord<z.ZodString, z.ZodNumber>;
|
|
85
|
+
}, z.core.$strict>;
|
|
86
|
+
init: () => {
|
|
87
|
+
turns: number;
|
|
88
|
+
steps: number;
|
|
89
|
+
llmMs: number;
|
|
90
|
+
toolMs: number;
|
|
91
|
+
ttftMs: number;
|
|
92
|
+
ttftSteps: number;
|
|
93
|
+
decodeMs: number;
|
|
94
|
+
decodeTokens: number;
|
|
95
|
+
lastTurn: null;
|
|
96
|
+
openStep: null;
|
|
97
|
+
pendingCalls: {};
|
|
98
|
+
};
|
|
99
|
+
apply: (state: NoInfer<SessionStatsState>, event: import("@unieai/rabi-session").SessionEvent) => SessionStatsState;
|
|
100
|
+
wire: {
|
|
101
|
+
viewSchema: z.ZodObject<{
|
|
102
|
+
turns: z.ZodNumber;
|
|
103
|
+
steps: z.ZodNumber;
|
|
104
|
+
llmMs: z.ZodNumber;
|
|
105
|
+
toolMs: z.ZodNumber;
|
|
106
|
+
ttftMs: z.ZodNumber;
|
|
107
|
+
ttftSteps: z.ZodNumber;
|
|
108
|
+
decodeMs: z.ZodNumber;
|
|
109
|
+
decodeTokens: z.ZodNumber;
|
|
110
|
+
}, z.core.$strict>;
|
|
111
|
+
view: (state: NoInfer<SessionStatsState>) => {
|
|
112
|
+
turns: number;
|
|
113
|
+
steps: number;
|
|
114
|
+
llmMs: number;
|
|
115
|
+
toolMs: number;
|
|
116
|
+
ttftMs: number;
|
|
117
|
+
ttftSteps: number;
|
|
118
|
+
decodeMs: number;
|
|
119
|
+
decodeTokens: number;
|
|
120
|
+
};
|
|
121
|
+
summary: false;
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
export {};
|
|
125
|
+
//# sourceMappingURL=projection.d.ts.map
|
|
@@ -0,0 +1,168 @@
|
|
|
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
|
+
summary: false,
|
|
167
|
+
},
|
|
168
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
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
|
+
/**
|
|
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>;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
//# 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/de.json
ADDED
package/locale/en.json
ADDED
package/locale/es.json
ADDED
package/locale/fr.json
ADDED
package/locale/ja.json
ADDED
package/locale/pt.json
ADDED
package/locale/ru.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unieai/rabi-session-stats",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"description": "Whole-log conversation counts and wall times projection (sessionStats) for the Rabi Harness",
|
|
4
|
+
"version": "0.2.2-rc.5",
|
|
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
|
+
"lib/types/**/*.d.ts.map",
|
|
34
|
+
"lib/**/*.js.map",
|
|
35
|
+
"src",
|
|
36
|
+
"README.md"
|
|
37
|
+
],
|
|
38
|
+
"license": "MIT",
|
|
39
|
+
"peerDependencies": {
|
|
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"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"zod": "4.6.6"
|
|
47
|
+
}
|
|
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
|
+
}
|